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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::error::BoolError;
use crate::gstring::GString;
use crate::translate::*;
use crate::Error;
use std::ffi::{OsStr, OsString};
use std::mem;
use std::path::{Path, PathBuf};
use std::ptr;

// rustdoc-stripper-ignore-next
/// Same as [`get_prgname()`].
///
/// [`get_prgname()`]: fn.get_prgname.html
#[doc(alias = "get_program_name")]
pub fn program_name() -> Option<String> {
    prgname()
}

#[doc(alias = "g_get_prgname")]
#[doc(alias = "get_prgname")]
pub fn prgname() -> Option<String> {
    unsafe { from_glib_none(ffi::g_get_prgname()) }
}

// rustdoc-stripper-ignore-next
/// Same as [`set_prgname()`].
///
/// [`set_prgname()`]: fn.set_prgname.html
pub fn set_program_name(name: Option<&str>) {
    set_prgname(name)
}

#[doc(alias = "g_set_prgname")]
pub fn set_prgname(name: Option<&str>) {
    unsafe { ffi::g_set_prgname(name.to_glib_none().0) }
}

#[doc(alias = "g_getenv")]
pub fn getenv<K: AsRef<OsStr>>(variable_name: K) -> Option<OsString> {
    #[cfg(not(windows))]
    use ffi::g_getenv;
    #[cfg(windows)]
    use ffi::g_getenv_utf8 as g_getenv;

    unsafe { from_glib_none(g_getenv(variable_name.as_ref().to_glib_none().0)) }
}

#[doc(alias = "g_setenv")]
pub fn setenv<K: AsRef<OsStr>, V: AsRef<OsStr>>(
    variable_name: K,
    value: V,
    overwrite: bool,
) -> Result<(), BoolError> {
    #[cfg(not(windows))]
    use ffi::g_setenv;
    #[cfg(windows)]
    use ffi::g_setenv_utf8 as g_setenv;

    unsafe {
        result_from_gboolean!(
            g_setenv(
                variable_name.as_ref().to_glib_none().0,
                value.as_ref().to_glib_none().0,
                overwrite.into_glib(),
            ),
            "Failed to set environment variable"
        )
    }
}

#[doc(alias = "g_unsetenv")]
pub fn unsetenv<K: AsRef<OsStr>>(variable_name: K) {
    #[cfg(not(windows))]
    use ffi::g_unsetenv;
    #[cfg(windows)]
    use ffi::g_unsetenv_utf8 as g_unsetenv;

    unsafe { g_unsetenv(variable_name.as_ref().to_glib_none().0) }
}

#[doc(alias = "g_environ_getenv")]
pub fn environ_getenv<K: AsRef<OsStr>>(envp: &[OsString], variable: K) -> Option<OsString> {
    unsafe {
        from_glib_none(ffi::g_environ_getenv(
            envp.to_glib_none().0,
            variable.as_ref().to_glib_none().0,
        ))
    }
}

#[doc(alias = "g_get_user_name")]
#[doc(alias = "get_user_name")]
pub fn user_name() -> OsString {
    #[cfg(not(all(windows, target_arch = "x86")))]
    use ffi::g_get_user_name;
    #[cfg(all(windows, target_arch = "x86"))]
    use ffi::g_get_user_name_utf8 as g_get_user_name;

    unsafe { from_glib_none(g_get_user_name()) }
}

#[doc(alias = "g_get_real_name")]
#[doc(alias = "get_real_name")]
pub fn real_name() -> OsString {
    #[cfg(not(all(windows, target_arch = "x86")))]
    use ffi::g_get_real_name;
    #[cfg(all(windows, target_arch = "x86"))]
    use ffi::g_get_real_name_utf8 as g_get_real_name;

    unsafe { from_glib_none(g_get_real_name()) }
}

#[doc(alias = "g_get_current_dir")]
#[doc(alias = "get_current_dir")]
pub fn current_dir() -> Option<PathBuf> {
    #[cfg(not(windows))]
    use ffi::g_get_current_dir;
    #[cfg(windows)]
    use ffi::g_get_current_dir_utf8 as g_get_current_dir;

    unsafe { from_glib_full(g_get_current_dir()) }
}

/// Converts an absolute filename to an escaped ASCII-encoded URI, with the path
/// component following Section 3.3. of RFC 2396.
/// ## `filename`
/// an absolute filename specified in the GLib file
///  name encoding, which is the on-disk file name bytes on Unix, and UTF-8
///  on Windows
/// ## `hostname`
/// A UTF-8 encoded hostname, or [`None`] for none.
///
/// # Returns
///
/// a newly-allocated string holding the resulting
///  URI, or [`None`] on an error.
#[doc(alias = "g_filename_to_uri")]
pub fn filename_to_uri<P: AsRef<Path>>(
    filename: P,
    hostname: Option<&str>,
) -> Result<GString, Error> {
    #[cfg(not(windows))]
    use ffi::g_filename_to_uri;
    #[cfg(windows)]
    use ffi::g_filename_to_uri_utf8 as g_filename_to_uri;

    let hostname = hostname.to_glib_none();
    unsafe {
        let mut error = std::ptr::null_mut();
        let ret = g_filename_to_uri(filename.as_ref().to_glib_none().0, hostname.0, &mut error);
        if error.is_null() {
            Ok(from_glib_full(ret))
        } else {
            Err(from_glib_full(error))
        }
    }
}

/// Converts an escaped ASCII-encoded URI to a local filename in the
/// encoding used for filenames.
/// ## `uri`
/// a uri describing a filename (escaped, encoded in ASCII).
///
/// # Returns
///
/// a newly-allocated string holding
///  the resulting filename, or [`None`] on an error.
///
/// ## `hostname`
/// Location to store hostname for the URI.
///  If there is no hostname in the URI, [`None`] will be
///  stored in this location.
#[doc(alias = "g_filename_from_uri")]
pub fn filename_from_uri(uri: &str) -> Result<(std::path::PathBuf, Option<GString>), Error> {
    #[cfg(not(windows))]
    use ffi::g_filename_from_uri;
    #[cfg(windows)]
    use ffi::g_filename_from_uri_utf8 as g_filename_from_uri;

    unsafe {
        let mut hostname = ptr::null_mut();
        let mut error = ptr::null_mut();
        let ret = g_filename_from_uri(uri.to_glib_none().0, &mut hostname, &mut error);
        if error.is_null() {
            Ok((from_glib_full(ret), from_glib_full(hostname)))
        } else {
            Err(from_glib_full(error))
        }
    }
}

/// Locates the first executable named `program` in the user's path, in the
/// same way that `execvp()` would locate it. Returns an allocated string
/// with the absolute path name, or [`None`] if the program is not found in
/// the path. If `program` is already an absolute path, returns a copy of
/// `program` if `program` exists and is executable, and [`None`] otherwise.
///
/// On Windows, if `program` does not have a file type suffix, tries
/// with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
/// the `PATHEXT` environment variable.
///
/// On Windows, it looks for the file in the same way as CreateProcess()
/// would. This means first in the directory where the executing
/// program was loaded from, then in the current directory, then in the
/// Windows 32-bit system directory, then in the Windows directory, and
/// finally in the directories in the `PATH` environment variable. If
/// the program is found, the return value contains the full name
/// including the type suffix.
/// ## `program`
/// a program name in the GLib file name encoding
///
/// # Returns
///
/// a newly-allocated
///  string with the absolute path, or [`None`]
#[doc(alias = "g_find_program_in_path")]
pub fn find_program_in_path<P: AsRef<Path>>(program: P) -> Option<PathBuf> {
    #[cfg(not(all(windows, target_arch = "x86")))]
    use ffi::g_find_program_in_path;
    #[cfg(all(windows, target_arch = "x86"))]
    use ffi::g_find_program_in_path_utf8 as g_find_program_in_path;

    unsafe { from_glib_full(g_find_program_in_path(program.as_ref().to_glib_none().0)) }
}

/// Gets the current user's home directory.
///
/// As with most UNIX tools, this function will return the value of the
/// `HOME` environment variable if it is set to an existing absolute path
/// name, falling back to the `passwd` file in the case that it is unset.
///
/// If the path given in `HOME` is non-absolute, does not exist, or is
/// not a directory, the result is undefined.
///
/// Before version 2.36 this function would ignore the `HOME` environment
/// variable, taking the value from the `passwd` database instead. This was
/// changed to increase the compatibility of GLib with other programs (and
/// the XDG basedir specification) and to increase testability of programs
/// based on GLib (by making it easier to run them from test frameworks).
///
/// If your program has a strong requirement for either the new or the
/// old behaviour (and if you don't wish to increase your GLib
/// dependency to ensure that the new behaviour is in effect) then you
/// should either directly check the `HOME` environment variable yourself
/// or unset it before calling any functions in GLib.
///
/// # Returns
///
/// the current user's home directory
#[doc(alias = "g_get_home_dir")]
#[doc(alias = "get_home_dir")]
pub fn home_dir() -> std::path::PathBuf {
    #[cfg(not(all(windows, target_arch = "x86")))]
    use ffi::g_get_home_dir;
    #[cfg(all(windows, target_arch = "x86"))]
    use ffi::g_get_home_dir_utf8 as g_get_home_dir;

    unsafe { from_glib_none(g_get_home_dir()) }
}

#[doc(alias = "g_get_tmp_dir")]
#[doc(alias = "get_tmp_dir")]
pub fn tmp_dir() -> std::path::PathBuf {
    #[cfg(not(all(windows, target_arch = "x86")))]
    use ffi::g_get_tmp_dir;
    #[cfg(all(windows, target_arch = "x86"))]
    use ffi::g_get_tmp_dir_utf8 as g_get_tmp_dir;

    unsafe { from_glib_none(g_get_tmp_dir()) }
}

#[doc(alias = "g_mkstemp")]
pub fn mkstemp<P: AsRef<std::path::Path>>(tmpl: P) -> i32 {
    #[cfg(not(windows))]
    use ffi::g_mkstemp;
    #[cfg(windows)]
    use ffi::g_mkstemp_utf8 as g_mkstemp;

    unsafe {
        // NOTE: This modifies the string in place, which is fine here because
        // to_glib_none() will create a temporary, NUL-terminated copy of the string.
        g_mkstemp(tmpl.as_ref().to_glib_none().0)
    }
}

#[doc(alias = "g_mkstemp_full")]
pub fn mkstemp_full(tmpl: impl AsRef<std::path::Path>, flags: i32, mode: i32) -> i32 {
    unsafe {
        // NOTE: This modifies the string in place, which is fine here because
        // to_glib_none() will create a temporary, NUL-terminated copy of the string.
        ffi::g_mkstemp_full(tmpl.as_ref().to_glib_none().0, flags, mode)
    }
}

#[doc(alias = "g_mkdtemp")]
pub fn mkdtemp(tmpl: impl AsRef<std::path::Path>) -> Option<std::path::PathBuf> {
    unsafe {
        // NOTE: This modifies the string in place and returns it but does not free it
        // if it returns NULL.
        let tmpl = tmpl.as_ref().to_glib_full();
        let res = ffi::g_mkdtemp(tmpl);
        if res.is_null() {
            ffi::g_free(tmpl as ffi::gpointer);
            None
        } else {
            from_glib_full(res)
        }
    }
}

#[doc(alias = "g_mkdtemp_full")]
pub fn mkdtemp_full(tmpl: impl AsRef<std::path::Path>, mode: i32) -> Option<std::path::PathBuf> {
    unsafe {
        // NOTE: This modifies the string in place and returns it but does not free it
        // if it returns NULL.
        let tmpl = tmpl.as_ref().to_glib_full();
        let res = ffi::g_mkdtemp_full(tmpl, mode);
        if res.is_null() {
            ffi::g_free(tmpl as ffi::gpointer);
            None
        } else {
            from_glib_full(res)
        }
    }
}

/// Reads an entire file into allocated memory, with good error
/// checking.
///
/// If the call was successful, it returns [`true`] and sets `contents` to the file
/// contents and `length` to the length of the file contents in bytes. The string
/// stored in `contents` will be nul-terminated, so for text files you can pass
/// [`None`] for the `length` argument. If the call was not successful, it returns
/// [`false`] and sets `error`. The error domain is `G_FILE_ERROR`. Possible error
/// codes are those in the `GFileError` enumeration. In the error case,
/// `contents` is set to [`None`] and `length` is set to zero.
/// ## `filename`
/// name of a file to read contents from, in the GLib file name encoding
///
/// # Returns
///
/// [`true`] on success, [`false`] if an error occurred
///
/// ## `contents`
/// location to store an allocated string, use `g_free()` to free
///  the returned string
#[doc(alias = "g_file_get_contents")]
pub fn file_get_contents(
    filename: impl AsRef<std::path::Path>,
) -> Result<crate::Slice<u8>, crate::Error> {
    #[cfg(not(windows))]
    use ffi::g_file_get_contents;
    #[cfg(windows)]
    use ffi::g_file_get_contents_utf8 as g_file_get_contents;

    unsafe {
        let mut contents = ptr::null_mut();
        let mut length = mem::MaybeUninit::uninit();
        let mut error = ptr::null_mut();
        let _ = g_file_get_contents(
            filename.as_ref().to_glib_none().0,
            &mut contents,
            length.as_mut_ptr(),
            &mut error,
        );
        if error.is_null() {
            Ok(crate::Slice::from_glib_full_num_copy(
                contents,
                length.assume_init() as usize,
            ))
        } else {
            Err(from_glib_full(error))
        }
    }
}

pub fn is_canonical_pspec_name(name: &str) -> bool {
    name.as_bytes().iter().enumerate().all(|(i, c)| {
        i != 0 && (*c >= b'0' && *c <= b'9' || *c == b'-')
            || (*c >= b'A' && *c <= b'Z')
            || (*c >= b'a' && *c <= b'z')
    })
}

#[doc(alias = "g_uri_escape_string")]
pub fn uri_escape_string(
    unescaped: &str,
    reserved_chars_allowed: Option<&str>,
    allow_utf8: bool,
) -> crate::GString {
    unsafe {
        from_glib_full(ffi::g_uri_escape_string(
            unescaped.to_glib_none().0,
            reserved_chars_allowed.to_glib_none().0,
            allow_utf8.into_glib(),
        ))
    }
}

#[doc(alias = "g_uri_unescape_string")]
pub fn uri_unescape_string(
    escaped_string: &str,
    illegal_characters: Option<&str>,
) -> Option<crate::GString> {
    unsafe {
        from_glib_full(ffi::g_uri_unescape_string(
            escaped_string.to_glib_none().0,
            illegal_characters.to_glib_none().0,
        ))
    }
}

#[doc(alias = "g_uri_parse_scheme")]
pub fn uri_parse_scheme(uri: &str) -> Option<crate::GString> {
    unsafe { from_glib_full(ffi::g_uri_parse_scheme(uri.to_glib_none().0)) }
}

#[doc(alias = "g_uri_unescape_segment")]
pub fn uri_unescape_segment(
    escaped_string: Option<&str>,
    escaped_string_end: Option<&str>,
    illegal_characters: Option<&str>,
) -> Option<crate::GString> {
    unsafe {
        from_glib_full(ffi::g_uri_unescape_segment(
            escaped_string.to_glib_none().0,
            escaped_string_end.to_glib_none().0,
            illegal_characters.to_glib_none().0,
        ))
    }
}

#[cfg(test)]
mod tests {
    use std::env;
    use std::sync::Mutex;

    //Mutex to prevent run environment tests parallel
    static LOCK: once_cell::sync::Lazy<Mutex<()>> = once_cell::sync::Lazy::new(|| Mutex::new(()));

    const VAR_NAME: &str = "function_environment_test";

    fn check_getenv(val: &str) {
        let _data = LOCK.lock().unwrap();

        env::set_var(VAR_NAME, val);
        assert_eq!(env::var_os(VAR_NAME), Some(val.into()));
        assert_eq!(crate::getenv(VAR_NAME), Some(val.into()));

        let environ = crate::environ();
        assert_eq!(crate::environ_getenv(&environ, VAR_NAME), Some(val.into()));
    }

    fn check_setenv(val: &str) {
        let _data = LOCK.lock().unwrap();

        crate::setenv(VAR_NAME, val, true).unwrap();
        assert_eq!(env::var_os(VAR_NAME), Some(val.into()));
    }

    #[test]
    fn getenv() {
        check_getenv("Test");
        check_getenv("Тест"); // "Test" in Russian
    }

    #[test]
    fn setenv() {
        check_setenv("Test");
        check_setenv("Тест"); // "Test" in Russian
    }

    #[test]
    fn test_filename_from_uri() {
        use crate::GString;
        use std::path::PathBuf;
        let uri: GString = "file:///foo/bar.txt".into();
        if let Ok((filename, hostname)) = crate::filename_from_uri(&uri) {
            assert_eq!(filename, PathBuf::from(r"/foo/bar.txt"));
            assert_eq!(hostname, None);
        } else {
            unreachable!();
        }

        let uri: GString = "file://host/foo/bar.txt".into();
        if let Ok((filename, hostname)) = crate::filename_from_uri(&uri) {
            assert_eq!(filename, PathBuf::from(r"/foo/bar.txt"));
            assert_eq!(hostname, Some(GString::from("host")));
        } else {
            unreachable!();
        }
    }

    #[test]
    fn test_uri_parsing() {
        use crate::GString;
        assert_eq!(
            crate::uri_parse_scheme("foo://bar"),
            Some(GString::from("foo"))
        );
        assert_eq!(crate::uri_parse_scheme("foo"), None);

        let escaped = crate::uri_escape_string("&foo", None, true);
        assert_eq!(escaped, GString::from("%26foo"));

        let unescaped = crate::uri_unescape_string(escaped.as_str(), None);
        assert_eq!(unescaped, Some(GString::from("&foo")));

        assert_eq!(
            crate::uri_unescape_segment(Some("/foo"), None, None),
            Some(GString::from("/foo"))
        );
        assert_eq!(crate::uri_unescape_segment(Some("/foo%"), None, None), None);
    }
}