Debian Codegraph @

src/search.c

raw symbols SCIP
1 /**
2 * SPDX-FileCopyrightText: 2016-2022 Dr. Tobias Quathamer <[email protected]>
3 *
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 */
6
7 #include <glib.h>
8 #include <glib/gi18n.h>
9 #include "isocodes.h"
10 #include "search.h"
11 #include "options.h"
12
13 /**
14 * Search for a given code
15 */
16 gboolean search_entry(gchar *code, GList *entries_list, GError **error)
17 {
18 // Set up a JSON object for an entry
19 JsonObject *entry;
20 // Set up fields in which to search
21 gchar *fields[] = { "alpha_2", "alpha_3", "alpha_4", "numeric", "code", "bibliographic", NULL };
22 gchar *normalized_code = search_get_normalized_code(code);
23 GList *list_entry = g_list_first(entries_list);
24 gboolean entry_found = FALSE;
25 // Cycle through all entries
26 while (list_entry) {
27 // Ensure that the list entry is an object
28 if (!JSON_NODE_HOLDS_OBJECT(list_entry->data)) {
29 continue;
30 }
31 entry = json_node_get_object(list_entry->data);
32 int i = 0;
33 while (fields[i]) {
34 if (!g_strcmp0(normalized_code, isocodes_get_string_member(entry, fields[i]))) {
35 isocodes_show_entry(entry);
36 entry_found = TRUE;
37 break;
38 }
39 i++;
40 }
41 if (entry_found) {
42 break;
43 }
44 list_entry = g_list_next(list_entry);
45 }
46 g_free(normalized_code);
47 if (!entry_found) {
48 // TRANSLATORS: The first placeholder is a code like "urgl" or
49 // "does-not-exist", the second placeholder is the current
50 // ISO standard like "3166-1" or "15924".
51 g_set_error(error, g_quark_from_string(GETTEXT_PACKAGE), 0, _("The code \"%1$s\" is not defined in ISO %2$s."),
52 code, option_standard);
53 }
54 return entry_found;
55 }
56
57 /**
58 * Return the normalized code and field to search in,
59 * depending on ISO standard.
60 */
61 gchar *search_get_normalized_code(gchar *code)
62 {
63 // Convert to upper case for ISO 3166 and 4217
64 gchar *normalized_code = g_utf8_strup(code, -1);
65 if (g_str_has_prefix(option_standard, "639")) {
66 // Convert to lower case for ISO 639 family
67 g_free(normalized_code);
68 normalized_code = g_utf8_strdown(code, -1);
69 } else if (!g_strcmp0(option_standard, "15924")) {
70 // Convert to title case for ISO 15924
71 // The first character is already uppercase, see above.
72 // Start at the second character and convert all to lowercase.
73 if (g_utf8_strlen(normalized_code, -1) > 1) {
74 gchar *titlecase;
75 gchar *trail = g_utf8_offset_to_pointer(normalized_code, 1);
76 gchar *lowercase = g_utf8_strdown(trail, -1);
77 // Terminate the string after the first character
78 *trail = 0;
79 // Construct the resulting string
80 titlecase = g_strdup_printf("%s%s", normalized_code, lowercase);
81 g_free(lowercase);
82 g_free(normalized_code);
83 normalized_code = titlecase;
84 }
85 }
86 return normalized_code;
87 }