glib/key_file.rs
1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{mem, path, ptr};
4
5use crate::{Error, GString, GStringPtr, KeyFile, KeyFileFlags, PtrSlice, ffi, translate::*};
6
7impl KeyFile {
8 /// Writes the contents of @self to @filename using
9 /// [`file_set_contents()`][crate::file_set_contents()].
10 ///
11 /// If you need stricter guarantees about durability of
12 /// the written file than are provided by [`file_set_contents()`][crate::file_set_contents()], use
13 /// [`file_set_contents_full()`][crate::file_set_contents_full()] with the return value of
14 /// [`to_data()`][Self::to_data()].
15 ///
16 /// This function can fail for any of the reasons that
17 /// [`file_set_contents()`][crate::file_set_contents()] may fail, or with
18 /// [error@GLib.FileError.FAILED] if the contents are too long to write.
19 /// ## `filename`
20 /// the name of the file to write to
21 ///
22 /// # Returns
23 ///
24 /// true if successful, false otherwise
25 #[doc(alias = "g_key_file_save_to_file")]
26 pub fn save_to_file<T: AsRef<std::path::Path>>(&self, filename: T) -> Result<(), Error> {
27 unsafe {
28 let mut error = ptr::null_mut();
29 let _ = ffi::g_key_file_save_to_file(
30 self.to_glib_none().0,
31 filename.as_ref().to_glib_none().0,
32 &mut error,
33 );
34 if error.is_null() {
35 Ok(())
36 } else {
37 Err(from_glib_full(error))
38 }
39 }
40 }
41
42 /// Looks for a key file named @file in the paths returned from
43 /// [`user_data_dir()`][crate::user_data_dir()] and [`system_data_dirs()`][crate::system_data_dirs()].
44 ///
45 /// The search algorithm from [`load_from_dirs()`][Self::load_from_dirs()] is used. If
46 /// @file is found, it’s loaded into @self and its full path is returned in
47 /// @full_path.
48 ///
49 /// If the file could not be loaded then either a [`FileError`][crate::FileError] or
50 /// [`KeyFileError`][crate::KeyFileError] is returned.
51 /// ## `file`
52 /// a relative path to a filename to open and parse
53 /// ## `flags`
54 /// flags from [`KeyFileFlags`][crate::KeyFileFlags]
55 ///
56 /// # Returns
57 ///
58 /// true if a key file could be loaded, false otherwise
59 ///
60 /// ## `full_path`
61 /// return location for a string
62 /// containing the full path of the file, or `NULL` to ignore
63 #[doc(alias = "g_key_file_load_from_data_dirs")]
64 pub fn load_from_data_dirs<T: AsRef<std::path::Path>>(
65 &self,
66 file: T,
67 flags: KeyFileFlags,
68 ) -> Result<path::PathBuf, Error> {
69 unsafe {
70 let mut error = ptr::null_mut();
71 let mut full_path: *mut libc::c_char = ptr::null_mut();
72 let _ = ffi::g_key_file_load_from_data_dirs(
73 self.to_glib_none().0,
74 file.as_ref().to_glib_none().0,
75 &mut full_path,
76 flags.into_glib(),
77 &mut error,
78 );
79 if error.is_null() {
80 let path: GString = from_glib_full(full_path);
81 Ok(path::PathBuf::from(&path))
82 } else {
83 Err(from_glib_full(error))
84 }
85 }
86 }
87
88 /// Looks for a key file named @file in the paths specified in @search_dirs,
89 /// loads the file into @self and returns the file’s full path in @full_path.
90 ///
91 /// @search_dirs are checked in the order listed in the array, with the highest
92 /// priority directory listed first. Within each directory, @file is looked for.
93 /// If it’s not found, `-` characters in @file are progressively replaced with
94 /// directory separators to search subdirectories of the search directory. If the
95 /// file has not been found after all `-` characters have been replaced, the next
96 /// search directory in @search_dirs is checked.
97 ///
98 /// If the file could not be found in any of the @search_dirs,
99 /// [error@GLib.KeyFileError.NOT_FOUND] is returned. If
100 /// the file is found but the OS returns an error when opening or reading the
101 /// file, a [`FileError`][crate::FileError] is returned. If there is a problem parsing the
102 /// file, a [`KeyFileError`][crate::KeyFileError] is returned.
103 /// ## `file`
104 /// a relative path to a filename to open and parse
105 /// ## `search_dirs`
106 /// `NULL`-terminated
107 /// array of directories to search
108 /// ## `flags`
109 /// flags from [`KeyFileFlags`][crate::KeyFileFlags]
110 ///
111 /// # Returns
112 ///
113 /// true if a key file could be loaded, false otherwise
114 ///
115 /// ## `full_path`
116 /// return location for a string
117 /// containing the full path of the file, or `NULL` to ignore
118 #[doc(alias = "g_key_file_load_from_dirs")]
119 pub fn load_from_dirs<T: AsRef<std::path::Path>, U: AsRef<std::path::Path>>(
120 &self,
121 file: T,
122 search_dirs: &[U],
123 flags: KeyFileFlags,
124 ) -> Result<path::PathBuf, Error> {
125 unsafe {
126 let search_dirs: Vec<&std::path::Path> =
127 search_dirs.iter().map(AsRef::as_ref).collect();
128 let mut error = ptr::null_mut();
129 let mut full_path: *mut libc::c_char = ptr::null_mut();
130 let _ = ffi::g_key_file_load_from_dirs(
131 self.to_glib_none().0,
132 file.as_ref().to_glib_none().0,
133 search_dirs.to_glib_none().0,
134 &mut full_path,
135 flags.into_glib(),
136 &mut error,
137 );
138 if error.is_null() {
139 let path: GString = from_glib_full(full_path);
140 Ok(path::PathBuf::from(&path))
141 } else {
142 Err(from_glib_full(error))
143 }
144 }
145 }
146
147 /// Outputs @self as a string.
148 ///
149 /// Note that this function never reports an error.
150 ///
151 /// # Returns
152 ///
153 /// a newly allocated string holding the contents of the key file
154 ///
155 /// ## `length`
156 /// return location for the length of the
157 /// returned string, or `NULL` to ignore
158 #[doc(alias = "g_key_file_to_data")]
159 pub fn to_data(&self) -> GString {
160 unsafe {
161 let ret =
162 ffi::g_key_file_to_data(self.to_glib_none().0, ptr::null_mut(), ptr::null_mut());
163 from_glib_full(ret)
164 }
165 }
166
167 /// Returns all groups in the key file loaded with @self.
168 ///
169 /// The array of returned groups will be `NULL`-terminated, so
170 /// @length may optionally be `NULL`.
171 ///
172 /// # Returns
173 ///
174 /// a newly-allocated
175 /// `NULL`-terminated array of strings. Use `strfreev()` to free it.
176 ///
177 /// ## `length`
178 /// return location for the number of returned groups,
179 /// or `NULL` to ignore
180 #[doc(alias = "g_key_file_get_groups")]
181 #[doc(alias = "get_groups")]
182 pub fn groups(&self) -> PtrSlice<GStringPtr> {
183 unsafe {
184 let mut length = mem::MaybeUninit::uninit();
185 let ret = ffi::g_key_file_get_groups(self.to_glib_none().0, length.as_mut_ptr());
186 FromGlibContainer::from_glib_full_num(ret, length.assume_init() as _)
187 }
188 }
189
190 /// Returns all keys for the group name @group_name.
191 ///
192 /// The array of returned keys will be `NULL`-terminated, so @length may
193 /// optionally be `NULL`. If the @group_name cannot be found,
194 /// [error@GLib.KeyFileError.GROUP_NOT_FOUND] is returned.
195 /// ## `group_name`
196 /// a group name
197 ///
198 /// # Returns
199 ///
200 /// a newly-allocated
201 /// `NULL`-terminated array of strings. Use `strfreev()` to free it.
202 ///
203 /// ## `length`
204 /// return location for the number of keys returned,
205 /// or `NULL` to ignore
206 #[doc(alias = "g_key_file_get_keys")]
207 #[doc(alias = "get_keys")]
208 pub fn keys(&self, group_name: &str) -> Result<PtrSlice<GStringPtr>, crate::Error> {
209 unsafe {
210 let mut length = mem::MaybeUninit::uninit();
211 let mut error = ptr::null_mut();
212 let ret = ffi::g_key_file_get_keys(
213 self.to_glib_none().0,
214 group_name.to_glib_none().0,
215 length.as_mut_ptr(),
216 &mut error,
217 );
218 if error.is_null() {
219 Ok(FromGlibContainer::from_glib_full_num(
220 ret,
221 length.assume_init() as _,
222 ))
223 } else {
224 Err(from_glib_full(error))
225 }
226 }
227 }
228
229 /// Returns the value associated with @key under @group_name as a
230 /// boolean.
231 ///
232 /// If @key cannot be found then [error@GLib.KeyFileError.KEY_NOT_FOUND] is
233 /// returned. Likewise, if the value associated with @key cannot be interpreted
234 /// as a boolean then [error@GLib.KeyFileError.INVALID_VALUE] is returned.
235 /// ## `group_name`
236 /// a group name
237 /// ## `key`
238 /// a key
239 ///
240 /// # Returns
241 ///
242 /// the value associated with the key as a boolean,
243 /// or false if the key was not found or could not be parsed.
244 #[doc(alias = "g_key_file_get_boolean")]
245 #[doc(alias = "get_boolean")]
246 pub fn boolean(&self, group_name: &str, key: &str) -> Result<bool, Error> {
247 unsafe {
248 let mut error = ptr::null_mut();
249 let ret = ffi::g_key_file_get_boolean(
250 self.to_glib_none().0,
251 group_name.to_glib_none().0,
252 key.to_glib_none().0,
253 &mut error,
254 );
255 if error.is_null() {
256 Ok(from_glib(ret))
257 } else {
258 Err(from_glib_full(error))
259 }
260 }
261 }
262
263 /// Looks whether the key file has the key @key in the group
264 /// @group_name.
265 ///
266 /// Note that this function does not follow the rules for [`Error`][crate::Error]
267 /// strictly;
268 /// the return value both carries meaning and signals an error. To use
269 /// this function, you must pass a [`Error`][crate::Error] pointer in @error, and
270 /// check whether it is not `NULL` to see if an error occurred.
271 ///
272 /// Language bindings should use [`value()`][Self::value()] to test whether
273 /// a key exists.
274 /// ## `group_name`
275 /// a group name
276 /// ## `key`
277 /// a key name
278 ///
279 /// # Returns
280 ///
281 /// true if @key is a part of @group_name, false otherwise
282 #[doc(alias = "g_key_file_has_key")]
283 pub fn has_key(&self, group_name: &str, key: &str) -> Result<bool, Error> {
284 unsafe {
285 let mut error = ptr::null_mut();
286 let ret = ffi::g_key_file_has_key(
287 self.to_glib_none().0,
288 group_name.to_glib_none().0,
289 key.to_glib_none().0,
290 &mut error,
291 );
292 if error.is_null() {
293 Ok(from_glib(ret))
294 } else {
295 Err(from_glib_full(error))
296 }
297 }
298 }
299
300 /// Returns the values associated with @key under @group_name as
301 /// booleans.
302 ///
303 /// If @key cannot be found then [error@GLib.KeyFileError.KEY_NOT_FOUND] is
304 /// returned. Likewise, if the values associated with @key cannot be interpreted
305 /// as booleans then [error@GLib.KeyFileError.INVALID_VALUE] is returned.
306 /// ## `group_name`
307 /// a group name
308 /// ## `key`
309 /// a key
310 ///
311 /// # Returns
312 ///
313 ///
314 /// the values associated with the key as a list of booleans, or `NULL` if the
315 /// key was not found or could not be parsed. The returned list of booleans
316 /// should be freed with `free()` when no longer needed.
317 #[doc(alias = "g_key_file_get_boolean_list")]
318 #[doc(alias = "get_boolean_list")]
319 pub fn boolean_list(&self, group_name: &str, key: &str) -> Result<Vec<bool>, Error> {
320 unsafe {
321 let mut length = mem::MaybeUninit::uninit();
322 let mut error = ptr::null_mut();
323 let ret = ffi::g_key_file_get_boolean_list(
324 self.to_glib_none().0,
325 group_name.to_glib_none().0,
326 key.to_glib_none().0,
327 length.as_mut_ptr(),
328 &mut error,
329 );
330 if !error.is_null() {
331 return Err(from_glib_full(error));
332 }
333 Ok(FromGlibContainer::from_glib_container_num(
334 ret,
335 length.assume_init() as _,
336 ))
337 }
338 }
339
340 /// Returns the string value associated with @key under @group_name.
341 ///
342 /// Unlike [`value()`][Self::value()], this function handles escape
343 /// sequences like `\s`.
344 ///
345 /// If the key cannot be found, [error@GLib.KeyFileError.KEY_NOT_FOUND] is
346 /// returned. If the @group_name cannot be found,
347 /// [error@GLib.KeyFileError.GROUP_NOT_FOUND] is returned.
348 /// ## `group_name`
349 /// a group name
350 /// ## `key`
351 /// a key
352 ///
353 /// # Returns
354 ///
355 /// a newly allocated string or `NULL` if the specified
356 /// key cannot be found.
357 #[doc(alias = "g_key_file_get_string")]
358 #[doc(alias = "get_string")]
359 pub fn string(&self, group_name: &str, key: &str) -> Result<GString, Error> {
360 unsafe {
361 let mut error = ptr::null_mut();
362 let ret = ffi::g_key_file_get_string(
363 self.to_glib_none().0,
364 group_name.to_glib_none().0,
365 key.to_glib_none().0,
366 &mut error,
367 );
368 if error.is_null() {
369 Ok(from_glib_full(ret))
370 } else {
371 ffi::g_free(ret as *mut _);
372 Err(from_glib_full(error))
373 }
374 }
375 }
376
377 /// Returns the values associated with @key under @group_name.
378 ///
379 /// If the key cannot be found, [error@GLib.KeyFileError.KEY_NOT_FOUND] is
380 /// returned. If the @group_name cannot be found,
381 /// [error@GLib.KeyFileError.GROUP_NOT_FOUND] is returned.
382 /// ## `group_name`
383 /// a group name
384 /// ## `key`
385 /// a key
386 ///
387 /// # Returns
388 ///
389 ///
390 /// a `NULL`-terminated string array or `NULL` if the specified
391 /// key cannot be found. The array should be freed with `strfreev()`.
392 #[doc(alias = "g_key_file_get_string_list")]
393 #[doc(alias = "get_string_list")]
394 pub fn string_list(&self, group_name: &str, key: &str) -> Result<PtrSlice<GStringPtr>, Error> {
395 unsafe {
396 let mut length = mem::MaybeUninit::uninit();
397 let mut error = ptr::null_mut();
398 let ret = ffi::g_key_file_get_string_list(
399 self.to_glib_none().0,
400 group_name.to_glib_none().0,
401 key.to_glib_none().0,
402 length.as_mut_ptr(),
403 &mut error,
404 );
405 if error.is_null() {
406 Ok(FromGlibContainer::from_glib_full_num(
407 ret,
408 length.assume_init() as _,
409 ))
410 } else {
411 ffi::g_strfreev(ret);
412 Err(from_glib_full(error))
413 }
414 }
415 }
416
417 /// Returns the value associated with @key under @group_name
418 /// translated in the given @locale if available.
419 ///
420 /// If @locale is `C` then the untranslated value is returned (since GLib 2.84).
421 ///
422 /// If @locale is `NULL` then the current locale is assumed.
423 ///
424 /// If @locale is to be non-`NULL`, or if the current locale will change over
425 /// the lifetime of the [`KeyFile`][crate::KeyFile], it must be loaded with
426 /// [flags@GLib.KeyFileFlags.KEEP_TRANSLATIONS] in order to load strings for all
427 /// locales.
428 ///
429 /// If @key cannot be found then [error@GLib.KeyFileError.KEY_NOT_FOUND] is
430 /// returned. If the value associated
431 /// with @key cannot be interpreted or no suitable translation can
432 /// be found then the untranslated value is returned.
433 /// ## `group_name`
434 /// a group name
435 /// ## `key`
436 /// a key
437 /// ## `locale`
438 /// a locale identifier or `NULL` to use the current locale
439 ///
440 /// # Returns
441 ///
442 /// a newly allocated string or `NULL` if the specified
443 /// key cannot be found.
444 #[doc(alias = "g_key_file_get_locale_string")]
445 #[doc(alias = "get_locale_string")]
446 pub fn locale_string(
447 &self,
448 group_name: &str,
449 key: &str,
450 locale: Option<&str>,
451 ) -> Result<GString, Error> {
452 unsafe {
453 let mut error = ptr::null_mut();
454 let ret = ffi::g_key_file_get_locale_string(
455 self.to_glib_none().0,
456 group_name.to_glib_none().0,
457 key.to_glib_none().0,
458 locale.to_glib_none().0,
459 &mut error,
460 );
461 if error.is_null() {
462 Ok(from_glib_full(ret))
463 } else {
464 ffi::g_free(ret as *mut _);
465 Err(from_glib_full(error))
466 }
467 }
468 }
469
470 /// Returns the values associated with @key under @group_name
471 /// translated in the given @locale if available.
472 ///
473 /// If @locale is `C` then the untranslated value is returned (since GLib 2.84).
474 ///
475 /// If @locale is `NULL` then the current locale is assumed.
476 ///
477 /// If @locale is to be non-`NULL`, or if the current locale will change over
478 /// the lifetime of the [`KeyFile`][crate::KeyFile], it must be loaded with
479 /// [flags@GLib.KeyFileFlags.KEEP_TRANSLATIONS] in order to load strings for all
480 /// locales.
481 ///
482 /// If @key cannot be found then [error@GLib.KeyFileError.KEY_NOT_FOUND] is
483 /// returned. If the values associated
484 /// with @key cannot be interpreted or no suitable translations
485 /// can be found then the untranslated values are returned. The
486 /// returned array is `NULL`-terminated, so @length may optionally
487 /// be `NULL`.
488 /// ## `group_name`
489 /// a group name
490 /// ## `key`
491 /// a key
492 /// ## `locale`
493 /// a locale identifier or `NULL` to use the current locale
494 ///
495 /// # Returns
496 ///
497 ///
498 /// a newly allocated `NULL`-terminated string array or `NULL` if the key
499 /// isn’t found. The string array should be freed with `strfreev()`.
500 #[doc(alias = "g_key_file_get_locale_string_list")]
501 #[doc(alias = "get_locale_string_list")]
502 pub fn locale_string_list(
503 &self,
504 group_name: &str,
505 key: &str,
506 locale: Option<&str>,
507 ) -> Result<PtrSlice<GStringPtr>, Error> {
508 unsafe {
509 let mut length = mem::MaybeUninit::uninit();
510 let mut error = ptr::null_mut();
511 let ret = ffi::g_key_file_get_locale_string_list(
512 self.to_glib_none().0,
513 group_name.to_glib_none().0,
514 key.to_glib_none().0,
515 locale.to_glib_none().0,
516 length.as_mut_ptr(),
517 &mut error,
518 );
519 if error.is_null() {
520 Ok(FromGlibContainer::from_glib_full_num(
521 ret,
522 length.assume_init() as _,
523 ))
524 } else {
525 ffi::g_strfreev(ret);
526 Err(from_glib_full(error))
527 }
528 }
529 }
530}