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
use std::env;
use std::fs::File;
use std::process::Command;
use std::io::{self, copy};
use std::path::PathBuf;
use dirs;
use env_perm;
use curl;
use curl::easy::Easy; 
use tempdir::TempDir;
use std::time::Duration;

const ADDRESS: &'static str = "https://sdk.lunarg.com/sdk/download/latest/mac/vulkan-sdk.tar.gz";

struct SDK {
    name: String,
    path: PathBuf,
    // this needs to not be dropped
    // yet or the directory is removed
    _tmp_dir: TempDir,
}

impl SDK {
    fn download() -> Result<Self, Error> {
        let tmp_dir = TempDir::new("sdk_download").map_err(|e|Error::IO(e))?;
        let mut handle = Easy::new();
        let mut response = Vec::new();
        handle.timeout(Duration::from_secs(0))
            .map_err(|_|Error::FailedCurlSetup("Set timeout failed".to_string()))?;
        handle.url(ADDRESS)
            .map_err(|_|Error::FailedSdkDownload)?;
        {
            let mut transfer = handle.transfer();
            transfer.write_function(|data| {
                let len = data.len();
                response.extend_from_slice(data);
                Ok(len)
            }).map_err(|_|Error::FailedCurlSetup("Failed to create write function".to_string()))?;
            transfer.perform().map_err(|_|Error::FailedSdkDownload)?;
        }
        let (file, downloaded) = {
            let file_name = ADDRESS.split('/')
                .last()
                .unwrap_or("vulkan-sdk.tar.gz");

            let path = tmp_dir.path().join(&file_name);
            (File::create(&path),
             SDK{ name: file_name.into(), path, _tmp_dir: tmp_dir })
        };
        file.and_then(|mut dest| copy(&mut &response[..], &mut dest))
            .and_then(move |_| Ok(downloaded) )
            .map_err(|e| Error::IO(e))
    }

    fn unpack(self) -> Result<(), Error> {
        let Self {
            name,
            path: dl_path,
            ..
        } = self;
        let home = dirs::home_dir()
            .ok_or(Error::IO(io::ErrorKind::NotFound.into()))?;
        let mut sdk_dir = home.clone();
        sdk_dir.push(".vulkan_sdk");

        // Make the vulkan sdk directory
        Command::new("mkdir")
            .arg(&sdk_dir)
            .output()
            .map_err(|_|Error::FailedCommand("Failed to mkdir".to_string()))?;

        // Move the downloaded SDK there
        Command::new("mv")
            .arg(&dl_path)
            .arg(&sdk_dir)
            .output()
            .map_err(|_|Error::FailedCommand("Failed to mv".to_string()))?;

        // Untar the contents
        Command::new("tar")
            .arg("-xzf")
            .arg(format!("{}/{}", sdk_dir.display(), name))
            .arg("-C")
            .arg(&sdk_dir)
            .arg("--strip-components=1")
            .output()
            .map_err(|_|Error::FailedCommand("Failed to tar".to_string()))?;

        // Remove the empty dirctory
        Command::new("rm")
            .arg(format!("{}/{}", sdk_dir.display(), name))
            .output()
            .map_err(|_|Error::FailedCommand("Failed to rm".to_string()))?;
        
        println!("The Vulkan SDK was successfully installed at {}", sdk_dir.display());
        Ok(())
    }
}

fn set_env_vars() -> Result<(), Error> {
    println!("Setting environment variables");
    //export VULKAN_SDK=$HOME/vulkan_sdk/macOS
    env_perm::check_or_set("VULKAN_SDK", r#""$HOME/.vulkan_sdk/macOS""#)
        .map_err(|e|Error::IO(e))?;
    //export PATH=$VULKAN_SDK/bin:$PATH
    env_perm::append("PATH", "$VULKAN_SDK/bin")
        .map_err(|e|Error::IO(e))?;
    //export DYLD_LIBRARY_PATH=$VULKAN_SDK/lib:$DYLD_LIBRARY_PATH
    env_perm::append("DYLD_LIBRARY_PATH", "$VULKAN_SDK/lib")
        .map_err(|e|Error::IO(e))?;
    //export VK_ICD_FILENAMES=$VULKAN_SDK/etc/vulkan/icd.d/MoltenVK_icd.json
    env_perm::check_or_set("VK_ICD_FILENAMES", r#""$VULKAN_SDK/etc/vulkan/icd.d/MoltenVK_icd.json""#)
        .map_err(|e|Error::IO(e))?;
    //export VK_LAYER_PATH=$VULKAN_SDK/etc/vulkan/explicit_layer.d
    env_perm::check_or_set("VK_LAYER_PATH", r#""$VULKAN_SDK/etc/vulkan/explicit_layer.d""#)
        .map_err(|e|Error::IO(e))?;
    set_temp_envs()?;
    Ok(())
}

// Sets the environment variables temporarily because the
// use has not source'd the .bash_profile yet.
fn set_temp_envs() -> Result<(), Error> {
    //export VULKAN_SDK=$HOME/vulkan_sdk/macOS
    let mut vulkan_sdk = dirs::home_dir()
            .ok_or(Error::IO(io::ErrorKind::NotFound.into()))?;
    vulkan_sdk.push(".vulkan_sdk");
    vulkan_sdk.push("macOS");
    env::set_var("VULKAN_SDK", vulkan_sdk.clone().into_os_string());

    //export PATH=$VULKAN_SDK/bin:$PATH
    let mut bin = vulkan_sdk.clone();
    bin.push("bin");
    if let Some(path) = env::var_os("PATH") {
        let mut paths = env::split_paths(&path).collect::<Vec<_>>();
        paths.push(bin);
        let new_path = env::join_paths(paths)
            .map_err(|_|Error::FailedSetEnvVar)?;
        env::set_var("PATH", &new_path);
    }
    
    //export DYLD_LIBRARY_PATH=$VULKAN_SDK/lib:$DYLD_LIBRARY_PATH
    let mut lib = vulkan_sdk.clone();
    lib.push("lib");
    let lib_path = lib.clone();
    if let Some(dyld) = env::var_os("DYLD_LIBRARY_PATH") {
        let mut libs = env::split_paths(&dyld).collect::<Vec<_>>();
        libs.push(lib);
        let new_dyld = env::join_paths(libs)
            .map_err(|_|Error::FailedSetEnvVar)?;
        env::set_var("DYLD_LIBRARY_PATH", &new_dyld);
    }

    // Temporary tell vulkano where the lib is
    // This is necessary because shared_library does not
    // receive temporary environment variables.
    env::set_var("VULKAN_LIB_PATH", lib_path.into_os_string());
    
    let mut icd = vulkan_sdk.clone();
    icd.push("etc");
    icd.push("vulkan");
    icd.push("icd.d");
    icd.push("MoltenVK_icd.json");
    //export VK_ICD_FILENAMES=$VULKAN_SDK/etc/vulkan/icd.d/MoltenVK_icd.json
    env::set_var("VK_ICD_FILENAMES", icd.into_os_string());
    
    //export VK_LAYER_PATH=$VULKAN_SDK/etc/vulkan/explicit_layer.d
    let mut layer = vulkan_sdk.clone();
    layer.push("etc");
    layer.push("vulkan");
    layer.push("explicit_layer.d");
    env::set_var("VK_LAYER_PATH", layer.into_os_string());

    Ok(())
}

// Is the default sdk directory empty
fn check_sdk_dir() -> Result<bool, Error> {
    let mut sdk_dir = dirs::home_dir()
        .ok_or(Error::IO(io::ErrorKind::NotFound.into()))?;
    sdk_dir.push(".vulkan_sdk");
    Ok(sdk_dir.exists())
}

// Is the VULKAN_SDK variable pointing at
// the default location and is that location empty.
fn is_default_dir_and_empty(vulkan_sdk: String) -> Result<bool, Error> {
    let mut default_dir = dirs::home_dir()
        .ok_or(Error::IO(io::ErrorKind::NotFound.into()))?;
    default_dir.push(".vulkan_sdk");
    default_dir.push("macOS");
    Ok(vulkan_sdk == default_dir.to_string_lossy() && !default_dir.exists())
}

#[derive(Debug)]
pub enum Error {
    IO(io::Error),
    FailedCurlSetup(String),
    FailedSdkDownload,
    FailedCommand(String),
    FailedSetEnvVar,
    /// User has sdk in non default directory
    /// Recommend continuing silently
    NonDefaultDir,
    /// Env vars needed to be reset
    /// Probably the user has not sourced .bash_profile yet
    /// Recommend continuing silently
    ResetEnvVars,
    /// User has chosen not to install the sdk
    ChoseNotToInstall,
}

/// Either install silently 
/// or with a message.
/// Can use Default::default()
/// which gives a default message
pub enum Install {
    Silent,
    Message(Message),
}

/// Specify messages to the user
/// for the install.
/// Can use Default::default()
pub struct Message {
    /// Initial question, do they want to install?
    pub question: String,
    /// Message while they are downloading
    pub downloading: String,
    /// Message for when complete
    pub complete: String,
}

impl Default for Install {
    fn default() -> Self {
        Install::Message(Default::default())
    }
}

impl Default for Message {
    fn default() -> Self {
        let question = format!("Vulkano requires the Vulkan SDK to use MoltenVK for MacOS \nWould you like to automatically install it now? (Y/n)");
        let downloading = format!("Downloading and installing Vulkan SDK, This may take some time. Grab a coffee :)");
        let complete = format!("Installation complete :D \nTo update simply remove the '~/.vulkan_sdk' directory");
        Message {
            question,
            downloading,
            complete
        }
    }
}


/// This will check if you have the
/// Vulkan SDK installed by checking
/// if the VULKAN_SDK env var is set.
/// If it's set then nothing will happen.
/// If it is not set then it will download
/// the latest SDK from lunarg.com and install
/// it at home/.vulkan_sdk.
/// It will then set the required environmnet 
/// variables.
/// You can install silently or with a message.
/// Use `check_or_install(Default::default())` 
/// for an install with a default message
pub fn check_or_install(install: Install) -> Result<(), Error> {
    match env::var("VULKAN_SDK") {
        // VULKAN_SDK is set 
        Ok(v) => {
            if is_default_dir_and_empty(v)? {
                // Install as the directory is empty
            } else {
                // VULKAN_SDK is set to a non-default or directory is not empty.
                // Return silently.
                return Err(Error::NonDefaultDir);
            }
        },
        Err(_) =>{
            // Environment Variables are not set
            // but might just need to be set temporarily.
            if check_sdk_dir()? {
                // Set env vars and return silently.
                set_temp_envs()?;
                return Err(Error::ResetEnvVars);
            }
            // Vulkan SDK needs to be installed
        },
    }

    match install {
        Install::Silent =>{
            let sdk = SDK::download()?;
            sdk.unpack()?;
            set_env_vars()?;
        },
        Install::Message(message) => {
            println!("{}", message.question);

            loop {
                let mut answer = String::new();
                io::stdin().read_line(&mut answer)
                    .map_err(|e|Error::IO(e))?;
                answer.pop();
                match answer.as_str() {
                    "Y" | "" => break,
                    "n" => return Err(Error::ChoseNotToInstall),
                    _ => println!("Invalid answer, enter 'Y' to install or 'n' to quit"),
                }
            }

            println!("{}", message.downloading);

            let sdk = SDK::download()?;
            sdk.unpack()?;
            set_env_vars()?;

            println!("{}", message.complete);
        },
    }

    Ok(())
}