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