2007-08-16 Armin Burgmeier <armin@openismus.com>
[modest] / src / maemo / easysetup / modest-easysetup-country-combo-box.c
1 /* Copyright (c) 2006, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #ifndef _GNU_SOURCE
31 #define _GNU_SOURCE /* So we can use the getline() function, which is a convenient GNU extension. */
32 #endif
33
34 #include <stdio.h>
35
36 #include "modest-easysetup-country-combo-box.h"
37 #include <gtk/gtkliststore.h>
38 #include <gtk/gtkcelllayout.h>
39 #include <gtk/gtkcellrenderertext.h>
40
41 #include <stdlib.h>
42 #include <string.h> /* For memcpy() */
43
44 #include <libintl.h> /* For dgettext(). */
45
46 /* Include config.h so that _() works: */
47 #ifdef HAVE_CONFIG_H
48 #include <config.h>
49 #endif
50
51 G_DEFINE_TYPE (EasysetupCountryComboBox, easysetup_country_combo_box, GTK_TYPE_COMBO_BOX);
52
53 #define COUNTRY_COMBO_BOX_GET_PRIVATE(o) \
54         (G_TYPE_INSTANCE_GET_PRIVATE ((o), EASYSETUP_TYPE_COUNTRY_COMBO_BOX, EasysetupCountryComboBoxPrivate))
55
56 typedef struct _EasysetupCountryComboBoxPrivate EasysetupCountryComboBoxPrivate;
57
58 struct _EasysetupCountryComboBoxPrivate
59 {
60         GtkTreeModel *model;
61 };
62
63 static void
64 easysetup_country_combo_box_get_property (GObject *object, guint property_id,
65                                                                                                                         GValue *value, GParamSpec *pspec)
66 {
67         switch (property_id) {
68         default:
69                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
70         }
71 }
72
73 static void
74 easysetup_country_combo_box_set_property (GObject *object, guint property_id,
75                                                                                                                         const GValue *value, GParamSpec *pspec)
76 {
77         switch (property_id) {
78         default:
79                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
80         }
81 }
82
83 static void
84 easysetup_country_combo_box_dispose (GObject *object)
85 {
86         if (G_OBJECT_CLASS (easysetup_country_combo_box_parent_class)->dispose)
87                 G_OBJECT_CLASS (easysetup_country_combo_box_parent_class)->dispose (object);
88 }
89
90 enum MODEL_COLS {
91         MODEL_COL_NAME = 0, /* string */
92         MODEL_COL_IDS = 1 /* A GSList* of guints. */
93 };
94
95 static gboolean 
96 on_model_foreach_release (GtkTreeModel *model, GtkTreePath *path, 
97         GtkTreeIter *iter, gpointer data)
98 {
99         GSList *list = NULL;
100         gtk_tree_model_get (model, iter, MODEL_COL_IDS, &list, -1); 
101         if (list)
102                 g_slist_free (list);
103                 
104         return FALSE; /* keep walking. */
105 }
106         
107 static void
108 easysetup_country_combo_box_finalize (GObject *object)
109 {
110         EasysetupCountryComboBoxPrivate *priv = COUNTRY_COMBO_BOX_GET_PRIVATE (object);
111
112         gtk_tree_model_foreach (priv->model, on_model_foreach_release, NULL);
113         g_object_unref (G_OBJECT (priv->model));
114
115         G_OBJECT_CLASS (easysetup_country_combo_box_parent_class)->finalize (object);
116 }
117
118 static void
119 easysetup_country_combo_box_class_init (EasysetupCountryComboBoxClass *klass)
120 {
121         GObjectClass *object_class = G_OBJECT_CLASS (klass);
122
123         g_type_class_add_private (klass, sizeof (EasysetupCountryComboBoxPrivate));
124
125         object_class->get_property = easysetup_country_combo_box_get_property;
126         object_class->set_property = easysetup_country_combo_box_set_property;
127         object_class->dispose = easysetup_country_combo_box_dispose;
128         object_class->finalize = easysetup_country_combo_box_finalize;
129 }
130
131 /** id and country must be freed.
132  */
133 static void parse_mcc_mapping_line (const char* line, char** id, char** country)
134 {
135         /* Initialize output parameters: */
136         *id = NULL;
137         *country = NULL;
138         
139         g_assert(line);
140         
141         const gboolean is_valid_utf8 = g_utf8_validate (line, -1, NULL);
142         if(!is_valid_utf8) {
143                 g_warning("UTF8 validation failed.");
144                 return;
145         }
146         
147         /* Look at each character, to find the whitespace between the ID and name: */
148         char* result_id = NULL;
149         char* result_country = NULL;
150         
151         const char* p = line;
152         const char* p_start_of_country = NULL;
153         while (p && *p)
154         {
155                 p = g_utf8_next_char(p);
156                 gunichar ch = g_utf8_get_char(p);
157                 if (g_unichar_isspace(ch)) { /* Note: This checks for any whitespace, not just space. */
158                         if(!result_id) {
159                                 /* The text before this must be the ID: */
160                                 const int length = p - line;
161                                 result_id = g_malloc (length + 1); /* 1 for null-termination. */
162                                 memcpy(result_id, line, length);
163                                 result_id[length] = 0; /* Null-termination. */
164                         }
165                         else if(p_start_of_country)
166                         {
167                                 /* This whitespace is probably the newline after the country. */
168                                 
169                                 /* The text after the whitespace, after the ID, must be the country: */
170                                 int length = p - p_start_of_country;
171                                 result_country = g_malloc(length + 1);
172                                 memcpy(result_country, p_start_of_country, length);
173                                 result_country[length] = 0; /* Null-termination. */
174                                 break;
175                         }
176                 }
177                 else if(result_id && !p_start_of_country) {
178                         p_start_of_country = p;
179                 }
180         }
181         
182         *id = result_id;
183         *country = result_country;
184 }
185
186 /** Note that the mcc_mapping file is installed 
187  * by the operator-wizard-settings package.
188  */
189 static void load_from_file (EasysetupCountryComboBox *self)
190 {
191         EasysetupCountryComboBoxPrivate *priv = COUNTRY_COMBO_BOX_GET_PRIVATE (self);
192         
193         /* Load the file one line at a time: */
194 #ifdef MODEST_HILDON_VERSION_0
195         const gchar* filepath = PROVIDER_DATA_DIR "/mcc_mapping";
196 #else
197         /* This is the official version, in the 'operator-wizard-settings' package */
198         const gchar* filepath = "/usr/share/operator-wizard/mcc_mapping";
199 #endif /*MODEST_HILDON_VERSION_0*/
200         /* printf ("DEBUG: %s: filepath=%s\n", __FUNCTION__, filepath); */
201         FILE *file = fopen(filepath, "r");
202         if (!file)
203         {
204                 const gchar* filepath_hack = HACK_TOP_SRCDIR "src/maemo/easysetup/mcc_mapping";
205                 g_warning ("Could not locate the official mcc_mapping countries list file from %s, "
206                         "so attempting to load it instead from %s", filepath, filepath_hack);
207                 file = fopen(filepath_hack, "r");
208         }
209         
210         if (!file) {
211                 g_warning("Could not open mcc_mapping file");
212                 return;
213         }
214
215         GtkListStore *liststore = GTK_LIST_STORE (priv->model);
216
217         /* We use the getline() GNU extension,
218          * because it reads per line, which simplifies our code,
219          * and it doesn't require us to hard-code a buffer length.
220          * TODO: Could we make this faster?
221          */
222         unsigned int len = 0;
223         char *line = NULL;
224         guint previous_id = 0;
225         gchar* previous_country = NULL;
226         GSList *list = NULL;
227         while (getline (&line, &len, file) > 0) { /* getline will realloc line if necessary. */
228                 /* printf ("DBEUG: len=%d, line: %s\n", len, line); */
229                 
230                 char *id_str = NULL;
231                 char *country = NULL;
232                 parse_mcc_mapping_line (line, &id_str, &country);
233                 /* printf("DEBUG: parsed: id=%s, country=%s\n", id_str, country); */
234                 
235                 if(id_str && country) {
236                         
237                         if (previous_country) {
238                                 /* printf ("  debug: storing id=%d for country=%s\n", previous_id, previous_country); */
239                                 list = g_slist_prepend (list, GUINT_TO_POINTER (previous_id));
240                         }
241                         
242                         /* Group multiple MMC IDs for the same country together:
243                          * This assumes that they are in sequence.
244                          * We don't know why some countries, such as the USA, have several MMC IDs.
245                          * If they are regions in the country, and we need to show them separately, then 
246                          * we would need to have that information in the file to distinguish them.
247                          */
248                         if (!previous_country || 
249                            (previous_country && strcmp (previous_country, country) != 0)) {
250                                 
251                                 /* Get the translation for the country name:
252                                  * Note that the osso_countries_1.0 translation domain files are installed 
253                                  * by the operator-wizard-settings package. */
254                                 /* For post-Bora, there is a separate (meta)package osso-countries-l10n-mr0 */
255                                 
256                                 /* Note: Even when the untranslated names are different, there may still be 
257                                  * duplicate translated names. They would be translation bugs.
258                                  */
259                                 const gchar *name_translated = dgettext ("osso-countries", previous_country);
260                                 if(!name_translated)
261                                   name_translated = previous_country;
262                                 
263                                 /* Add the row to the model: */
264                                 GtkTreeIter iter;
265                                 gtk_list_store_append (liststore, &iter);
266                                 gtk_list_store_set(liststore, &iter, MODEL_COL_IDS, list, MODEL_COL_NAME, name_translated, -1);
267                                 
268                                 /* The list will be freed in our finalize(). */
269                                 list = NULL;
270                         }
271                         
272                         g_free (previous_country);
273                         previous_country = country;
274                         
275                         const guint id = (guint)g_ascii_strtod(id_str, NULL); /* Note that this parses locale-independent text. */
276                         previous_id = id;
277                 }
278                 else if (country) {
279                         g_free (country);
280                 }
281                 
282                 g_free (id_str);
283         }
284         
285         /* Deal with the last country: */
286         const gchar *name_translated = dgettext ("osso-countries", previous_country);
287         if(!name_translated)
288           name_translated = previous_country;
289         
290         /* Add the row to the model: */
291         GtkTreeIter iter;
292         gtk_list_store_append (liststore, &iter);
293         gtk_list_store_set(liststore, &iter, MODEL_COL_IDS, list, MODEL_COL_NAME, name_translated, -1);
294
295         g_free(previous_country);
296
297         if (list) {
298                 g_slist_free (list);
299                 list = NULL;
300         }
301                                 
302
303         if (line)
304                 free (line);
305                 
306         fclose (file);
307         
308         /* Sort the items: */
309         gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (liststore), 
310                 MODEL_COL_NAME, GTK_SORT_ASCENDING);
311 }
312
313 static void
314 easysetup_country_combo_box_init (EasysetupCountryComboBox *self)
315 {
316         EasysetupCountryComboBoxPrivate *priv = COUNTRY_COMBO_BOX_GET_PRIVATE (self);
317
318         /* Create a tree model for the combo box,
319          * with a string for the name, and an int for the MCC ID.
320          * This must match our MODEL_COLS enum constants.
321          */
322         priv->model = GTK_TREE_MODEL (gtk_list_store_new (2, 
323                 G_TYPE_STRING, 
324                 G_TYPE_POINTER));
325
326         /* Setup the combo box: */
327         GtkComboBox *combobox = GTK_COMBO_BOX (self);
328         gtk_combo_box_set_model (combobox, priv->model);
329
330         /* Country column:
331          * The ID model column in not shown in the view. */
332         GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();
333         gtk_cell_layout_pack_start(GTK_CELL_LAYOUT (combobox), renderer, TRUE);
334         gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combobox), renderer, 
335         "text", MODEL_COL_NAME, NULL);
336         
337         /* Fill the model with rows: */
338         load_from_file (self);
339 }
340
341 EasysetupCountryComboBox*
342 easysetup_country_combo_box_new (void)
343 {
344         return g_object_new (EASYSETUP_TYPE_COUNTRY_COMBO_BOX, NULL);
345 }
346
347 /**
348  * Returns the MCC number of the selected country, or 0 if no country was selected. 
349  * The list should not be freed.
350  */
351 GSList *
352 easysetup_country_combo_box_get_active_country_ids (EasysetupCountryComboBox *self)
353 {
354         GtkTreeIter active;
355         const gboolean found = gtk_combo_box_get_active_iter (GTK_COMBO_BOX (self), &active);
356         if (found) {
357                 EasysetupCountryComboBoxPrivate *priv = COUNTRY_COMBO_BOX_GET_PRIVATE (self);
358
359                 GSList *list = NULL;
360                 gtk_tree_model_get (priv->model, &active, MODEL_COL_IDS, &list, -1); 
361                 return list;    
362         }
363
364         return NULL; /* Failed. */
365 }
366
367
368 /* This allows us to pass more than one piece of data to the signal handler,
369  * and get a result: */
370 typedef struct 
371 {
372                 EasysetupCountryComboBox* self;
373                 guint mcc_id;
374                 gboolean found;
375 } ForEachData;
376
377 static gboolean
378 on_model_foreach_select_id(GtkTreeModel *model, 
379         GtkTreePath *path, GtkTreeIter *iter, gpointer user_data)
380 {
381         ForEachData *state = (ForEachData*)(user_data);
382         
383         /* Select the item if it has the matching ID: */
384         GSList *list = NULL;
385         gtk_tree_model_get (model, iter, MODEL_COL_IDS, &list, -1);
386         if(list && g_slist_find (list, GUINT_TO_POINTER (state->mcc_id))) {
387                 gtk_combo_box_set_active_iter (GTK_COMBO_BOX (state->self), iter);
388                 
389                 state->found = TRUE;
390                 return TRUE; /* Stop walking the tree. */
391         }
392         
393         return FALSE; /* Keep walking the tree. */
394 }
395
396 /**
397  * Selects the MCC number of the selected country.
398  * Specify 0 to select no country. 
399  */
400 gboolean
401 easysetup_country_combo_box_set_active_country_id (EasysetupCountryComboBox *self, guint mcc_id)
402 {
403         EasysetupCountryComboBoxPrivate *priv = COUNTRY_COMBO_BOX_GET_PRIVATE (self);
404         
405         /* Create a state instance so we can send two items of data to the signal handler: */
406         ForEachData *state = g_new0 (ForEachData, 1);
407         state->self = self;
408         state->mcc_id = mcc_id;
409         state->found = FALSE;
410         
411         /* Look at each item, and select the one with the correct ID: */
412         gtk_tree_model_foreach (priv->model, &on_model_foreach_select_id, state);
413
414         const gboolean result = state->found;
415         
416         /* Free the state instance: */
417         g_free(state);
418         
419         return result;
420 }
421