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
use std::process::Command;
use enquote;
use std::error::Error;
use clokwerk::{Scheduler, TimeUnits};
use std::thread;
use std::time::Duration;
use toml;
use serde::{Serialize,Deserialize};

/// Stores the times and filepaths as a vector of strings
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
    pub times : Vec<String>,
    pub walls : Vec<String>,
}
/// Check if desktop is Gnome compliant
fn is_gnome_compliant(desktop: &str) -> bool {
    desktop.contains("GNOME") || desktop == "Unity" || desktop == "Pantheon"
}

/// args - NONE
/// return Result<String, Box<error>
/// Purpose - Get's path of the current wallpaper
pub fn get_wallpaper() -> Result<String,  Box<dyn Error>>{

    let desktop = get_envt()?;

    if is_gnome_compliant(&desktop) {
        Command::new("gsettings")
        .args(&["get", "org.gnome.desktop.background", "picture-uri"])
        .output()?;
    }

    let output = match desktop.as_str() {
        "X-Cinnamon" => {
            Command::new("dconf")
            .arg("read")
            .arg("/org/cinnamon/desktop/background/picture-uri")
            .output()?
        },

        "MATE" => {
            Command::new("dconf")
            .args(&["read", "/org/mate/desktop/background/picture-filename"])
            .output()?

        },

        "XFCE" => {
            Command::new("xfconf-query")
            .args(&["-c", "xfce4-desktop", "-p", "/backdrop/screen0/monitor0/workspace0/last-image"])
            .output()?         
        },

        "Deepin" => {
            Command::new("dconf")
            .args(&["read", "/com/deepin/wrap/gnome/desktop/background/picture-uri"])
            .output()?
        },
        // Panics since flowy does not support others yet
        _ => {
            panic!("Unsupported Desktop Environment")
        }
    };
    

    return  Ok(enquote::unquote(String::from_utf8(output.stdout)?.trim().into())?)

    }

/// args - None
/// return <Result, Error>
/// Purpose - get the current envt
pub fn get_envt() -> Result<String, Box<dyn Error>> {

    Ok(std::env::var("XDG_CURRENT_DESKTOP")?)

}

/// args - filepath
/// return - Result<(), Error>
/// purpose - set's the wallpaper to filepath
pub fn set_paper (path : &str) -> Result<(), Box<dyn Error>>  {

    let path = enquote::enquote('"', &format!("{}", path));
    // Getting desktop here
    let desktop = get_envt()?;
    // Checking if it is GNOME based
    if is_gnome_compliant(&desktop) {
        Command::new("gsettings")
        .args(&["set", "org.gnome.desktop.background", "picture-uri", &path])
        .output()?;
    }
    match desktop.as_str() {
        "X-Cinnamon" => {
            Command::new("dconf")
            .args(&["write", "/org/cinnamon/desktop/background/picture-uri",&path])
            .output()?;
        }

        "MATE" => {
            let mate_path = &path[7..];
            Command::new("dconf")
            .args(&["write", "/org/mate/desktop/background/picture-filename",&mate_path])
            .output()?;

        }

        "XFCE" => {
            let xfce_path = &path[7..];
            Command::new("xfconf-query")
            .args(&["-c", "xfce4-desktop", "-p", "/backdrop/screen0/monitor0/workspace0/last-image", "-s", &xfce_path])
            .output()?;            
        }

        "Deepin" => {
            Command::new("dconf")
            .args(&["write", "/com/deepin/wrap/gnome/desktop/background/picture-uri",&path])
            .output()?;
        }
        // Panics since flowy does not support others yet
        _ => {
            panic!("Unsupported Desktop Environment")
        }
    }
     
        Ok(())

}

// TODO - Someday, add some Result error return here
/// The main function that reads the config and runs the daemon
pub fn set_times () {
    let config = get_config("times.toml").unwrap();
    let walls = config.walls;
    let times = config.times;
    println!("Times - {:#?}", &times);
    println!("Paths - {:#?}", &walls);
    let mut scheduler = Scheduler::new();
    for (i, time) in times.into_iter().enumerate() {
        // Workaround becase Rust was being a bitch
        let wall = walls[i].clone();
        scheduler.every(1.day()).at(&time).run(move|| set_paper(&wall).unwrap());
    }
    loop {
        scheduler.run_pending();
        thread::sleep(Duration::from_millis(1000));
    }
}

/// Creates a new instance of struct Config and returns it
pub fn get_config(path : &str) -> Result<Config, Box<dyn Error>> {
    let toml_file = std::fs::read_to_string(path)?;
    let toml_data : Config = toml::from_str(&toml_file)?;
    
    Ok(toml_data)
}

/// Returns the contents of a given dir 
pub fn get_dir (path : &str) -> Result<Vec<String>, Box<dyn Error>> {
    let mut files : Vec<String> = std::fs::read_dir(path)?.
    into_iter().
    map(|x| x.unwrap().path().display().to_string())
    .collect();

    // Appens file:// to the start of each item
    files = files
    .into_iter()
    .map(|y| "file://".to_string() + &y)
    .collect();
    // The read_dir iterator returns in an arbitrary manner
    // Sorted so that the images are viewed at the right time
    // Naming Mechanism - 00, 01, 02..
    files.sort();
    Ok(files)
}

/// Generates the config file. Takes the wallpaper folder path as args.
pub fn generate_config (path : &str) -> Result<(), Box<dyn Error>>{
    let files = get_dir(path)?;
    let length = files.len();
    let div = 1440/length;
    let mut times = Vec::new();
    let mut start_sec = 0;
    for _ in 0..length {
       times.push(format!("{}:{}",start_sec/60, start_sec%60 ));
       start_sec+=div;
    }

    let file = Config {
        times,
        walls : files,
    };

    let toml_string = toml::to_string(&file)?;
    std::fs::write("times.toml", toml_string)?;
    Ok(())
}