Debian Codegraph @

lib/common/font-manager-utils.c

raw
1 /* font-manager-utils.c
2 *
3 * Copyright (C) 2009-2025 Jerry Casiano
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program.
17 *
18 * If not, see <http://www.gnu.org/licenses/gpl-3.0.txt>.
19 */
20
21 #include "font-manager-utils.h"
22
23 /**
24 * SECTION: font-manager-utils
25 * @title: Utility Functions
26 * @short_description: General purpose utility functions
27 * @include: font-manager-utils.h
28 */
29
30 static const gchar *POSSIBLE_SCHEMA_DIRS[] = {
31 PREFIX"/share/glib-2.0/schemas",
32 #ifdef NOT_REPRODUCIBLE
33 SRCDIR"/data"
34 #endif
35 };
36
37 static GSList *
38 get_possible_schema_dirs (void)
39 {
40 GSList *slist = NULL;
41 gchar *user_schema_dir = g_build_filename(g_get_user_data_dir(), "glib-2.0", "schemas", NULL);
42 for (gint i = 0; i < (gint) G_N_ELEMENTS(POSSIBLE_SCHEMA_DIRS); i++) {
43 slist = g_slist_append(slist, g_strdup(POSSIBLE_SCHEMA_DIRS[i]));
44 if (i == 0)
45 slist = g_slist_append(slist, user_schema_dir);
46 }
47 return slist;
48 }
49
50 /**
51 * font_manager_setup_i18n:
52 *
53 * Initializes gettext translations
54 */
55 void
56 font_manager_setup_i18n ()
57 {
58 setlocale(LC_ALL, "");
59 bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
60 bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
61 textdomain(GETTEXT_PACKAGE);
62 return;
63 }
64
65 /**
66 * font_manager_print_os_info:
67 *
68 * Print OS name and version.
69 */
70 void
71 font_manager_print_os_info ()
72 {
73 g_autofree gchar *pretty_name = g_get_os_info(G_OS_INFO_KEY_PRETTY_NAME);
74 if (pretty_name)
75 g_debug("%s", pretty_name);
76 else {
77 g_autofree gchar *name = g_get_os_info(G_OS_INFO_KEY_NAME);
78 g_autofree gchar *version = g_get_os_info(G_OS_INFO_KEY_VERSION);
79 g_debug("%s %s", name, version ? version : "");
80 }
81 g_debug("%s", setlocale(LC_ALL, NULL));
82 return;
83 }
84
85 /**
86 * font_manager_print_library_versions:
87 *
88 * Logs the versions of libraries in use for debugging purposes.
89 */
90 void
91 font_manager_print_library_versions ()
92 {
93 g_debug("Fontconfig version : %i", FcGetVersion());
94
95 g_debug("Freetype version (compile-time) : %i.%i.%i", FREETYPE_MAJOR,
96 FREETYPE_MINOR,
97 FREETYPE_PATCH);
98 FT_Library library;
99 FT_Error ft_error = FT_Init_FreeType(&library);
100 if (!ft_error) {
101 FT_Int major, minor, patch;
102 FT_Library_Version(library, &major, &minor, &patch);
103 g_debug("Freetype version (run-time) : %i.%i.%i", major, minor, patch);
104 }
105 FT_Done_FreeType(library);
106
107 g_debug("Harfbuzz version (compile-time) : %s", HB_VERSION_STRING);
108 g_debug("Harfbuzz version (run-time) : %s", hb_version_string());
109
110 g_debug("JSON-GLib version : %s", JSON_VERSION_S);
111
112 g_debug("Pango version (compile-time) : %s", PANGO_VERSION_STRING);
113 g_debug("Pango version (run-time) : %i", pango_version());
114
115 g_debug("libxml2 version : %s", LIBXML_VERSION_STRING);
116
117 g_debug("SQLite version (compile-time) : %s", SQLITE_VERSION);
118 g_debug("SQLite version (run-time) : %s", sqlite3_libversion());
119
120 g_debug("GLib version (compile-time) : %i.%i.%i", GLIB_MAJOR_VERSION,
121 GLIB_MINOR_VERSION,
122 GLIB_MICRO_VERSION);
123 g_debug("GLib version (run-time) : %i.%i.%i", glib_major_version,
124 glib_minor_version,
125 glib_micro_version);
126
127 g_debug("GTK version (compile-time) : %i.%i.%i", GTK_MAJOR_VERSION,
128 GTK_MINOR_VERSION,
129 GTK_MICRO_VERSION);
130 g_debug("GTK version (run-time) : %i.%i.%i", gtk_get_major_version(),
131 gtk_get_minor_version(),
132 gtk_get_micro_version());
133
134 return;
135 }
136
137 /**
138 * font_manager_is_dir:
139 * @filepath: full path to file
140 *
141 * Returns: %TRUE if @filepath is a directory
142 */
143 gboolean
144 font_manager_is_dir (const gchar *filepath)
145 {
146 return g_file_test(filepath, G_FILE_TEST_IS_DIR);
147 }
148
149 /**
150 * font_manager_exists:
151 * @filepath: full path to file
152 *
153 * Returns: %TRUE if @filepath exists
154 */
155 gboolean
156 font_manager_exists (const gchar *filepath)
157 {
158 return g_file_test(filepath, G_FILE_TEST_EXISTS);
159 }
160
161 static gboolean
162 ensure_dir_exists (const gchar *dir)
163 {
164 return (G_LIKELY(font_manager_exists(dir)) || (g_mkdir_with_parents(dir, 0755) == 0));
165 }
166
167 /**
168 * font_manager_natural_sort:
169 * @str1: a nul-terminated string
170 * @str2: a nul-terminated string
171 *
172 * Returns: An integer less than, equal to, or greater than zero,
173 * if str1 is <, == or > than str2 .
174 */
175 gint
176 font_manager_natural_sort (const gchar *str1, const gchar *str2)
177 {
178 g_return_val_if_fail((str1 != NULL && str2 != NULL), 0);
179 g_autofree gchar *s1 = g_utf8_collate_key_for_filename(str1, -1);
180 g_autofree gchar *s2 = g_utf8_collate_key_for_filename(str2, -1);
181 return g_strcmp0(s1, s2);
182 }
183
184 /**
185 * font_manager_get_file_owner:
186 * @filepath: full path to file
187 *
188 * Returns: 0 if current user has read/write permissions, -1 otherwise
189 */
190 gint
191 font_manager_get_file_owner (const gchar *filepath)
192 {
193 return g_access(filepath, R_OK | W_OK);
194 }
195
196 /**
197 * font_manager_timecmp:
198 * @file_a: #GFile
199 * @file_b: #GFile
200 *
201 * Compare the modification time of two different files.
202 *
203 * Returns: An integer less than, equal to, or greater than zero,
204 * if a is <, == or > than b.
205 */
206 gint
207 font_manager_timecmp (GFile *file_a, GFile *file_b)
208 {
209 g_autoptr(GError) error = NULL;
210 gchar *attrs = G_FILE_ATTRIBUTE_TIME_MODIFIED;
211 GFileQueryInfoFlags flags = G_FILE_QUERY_INFO_NONE;
212 g_return_val_if_fail(g_file_query_exists(file_a, NULL), 0);
213 g_return_val_if_fail(g_file_query_exists(file_b, NULL), 0);
214 g_autoptr(GFileInfo) info_a = g_file_query_info(file_a, attrs, flags, NULL, &error);
215 g_return_val_if_fail(error == NULL, 0);
216 g_autoptr(GFileInfo) info_b = g_file_query_info(file_b, attrs, flags, NULL, &error);
217 g_return_val_if_fail(error == NULL, 0);
218 g_autoptr(GDateTime) time_a = g_file_info_get_modification_date_time(info_a);
219 g_return_val_if_fail(time_a != NULL, 0);
220 g_autoptr(GDateTime) time_b = g_file_info_get_modification_date_time(info_b);
221 g_return_val_if_fail(time_b != NULL, 0);
222 return g_date_time_compare(time_a, time_b);
223 }
224
225 /**
226 * font_manager_get_file_extension:
227 * @filepath: full path to file
228 *
229 * Returns: (transfer full) (nullable):
230 * A newly allocated string that must be freed with #g_free or %NULL
231 */
232 gchar *
233 font_manager_get_file_extension (const gchar *filepath)
234 {
235 g_return_val_if_fail(filepath != NULL, NULL);
236 g_return_val_if_fail(g_strrstr(filepath, ".") != NULL, NULL);
237 gchar ** str_arr = g_strsplit(filepath, ".", -1);
238 g_return_val_if_fail(str_arr != NULL, NULL);
239 guint arr_len = g_strv_length(str_arr);
240 g_autofree gchar *res = g_strdup(str_arr[arr_len - 1]);
241 g_strfreev(str_arr);
242 return g_ascii_strdown(res, -1);
243 }
244
245 /**
246 * font_manager_get_local_time:
247 *
248 * Returns: (transfer full) (nullable): A newly allocated string formatted
249 * to the requested format or %NULL if there was an error.
250 * The returned string must be freed using #g_free().
251 */
252 gchar *
253 font_manager_get_local_time (void)
254 {
255 g_autoptr(GDateTime) local_time = g_date_time_new_now_local();
256 return g_date_time_format(local_time, "%c");
257 }
258
259 /**
260 * font_manager_get_user_font_directory:
261 *
262 * This function attempts to create the directory if it doesn't already exist
263 * and returns the filepath as a string if successful.
264 *
265 * Returns: (transfer full) (nullable):
266 * A newly allocated string that must be freed with #g_free or %NULL
267 */
268 gchar *
269 font_manager_get_user_font_directory (void)
270 {
271 g_autofree gchar *font_dir = g_build_filename(g_get_user_data_dir(), "fonts", NULL);
272 if (ensure_dir_exists(font_dir))
273 return g_steal_pointer(&font_dir);
274 return NULL;
275 }
276
277 /**
278 * font_manager_get_package_cache_directory:
279 *
280 * This function attempts to create the directory if it doesn't already exist
281 * and returns the filepath as a string if successful.
282 *
283 * Returns: (transfer full) (nullable):
284 * A newly allocated string that must be freed with #g_free or %NULL
285 */
286 gchar *
287 font_manager_get_package_cache_directory (void)
288 {
289 g_autofree gchar *cache_dir = g_build_filename(g_get_user_cache_dir(), PACKAGE_NAME, NULL);
290 if (ensure_dir_exists(cache_dir))
291 return g_steal_pointer(&cache_dir);
292 return NULL;
293 }
294
295 /**
296 * font_manager_get_package_config_directory:
297 *
298 * This function attempts to create the directory if it doesn't already exist
299 * and returns the filepath as a string if successful.
300 *
301 * Returns: (transfer full) (nullable):
302 * A newly allocated string that must be freed with #g_free or %NULL
303 */
304 gchar *
305 font_manager_get_package_config_directory (void)
306 {
307 g_autofree gchar *config_dir = g_build_filename(g_get_user_config_dir(), PACKAGE_NAME, NULL);
308 if (ensure_dir_exists(config_dir))
309 return g_steal_pointer(&config_dir);
310 return NULL;
311 }
312
313 /**
314 * font_manager_get_user_fontconfig_directory:
315 *
316 * This function attempts to create the directory if it doesn't already exist
317 * and returns the filepath as a string if successful.
318 *
319 * Returns: (transfer full) (nullable):
320 * A newly allocated string that must be freed with #g_free or %NULL
321 */
322 gchar *
323 font_manager_get_user_fontconfig_directory (void)
324 {
325 g_autofree gchar *config_dir = g_build_filename(g_get_user_config_dir(), "fontconfig", "conf.d", NULL);
326 if (ensure_dir_exists(config_dir))
327 return g_steal_pointer(&config_dir);
328 return NULL;
329 }
330
331 /**
332 * font_manager_str_replace: (skip)
333 * @str: a nul-terminated string
334 * @target: the nul-terminated string to search for
335 * @replacement: the nul-terminated string to replace target with
336 *
337 * Returns: (transfer full) (nullable):
338 * A newly allocated string that must be freed with #g_free or %NULL
339 */
340 gchar *
341 font_manager_str_replace (const gchar *str, const gchar *target, const gchar *replacement)
342 {
343 g_return_val_if_fail((str != NULL && target != NULL && replacement != NULL), NULL);
344 gchar *res = NULL;
345 g_autoptr(GError) error = NULL;
346 g_autofree gchar *escaped_str = g_regex_escape_string(target, -1);
347 g_autoptr(GRegex) regex = g_regex_new(escaped_str, 0, 0, &error);
348 if (error == NULL)
349 res = g_regex_replace_literal(regex, str, -1, 0, replacement, 0, &error);
350 if (error != NULL) {
351 g_warning("%i - %s", error->code, error->message);
352 g_clear_pointer(&res, g_free);
353 }
354 return res;
355 }
356
357 /**
358 * font_manager_to_filename:
359 * @str: a nul-terminated string
360 *
361 * Replaces spaces and dashes with an underscore.
362 *
363 * Returns: (transfer full) (nullable):
364 * A newly allocated string that must be freed with #g_free or %NULL
365 */
366 gchar *
367 font_manager_to_filename (const gchar *str)
368 {
369 g_return_val_if_fail(str != NULL, NULL);
370 g_autofree gchar *tmp = font_manager_str_replace(str, " ", "_");
371 return font_manager_str_replace(tmp, "-", "_");
372 }
373
374 /**
375 * font_manager_install_file:
376 * @file: #GFile
377 * @directory: #GFile
378 * @error: #GError or %NULL to ignore errors
379 *
380 * Returns: %TRUE if installation was successful.
381 */
382 gboolean
383 font_manager_install_file (GFile *file, GFile *directory, GError **error)
384 {
385 g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
386 g_return_val_if_fail(file != NULL, FALSE);
387 g_return_val_if_fail(directory != NULL, FALSE);
388 g_autoptr(GFile) target = font_manager_get_installation_target(file, directory, TRUE, error);
389 g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
390 GFileCopyFlags flags = G_FILE_COPY_ALL_METADATA | G_FILE_COPY_OVERWRITE | G_FILE_COPY_TARGET_DEFAULT_PERMS;
391 g_file_copy(file, target, flags, NULL, NULL, NULL, error);
392 g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
393 return TRUE;
394 }
395
396 /**
397 * font_manager_get_command_line_files:
398 * @cmdline: #GApplicationCommandLine
399 *
400 * Returns: (transfer full): #FontManagerStringSet containing filepaths for each
401 * file specified in @cmdline or %NULL if no files were specified.
402 */
403 FontManagerStringSet *
404 font_manager_get_command_line_files (GApplicationCommandLine *cmdline)
405 {
406 g_return_val_if_fail(cmdline != NULL, NULL);
407 GVariantDict *options = g_application_command_line_get_options_dict(cmdline);
408 g_autoptr(GVariant) argv = g_variant_dict_lookup_value(options,
409 "",
410 G_VARIANT_TYPE_BYTESTRING_ARRAY);
411 if (!argv)
412 return NULL;
413 g_debug("Processing files passed on command line");
414 gsize array_length;
415 const gchar **filelist = g_variant_get_bytestring_array(argv, &array_length);
416 if G_UNLIKELY(array_length == 0)
417 return NULL;
418 FontManagerStringSet *files = font_manager_string_set_new();
419 gint i = 0;
420 while (filelist[i]) {
421 g_autoptr(GFile) file = g_application_command_line_create_file_for_arg(cmdline, filelist[i]);
422 g_autofree gchar *path = g_file_get_path(file);
423 g_debug("Adding %s to list of command line files", path);
424 font_manager_string_set_add(files, path);
425 i++;
426 }
427 g_free(filelist);
428 return files;
429 }
430
431 static GHashTable *gsettings = NULL;
432
433 /**
434 * font_manager_get_gsettings:
435 * @schema_id: the id of the schema
436 *
437 * Returns: (transfer full) (nullable):
438 * A newly created #GSettings instance or %NULL if schema_id could not be found
439 */
440 GSettings *
441 font_manager_get_gsettings (const gchar *schema_id)
442 {
443 if (!gsettings)
444 gsettings = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_object_unref);
445 else {
446 gpointer stored = g_hash_table_lookup(gsettings, schema_id);
447 if (stored) {
448 g_debug("Using existing settings instance for %s", schema_id);
449 return (GSettings *) g_object_ref(stored);
450 }
451 }
452 GSettingsSchemaSource *schema_source = g_settings_schema_source_get_default();
453 g_return_val_if_fail(schema_source != NULL, NULL);
454 g_autoptr(GSettingsSchema) schema = g_settings_schema_source_lookup(schema_source, schema_id, TRUE);
455 if (schema != NULL) {
456 g_debug("Found schema with id %s in default source", schema_id);
457 }
458 g_debug("Checking for schema overrides");
459 GSList *slist = get_possible_schema_dirs();
460 GSList *iter;
461 for (iter = slist; iter != NULL; iter = iter->next) {
462 const gchar *dir = iter->data;
463 if (!g_file_test(dir, G_FILE_TEST_IS_DIR)) {
464 g_debug("Skipping invalid or non-existent directory path %s", dir);
465 continue;
466 }
467 g_autoptr(GSettingsSchemaSource) source = NULL;
468 source = g_settings_schema_source_new_from_directory(dir, schema_source, FALSE, NULL);
469 if (source == NULL) {
470 g_debug("Failed to create schema source for %s", dir);
471 continue;
472 }
473 g_debug("Checking for schema with id %s in %s", schema_id, dir);
474 GSettingsSchema *override = g_settings_schema_source_lookup(source, schema_id, TRUE);
475 if (override) {
476 g_settings_schema_unref(g_steal_pointer(&schema));
477 schema = override;
478 g_debug("Using schema with id %s from %s", schema_id, dir);
479 }
480 }
481 g_slist_free_full(slist, g_free);
482 if (schema == NULL) {
483 g_debug("Failed to locate schema for id %s", schema_id);
484 g_debug("Settings will not persist");
485 return NULL;
486 }
487 GSettings *result = g_settings_new_full(schema, NULL, NULL);
488 g_hash_table_insert(gsettings, g_strdup(schema_id), g_object_ref(result));
489 return result;
490 }
491
492 /**
493 * font_manager_free_gsettings:
494 *
495 * Free stored gsettings
496 */
497 void
498 font_manager_free_gsettings () {
499 if (gsettings) {
500 g_hash_table_remove_all(gsettings);
501 g_hash_table_unref(gsettings);
502 }
503 return;
504 }
505