Implement autoconfiguration in wizard
[claws.git] / src / gtk / gtkutils.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2013 Hiroyuki Yamamoto and the Claws Mail team
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. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #include <glib.h>
26 #include <glib/gi18n.h>
27 #include <gdk/gdkkeysyms.h>
28 #include <gdk/gdk.h>
29 #include <gtk/gtk.h>
30 #include "gtk/gtksctree.h"
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <sys/stat.h>
34
35 #include "combobox.h"
36
37 #if HAVE_LIBCOMPFACE
38 #  include <compface.h>
39 #endif
40
41 #if HAVE_LIBCOMPFACE
42 #define XPM_XFACE_HEIGHT        (HEIGHT + 3)  /* 3 = 1 header + 2 colors */
43 #endif
44
45 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
46 #  include <wchar.h>
47 #  include <wctype.h>
48 #endif
49
50 #include "defs.h"
51 #include "gtkutils.h"
52 #include "utils.h"
53 #include "gtksctree.h"
54 #include "codeconv.h"
55 #include "stock_pixmap.h"
56 #include "menu.h"
57 #include "prefs_account.h"
58 #include "prefs_common.h"
59 #include "manage_window.h"
60 #include "base64.h"
61 #include "manual.h"
62 #include "combobox.h"
63
64 gboolean gtkut_get_font_size(GtkWidget *widget,
65                              gint *width, gint *height)
66 {
67         PangoLayout *layout;
68         const gchar *str = "Abcdef";
69
70         cm_return_val_if_fail(GTK_IS_WIDGET(widget), FALSE);
71
72         layout = gtk_widget_create_pango_layout(widget, str);
73         cm_return_val_if_fail(layout, FALSE);
74         pango_layout_get_pixel_size(layout, width, height);
75         if (width)
76                 *width = *width / g_utf8_strlen(str, -1);
77         g_object_unref(layout);
78
79         return TRUE;
80 }
81
82 void gtkut_widget_set_small_font_size(GtkWidget *widget)
83 {
84         PangoFontDescription *font_desc;
85         gint size;
86
87         cm_return_if_fail(widget != NULL);
88         cm_return_if_fail(gtk_widget_get_style(widget) != NULL);
89
90         if (prefs_common.derive_from_normal_font || !SMALL_FONT) {
91                 font_desc = pango_font_description_from_string(NORMAL_FONT);
92                 size = pango_font_description_get_size(font_desc);
93                 pango_font_description_set_size(font_desc, size * PANGO_SCALE_SMALL);
94                 gtk_widget_modify_font(widget, font_desc);
95                 pango_font_description_free(font_desc);
96         } else {
97                 font_desc = pango_font_description_from_string(SMALL_FONT);
98                 gtk_widget_modify_font(widget, font_desc);
99                 pango_font_description_free(font_desc);
100         }
101 }
102
103 void gtkut_convert_int_to_gdk_color(gint rgbvalue, GdkColor *color)
104 {
105         cm_return_if_fail(color != NULL);
106
107         color->pixel = 0L;
108         color->red   = (int) (((gdouble)((rgbvalue & 0xff0000) >> 16) / 255.0) * 65535.0);
109         color->green = (int) (((gdouble)((rgbvalue & 0x00ff00) >>  8) / 255.0) * 65535.0);
110         color->blue  = (int) (((gdouble) (rgbvalue & 0x0000ff)        / 255.0) * 65535.0);
111 }
112
113 #define CL(x)   (((gulong) (x) >> (gulong) 8) & 0xFFUL)
114 #define RGB_FROM_GDK_COLOR(c) \
115         ((CL(c->red)   << (gulong) 16) | \
116          (CL(c->green) << (gulong)  8) | \
117          (CL(c->blue)))
118
119 gint gtkut_convert_gdk_color_to_int(GdkColor *color)
120 {
121         return RGB_FROM_GDK_COLOR(color);
122 }
123
124 void gtkut_stock_button_add_help(GtkWidget *bbox, GtkWidget **help_btn)
125 {
126         cm_return_if_fail(bbox != NULL);
127
128         *help_btn = gtk_button_new_from_stock(GTK_STOCK_HELP);
129
130         gtkut_widget_set_can_default(*help_btn, TRUE);
131         gtk_box_pack_end(GTK_BOX (bbox), *help_btn, TRUE, TRUE, 0);
132         gtk_button_box_set_child_secondary(GTK_BUTTON_BOX (bbox),
133                         *help_btn, TRUE);
134         gtk_widget_set_sensitive(*help_btn,
135                         manual_available(MANUAL_MANUAL_CLAWS));
136         gtk_widget_show(*help_btn);
137 }
138
139 void gtkut_stock_button_set_create_with_help(GtkWidget **bbox,
140                 GtkWidget **help_button,
141                 GtkWidget **button1, const gchar *label1,
142                 GtkWidget **button2, const gchar *label2,
143                 GtkWidget **button3, const gchar *label3)
144 {
145         cm_return_if_fail(bbox != NULL);
146         cm_return_if_fail(button1 != NULL);
147
148         gtkut_stock_button_set_create(bbox, button1, label1,
149                         button2, label2, button3, label3);
150
151         gtkut_stock_button_add_help(*bbox, help_button);
152 }
153
154 void gtkut_stock_button_set_create(GtkWidget **bbox,
155                                    GtkWidget **button1, const gchar *label1,
156                                    GtkWidget **button2, const gchar *label2,
157                                    GtkWidget **button3, const gchar *label3)
158 {
159         cm_return_if_fail(bbox != NULL);
160         cm_return_if_fail(button1 != NULL);
161
162         *bbox = gtk_hbutton_box_new();
163         gtk_button_box_set_layout(GTK_BUTTON_BOX(*bbox), GTK_BUTTONBOX_END);
164         gtk_box_set_spacing(GTK_BOX(*bbox), 5);
165
166         *button1 = gtk_button_new_from_stock(label1);
167         gtkut_widget_set_can_default(*button1, TRUE);
168         gtk_box_pack_start(GTK_BOX(*bbox), *button1, TRUE, TRUE, 0);
169         gtk_widget_show(*button1);
170
171         if (button2) {
172                 *button2 = gtk_button_new_from_stock(label2);
173                 gtkut_widget_set_can_default(*button2, TRUE);
174                 gtk_box_pack_start(GTK_BOX(*bbox), *button2, TRUE, TRUE, 0);
175                 gtk_widget_show(*button2);
176         }
177
178         if (button3) {
179                 *button3 = gtk_button_new_from_stock(label3);
180                 gtkut_widget_set_can_default(*button3, TRUE);
181                 gtk_box_pack_start(GTK_BOX(*bbox), *button3, TRUE, TRUE, 0);
182                 gtk_widget_show(*button3);
183         }
184 }
185
186 void gtkut_stock_with_text_button_set_create(GtkWidget **bbox,
187                                    GtkWidget **button1, const gchar *label1, const gchar *text1,
188                                    GtkWidget **button2, const gchar *label2, const gchar *text2,
189                                    GtkWidget **button3, const gchar *label3, const gchar *text3)
190 {
191         cm_return_if_fail(bbox != NULL);
192         cm_return_if_fail(button1 != NULL);
193
194         *bbox = gtk_hbutton_box_new();
195         gtk_button_box_set_layout(GTK_BUTTON_BOX(*bbox), GTK_BUTTONBOX_END);
196         gtk_box_set_spacing(GTK_BOX(*bbox), 5);
197
198         *button1 = gtk_button_new_with_mnemonic(text1);
199         gtk_button_set_image(GTK_BUTTON(*button1),
200                 gtk_image_new_from_stock(label1, GTK_ICON_SIZE_BUTTON));
201         gtkut_widget_set_can_default(*button1, TRUE);
202         gtk_box_pack_start(GTK_BOX(*bbox), *button1, TRUE, TRUE, 0);
203         gtk_widget_show(*button1);
204
205         if (button2) {
206                 *button2 = gtk_button_new_with_mnemonic(text2);
207                 gtk_button_set_image(GTK_BUTTON(*button2),
208                         gtk_image_new_from_stock(label2, GTK_ICON_SIZE_BUTTON));
209                 gtkut_widget_set_can_default(*button2, TRUE);
210                 gtk_box_pack_start(GTK_BOX(*bbox), *button2, TRUE, TRUE, 0);
211                 gtk_widget_show(*button2);
212         }
213
214         if (button3) {
215                 *button3 = gtk_button_new_with_mnemonic(text3);
216                 gtk_button_set_image(GTK_BUTTON(*button3),
217                         gtk_image_new_from_stock(label3, GTK_ICON_SIZE_BUTTON));
218                 gtkut_widget_set_can_default(*button3, TRUE);
219                 gtk_box_pack_start(GTK_BOX(*bbox), *button3, TRUE, TRUE, 0);
220                 gtk_widget_show(*button3);
221         }
222 }
223
224 #define CELL_SPACING 1
225 #define ROW_TOP_YPIXEL(clist, row) (((clist)->row_height * (row)) + \
226                                     (((row) + 1) * CELL_SPACING) + \
227                                     (clist)->voffset)
228 #define ROW_FROM_YPIXEL(clist, y) (((y) - (clist)->voffset) / \
229                                    ((clist)->row_height + CELL_SPACING))
230
231 void gtkut_ctree_node_move_if_on_the_edge(GtkCMCTree *ctree, GtkCMCTreeNode *node, gint _row)
232 {
233         GtkCMCList *clist = GTK_CMCLIST(ctree);
234         gint row;
235         GtkVisibility row_visibility, prev_row_visibility, next_row_visibility;
236
237         cm_return_if_fail(ctree != NULL);
238         cm_return_if_fail(node != NULL);
239
240         row = (_row != -1 ? _row : g_list_position(clist->row_list, (GList *)node));
241
242         if (row < 0 || row >= clist->rows || clist->row_height == 0) return;
243         row_visibility = gtk_cmclist_row_is_visible(clist, row);
244         prev_row_visibility = gtk_cmclist_row_is_visible(clist, row - 1);
245         next_row_visibility = gtk_cmclist_row_is_visible(clist, row + 1);
246
247         if (row_visibility == GTK_VISIBILITY_NONE) {
248                 gtk_cmclist_moveto(clist, row, -1, 0.5, 0);
249                 return;
250         }
251         if (row_visibility == GTK_VISIBILITY_FULL &&
252             prev_row_visibility == GTK_VISIBILITY_FULL &&
253             next_row_visibility == GTK_VISIBILITY_FULL)
254                 return;
255         if (prev_row_visibility != GTK_VISIBILITY_FULL &&
256             next_row_visibility != GTK_VISIBILITY_FULL)
257                 return;
258
259         if (prev_row_visibility != GTK_VISIBILITY_FULL) {
260                 gtk_cmclist_moveto(clist, row, -1, 0.2, 0);
261                 return;
262         }
263         if (next_row_visibility != GTK_VISIBILITY_FULL) {
264                 gtk_cmclist_moveto(clist, row, -1, 0.8, 0);
265                 return;
266         }
267 }
268
269 #undef CELL_SPACING
270 #undef ROW_TOP_YPIXEL
271 #undef ROW_FROM_YPIXEL
272
273 gint gtkut_ctree_get_nth_from_node(GtkCMCTree *ctree, GtkCMCTreeNode *node)
274 {
275         cm_return_val_if_fail(ctree != NULL, -1);
276         cm_return_val_if_fail(node != NULL, -1);
277
278         return g_list_position(GTK_CMCLIST(ctree)->row_list, (GList *)node);
279 }
280
281 /* get the next node, including the invisible one */
282 GtkCMCTreeNode *gtkut_ctree_node_next(GtkCMCTree *ctree, GtkCMCTreeNode *node)
283 {
284         GtkCMCTreeNode *parent;
285
286         if (!node) return NULL;
287
288         if (GTK_CMCTREE_ROW(node)->children)
289                 return GTK_CMCTREE_ROW(node)->children;
290
291         if (GTK_CMCTREE_ROW(node)->sibling)
292                 return GTK_CMCTREE_ROW(node)->sibling;
293
294         for (parent = GTK_CMCTREE_ROW(node)->parent; parent != NULL;
295              parent = GTK_CMCTREE_ROW(parent)->parent) {
296                 if (GTK_CMCTREE_ROW(parent)->sibling)
297                         return GTK_CMCTREE_ROW(parent)->sibling;
298         }
299
300         return NULL;
301 }
302
303 /* get the previous node, including the invisible one */
304 GtkCMCTreeNode *gtkut_ctree_node_prev(GtkCMCTree *ctree, GtkCMCTreeNode *node)
305 {
306         GtkCMCTreeNode *prev;
307         GtkCMCTreeNode *child;
308
309         if (!node) return NULL;
310
311         prev = GTK_CMCTREE_NODE_PREV(node);
312         if (prev == GTK_CMCTREE_ROW(node)->parent)
313                 return prev;
314
315         child = prev;
316         while (GTK_CMCTREE_ROW(child)->children != NULL) {
317                 child = GTK_CMCTREE_ROW(child)->children;
318                 while (GTK_CMCTREE_ROW(child)->sibling != NULL)
319                         child = GTK_CMCTREE_ROW(child)->sibling;
320         }
321
322         return child;
323 }
324
325 gboolean gtkut_ctree_node_is_selected(GtkCMCTree *ctree, GtkCMCTreeNode *node)
326 {
327         GtkCMCList *clist = GTK_CMCLIST(ctree);
328         GList *cur;
329
330         for (cur = clist->selection; cur != NULL; cur = cur->next) {
331                 if (node == GTK_CMCTREE_NODE(cur->data))
332                         return TRUE;
333         }
334
335         return FALSE;
336 }
337
338 GtkCMCTreeNode *gtkut_ctree_find_collapsed_parent(GtkCMCTree *ctree,
339                                                 GtkCMCTreeNode *node)
340 {
341         if (!node) return NULL;
342
343         while ((node = GTK_CMCTREE_ROW(node)->parent) != NULL) {
344                 if (!GTK_CMCTREE_ROW(node)->expanded)
345                         return node;
346         }
347
348         return NULL;
349 }
350
351 void gtkut_ctree_expand_parent_all(GtkCMCTree *ctree, GtkCMCTreeNode *node)
352 {
353         while ((node = gtkut_ctree_find_collapsed_parent(ctree, node)) != NULL)
354                 gtk_cmctree_expand(ctree, node);
355 }
356
357 gboolean gtkut_ctree_node_is_parent(GtkCMCTreeNode *parent, GtkCMCTreeNode *node)
358 {
359         GtkCMCTreeNode *tmp;
360         cm_return_val_if_fail(node != NULL, FALSE);
361         cm_return_val_if_fail(parent != NULL, FALSE);
362         tmp = node;
363         
364         while (tmp) {
365                 if(GTK_CMCTREE_ROW(tmp)->parent && GTK_CMCTREE_ROW(tmp)->parent == parent)
366                         return TRUE;
367                 tmp = GTK_CMCTREE_ROW(tmp)->parent;
368         }
369         
370         return FALSE;
371 }
372
373 void gtkut_ctree_set_focus_row(GtkCMCTree *ctree, GtkCMCTreeNode *node)
374 {
375         if (node == NULL)
376                 return;
377         gtkut_clist_set_focus_row(GTK_CMCLIST(ctree),
378                                   gtkut_ctree_get_nth_from_node(ctree, node));
379 }
380
381 void gtkut_clist_set_focus_row(GtkCMCList *clist, gint row)
382 {
383         clist->focus_row = row;
384         GTKUT_CTREE_REFRESH(clist);
385 }
386
387 void gtkut_container_remove(GtkContainer *container, GtkWidget *widget)
388 {
389         gtk_container_remove(container, widget);
390 }
391
392 static gboolean gtkut_text_buffer_match_string(GtkTextBuffer *textbuf,
393                                         const GtkTextIter *iter,
394                                         gunichar *wcs, gint len,
395                                         gboolean case_sens)
396 {
397         GtkTextIter start_iter, end_iter;
398         gchar *utf8str, *p;
399         gint match_count;
400
401         start_iter = end_iter = *iter;
402         gtk_text_iter_forward_chars(&end_iter, len);
403
404         utf8str = gtk_text_buffer_get_text(textbuf, &start_iter, &end_iter,
405                                            FALSE);
406         if (!utf8str) return FALSE;
407
408         if ((gint)g_utf8_strlen(utf8str, -1) != len) {
409                 g_free(utf8str);
410                 return FALSE;
411         }
412
413         for (p = utf8str, match_count = 0;
414              *p != '\0' && match_count < len;
415              p = g_utf8_next_char(p), match_count++) {
416                 gunichar wc;
417
418                 wc = g_utf8_get_char(p);
419
420                 if (case_sens) {
421                         if (wc != wcs[match_count])
422                                 break;
423                 } else {
424                         if (g_unichar_tolower(wc) !=
425                             g_unichar_tolower(wcs[match_count]))
426                                 break;
427                 }
428         }
429
430         g_free(utf8str);
431
432         if (match_count == len)
433                 return TRUE;
434         else
435                 return FALSE;
436 }
437
438 static gboolean gtkut_text_buffer_find(GtkTextBuffer *buffer, const GtkTextIter *iter,
439                                 const gchar *str, gboolean case_sens,
440                                 GtkTextIter *match_pos)
441 {
442         gunichar *wcs;
443         gint len;
444         glong items_read = 0, items_written = 0;
445         GError *error = NULL;
446         GtkTextIter iter_;
447         gboolean found = FALSE;
448
449         wcs = g_utf8_to_ucs4(str, -1, &items_read, &items_written, &error);
450         if (error != NULL) {
451                 g_warning("An error occurred while converting a string from UTF-8 to UCS-4: %s\n",
452                           error->message);
453                 g_error_free(error);
454         }
455         if (!wcs || items_written <= 0) return FALSE;
456         len = (gint)items_written;
457
458         iter_ = *iter;
459         do {
460                 found = gtkut_text_buffer_match_string
461                         (buffer, &iter_, wcs, len, case_sens);
462                 if (found) {
463                         *match_pos = iter_;
464                         break;
465                 }
466         } while (gtk_text_iter_forward_char(&iter_));
467
468         g_free(wcs);
469
470         return found;
471 }
472
473 static gboolean gtkut_text_buffer_find_backward(GtkTextBuffer *buffer,
474                                          const GtkTextIter *iter,
475                                          const gchar *str, gboolean case_sens,
476                                          GtkTextIter *match_pos)
477 {
478         gunichar *wcs;
479         gint len;
480         glong items_read = 0, items_written = 0;
481         GError *error = NULL;
482         GtkTextIter iter_;
483         gboolean found = FALSE;
484
485         wcs = g_utf8_to_ucs4(str, -1, &items_read, &items_written, &error);
486         if (error != NULL) {
487                 g_warning("An error occurred while converting a string from UTF-8 to UCS-4: %s\n",
488                           error->message);
489                 g_error_free(error);
490         }
491         if (!wcs || items_written <= 0) return FALSE;
492         len = (gint)items_written;
493
494         iter_ = *iter;
495         while (gtk_text_iter_backward_char(&iter_)) {
496                 found = gtkut_text_buffer_match_string
497                         (buffer, &iter_, wcs, len, case_sens);
498                 if (found) {
499                         *match_pos = iter_;
500                         break;
501                 }
502         }
503
504         g_free(wcs);
505
506         return found;
507 }
508
509 gchar *gtkut_text_view_get_selection(GtkTextView *textview)
510 {
511         GtkTextBuffer *buffer;
512         GtkTextIter start_iter, end_iter;
513         gboolean found;
514
515         cm_return_val_if_fail(GTK_IS_TEXT_VIEW(textview), NULL);
516
517         buffer = gtk_text_view_get_buffer(textview);
518         found = gtk_text_buffer_get_selection_bounds(buffer,
519                                                      &start_iter,
520                                                      &end_iter);
521         if (found)
522                 return gtk_text_buffer_get_text(buffer, &start_iter, &end_iter,
523                                                 FALSE);
524         else
525                 return NULL;
526 }
527
528
529 void gtkut_text_view_set_position(GtkTextView *text, gint pos)
530 {
531         GtkTextBuffer *buffer;
532         GtkTextIter iter;
533         GtkTextMark *mark;
534
535         cm_return_if_fail(text != NULL);
536
537         buffer = gtk_text_view_get_buffer(text);
538
539         gtk_text_buffer_get_iter_at_offset(buffer, &iter, pos);
540         gtk_text_buffer_place_cursor(buffer, &iter);
541         mark = gtk_text_buffer_create_mark(buffer, NULL, &iter, TRUE);
542         gtk_text_view_scroll_to_mark(text, mark, 0.0, FALSE, 0.0, 0.0);
543 }
544
545 gboolean gtkut_text_view_search_string(GtkTextView *text, const gchar *str,
546                                         gboolean case_sens)
547 {
548         GtkTextBuffer *buffer;
549         GtkTextIter iter, match_pos;
550         GtkTextMark *mark;
551         gint len;
552
553         cm_return_val_if_fail(text != NULL, FALSE);
554         cm_return_val_if_fail(str != NULL, FALSE);
555
556         buffer = gtk_text_view_get_buffer(text);
557
558         len = g_utf8_strlen(str, -1);
559         cm_return_val_if_fail(len >= 0, FALSE);
560
561         mark = gtk_text_buffer_get_insert(buffer);
562         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
563
564         if (gtkut_text_buffer_find(buffer, &iter, str, case_sens,
565                                    &match_pos)) {
566                 GtkTextIter end = match_pos;
567
568                 gtk_text_iter_forward_chars(&end, len);
569                 /* place "insert" at the last character */
570                 gtk_text_buffer_select_range(buffer, &end, &match_pos);
571                 gtk_text_view_scroll_to_mark(text, mark, 0.0, TRUE, 0.0, 0.5);
572                 return TRUE;
573         }
574
575         return FALSE;
576 }
577
578 gboolean gtkut_text_view_search_string_backward(GtkTextView *text, const gchar *str,
579                                         gboolean case_sens)
580 {
581         GtkTextBuffer *buffer;
582         GtkTextIter iter, match_pos;
583         GtkTextMark *mark;
584         gint len;
585
586         cm_return_val_if_fail(text != NULL, FALSE);
587         cm_return_val_if_fail(str != NULL, FALSE);
588
589         buffer = gtk_text_view_get_buffer(text);
590
591         len = g_utf8_strlen(str, -1);
592         cm_return_val_if_fail(len >= 0, FALSE);
593
594         mark = gtk_text_buffer_get_insert(buffer);
595         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
596
597         if (gtkut_text_buffer_find_backward(buffer, &iter, str, case_sens,
598                                             &match_pos)) {
599                 GtkTextIter end = match_pos;
600
601                 gtk_text_iter_forward_chars(&end, len);
602                 gtk_text_buffer_select_range(buffer, &match_pos, &end);
603                 gtk_text_view_scroll_to_mark(text, mark, 0.0, TRUE, 0.0, 0.5);
604                 return TRUE;
605         }
606
607         return FALSE;
608 }
609
610 void gtkut_window_popup(GtkWidget *window)
611 {
612         GdkWindow *gdkwin;
613         gint x, y, sx, sy, new_x, new_y;
614
615         gdkwin = gtk_widget_get_window(window);
616
617         cm_return_if_fail(window != NULL);
618         cm_return_if_fail(gdkwin != NULL);
619
620         sx = gdk_screen_width();
621         sy = gdk_screen_height();
622
623         gdk_window_get_origin(gdkwin, &x, &y);
624         new_x = x % sx; if (new_x < 0) new_x = 0;
625         new_y = y % sy; if (new_y < 0) new_y = 0;
626         if (new_x != x || new_y != y)
627                 gdk_window_move(gdkwin, new_x, new_y);
628
629         gtk_window_set_skip_taskbar_hint(GTK_WINDOW(window), FALSE);
630         gtk_window_present_with_time(GTK_WINDOW(window), time(NULL));
631 }
632
633 void gtkut_widget_get_uposition(GtkWidget *widget, gint *px, gint *py)
634 {
635         GdkWindow *gdkwin;
636         gint x, y;
637         gint sx, sy;
638
639         gdkwin = gtk_widget_get_window(widget);
640
641         cm_return_if_fail(widget != NULL);
642         cm_return_if_fail(gdkwin != NULL);
643
644         sx = gdk_screen_width();
645         sy = gdk_screen_height();
646
647         /* gdk_window_get_root_origin ever return *rootwindow*'s position */
648         gdk_window_get_root_origin(gdkwin, &x, &y);
649
650         x %= sx; if (x < 0) x = 0;
651         y %= sy; if (y < 0) y = 0;
652         *px = x;
653         *py = y;
654 }
655
656 void gtkut_widget_draw_now(GtkWidget *widget)
657 {
658         if (widget && gtk_widget_get_visible(widget) && gtk_widget_is_drawable(widget))
659                 gdk_window_process_updates(gtk_widget_get_window(widget), FALSE);
660 }
661
662 static void gtkut_clist_bindings_add(GtkWidget *clist)
663 {
664         GtkBindingSet *binding_set;
665
666         binding_set = gtk_binding_set_by_class
667                 (GTK_CMCLIST_GET_CLASS(clist));
668
669         gtk_binding_entry_add_signal(binding_set, GDK_KEY_n, GDK_CONTROL_MASK,
670                                      "scroll_vertical", 2,
671                                      G_TYPE_ENUM, GTK_SCROLL_STEP_FORWARD,
672                                      G_TYPE_FLOAT, 0.0);
673         gtk_binding_entry_add_signal(binding_set, GDK_KEY_p, GDK_CONTROL_MASK,
674                                      "scroll_vertical", 2,
675                                      G_TYPE_ENUM, GTK_SCROLL_STEP_BACKWARD,
676                                      G_TYPE_FLOAT, 0.0);
677 }
678
679 void gtkut_widget_init(void)
680 {
681         GtkWidget *clist;
682
683         clist = gtk_cmclist_new(1);
684         g_object_ref(G_OBJECT(clist));
685 #if GLIB_CHECK_VERSION(2,10,0)
686         g_object_ref_sink (G_OBJECT(clist));
687 #else
688         gtk_object_ref (G_OBJECT(clist));
689         gtk_object_sink (G_OBJECT(clist));
690 #endif
691         gtkut_clist_bindings_add(clist);
692         g_object_unref(G_OBJECT(clist));
693
694         clist = gtk_cmctree_new(1, 0);
695         g_object_ref(G_OBJECT(clist));
696 #if GLIB_CHECK_VERSION(2,10,0)
697         g_object_ref_sink (G_OBJECT(clist));
698 #else
699         gtk_object_ref (G_OBJECT(clist));
700         gtk_object_sink (G_OBJECT(clist));
701 #endif
702         gtkut_clist_bindings_add(clist);
703         g_object_unref(G_OBJECT(clist));
704
705         clist = gtk_sctree_new_with_titles(1, 0, NULL);
706         g_object_ref(G_OBJECT(clist));
707 #if GLIB_CHECK_VERSION(2,10,0)
708         g_object_ref_sink (G_OBJECT(clist));
709 #else
710         gtk_object_ref (G_OBJECT(clist));
711         gtk_object_sink (G_OBJECT(clist));
712 #endif
713         gtkut_clist_bindings_add(clist);
714         g_object_unref(G_OBJECT(clist));
715 }
716
717 void gtkut_widget_set_app_icon(GtkWidget *widget)
718 {
719         static GList *icon_list = NULL;
720
721         cm_return_if_fail(widget != NULL);
722         cm_return_if_fail(gtk_widget_get_window(widget) != NULL);
723         if (!icon_list) {
724                 GdkPixbuf *icon = NULL, *big_icon = NULL;
725                 stock_pixbuf_gdk(widget, STOCK_PIXMAP_CLAWS_MAIL_ICON, &icon);
726                 stock_pixbuf_gdk(widget, STOCK_PIXMAP_CLAWS_MAIL_LOGO, &big_icon);
727                 if (icon)
728                         icon_list = g_list_append(icon_list, icon);
729                 if (big_icon)
730                         icon_list = g_list_append(icon_list, big_icon);
731         }
732         if (icon_list)
733                 gtk_window_set_icon_list(GTK_WINDOW(widget), icon_list);
734 }
735
736 void gtkut_widget_set_composer_icon(GtkWidget *widget)
737 {
738         static GList *icon_list = NULL;
739
740         cm_return_if_fail(widget != NULL);
741         cm_return_if_fail(gtk_widget_get_window(widget) != NULL);
742         if (!icon_list) {
743                 GdkPixbuf *icon = NULL, *big_icon = NULL;
744                 stock_pixbuf_gdk(widget, STOCK_PIXMAP_MAIL_COMPOSE, &icon);
745                 stock_pixbuf_gdk(widget, STOCK_PIXMAP_MAIL_COMPOSE_LOGO, &big_icon);
746                 if (icon)
747                         icon_list = g_list_append(icon_list, icon);
748                 if (big_icon)
749                         icon_list = g_list_append(icon_list, big_icon);
750         }
751         if (icon_list)
752                 gtk_window_set_icon_list(GTK_WINDOW(widget), icon_list);
753 }
754
755 static gboolean move_bar = FALSE;
756 static gint move_bar_id = -1;
757
758 static gboolean move_bar_cb(gpointer data)
759 {
760         GtkWidget *w = (GtkWidget *)data;
761         if (!move_bar)
762                 return FALSE;
763
764         if (!GTK_IS_PROGRESS_BAR(w)) {
765                 return FALSE;
766         }
767
768         gtk_progress_bar_pulse(GTK_PROGRESS_BAR(w));
769         GTK_EVENTS_FLUSH();
770         return TRUE;
771 }
772
773 GtkWidget *label_window_create(const gchar *str)
774 {
775         GtkWidget *window;
776         GtkWidget *label, *vbox, *hbox;
777         GtkWidget *wait_progress = gtk_progress_bar_new();
778
779         window = gtkut_window_new(GTK_WINDOW_TOPLEVEL, "gtkutils");
780         gtk_widget_set_size_request(window, 380, 70);
781         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
782         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
783         gtk_window_set_title(GTK_WINDOW(window), str);
784         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
785         gtk_window_set_resizable(GTK_WINDOW(window), FALSE);
786         manage_window_set_transient(GTK_WINDOW(window));
787
788         label = gtk_label_new(str);
789         
790         vbox = gtk_vbox_new(FALSE, 6);
791         hbox = gtk_hbox_new(FALSE, 6);
792         gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, FALSE, 0);
793         gtk_box_pack_start(GTK_BOX(vbox), hbox, TRUE, FALSE, 0);
794         hbox = gtk_hbox_new(FALSE, 6);
795         gtk_box_pack_start(GTK_BOX(hbox), wait_progress, TRUE, FALSE, 0);
796         gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
797         
798         gtk_container_add(GTK_CONTAINER(window), vbox);
799         gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
800         gtk_misc_set_alignment(GTK_MISC(label), 0.5, 0.5);
801         gtk_widget_show_all(vbox);
802
803         gtk_widget_show_now(window);
804         
805         if (move_bar_id == -1) {
806                 move_bar_id = g_timeout_add(200, move_bar_cb, wait_progress);
807                 move_bar = TRUE;
808         }
809
810         GTK_EVENTS_FLUSH();
811
812         return window;
813 }
814
815 void label_window_destroy(GtkWidget *window)
816 {
817         move_bar = FALSE;
818         g_source_remove(move_bar_id);
819         move_bar_id = -1;
820         GTK_EVENTS_FLUSH();
821         gtk_widget_destroy(window);     
822 }
823
824 GtkWidget *gtkut_account_menu_new(GList                 *ac_list,
825                                         GCallback               callback,
826                                   gpointer              data)
827 {
828         GList *cur_ac;
829         GtkWidget *optmenu;
830         GtkListStore *menu;
831         GtkTreeIter iter;
832         PrefsAccount *account;
833         gchar *name;
834         
835         cm_return_val_if_fail(ac_list != NULL, NULL);
836
837         optmenu = gtkut_sc_combobox_create(NULL, FALSE);
838         menu = GTK_LIST_STORE(gtk_combo_box_get_model(GTK_COMBO_BOX(optmenu)));
839
840         for (cur_ac = ac_list; cur_ac != NULL; cur_ac = cur_ac->next) {
841                 account = (PrefsAccount *) cur_ac->data;
842                 if (account->name)
843                         name = g_strdup_printf("%s: %s <%s>",
844                                                account->account_name,
845                                                account->name,
846                                                account->address);
847                 else
848                         name = g_strdup_printf("%s: %s",
849                                                account->account_name,
850                                                account->address);
851                 COMBOBOX_ADD_ESCAPED(menu, name, account->account_id);
852                 g_free(name);
853         }
854         gtk_combo_box_set_active(GTK_COMBO_BOX(optmenu), 0);
855
856         if( callback != NULL )
857                 g_signal_connect(G_OBJECT(optmenu), "changed", callback, data);
858
859         return optmenu;
860 }
861
862 void gtkut_set_widget_bgcolor_rgb(GtkWidget *widget, guint rgbvalue)
863 {
864         GtkStyle *newstyle;
865         GdkColor gdk_color;
866
867         gtkut_convert_int_to_gdk_color(rgbvalue, &gdk_color);
868         newstyle = gtk_style_copy(gtk_widget_get_default_style());
869         newstyle->bg[GTK_STATE_NORMAL]   = gdk_color;
870         newstyle->bg[GTK_STATE_PRELIGHT] = gdk_color;
871         newstyle->bg[GTK_STATE_ACTIVE]   = gdk_color;
872         gtk_widget_set_style(widget, newstyle);
873 }
874   
875 /*!
876  *\brief        Tries to find a focused child using a lame strategy
877  */
878 GtkWidget *gtkut_get_focused_child(GtkContainer *parent)
879 {
880         GtkWidget *result = NULL;
881         GList *child_list = NULL;
882         GList *c;
883
884         cm_return_val_if_fail(parent, NULL);
885
886         /* Get children list and see which has the focus. */
887         child_list = gtk_container_get_children(parent);
888         if (!child_list)
889                 return NULL;
890
891         for (c = child_list; c != NULL; c = g_list_next(c)) {
892                 if (c->data && GTK_IS_WIDGET(c->data)) {
893                         if (gtk_widget_has_focus(GTK_WIDGET(c->data))) {
894                                 result = GTK_WIDGET(c->data);
895                                 break;
896                         }
897                 }
898         }
899         
900         /* See if the returned widget is a container itself; if it is,
901          * see if one of its children is focused. If the focused 
902          * container has no focused child, it is itself a focusable 
903          * child, and has focus. */
904         if (result && GTK_IS_CONTAINER(result)) {
905                 GtkWidget *tmp =  gtkut_get_focused_child(GTK_CONTAINER(result)); 
906                 
907                 if (tmp) 
908                         result = tmp;
909         } else {
910                 /* Try the same for each container in the chain */
911                 for (c = child_list; c != NULL && !result; c = g_list_next(c)) {
912                         if (c->data && GTK_IS_WIDGET(c->data) 
913                         &&  GTK_IS_CONTAINER(c->data)) {
914                                 result = gtkut_get_focused_child
915                                         (GTK_CONTAINER(c->data));
916                         }
917                 }
918         
919         }
920         
921         g_list_free(child_list);
922                 
923         return result;
924 }
925
926 /*!
927  *\brief        Create a Browse (file) button based on GTK+ stock
928  */
929 GtkWidget *gtkut_get_browse_file_btn(const gchar *button_label)
930 {
931         GtkWidget *button;
932
933         button = gtk_button_new_with_mnemonic(button_label);
934         gtk_button_set_image(GTK_BUTTON(button),
935                 gtk_image_new_from_stock(GTK_STOCK_DIRECTORY, GTK_ICON_SIZE_BUTTON));
936
937         return button;
938 }
939
940 /*!
941  *\brief        Create a Browse (directory) button based on GTK+ stock
942  */
943 GtkWidget *gtkut_get_browse_directory_btn(const gchar *button_label)
944 {
945         GtkWidget *button;
946
947         button = gtk_button_new_with_mnemonic(button_label);
948         gtk_button_set_image(GTK_BUTTON(button),
949                 gtk_image_new_from_stock(GTK_STOCK_DIRECTORY, GTK_ICON_SIZE_BUTTON));
950
951         return button;
952 }
953
954 GtkWidget *gtkut_get_replace_btn(const gchar *button_label)
955 {
956         GtkWidget *button;
957
958         button = gtk_button_new_with_mnemonic(button_label);
959         gtk_button_set_image(GTK_BUTTON(button),
960                 gtk_image_new_from_stock(GTK_STOCK_REFRESH, GTK_ICON_SIZE_BUTTON));
961
962         return button;
963 }
964
965 /**
966  * merge some part of code into one function : it creates a frame and add
967  *      these into gtk box widget passed in param.
968  * \param box gtk box where adding new created frame.
969  * \param pframe pointer with which to assign the frame. If NULL, no pointer
970  *      is assigned but the frame is anyway created and added to @box.
971  * \param frame_label frame label of new created frame.
972  */
973 GtkWidget *gtkut_get_options_frame(GtkWidget *box, GtkWidget **pframe,
974                 const gchar *frame_label)
975 {
976         GtkWidget *vbox;
977         GtkWidget *frame;
978
979         frame = gtk_frame_new(frame_label);
980         gtk_widget_show(frame);
981         gtk_box_pack_start(GTK_BOX(box), frame, FALSE, TRUE, 0);
982         gtk_frame_set_label_align(GTK_FRAME(frame), 0.01, 0.5);
983
984         vbox = gtk_vbox_new (FALSE, 4);
985         gtk_widget_show(vbox);
986         gtk_container_add(GTK_CONTAINER (frame), vbox);
987         gtk_container_set_border_width (GTK_CONTAINER (vbox), 8);
988
989         if (pframe != NULL)
990                 *pframe = frame;
991
992         return vbox;
993 }
994
995 #if HAVE_LIBCOMPFACE
996 static gint create_xpm_from_xface(gchar *xpm[], const gchar *xface)
997 {
998         static gchar *bit_pattern[] = {
999                 "....",
1000                 "...#",
1001                 "..#.",
1002                 "..##",
1003                 ".#..",
1004                 ".#.#",
1005                 ".##.",
1006                 ".###",
1007                 "#...",
1008                 "#..#",
1009                 "#.#.",
1010                 "#.##",
1011                 "##..",
1012                 "##.#",
1013                 "###.",
1014                 "####"
1015         };
1016
1017         static gchar *xface_header = "48 48 2 1";
1018         static gchar *xface_black  = "# c #000000";
1019         static gchar *xface_white  = ". c #ffffff";
1020
1021         gint i, line = 0;
1022         const guchar *p;
1023         gchar buf[WIDTH * 4 + 1];  /* 4 = strlen("0x0000") */
1024
1025         p = xface;
1026
1027         strcpy(xpm[line++], xface_header);
1028         strcpy(xpm[line++], xface_black);
1029         strcpy(xpm[line++], xface_white);
1030
1031         for (i = 0; i < HEIGHT; i++) {
1032                 gint col;
1033
1034                 buf[0] = '\0';
1035      
1036                 for (col = 0; col < 3; col++) {
1037                         gint figure;
1038
1039                         p += 2;  /* skip '0x' */
1040
1041                         for (figure = 0; figure < 4; figure++) {
1042                                 gint n = 0;
1043
1044                                 if ('0' <= *p && *p <= '9') {
1045                                         n = *p - '0';
1046                                 } else if ('a' <= *p && *p <= 'f') {
1047                                         n = *p - 'a' + 10;
1048                                 } else if ('A' <= *p && *p <= 'F') {
1049                                         n = *p - 'A' + 10;
1050                                 }
1051
1052                                 strcat(buf, bit_pattern[n]);
1053                                 p++;  /* skip ',' */
1054                         }
1055
1056                         p++;  /* skip '\n' */
1057                 }
1058
1059                 strcpy(xpm[line++], buf);
1060                 p++;
1061         }
1062
1063         return 0;
1064 }
1065 #endif
1066
1067 gboolean get_tag_range(GtkTextIter *iter,
1068                                        GtkTextTag *tag,
1069                                        GtkTextIter *start_iter,
1070                                        GtkTextIter *end_iter)
1071 {
1072         GtkTextIter _start_iter, _end_iter;
1073
1074         _end_iter = *iter;
1075         if (!gtk_text_iter_forward_to_tag_toggle(&_end_iter, tag)) {
1076                 debug_print("Can't find end");
1077                 return FALSE;
1078         }
1079
1080         _start_iter = _end_iter;
1081         if (!gtk_text_iter_backward_to_tag_toggle(&_start_iter, tag)) {
1082                 debug_print("Can't find start.");
1083                 return FALSE;
1084         }
1085
1086         *start_iter = _start_iter;
1087         *end_iter = _end_iter;
1088
1089         return TRUE;
1090 }
1091
1092 #if HAVE_LIBCOMPFACE
1093 GtkWidget *xface_get_from_header(const gchar *o_xface)
1094 {
1095         static gchar *xpm_xface[XPM_XFACE_HEIGHT];
1096         static gboolean xpm_xface_init = TRUE;
1097         gchar xface[2048];
1098         strncpy(xface, o_xface, sizeof(xface));
1099
1100         if (uncompface(xface) < 0) {
1101                 g_warning("uncompface failed\n");
1102                 return NULL;
1103         }
1104
1105         if (xpm_xface_init) {
1106                 gint i;
1107
1108                 for (i = 0; i < XPM_XFACE_HEIGHT; i++) {
1109                         xpm_xface[i] = g_malloc(WIDTH + 1);
1110                         *xpm_xface[i] = '\0';
1111                 }
1112                 xpm_xface_init = FALSE;
1113         }
1114
1115         create_xpm_from_xface(xpm_xface, xface);
1116
1117         return gtk_image_new_from_pixbuf(
1118                 gdk_pixbuf_new_from_xpm_data((const char **)xpm_xface));
1119 }
1120 #endif
1121
1122 GtkWidget *face_get_from_header(const gchar *o_face)
1123 {
1124         gchar face[2048];
1125         gchar face_png[2048];
1126         gint pngsize;
1127         GdkPixbuf *pixbuf;
1128         GError *error = NULL;
1129         GdkPixbufLoader *loader = gdk_pixbuf_loader_new ();
1130         GtkWidget *image;
1131         
1132         if (o_face == NULL || strlen(o_face) == 0)
1133                 return NULL;
1134
1135         strncpy2(face, o_face, sizeof(face));
1136
1137         unfold_line(face); /* strip all whitespace and linebreaks */
1138         remove_space(face);
1139
1140         pngsize = base64_decode(face_png, face, strlen(face));
1141
1142         if (!gdk_pixbuf_loader_write (loader, face_png, pngsize, &error) ||
1143             !gdk_pixbuf_loader_close (loader, &error)) {
1144                 g_warning("loading face failed\n");
1145                 g_object_unref(loader);
1146                 return NULL;
1147         }
1148
1149         pixbuf = g_object_ref(gdk_pixbuf_loader_get_pixbuf(loader));
1150
1151         g_object_unref(loader);
1152
1153         if ((gdk_pixbuf_get_width(pixbuf) != 48) || (gdk_pixbuf_get_height(pixbuf) != 48)) {
1154                 g_object_unref(pixbuf);
1155                 g_warning("wrong_size\n");
1156                 return NULL;
1157         }
1158
1159         image = gtk_image_new_from_pixbuf(pixbuf);
1160         g_object_unref(pixbuf);
1161         return image;
1162 }
1163
1164 static GdkCursor *hand_cursor = NULL;
1165
1166 static void link_btn_enter(GtkButton *button, gpointer data)
1167 {
1168         GdkWindow *gdkwin;
1169         GtkWidget *window = (GtkWidget *)data;
1170
1171         gdkwin = gtk_widget_get_window(window);
1172
1173         if (!hand_cursor)
1174                 hand_cursor = gdk_cursor_new(GDK_HAND2);
1175         if (window && gdkwin)
1176                 gdk_window_set_cursor(gdkwin, hand_cursor);
1177
1178         gtk_button_set_relief(button, GTK_RELIEF_NONE);
1179         gtk_widget_set_state(GTK_WIDGET(button), GTK_STATE_NORMAL);
1180         
1181 }
1182
1183 static void link_btn_leave(GtkButton *button, gpointer data)
1184 {
1185         GdkWindow *gdkwin;
1186         GtkWidget *window = (GtkWidget *)data;
1187
1188         gdkwin = gtk_widget_get_window(window);
1189
1190         if (window && gdkwin)
1191                 gdk_window_set_cursor(gdkwin, NULL);
1192
1193         gtk_button_set_relief(button, GTK_RELIEF_NONE);
1194         gtk_widget_set_state(GTK_WIDGET(button), GTK_STATE_NORMAL);
1195 }
1196
1197 static void link_btn_pressed(GtkButton *button, gpointer data)
1198 {
1199         gtk_button_set_relief(button, GTK_RELIEF_NONE);
1200         gtk_widget_set_state(GTK_WIDGET(button), GTK_STATE_NORMAL);
1201 }
1202
1203 static void link_btn_released(GtkButton *button, gpointer data)
1204 {
1205         gtk_button_set_relief(button, GTK_RELIEF_NONE);
1206         gtk_widget_set_state(GTK_WIDGET(button), GTK_STATE_NORMAL);
1207 }
1208
1209 static void link_btn_clicked(GtkButton *button, gpointer data)
1210 {
1211         gchar *url = (gchar *)data;
1212         gtk_button_set_relief(button, GTK_RELIEF_NONE);
1213         gtk_widget_set_state(GTK_WIDGET(button), GTK_STATE_NORMAL);
1214         open_uri(url, prefs_common_get_uri_cmd());
1215 }
1216
1217 static void link_btn_unrealize(GtkButton *button, gpointer data)
1218 {
1219         gchar *url = (gchar *)data;
1220         g_signal_handlers_disconnect_by_func(G_OBJECT(button), 
1221                          G_CALLBACK(link_btn_clicked), url);
1222         g_free(url);
1223 }
1224
1225 GtkWidget *gtkut_get_link_btn(GtkWidget *window, const gchar *url, const gchar *label)
1226 {
1227         GtkWidget *btn;
1228         GtkWidget *btn_label;
1229 #if !GTK_CHECK_VERSION(3, 0, 0)
1230         GdkColormap *cmap;
1231         gboolean success[2];
1232 #endif
1233         GdkColor uri_color[2] = {{0, 0, 0, 0xffff}, {0, 0xffff, 0, 0}};
1234         gchar *local_url = NULL;
1235         if (!url)
1236                 return NULL;
1237
1238         gtkut_convert_int_to_gdk_color(prefs_common.uri_col,
1239                                                &uri_color[0]);
1240         gtkut_convert_int_to_gdk_color(prefs_common.uri_col,
1241                                                &uri_color[1]);
1242
1243         btn = gtk_button_new_with_label(label?label:url);
1244         gtk_button_set_relief(GTK_BUTTON(btn), GTK_RELIEF_NONE);
1245         btn_label = gtk_bin_get_child(GTK_BIN((btn)));
1246 #if !GTK_CHECK_VERSION(3, 0, 0)
1247         cmap = gdk_drawable_get_colormap(gtk_widget_get_window(window));
1248         gdk_colormap_alloc_colors(cmap, uri_color, 2, FALSE, TRUE, success);
1249         if (success[0] == TRUE && success[1] == TRUE) {
1250 #endif
1251                 GtkStyle *style;
1252                 gtk_widget_ensure_style(btn_label);
1253                 style = gtk_style_copy
1254                         (gtk_widget_get_style(btn_label));
1255                 style->fg[GTK_STATE_NORMAL]   = uri_color[0];
1256                 style->fg[GTK_STATE_ACTIVE]   = uri_color[1];
1257                 style->fg[GTK_STATE_PRELIGHT] = uri_color[0];
1258                 gtk_widget_set_style(btn_label, style);
1259 #if !GTK_CHECK_VERSION(3, 0, 0)
1260         } else
1261                 g_warning("color allocation failed\n");
1262 #endif
1263
1264         g_signal_connect(G_OBJECT(btn), "enter",
1265                          G_CALLBACK(link_btn_enter), window);
1266         g_signal_connect(G_OBJECT(btn), "leave",
1267                          G_CALLBACK(link_btn_leave), window);
1268         g_signal_connect(G_OBJECT(btn), "pressed",
1269                          G_CALLBACK(link_btn_pressed), window);
1270         g_signal_connect(G_OBJECT(btn), "released",
1271                          G_CALLBACK(link_btn_released), window);
1272                          
1273         local_url = g_strdup(url);
1274         g_signal_connect(G_OBJECT(btn), "clicked",
1275                          G_CALLBACK(link_btn_clicked), local_url);
1276         g_signal_connect(G_OBJECT(btn), "unrealize",
1277                          G_CALLBACK(link_btn_unrealize), local_url);
1278         return btn;
1279 }
1280
1281 static gboolean _combobox_separator_func(GtkTreeModel *model,
1282                 GtkTreeIter *iter, gpointer data)
1283 {
1284         gchar *txt = NULL;
1285
1286         cm_return_val_if_fail(model != NULL, FALSE);
1287
1288         gtk_tree_model_get(model, iter, COMBOBOX_TEXT, &txt, -1);
1289
1290         if( txt == NULL )
1291                 return TRUE;
1292         
1293         g_free(txt);
1294         return FALSE;
1295 }
1296
1297 GtkWidget *gtkut_sc_combobox_create(GtkWidget *eventbox, gboolean focus_on_click)
1298 {
1299         GtkWidget *combobox;
1300         GtkListStore *menu;
1301         GtkCellRenderer *rend;
1302
1303         menu = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_BOOLEAN);
1304
1305         combobox = gtk_combo_box_new_with_model(GTK_TREE_MODEL(menu));
1306
1307         rend = gtk_cell_renderer_text_new();
1308         gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combobox), rend, TRUE);
1309         gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combobox), rend,
1310                         "markup", COMBOBOX_TEXT,
1311                         "sensitive", COMBOBOX_SENS,
1312                         NULL);
1313
1314         if( eventbox != NULL )
1315                 gtk_container_add(GTK_CONTAINER(eventbox), combobox);
1316         gtk_combo_box_set_focus_on_click(GTK_COMBO_BOX(combobox), focus_on_click);
1317
1318         gtk_combo_box_set_row_separator_func(GTK_COMBO_BOX(combobox),
1319                         (GtkTreeViewRowSeparatorFunc)_combobox_separator_func, NULL, NULL);
1320
1321         return combobox;
1322 }
1323
1324 static void gtkutils_smooth_scroll_do(GtkWidget *widget, GtkAdjustment *vadj,
1325                                       gfloat old_value, gfloat last_value,
1326                                       gint step)
1327 {
1328         gint change_value;
1329         gboolean up;
1330         gint i;
1331
1332         if (old_value < last_value) {
1333                 change_value = last_value - old_value;
1334                 up = FALSE;
1335         } else {
1336                 change_value = old_value - last_value;
1337                 up = TRUE;
1338         }
1339
1340         for (i = step; i <= change_value; i += step) {
1341                 gtk_adjustment_set_value(vadj, old_value + (up ? -i : i));
1342                 g_signal_emit_by_name(G_OBJECT(vadj),
1343                                       "value_changed", 0);
1344         }
1345
1346         gtk_adjustment_set_value(vadj, last_value);
1347         g_signal_emit_by_name(G_OBJECT(vadj), "value_changed", 0);
1348
1349         gtk_widget_queue_draw(widget);
1350 }
1351
1352 static gboolean gtkutils_smooth_scroll_page(GtkWidget *widget, GtkAdjustment *vadj, gboolean up)
1353 {
1354         gfloat upper;
1355         gfloat page_incr;
1356         gfloat old_value;
1357         gfloat last_value;
1358
1359         page_incr = gtk_adjustment_get_page_increment(vadj);
1360         if (prefs_common.scroll_halfpage)
1361                 page_incr /= 2;
1362
1363         old_value = gtk_adjustment_get_value(vadj);
1364         if (!up) {
1365                 upper = gtk_adjustment_get_upper(vadj) - gtk_adjustment_get_page_size(vadj);
1366                 if (old_value < upper) {
1367                         last_value = old_value + page_incr;
1368                         last_value = MIN(last_value, upper);
1369
1370                         gtkutils_smooth_scroll_do(widget, vadj, old_value,
1371                                                   last_value,
1372                                                   prefs_common.scroll_step);
1373                 } else
1374                         return FALSE;
1375         } else {
1376                 if (old_value > 0.0) {
1377                         last_value = old_value - page_incr;
1378                         last_value = MAX(last_value, 0.0);
1379
1380                         gtkutils_smooth_scroll_do(widget, vadj, old_value,
1381                                                   last_value,
1382                                                   prefs_common.scroll_step);
1383                 } else
1384                         return FALSE;
1385         }
1386
1387         return TRUE;
1388 }
1389
1390 gboolean gtkutils_scroll_page(GtkWidget *widget, GtkAdjustment *vadj, gboolean up)
1391 {
1392         gfloat upper;
1393         gfloat page_incr;
1394         gfloat old_value;
1395
1396         if (prefs_common.enable_smooth_scroll)
1397                 return gtkutils_smooth_scroll_page(widget, vadj, up);
1398
1399         page_incr = gtk_adjustment_get_page_increment(vadj);
1400         if (prefs_common.scroll_halfpage)
1401                 page_incr /= 2;
1402
1403         old_value = gtk_adjustment_get_value(vadj);
1404         if (!up) {
1405                 upper = gtk_adjustment_get_upper(vadj) - gtk_adjustment_get_page_size(vadj);
1406                 if (old_value < upper) {
1407                         old_value += page_incr;
1408                         old_value = MIN(old_value, upper);
1409                         gtk_adjustment_set_value(vadj, old_value);
1410                         g_signal_emit_by_name(G_OBJECT(vadj),
1411                                               "value_changed", 0);
1412                 } else
1413                         return FALSE;
1414         } else {
1415                 if (old_value > 0.0) {
1416                         old_value -= page_incr;
1417                         old_value = MAX(old_value, 0.0);
1418                         gtk_adjustment_set_value(vadj, old_value);
1419                         g_signal_emit_by_name(G_OBJECT(vadj),
1420                                               "value_changed", 0);
1421                 } else
1422                         return FALSE;
1423         }
1424         return TRUE;
1425 }
1426
1427 static void gtkutils_smooth_scroll_one_line(GtkWidget *widget, GtkAdjustment *vadj, gboolean up)
1428 {
1429         gfloat upper;
1430         gfloat old_value;
1431         gfloat last_value;
1432
1433         old_value = gtk_adjustment_get_value(vadj);
1434         if (!up) {
1435                 upper = gtk_adjustment_get_upper(vadj) - gtk_adjustment_get_page_size(vadj);
1436                 if (old_value < upper) {
1437                         last_value = old_value + gtk_adjustment_get_step_increment(vadj);
1438                         last_value = MIN(last_value, upper);
1439
1440                         gtkutils_smooth_scroll_do(widget, vadj, old_value,
1441                                                   last_value,
1442                                                   prefs_common.scroll_step);
1443                 }
1444         } else {
1445                 if (old_value > 0.0) {
1446                         last_value = old_value - gtk_adjustment_get_step_increment(vadj);
1447                         last_value = MAX(last_value, 0.0);
1448
1449                         gtkutils_smooth_scroll_do(widget, vadj, old_value,
1450                                                   last_value,
1451                                                   prefs_common.scroll_step);
1452                 }
1453         }
1454 }
1455
1456 void gtkutils_scroll_one_line(GtkWidget *widget, GtkAdjustment *vadj, gboolean up)
1457 {
1458         gfloat upper;
1459         gfloat old_value;
1460
1461         if (prefs_common.enable_smooth_scroll) {
1462                 gtkutils_smooth_scroll_one_line(widget, vadj, up);
1463                 return;
1464         }
1465
1466         old_value = gtk_adjustment_get_value(vadj);
1467         if (!up) {
1468                 upper = gtk_adjustment_get_upper(vadj) - gtk_adjustment_get_page_size(vadj);
1469                 if (old_value < upper) {
1470                         old_value += gtk_adjustment_get_step_increment(vadj);
1471                         old_value = MIN(old_value, upper);
1472                         gtk_adjustment_set_value(vadj, old_value);
1473                         g_signal_emit_by_name(G_OBJECT(vadj),
1474                                               "value_changed", 0);
1475                 }
1476         } else {
1477                 if (old_value > 0.0) {
1478                         old_value -= gtk_adjustment_get_step_increment(vadj);
1479                         old_value = MAX(old_value, 0.0);
1480                         gtk_adjustment_set_value(vadj, old_value);
1481                         g_signal_emit_by_name(G_OBJECT(vadj),
1482                                               "value_changed", 0);
1483                 }
1484         }
1485 }
1486
1487 gboolean gtkut_tree_model_text_iter_prev(GtkTreeModel *model,
1488                                  GtkTreeIter *iter,
1489                                  const gchar* text)
1490 /* do the same as gtk_tree_model_iter_next, but _prev instead.
1491    to use with widgets with one text column (gtk_combo_box_new_text()
1492    and with GtkComboBoxEntry's for instance),
1493 */
1494 {
1495         GtkTreeIter cur_iter;
1496         gchar *cur_value;
1497         gboolean valid;
1498         gint count;
1499
1500         cm_return_val_if_fail(model != NULL, FALSE);
1501         cm_return_val_if_fail(iter != NULL, FALSE);
1502
1503         if (text == NULL || *text == '\0')
1504                 return FALSE;
1505
1506         valid = gtk_tree_model_get_iter_first(model, &cur_iter);
1507         count = 0;
1508         while (valid) {
1509                 gtk_tree_model_get(model, &cur_iter, 0, &cur_value, -1);
1510
1511                 if (strcmp(text, cur_value) == 0) {
1512                         if (count <= 0)
1513                                 return FALSE;
1514
1515                         return gtk_tree_model_iter_nth_child(model, iter, NULL, count - 1);
1516                 }
1517
1518                 valid = gtk_tree_model_iter_next(model, &cur_iter);
1519                 count++;
1520         }
1521         return FALSE;           
1522 }
1523
1524 gboolean gtkut_tree_model_get_iter_last(GtkTreeModel *model,
1525                                  GtkTreeIter *iter)
1526 /* do the same as gtk_tree_model_get_iter_first, but _last instead.
1527 */
1528 {
1529         gint count;
1530
1531         cm_return_val_if_fail(model != NULL, FALSE);
1532         cm_return_val_if_fail(iter != NULL, FALSE);
1533
1534         count = gtk_tree_model_iter_n_children(model, NULL);
1535
1536         if (count <= 0)
1537                 return FALSE;
1538
1539         return gtk_tree_model_iter_nth_child(model, iter, NULL, count - 1);
1540 }
1541
1542 GtkWidget *gtkut_window_new             (GtkWindowType   type,
1543                                          const gchar    *class)
1544 {
1545         GtkWidget *window = gtk_window_new(type);
1546         gtk_window_set_role(GTK_WINDOW(window), class);
1547         return window;
1548 }
1549
1550 static gboolean gtkut_tree_iter_comp(GtkTreeModel *model, 
1551                                      GtkTreeIter *iter1, 
1552                                      GtkTreeIter *iter2)
1553 {
1554         GtkTreePath *path1 = gtk_tree_model_get_path(model, iter1);
1555         GtkTreePath *path2 = gtk_tree_model_get_path(model, iter2);
1556         gboolean result;
1557
1558         result = gtk_tree_path_compare(path1, path2) == 0;
1559
1560         gtk_tree_path_free(path1);
1561         gtk_tree_path_free(path2);
1562         
1563         return result;
1564 }
1565
1566 /*!
1567  *\brief        Get selected row number.
1568  */
1569 gint gtkut_list_view_get_selected_row(GtkWidget *list_view)
1570 {
1571         GtkTreeView *view = GTK_TREE_VIEW(list_view);
1572         GtkTreeModel *model = gtk_tree_view_get_model(view);
1573         int n_rows = gtk_tree_model_iter_n_children(model, NULL);
1574         GtkTreeSelection *selection;
1575         GtkTreeIter iter;
1576         int row;
1577
1578         if (n_rows == 0) 
1579                 return -1;
1580         
1581         selection = gtk_tree_view_get_selection(view);
1582         if (!gtk_tree_selection_get_selected(selection, &model, &iter))
1583                 return -1;
1584         
1585         /* get all iterators and compare them... */
1586         for (row = 0; row < n_rows; row++) {
1587                 GtkTreeIter itern;
1588
1589                 gtk_tree_model_iter_nth_child(model, &itern, NULL, row);
1590                 if (gtkut_tree_iter_comp(model, &iter, &itern))
1591                         return row;
1592         }
1593         
1594         return -1;
1595 }
1596
1597 /*!
1598  *\brief        Select a row by its number.
1599  */
1600 gboolean gtkut_list_view_select_row(GtkWidget *list, gint row)
1601 {
1602         GtkTreeView *list_view = GTK_TREE_VIEW(list);
1603         GtkTreeSelection *selection = gtk_tree_view_get_selection(list_view);
1604         GtkTreeModel *model = gtk_tree_view_get_model(list_view);
1605         GtkTreeIter iter;
1606         GtkTreePath *path;
1607
1608         if (!gtk_tree_model_iter_nth_child(model, &iter, NULL, row))
1609                 return FALSE;
1610         
1611         gtk_tree_selection_select_iter(selection, &iter);
1612
1613         path = gtk_tree_model_get_path(model, &iter);
1614         gtk_tree_view_set_cursor(list_view, path, NULL, FALSE);
1615         gtk_tree_path_free(path);
1616         
1617         return TRUE;
1618 }
1619
1620 static GtkUIManager *gui_manager = NULL;
1621
1622 GtkUIManager *gtkut_create_ui_manager(void)
1623 {
1624         cm_return_val_if_fail(gui_manager == NULL, gui_manager);
1625         return (gui_manager = gtk_ui_manager_new());
1626 }
1627
1628 GtkUIManager *gtkut_ui_manager(void)
1629 {
1630         return gui_manager;
1631 }
1632
1633 typedef struct _ClawsIOClosure ClawsIOClosure;
1634
1635 struct _ClawsIOClosure
1636 {
1637   ClawsIOFunc function;
1638   GIOCondition condition;
1639   GDestroyNotify notify;
1640   gpointer data;
1641 };
1642
1643 static gboolean  
1644 claws_io_invoke (GIOChannel   *source,
1645                  GIOCondition  condition,
1646                  gpointer      data)
1647 {
1648   ClawsIOClosure *closure = data;
1649   int fd;
1650 #ifndef G_OS_WIN32
1651   fd = g_io_channel_unix_get_fd (source);
1652 #else
1653   fd = g_io_channel_win32_get_fd (source);
1654 #endif
1655   if (closure->condition & condition)
1656     closure->function (closure->data, fd, condition);
1657
1658   return TRUE;
1659 }
1660
1661 static void
1662 claws_io_destroy (gpointer data)
1663 {
1664   ClawsIOClosure *closure = data;
1665
1666   if (closure->notify)
1667     closure->notify (closure->data);
1668
1669   g_free (closure);
1670 }
1671
1672 gint
1673 claws_input_add    (gint              source,
1674                     GIOCondition      condition,
1675                     ClawsIOFunc       function,
1676                     gpointer          data,
1677                     gboolean          is_sock)
1678 {
1679   guint result;
1680   ClawsIOClosure *closure = g_new (ClawsIOClosure, 1);
1681   GIOChannel *channel;
1682
1683   closure->function = function;
1684   closure->condition = condition;
1685   closure->notify = NULL;
1686   closure->data = data;
1687
1688 #ifndef G_OS_WIN32
1689   channel = g_io_channel_unix_new (source);
1690 #else
1691   if (is_sock)
1692     channel = g_io_channel_win32_new_socket(source);
1693   else
1694     channel = g_io_channel_win32_new_fd(source);
1695 #endif
1696   result = g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, 
1697                                 claws_io_invoke,
1698                                 closure, claws_io_destroy);
1699   g_io_channel_unref (channel);
1700
1701   return result;
1702 }
1703
1704 void gtkut_widget_set_mapped(GtkWidget *widget, gboolean mapped)
1705 {
1706 #if GTK_CHECK_VERSION(2,20,0)
1707         gtk_widget_set_mapped(widget, mapped);
1708 #else
1709         if (mapped)
1710                 GTK_WIDGET_SET_FLAGS(widget, GTK_MAPPED);
1711         else
1712                 GTK_WIDGET_UNSET_FLAGS(widget, GTK_MAPPED);
1713 #endif
1714 }
1715
1716 void gtkut_widget_set_realized(GtkWidget *widget, gboolean realized)
1717 {
1718 #if GTK_CHECK_VERSION(2,20,0)
1719         gtk_widget_set_realized(widget, realized);
1720 #else
1721         if (realized)
1722                 GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);
1723         else
1724                 GTK_WIDGET_UNSET_FLAGS(widget, GTK_REALIZED);
1725 #endif
1726 }
1727
1728 void gtkut_widget_set_can_default(GtkWidget *widget, gboolean can_default)
1729 {
1730 #if GTK_CHECK_VERSION(2,20,0)
1731         gtk_widget_set_can_default(widget, can_default);
1732 #else
1733         if (can_default)
1734                 GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_DEFAULT);
1735         else
1736                 GTK_WIDGET_UNSET_FLAGS(widget, GTK_CAN_DEFAULT);
1737 #endif
1738 }
1739
1740 void gtkut_widget_set_receives_default(GtkWidget *widget, gboolean receives_default)
1741 {
1742 #if GTK_CHECK_VERSION(2,20,0)
1743         gtk_widget_set_receives_default(widget, receives_default);
1744 #else
1745         if (receives_default)
1746                 GTK_WIDGET_SET_FLAGS(widget, GTK_RECEIVES_DEFAULT);
1747         else
1748                 GTK_WIDGET_UNSET_FLAGS(widget, GTK_RECEIVES_DEFAULT);
1749 #endif
1750 }
1751
1752 void gtkut_widget_set_can_focus(GtkWidget *widget, gboolean can_focus)
1753 {
1754 #if GTK_CHECK_VERSION(2,20,0)
1755         gtk_widget_set_can_focus(widget, can_focus);
1756 #else
1757         if (can_focus)
1758                 GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);
1759         else
1760                 GTK_WIDGET_UNSET_FLAGS(widget, GTK_CAN_FOCUS);
1761 #endif
1762 }
1763
1764 void gtkut_widget_set_has_window(GtkWidget *widget, gboolean has_window)
1765 {
1766 #if GTK_CHECK_VERSION(2,20,0)
1767         gtk_widget_set_has_window(widget, has_window);
1768 #else
1769         if (has_window) /* Inverted logic there */
1770                 GTK_WIDGET_UNSET_FLAGS(widget, GTK_NO_WINDOW);
1771         else
1772                 GTK_WIDGET_SET_FLAGS(widget, GTK_NO_WINDOW);
1773 #endif
1774 }
1775
1776 /**
1777  * Load a pixbuf fitting inside the specified size. EXIF orientation is
1778  * respected if available.
1779  *
1780  * @param[in] filename          the file to load
1781  * @param[in] box_width         the max width (-1 for no resize)
1782  * @param[in] box_height        the max height (-1 for no resize)
1783  * @param[out] error            the possible load error
1784  *
1785  * @return a GdkPixbuf
1786  */
1787 GdkPixbuf *claws_load_pixbuf_fitting(GdkPixbuf *src_pixbuf, int box_width,
1788                                      int box_height)
1789 {
1790         gint w, h, orientation, angle;
1791         gint avail_width, avail_height;
1792         gboolean flip_horiz, flip_vert;
1793         const gchar *orient_str;
1794         GdkPixbuf *pixbuf, *t_pixbuf;
1795
1796         pixbuf = src_pixbuf;
1797
1798         if (pixbuf == NULL)
1799                 return NULL;
1800
1801         angle = 0;
1802         flip_horiz = flip_vert = FALSE;
1803
1804         /* EXIF orientation */
1805         orient_str = gdk_pixbuf_get_option(pixbuf, "orientation");
1806         if (orient_str != NULL && *orient_str != '\0') {
1807                 orientation = atoi(orient_str);
1808                 switch(orientation) {
1809                         /* See EXIF standard for different values */
1810                         case 1: break;
1811                         case 2: flip_horiz = 1;
1812                                 break;
1813                         case 3: angle = 180;
1814                                 break;
1815                         case 4: flip_vert = 1;
1816                                 break;
1817                         case 5: angle = 90;
1818                                 flip_horiz = 1;
1819                                 break;
1820                         case 6: angle = 270;
1821                                 break;
1822                         case 7: angle = 90;
1823                                 flip_vert = 1;
1824                                 break;
1825                         case 8: angle = 90;
1826                                 break;
1827                 }
1828         }
1829
1830         w = gdk_pixbuf_get_width(pixbuf);
1831         h = gdk_pixbuf_get_height(pixbuf);
1832
1833         if (angle == 90 || angle == 270) {
1834                 avail_height = box_width;
1835                 avail_width = box_height;
1836         } else {
1837                 avail_width = box_width;
1838                 avail_height = box_height;
1839         }
1840
1841         /* Scale first */
1842         if (box_width != -1 && box_height != -1 && avail_width - 100 > 0) {
1843                 if (w > avail_width) {
1844                         h = (avail_width * h) / w;
1845                         w = avail_width;
1846                 }
1847                 if (h > avail_height) {
1848                         w = (avail_height * w) / h;
1849                         h = avail_height;
1850                 }
1851                 t_pixbuf = gdk_pixbuf_scale_simple(pixbuf, 
1852                         w, h, GDK_INTERP_BILINEAR);
1853                 g_object_unref(pixbuf);
1854                 pixbuf = t_pixbuf;
1855         }
1856
1857         /* Rotate if needed */
1858         if (angle != 0) {
1859                 t_pixbuf = gdk_pixbuf_rotate_simple(pixbuf, angle);
1860                 g_object_unref(pixbuf);
1861                 pixbuf = t_pixbuf;
1862         }
1863
1864         /* Flip horizontally if needed */
1865         if (flip_horiz) {
1866                 t_pixbuf = gdk_pixbuf_flip(pixbuf, TRUE);
1867                 g_object_unref(pixbuf);
1868                 pixbuf = t_pixbuf;
1869         }
1870
1871         /* Flip vertically if needed */
1872         if (flip_vert) {
1873                 t_pixbuf = gdk_pixbuf_flip(pixbuf, FALSE);
1874                 g_object_unref(pixbuf);
1875                 pixbuf = t_pixbuf;
1876         }
1877
1878         return pixbuf;
1879 }
1880
1881 #if (defined USE_GNUTLS && GLIB_CHECK_VERSION(2,22,0))
1882 static void auto_configure_done(const gchar *hostname, gint port, gboolean ssl, AutoConfigureData *data)
1883 {
1884         if (hostname != NULL) {
1885                 if (data->hostname_entry)
1886                         gtk_entry_set_text(data->hostname_entry, hostname);
1887                 if (data->set_port)
1888                         gtk_toggle_button_set_active(data->set_port,
1889                                 (ssl && port == data->default_ssl_port) || (!ssl && port == data->default_port));
1890                 if (data->port)
1891                         gtk_spin_button_set_value(data->port, port);
1892                 else if (data->hostname_entry) {
1893                         gchar *tmp = g_strdup_printf("%s:%d", hostname, port);
1894                         gtk_entry_set_text(data->hostname_entry, tmp);
1895                         g_free(tmp);
1896                 }
1897
1898                 if (ssl && data->ssl_checkbtn) {
1899                         gtk_toggle_button_set_active(data->ssl_checkbtn, TRUE);
1900                         gtk_toggle_button_set_active(data->tls_checkbtn, FALSE);
1901                 } else if (data->tls_checkbtn) {
1902                         if (!GTK_IS_RADIO_BUTTON(data->ssl_checkbtn)) {
1903                                 /* Wizard where TLS is [x]SSL + [x]TLS */
1904                                 gtk_toggle_button_set_active(data->ssl_checkbtn, TRUE);
1905                         }
1906                         gtk_toggle_button_set_active(data->tls_checkbtn, TRUE);
1907                 }
1908
1909                 gtk_label_set_text(data->info_label, _("Done."));
1910         } else {
1911         gtk_label_set_text(data->info_label, _("Failed."));
1912         }
1913         gtk_widget_show(GTK_WIDGET(data->configure_button));
1914         gtk_widget_hide(GTK_WIDGET(data->cancel_button));
1915         g_free(data->domain);
1916         g_free(data);
1917 }
1918
1919 static void resolve_done(GObject *source, GAsyncResult *result, gpointer user_data)
1920 {
1921         AutoConfigureData *data = (AutoConfigureData *)user_data;
1922         GResolver *resolver = (GResolver *)source;
1923         GError *error = NULL;
1924         gchar *hostname = NULL;
1925         guint16 port;
1926         GList *answers, *cur;
1927         gboolean found = FALSE;
1928         gboolean abort = FALSE;
1929
1930         answers = g_resolver_lookup_service_finish(resolver, result, &error);
1931
1932         if (answers) {
1933                 for (cur = g_srv_target_list_sort(answers); cur; cur = cur->next) {
1934                         GSrvTarget *target = (GSrvTarget *)cur->data;
1935                         const gchar *h = g_srv_target_get_hostname(target);
1936                         port = g_srv_target_get_port(target);
1937                         if (h && strcmp(h,"") && port > 0) {
1938                                 hostname = g_strdup(h);
1939                                 found = TRUE;
1940                                 break;
1941                         }
1942                 }
1943                 g_resolver_free_targets(answers);
1944         } else if (error) {
1945                 if (error->code == G_IO_ERROR_CANCELLED)
1946                         abort = TRUE;
1947                 debug_print("error %s\n", error->message);
1948                 g_error_free(error);
1949         }
1950
1951         if (found) {
1952                 auto_configure_done(hostname, port, data->ssl_service != NULL, data);
1953         } else if (data->ssl_service && !abort) {
1954                 /* Fallback to TLS */
1955                 data->ssl_service = NULL;
1956                 auto_configure_service(data);
1957         } else {
1958                 auto_configure_done(NULL, 0, FALSE, data);
1959         }
1960         g_free(hostname);
1961         g_object_unref(resolver);
1962 }
1963
1964 void auto_configure_service(AutoConfigureData *data)
1965 {
1966         GResolver *resolver;
1967         const gchar *cur_service = data->ssl_service != NULL ? data->ssl_service : data->tls_service;
1968
1969         cm_return_if_fail(cur_service != NULL);
1970         cm_return_if_fail(data->domain != NULL);
1971
1972         resolver = g_resolver_get_default();
1973         if (resolver != NULL) {
1974                 gtk_label_set_text(data->info_label, _("Configuring..."));
1975                 gtk_widget_hide(GTK_WIDGET(data->configure_button));
1976                 gtk_widget_show(GTK_WIDGET(data->cancel_button));
1977                 g_resolver_lookup_service_async(resolver, cur_service, "tcp", data->domain,
1978                                         data->cancel, resolve_done, data);
1979         }
1980 }
1981 #endif