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