b3e48177ec2b5db979afb9ef9dff1c7b506dc727
[claws.git] / src / addressbook.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2003 Hiroyuki Yamamoto
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 2 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, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <gdk/gdkkeysyms.h>
29 #include <gtk/gtkwindow.h>
30 #include <gtk/gtksignal.h>
31 #include <gtk/gtkvbox.h>
32 #include <gtk/gtkscrolledwindow.h>
33 #include <gtk/gtkhpaned.h>
34 #include <gtk/gtkhbox.h>
35 #include <gtk/gtklabel.h>
36 #include <gtk/gtkentry.h>
37 #include <gtk/gtkctree.h>
38 #include <gtk/gtkclist.h>
39 #include <gtk/gtktable.h>
40 #include <gtk/gtkhbbox.h>
41 #include <gtk/gtkbutton.h>
42 #include <gtk/gtkmenu.h>
43 #include <gtk/gtkmenuitem.h>
44 #include <gtk/gtkitemfactory.h>
45 #include <string.h>
46 #include <setjmp.h>
47
48 #include "main.h"
49 #include "addressbook.h"
50 #include "manage_window.h"
51 #include "prefs_common.h"
52 #include "alertpanel.h"
53 #include "inputdialog.h"
54 #include "menu.h"
55 #include "stock_pixmap.h"
56 #include "xml.h"
57 #include "prefs_gtk.h"
58 #include "procmime.h"
59 #include "utils.h"
60 #include "gtkutils.h"
61 #include "codeconv.h"
62 #include "about.h"
63 #include "addr_compl.h"
64
65 #include "mgutils.h"
66 #include "addressitem.h"
67 #include "addritem.h"
68 #include "addrcache.h"
69 #include "addrbook.h"
70 #include "addrindex.h"
71 #include "addressadd.h"
72 #include "vcard.h"
73 #include "editvcard.h"
74 #include "editgroup.h"
75 #include "editaddress.h"
76 #include "editbook.h"
77 #include "importldif.h"
78 #include "importmutt.h"
79 #include "importpine.h"
80
81 #ifdef USE_JPILOT
82 #include "jpilot.h"
83 #include "editjpilot.h"
84 #endif
85
86 #ifdef USE_LDAP
87 #include <pthread.h>
88 #include "ldapserver.h"
89 #include "editldap.h"
90
91 #define ADDRESSBOOK_LDAP_BUSYMSG "Busy"
92 #endif
93
94 #include "addrquery.h"
95 #include "addrselect.h"
96 #include "addrclip.h"
97 #include "addrgather.h"
98 #include "adbookbase.h"
99 #include "exphtmldlg.h"
100 #include "expldifdlg.h"
101 #include "browseldap.h"
102
103 typedef enum
104 {
105         COL_SOURCES     = 0,
106         N_INDEX_COLS    = 1
107 } AddressIndexColumns;
108
109 typedef enum
110 {
111         COL_NAME        = 0,
112         COL_ADDRESS     = 1,
113         COL_REMARKS     = 2,
114         N_LIST_COLS     = 3
115 } AddressListColumns;
116
117 #define COL_NAME_WIDTH          164
118 #define COL_ADDRESS_WIDTH       156
119
120 #define COL_FOLDER_WIDTH        170
121 #define ADDRESSBOOK_WIDTH       640
122 #define ADDRESSBOOK_HEIGHT      360
123
124 #define ADDRESSBOOK_MSGBUF_SIZE 2048
125
126 static GdkPixmap *folderxpm;
127 static GdkBitmap *folderxpmmask;
128 static GdkPixmap *folderopenxpm;
129 static GdkBitmap *folderopenxpmmask;
130 static GdkPixmap *groupxpm;
131 static GdkBitmap *groupxpmmask;
132 static GdkPixmap *interfacexpm;
133 static GdkBitmap *interfacexpmmask;
134 static GdkPixmap *bookxpm;
135 static GdkBitmap *bookxpmmask;
136 static GdkPixmap *addressxpm;
137 static GdkBitmap *addressxpmmask;
138 static GdkPixmap *vcardxpm;
139 static GdkBitmap *vcardxpmmask;
140 static GdkPixmap *jpilotxpm;
141 static GdkBitmap *jpilotxpmmask;
142 static GdkPixmap *categoryxpm;
143 static GdkBitmap *categoryxpmmask;
144 static GdkPixmap *ldapxpm;
145 static GdkBitmap *ldapxpmmask;
146 static GdkPixmap *addrsearchxpm;
147 static GdkPixmap *addrsearchxpmmask;
148
149 /* Message buffer */
150 static gchar addressbook_msgbuf[ ADDRESSBOOK_MSGBUF_SIZE ];
151
152 /* Address list selection */
153 static AddrSelectList *_addressSelect_ = NULL;
154 static AddressClipboard *_clipBoard_ = NULL;
155
156 /* Address index file and interfaces */
157 static AddressIndex *_addressIndex_ = NULL;
158 static GList *_addressInterfaceList_ = NULL;
159 static GList *_addressIFaceSelection_ = NULL;
160 #define ADDRESSBOOK_IFACE_SELECTION "1/y,3/y,4/y,2/n"
161
162 static AddressBook_win addrbook;
163
164 static GHashTable *_addressBookTypeHash_ = NULL;
165 static GList *_addressBookTypeList_ = NULL;
166
167 static void addressbook_create                  (void);
168 static gint addressbook_close                   (void);
169 static void addressbook_button_set_sensitive    (void);
170
171 /* callback functions */
172 static void addressbook_del_clicked             (GtkButton      *button,
173                                                  gpointer        data);
174 static void addressbook_reg_clicked             (GtkButton      *button,
175                                                  gpointer        data);
176 static void addressbook_to_clicked              (GtkButton      *button,
177                                                  gpointer        data);
178 static void addressbook_lup_clicked             (GtkButton      *button,
179                                                  gpointer       data);
180 static void addressbook_close_clicked           (GtkButton      *button,
181                                                  gpointer       data);
182
183 static void addressbook_tree_selected   (GtkCTree       *ctree,
184                                                  GtkCTreeNode   *node,
185                                                  gint            column,
186                                                  gpointer        data);
187 static void addressbook_select_row_tree         (GtkCTree       *ctree,
188                                                  GtkCTreeNode   *node,
189                                                  gint            column,
190                                                  gpointer        data);
191 static void addressbook_list_row_selected       (GtkCTree       *clist,
192                                                  GtkCTreeNode   *node,
193                                                  gint            column,
194                                                  gpointer        data);
195 static void addressbook_list_row_unselected     (GtkCTree       *clist,
196                                                  GtkCTreeNode   *node,
197                                                  gint            column,
198                                                  gpointer        data);
199 static void addressbook_person_expand_node      (GtkCTree       *ctree,
200                                                  GList          *node,
201                                                  gpointer       *data );
202 static void addressbook_person_collapse_node    (GtkCTree       *ctree,
203                                                  GList          *node,
204                                                  gpointer       *data );
205
206 #if 0
207 static void addressbook_entry_changed           (GtkWidget      *widget);
208 #endif
209
210 static gboolean addressbook_list_button_pressed (GtkWidget      *widget,
211                                                  GdkEventButton *event,
212                                                  gpointer        data);
213 static gboolean addressbook_list_button_released(GtkWidget      *widget,
214                                                  GdkEventButton *event,
215                                                  gpointer        data);
216 static gboolean addressbook_tree_button_pressed (GtkWidget      *ctree,
217                                                  GdkEventButton *event,
218                                                  gpointer        data);
219 static gboolean addressbook_tree_button_released(GtkWidget      *ctree,
220                                                  GdkEventButton *event,
221                                                  gpointer        data);
222
223 static void addressbook_new_folder_cb           (gpointer        data,
224                                                  guint           action,
225                                                  GtkWidget      *widget);
226 static void addressbook_new_group_cb            (gpointer        data,
227                                                  guint           action,
228                                                  GtkWidget      *widget);
229 static void addressbook_treenode_edit_cb        (gpointer        data,
230                                                  guint           action,
231                                                  GtkWidget      *widget);
232 static void addressbook_treenode_delete_cb      (gpointer        data,
233                                                  guint           action,
234                                                  GtkWidget      *widget);
235
236 static void addressbook_change_node_name        (GtkCTreeNode   *node,
237                                                  const gchar    *name);
238
239 static void addressbook_new_address_cb          (gpointer        data,
240                                                  guint           action,
241                                                  GtkWidget      *widget);
242 static void addressbook_edit_address_cb         (gpointer        data,
243                                                  guint           action,
244                                                  GtkWidget      *widget);
245 static void addressbook_delete_address_cb       (gpointer        data,
246                                                  guint           action,
247                                                  GtkWidget      *widget);
248
249 static void close_cb                            (gpointer        data,
250                                                  guint           action,
251                                                  GtkWidget      *widget);
252 static void addressbook_file_save_cb            (gpointer        data,
253                                                  guint           action,
254                                                  GtkWidget      *widget);
255
256 /* Data source edit stuff */
257 static void addressbook_new_book_cb             (gpointer        data,
258                                                  guint           action,
259                                                  GtkWidget      *widget);
260 static void addressbook_new_vcard_cb            (gpointer        data,
261                                                  guint           action,
262                                                  GtkWidget      *widget);
263
264 #ifdef USE_JPILOT
265 static void addressbook_new_jpilot_cb           (gpointer        data,
266                                                  guint           action,
267                                                  GtkWidget      *widget);
268 #endif
269
270 #ifdef USE_LDAP
271 static void addressbook_new_ldap_cb             (gpointer        data,
272                                                  guint           action,
273                                                  GtkWidget      *widget);
274 #endif
275
276 static void addressbook_set_clist               (AddressObject  *obj,
277                                                  gboolean        refresh);
278
279 static void addressbook_load_tree               (void);
280 void addressbook_read_file                      (void);
281
282 static GtkCTreeNode *addressbook_add_object     (GtkCTreeNode   *node,
283                                                  AddressObject  *obj);
284 static void addressbook_treenode_remove_item    ( void );
285
286 static AddressDataSource *addressbook_find_datasource
287                                                 (GtkCTreeNode   *node );
288
289 static AddressBookFile *addressbook_get_book_file(void);
290
291 static GtkCTreeNode *addressbook_node_add_folder
292                                                 (GtkCTreeNode   *node,
293                                                 AddressDataSource *ds,
294                                                 ItemFolder      *itemFolder,
295                                                 AddressObjectType otype);
296 static GtkCTreeNode *addressbook_node_add_group (GtkCTreeNode   *node,
297                                                 AddressDataSource *ds,
298                                                 ItemGroup       *itemGroup);
299 static void addressbook_tree_remove_children    (GtkCTree       *ctree,
300                                                 GtkCTreeNode    *parent);
301 static void addressbook_move_nodes_up           (GtkCTree       *ctree,
302                                                 GtkCTreeNode    *node);
303 static GtkCTreeNode *addressbook_find_group_node (GtkCTreeNode  *parent,
304                                                    ItemGroup    *group);
305 static gboolean addressbook_entry_key_pressed   (GtkWidget      *widget,
306                                                  GdkEventKey    *event,
307                                                  gpointer        data);
308 static gint addressbook_treenode_compare_func   (GtkCList       *clist,
309                                                  gconstpointer   ptr1,
310                                                  gconstpointer   ptr2);
311 static gint addressbook_list_compare_func       (GtkCList       *clist,
312                                                  gconstpointer   ptr1,
313                                                  gconstpointer   ptr2);
314 static void addressbook_folder_load_one_person  (GtkCTree *clist, 
315                                                  ItemPerson *person,  
316                                                  AddressTypeControlItem *atci, 
317                                                  AddressTypeControlItem *atciMail);
318 static void addressbook_folder_refresh_one_person(GtkCTree *clist, 
319                                                   ItemPerson *person);
320 static void addressbook_folder_remove_one_person(GtkCTree *clist, 
321                                                  ItemPerson *person);
322 static void addressbook_folder_remove_node      (GtkCTree *clist, 
323                                                  GtkCTreeNode *node);
324
325 /* LUT's and IF stuff */
326 static void addressbook_free_treenode           ( gpointer data );
327 AddressTypeControlItem *addrbookctl_lookup      (gint            ot);
328 AddressTypeControlItem *addrbookctl_lookup_iface(AddressIfType   ifType);
329
330 void addrbookctl_build_map                      (GtkWidget      *window);
331 void addrbookctl_build_iflist                   (void);
332 AdapterInterface *addrbookctl_find_interface    (AddressIfType   ifType);
333 void addrbookctl_build_ifselect                 (void);
334
335 static void addrbookctl_free_interface          (AdapterInterface *adapter);
336 static void addrbookctl_free_datasource         (AdapterDSource   *adapter);
337 static void addrbookctl_free_folder             (AdapterFolder    *adapter);
338 static void addrbookctl_free_group              (AdapterGroup     *adapter);
339
340 static void addressbook_list_select_clear       ( void );
341 static void addressbook_list_select_add         ( AddrItemObject    *aio,
342                                                   AddressDataSource *ds );
343 static void addressbook_list_select_remove      ( AddrItemObject    *aio );
344
345 static void addressbook_import_ldif_cb          ( void );
346 static void addressbook_import_mutt_cb          ( void );
347 static void addressbook_import_pine_cb          ( void );
348 static void addressbook_export_html_cb          ( void );
349 static void addressbook_export_ldif_cb          ( void );
350 static void addressbook_clip_cut_cb             ( void );
351 static void addressbook_clip_copy_cb            ( void );
352 static void addressbook_clip_paste_cb           ( void );
353 static void addressbook_treenode_cut_cb         ( void );
354 static void addressbook_treenode_copy_cb        ( void );
355 static void addressbook_treenode_paste_cb       ( void );
356
357 static void addressbook_mail_to_cb              ( void );
358
359 #ifdef USE_LDAP
360 static void addressbook_browse_entry_cb         ( void );
361 #endif
362 static void addressbook_edit_clicked(GtkButton *button, gpointer data);
363
364 static void addressbook_start_drag(GtkWidget *widget, gint button, 
365                                    GdkEvent *event,
366                                    void *data);
367 static void addressbook_drag_data_get(GtkWidget        *widget,
368                                      GdkDragContext   *drag_context,
369                                      GtkSelectionData *selection_data,
370                                      guint             info,
371                                      guint             time,
372                                      void             *data);
373 static gboolean addressbook_drag_motion_cb(GtkWidget      *widget,
374                                           GdkDragContext *context,
375                                           gint            x,
376                                           gint            y,
377                                           guint           time,
378                                           void           *data);
379 static void addressbook_drag_leave_cb(GtkWidget      *widget,
380                                      GdkDragContext *context,
381                                      guint           time,
382                                      void           *data);
383 static void addressbook_drag_received_cb(GtkWidget        *widget,
384                                         GdkDragContext   *drag_context,
385                                         gint              x,
386                                         gint              y,
387                                         GtkSelectionData *data,
388                                         guint             info,
389                                         guint             time,
390                                         void             *pdata);
391 static void addressbook_list_menu_setup( void );
392
393 static GtkTargetEntry addressbook_drag_types[] =
394 {
395         {"text/plain", GTK_TARGET_SAME_APP, TARGET_DUMMY}
396 };
397
398 static GtkTargetList *addressbook_target_list = NULL;
399
400
401 static GtkItemFactoryEntry addressbook_entries[] =
402 {
403         {N_("/_Book"),                  NULL,           NULL, 0, "<Branch>"},
404         {N_("/_Book/New _Book"),        "<control>B",   addressbook_new_book_cb,        0, NULL},
405         {N_("/_Book/New _Folder"),      "<control>R",   addressbook_new_folder_cb,      0, NULL},
406         {N_("/_Book/New _vCard"),       "<control><shift>D",    addressbook_new_vcard_cb,       0, NULL},
407 #ifdef USE_JPILOT
408         {N_("/_Book/New _JPilot"),      "<control>J",   addressbook_new_jpilot_cb,      0, NULL},
409 #endif
410 #ifdef USE_LDAP
411         {N_("/_Book/New _Server"),      "<control><shift>S",    addressbook_new_ldap_cb,        0, NULL},
412 #endif
413         {N_("/_Book/---"),              NULL,           NULL, 0, "<Separator>"},
414         {N_("/_Book/_Edit book"),       NULL,           addressbook_treenode_edit_cb,   0, NULL},
415         {N_("/_Book/_Delete book"),     NULL,           addressbook_treenode_delete_cb, 0, NULL},
416         {N_("/_Book/---"),              NULL,           NULL, 0, "<Separator>"},
417         {N_("/_Book/_Save"),            "<control>S",   addressbook_file_save_cb,       0, NULL},
418         {N_("/_Book/_Close"),           "<control>W",   close_cb,                       0, NULL},
419         {N_("/_Address"),                       NULL,           NULL, 0, "<Branch>"},
420         {N_("/_Address/C_ut"),          "<control>X",   addressbook_clip_cut_cb,        0, NULL},
421         {N_("/_Address/_Copy"),         "<control>C",   addressbook_clip_copy_cb,       0, NULL},
422         {N_("/_Address/_Paste"),        "<control>V",   addressbook_clip_paste_cb,      0, NULL},
423         {N_("/_Address/---"),           NULL,           NULL, 0, "<Separator>"},
424         {N_("/_Address/_Edit"),         "<control>Return",addressbook_edit_address_cb,    0, NULL},
425         {N_("/_Address/_Delete"),       "<control>D",   addressbook_delete_address_cb,  0, NULL},
426         {N_("/_Address/---"),           NULL,           NULL, 0, "<Separator>"},
427         {N_("/_Address/New _Address"),  "<control>N",   addressbook_new_address_cb,     0, NULL},
428         {N_("/_Address/New _Group"),    "<control>G",   addressbook_new_group_cb,       0, NULL},
429         {N_("/_Address/---"),           NULL,           NULL, 0, "<Separator>"},
430         {N_("/_Address/_Mail To"),      NULL,           addressbook_mail_to_cb,         0, NULL},
431         {N_("/_Tools"),                 NULL,           NULL, 0, "<Branch>"},
432         {N_("/_Tools/Import _LDIF file..."), NULL,      addressbook_import_ldif_cb,     0, NULL},
433         {N_("/_Tools/Import M_utt file..."), NULL,      addressbook_import_mutt_cb,     0, NULL},
434         {N_("/_Tools/Import _Pine file..."), NULL,      addressbook_import_pine_cb,     0, NULL},
435         {N_("/_Tools/---"),             NULL,           NULL, 0, "<Separator>"},
436         {N_("/_Tools/Export _HTML..."), NULL,           addressbook_export_html_cb,     0, NULL},
437         {N_("/_Tools/Export LDI_F..."), NULL,           addressbook_export_ldif_cb,     0, NULL},
438         {N_("/_Help"),                  NULL,           NULL, 0, "<Branch>"},
439         {N_("/_Help/_About"),           NULL,           about_show, 0, NULL}
440 };
441
442 static GtkItemFactoryEntry addressbook_tree_popup_entries[] =
443 {
444         {N_("/_Edit"),          NULL, addressbook_treenode_edit_cb,   0, NULL},
445         {N_("/_Delete"),        NULL, addressbook_treenode_delete_cb, 0, NULL},
446         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
447         {N_("/New _Folder"),    NULL, addressbook_new_folder_cb,      0, NULL},
448         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
449         {N_("/C_ut"),           NULL, addressbook_treenode_cut_cb,    0, NULL},
450         {N_("/_Copy"),          NULL, addressbook_treenode_copy_cb,   0, NULL},
451         {N_("/_Paste"),         NULL, addressbook_treenode_paste_cb,  0, NULL}
452 };
453
454 static GtkItemFactoryEntry addressbook_list_popup_entries[] =
455 {
456         {N_("/_Edit"),          NULL, addressbook_edit_address_cb,   0, NULL},
457         {N_("/_Delete"),        NULL, addressbook_delete_address_cb, 0, NULL},
458         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
459         {N_("/New _Address"),   NULL, addressbook_new_address_cb,    0, NULL},
460         {N_("/New _Group"),     NULL, addressbook_new_group_cb,      0, NULL},
461         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
462         {N_("/C_ut"),           NULL, addressbook_clip_cut_cb,       0, NULL},
463         {N_("/_Copy"),          NULL, addressbook_clip_copy_cb,      0, NULL},
464         {N_("/_Paste"),         NULL, addressbook_clip_paste_cb,     0, NULL},
465         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
466 /*      {N_("/Pa_ste Address"), NULL, addressbook_clip_paste_address_cb, 0, NULL},*/
467         {N_("/_Mail To"),       NULL, addressbook_mail_to_cb,            0, NULL},
468 #ifdef USE_LDAP
469         {N_("/_Browse Entry"),  NULL, addressbook_browse_entry_cb,       0, NULL},
470 #endif  
471 };
472
473 /**
474  * Structure of error message table.
475  */
476 typedef struct _ErrMsgTableEntry ErrMsgTableEntry;
477 struct _ErrMsgTableEntry {
478         gint    code;
479         gchar   *description;
480 };
481
482 static gchar *_errMsgUnknown_ = N_( "Unknown" );
483
484 /**
485  * Lookup table of error messages for general errors. Note that a NULL
486  * description signifies the end of the table.
487  */
488 static ErrMsgTableEntry _lutErrorsGeneral_[] = {
489         { MGU_SUCCESS,          N_("Success") },
490         { MGU_BAD_ARGS,         N_("Bad arguments") },
491         { MGU_NO_FILE,          N_("File not specified") },
492         { MGU_OPEN_FILE,        N_("Error opening file") },
493         { MGU_ERROR_READ,       N_("Error reading file") },
494         { MGU_EOF,              N_("End of file encountered") },
495         { MGU_OO_MEMORY,        N_("Error allocating memory") },
496         { MGU_BAD_FORMAT,       N_("Bad file format") },
497         { MGU_ERROR_WRITE,      N_("Error writing to file") },
498         { MGU_OPEN_DIRECTORY,   N_("Error opening directory") },
499         { MGU_NO_PATH,          N_("No path specified") },
500         { 0,                    NULL }
501 };
502
503 #ifdef USE_LDAP
504 /**
505  * Lookup table of error messages for LDAP errors.
506  */
507 static ErrMsgTableEntry _lutErrorsLDAP_[] = {
508         { LDAPRC_SUCCESS,       N_("Success") },
509         { LDAPRC_CONNECT,       N_("Error connecting to LDAP server") },
510         { LDAPRC_INIT,          N_("Error initializing LDAP") },
511         { LDAPRC_BIND,          N_("Error binding to LDAP server") },
512         { LDAPRC_SEARCH,        N_("Error searching LDAP database") },
513         { LDAPRC_TIMEOUT,       N_("Timeout performing LDAP operation") },
514         { LDAPRC_CRITERIA,      N_("Error in LDAP search criteria") },
515         { LDAPRC_NOENTRIES,     N_("No LDAP entries found for search criteria") },
516         { LDAPRC_STOP_FLAG,     N_("LDAP search terminated on request") },
517         { LDAPRC_TLS,           N_("Error starting TLS connection") },
518         { 0,                    NULL }
519 };
520 #endif
521
522 /**
523  * Lookup message for specified error code.
524  * \param lut  Lookup table.
525  * \param code Code to lookup.
526  * \return Description associated to code.
527  */
528 static gchar *addressbook_err2string( ErrMsgTableEntry lut[], gint code ) {
529         gchar *desc = NULL;
530         ErrMsgTableEntry entry;
531         gint i;
532
533         for( i = 0; ; i++ ) {
534                 entry = lut[ i ];
535                 if( entry.description == NULL ) break;
536                 if( entry.code == code ) {
537                         desc = entry.description;
538                         break;
539                 }
540         }
541         if( ! desc ) {
542                 desc = _errMsgUnknown_;
543         }
544         return desc;
545 }
546
547 static gboolean lastCanLookup = FALSE;
548
549 void addressbook_show_buttons(gboolean add_and_delete, gboolean lookup, gboolean mail_ops)
550 {
551         if (add_and_delete) {
552                 gtk_widget_show(addrbook.edit_btn);
553                 gtk_widget_show(addrbook.del_btn);
554                 gtk_widget_show(addrbook.reg_btn);
555         } else {
556                 gtk_widget_hide(addrbook.edit_btn);
557                 gtk_widget_hide(addrbook.del_btn);
558                 gtk_widget_hide(addrbook.reg_btn);
559         }
560         
561         if (lookup) {
562                 gtk_widget_show(addrbook.lup_btn);
563                 gtk_widget_show(addrbook.entry);
564                 gtk_widget_show(addrbook.label);
565         } else {
566                 gtk_widget_hide(addrbook.lup_btn);
567                 gtk_widget_hide(addrbook.entry);
568                 gtk_widget_hide(addrbook.label);
569         }
570
571         lastCanLookup = lookup;
572
573         if (mail_ops) {
574                 gtk_widget_show(addrbook.to_btn);
575                 gtk_widget_show(addrbook.cc_btn);
576                 gtk_widget_show(addrbook.bcc_btn);
577         } else {
578                 gtk_widget_hide(addrbook.to_btn);
579                 gtk_widget_hide(addrbook.cc_btn);
580                 gtk_widget_hide(addrbook.bcc_btn);
581         }
582 }
583
584 void addressbook_open(Compose *target)
585 {
586         /* Initialize all static members */
587         if( _clipBoard_ == NULL ) {
588                 _clipBoard_ = addrclip_create();
589         }
590         if( _addressIndex_ != NULL ) {
591                 addrclip_set_index( _clipBoard_, _addressIndex_ );
592         }
593         if( _addressSelect_ == NULL ) {
594                 _addressSelect_ = addrselect_list_create();
595         }
596         if (!addrbook.window) {
597                 addressbook_read_file();
598                 addressbook_create();
599                 addressbook_load_tree();
600                 gtk_sctree_select( GTK_SCTREE(addrbook.ctree),
601                                  GTK_CTREE_NODE(GTK_CLIST(addrbook.ctree)->row_list));
602         }
603         else {
604                 gtk_widget_hide(addrbook.window);
605         }
606
607         gtk_widget_show_all(addrbook.window);
608         addressbook_show_buttons(target == NULL, lastCanLookup, target != NULL);
609         addressbook_set_target_compose(target);
610 }
611
612 /**
613  * Destroy addressbook.
614  */
615 void addressbook_destroy( void ) {
616         /* Free up address stuff */
617         if( _addressSelect_ != NULL ) {
618                 addrselect_list_free( _addressSelect_ );
619         }
620         if( _clipBoard_ != NULL ) {
621                 addrclip_free( _clipBoard_ );
622         }
623         if( _addressIndex_ != NULL ) {
624                 addrindex_free_index( _addressIndex_ );
625                 addrindex_teardown();
626         }
627         _addressSelect_ = NULL;
628         _clipBoard_ = NULL;
629         _addressIndex_ = NULL;
630 }
631
632 void addressbook_set_target_compose(Compose *target)
633 {
634         addrbook.target_compose = target;
635         addressbook_button_set_sensitive();
636 }
637
638 Compose *addressbook_get_target_compose(void)
639 {
640         return addrbook.target_compose;
641 }
642
643 /**
644  * Refresh addressbook and save to file(s).
645  */
646 void addressbook_refresh( void )
647 {
648         if (addrbook.window) {
649                 if (addrbook.treeSelected) {
650                         gtk_sctree_select( GTK_SCTREE(addrbook.ctree),
651                                          addrbook.treeSelected);
652                 }
653         }
654         addressbook_export_to_file();
655 }
656
657 static gboolean key_pressed(GtkWidget *widget, GdkEventKey *event, gpointer data)
658 {
659         if (event && event->keyval == GDK_Escape)
660                 addressbook_close();
661         else if (event && event->keyval == GDK_Delete)
662                 addressbook_del_clicked(NULL, NULL);
663         return FALSE;
664 }
665
666 /*!
667  *\brief        Save Gtk object size to prefs dataset
668  */
669 static void addressbook_size_allocate_cb(GtkWidget *widget,
670                                          GtkAllocation *allocation)
671 {
672         g_return_if_fail(allocation != NULL);
673
674         prefs_common.addressbookwin_width = allocation->width;
675         prefs_common.addressbookwin_height = allocation->height;
676 }
677
678 /*
679 * Create the address book widgets. The address book contains two CTree widgets: the
680 * address index tree on the left and the address list on the right.
681 *
682 * The address index tree displays a hierarchy of interfaces and groups. Each node in
683 * this tree is linked to an address Adapter. Adapters have been created for interfaces,
684 * data sources and folder objects.
685 *
686 * The address list displays group, person and email objects. These items are linked
687 * directly to ItemGroup, ItemPerson and ItemEMail objects inside the address book data
688 * sources.
689 *
690 * In the tradition of MVC architecture, the data stores have been separated from the
691 * GUI components. The addrindex.c file provides the interface to all data stores.
692 */
693 static void addressbook_create(void)
694 {
695         GtkWidget *window;
696         GtkWidget *vbox;
697         GtkWidget *menubar;
698         GtkWidget *vbox2;
699         GtkWidget *ctree_swin;
700         GtkWidget *ctree;
701         GtkWidget *clist_vbox;
702         GtkWidget *clist_swin;
703         GtkWidget *clist;
704         GtkWidget *paned;
705         GtkWidget *hbox;
706         GtkWidget *label;
707         GtkWidget *entry;
708         GtkWidget *statusbar;
709         GtkWidget *hbbox;
710         GtkWidget *hsbox;
711         GtkWidget *del_btn;
712         GtkWidget *edit_btn;
713         GtkWidget *reg_btn;
714         GtkWidget *lup_btn;
715         GtkWidget *to_btn;
716         GtkWidget *cc_btn;
717         GtkWidget *bcc_btn;
718         GtkWidget *close_btn;
719         GtkWidget *tree_popup;
720         GtkWidget *list_popup;
721         GtkItemFactory *tree_factory;
722         GtkItemFactory *list_factory;
723         GtkItemFactory *menu_factory;
724         gint n_entries;
725         GList *nodeIf;
726
727         gchar *index_titles[N_INDEX_COLS];
728         gchar *list_titles[N_LIST_COLS];
729         gchar *text;
730         gint i;
731
732         static GdkGeometry geometry;
733
734         debug_print("Creating addressbook window...\n");
735
736         index_titles[COL_SOURCES] = _("Sources");
737         list_titles[COL_NAME]    = _("Name");
738         list_titles[COL_ADDRESS] = _("E-Mail address");
739         list_titles[COL_REMARKS] = _("Remarks");
740
741         /* Address book window */
742         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
743         gtk_window_set_title(GTK_WINDOW(window), _("Address book"));
744         gtk_window_set_resizable(GTK_WINDOW(window), TRUE);
745         gtk_widget_realize(window);
746
747         g_signal_connect(G_OBJECT(window), "delete_event",
748                          G_CALLBACK(addressbook_close), NULL);
749         g_signal_connect(G_OBJECT(window), "size_allocate",
750                          G_CALLBACK(addressbook_size_allocate_cb), NULL);
751         g_signal_connect(G_OBJECT(window), "key_press_event",
752                          G_CALLBACK(key_pressed), NULL);
753         MANAGE_WINDOW_SIGNALS_CONNECT(window);
754
755         vbox = gtk_vbox_new(FALSE, 0);
756         gtk_container_add(GTK_CONTAINER(window), vbox);
757
758         /* Menu bar */
759         n_entries = sizeof(addressbook_entries) /
760                 sizeof(addressbook_entries[0]);
761         menubar = menubar_create(window, addressbook_entries, n_entries,
762                                  "<AddressBook>", NULL);
763         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
764         menu_factory = gtk_item_factory_from_widget(menubar);
765
766         vbox2 = gtk_vbox_new(FALSE, BORDER_WIDTH);
767         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
768         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
769
770         ctree_swin = gtk_scrolled_window_new(NULL, NULL);
771         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(ctree_swin),
772                                        GTK_POLICY_AUTOMATIC,
773                                        GTK_POLICY_AUTOMATIC);
774         gtk_widget_set_size_request(ctree_swin, COL_FOLDER_WIDTH + 40, -1);
775
776         /* Address index */
777         ctree = gtk_sctree_new_with_titles(N_INDEX_COLS, 0, index_titles);
778         gtk_container_add(GTK_CONTAINER(ctree_swin), ctree);
779         gtk_clist_set_selection_mode(GTK_CLIST(ctree), GTK_SELECTION_BROWSE);
780         gtk_clist_set_column_width(GTK_CLIST(ctree), 0, COL_FOLDER_WIDTH);
781         gtk_ctree_set_line_style(GTK_CTREE(ctree), GTK_CTREE_LINES_DOTTED);
782         gtk_ctree_set_expander_style(GTK_CTREE(ctree),
783                                      GTK_CTREE_EXPANDER_SQUARE);
784         gtk_ctree_set_indent(GTK_CTREE(ctree), CTREE_INDENT);
785         gtk_clist_set_compare_func(GTK_CLIST(ctree),
786                                    addressbook_treenode_compare_func);
787
788         g_signal_connect(G_OBJECT(ctree), "tree_select_row",
789                          G_CALLBACK(addressbook_tree_selected), NULL);
790         g_signal_connect(G_OBJECT(ctree), "button_press_event",
791                          G_CALLBACK(addressbook_tree_button_pressed),
792                          NULL);
793         g_signal_connect(G_OBJECT(ctree), "button_release_event",
794                          G_CALLBACK(addressbook_tree_button_released),
795                          NULL);
796         /* TEMPORARY */
797         g_signal_connect(G_OBJECT(ctree), "select_row",
798                          G_CALLBACK(addressbook_select_row_tree), NULL);
799
800         gtk_drag_dest_set(ctree, GTK_DEST_DEFAULT_ALL & ~GTK_DEST_DEFAULT_HIGHLIGHT,
801                           addressbook_drag_types, 1,
802                           GDK_ACTION_MOVE | GDK_ACTION_COPY | GDK_ACTION_DEFAULT);
803         g_signal_connect(G_OBJECT(ctree), "drag_motion",
804                          G_CALLBACK(addressbook_drag_motion_cb),
805                          ctree);
806         g_signal_connect(G_OBJECT(ctree), "drag_leave",
807                          G_CALLBACK(addressbook_drag_leave_cb),
808                          ctree);
809         g_signal_connect(G_OBJECT(ctree), "drag_data_received",
810                          G_CALLBACK(addressbook_drag_received_cb),
811                          ctree);
812
813         clist_vbox = gtk_vbox_new(FALSE, 4);
814
815         clist_swin = gtk_scrolled_window_new(NULL, NULL);
816         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(clist_swin),
817                                        GTK_POLICY_AUTOMATIC,
818                                        GTK_POLICY_AUTOMATIC);
819         gtk_box_pack_start(GTK_BOX(clist_vbox), clist_swin, TRUE, TRUE, 0);
820
821         /* Address list */
822         clist = gtk_sctree_new_with_titles(N_LIST_COLS, 0, list_titles);
823         gtk_container_add(GTK_CONTAINER(clist_swin), clist);
824         gtk_clist_set_selection_mode(GTK_CLIST(clist), GTK_SELECTION_EXTENDED);
825         gtk_ctree_set_line_style(GTK_CTREE(clist), GTK_CTREE_LINES_NONE);
826         gtk_ctree_set_expander_style(GTK_CTREE(clist), GTK_CTREE_EXPANDER_SQUARE);
827         gtk_ctree_set_indent(GTK_CTREE(clist), CTREE_INDENT);
828         gtk_clist_set_column_width(GTK_CLIST(clist), COL_NAME,
829                                    COL_NAME_WIDTH);
830         gtk_clist_set_column_width(GTK_CLIST(clist), COL_ADDRESS,
831                                    COL_ADDRESS_WIDTH);
832         gtk_clist_set_compare_func(GTK_CLIST(clist),
833                                    addressbook_list_compare_func);
834
835         for (i = 0; i < N_LIST_COLS; i++)
836                 GTK_WIDGET_UNSET_FLAGS(GTK_CLIST(clist)->column[i].button,
837                                        GTK_CAN_FOCUS);
838
839         g_signal_connect(G_OBJECT(clist), "tree_select_row",
840                          G_CALLBACK(addressbook_list_row_selected), NULL);
841         g_signal_connect(G_OBJECT(clist), "tree_unselect_row",
842                          G_CALLBACK(addressbook_list_row_unselected), NULL);
843         g_signal_connect(G_OBJECT(clist), "button_press_event",
844                          G_CALLBACK(addressbook_list_button_pressed),
845                          NULL);
846         g_signal_connect(G_OBJECT(clist), "button_release_event",
847                          G_CALLBACK(addressbook_list_button_released),
848                          NULL);
849         g_signal_connect(G_OBJECT(clist), "tree_expand",
850                          G_CALLBACK(addressbook_person_expand_node), NULL );
851         g_signal_connect(G_OBJECT(clist), "tree_collapse",
852                          G_CALLBACK(addressbook_person_collapse_node), NULL );
853         g_signal_connect(G_OBJECT(clist), "start_drag",
854                          G_CALLBACK(addressbook_start_drag), NULL);
855         g_signal_connect(G_OBJECT(clist), "drag_data_get",
856                          G_CALLBACK(addressbook_drag_data_get), NULL);  
857         hbox = gtk_hbox_new(FALSE, 4);
858         gtk_box_pack_start(GTK_BOX(clist_vbox), hbox, FALSE, FALSE, 0);
859
860         label = gtk_label_new(_("Lookup name:"));
861         gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);
862
863         entry = gtk_entry_new();
864         gtk_box_pack_start(GTK_BOX(hbox), entry, TRUE, TRUE, 0);
865
866         address_completion_register_entry(GTK_ENTRY(entry));
867
868         g_signal_connect(G_OBJECT(entry), "key_press_event",
869                          G_CALLBACK(addressbook_entry_key_pressed),
870                          NULL);
871 #if 0
872         g_signal_connect(G_OBJECT(entry), "changed",
873                          G_CALLBACK(addressbook_entry_changed), NULL);
874 #endif
875
876         paned = gtk_hpaned_new();
877         gtk_box_pack_start(GTK_BOX(vbox2), paned, TRUE, TRUE, 0);
878         gtk_paned_add1(GTK_PANED(paned), ctree_swin);
879         gtk_paned_add2(GTK_PANED(paned), clist_vbox);
880
881         /* Status bar */
882         hsbox = gtk_hbox_new(FALSE, 0);
883         gtk_box_pack_end(GTK_BOX(vbox), hsbox, FALSE, FALSE, BORDER_WIDTH);
884         statusbar = gtk_statusbar_new();
885         gtk_box_pack_start(GTK_BOX(hsbox), statusbar, TRUE, TRUE, BORDER_WIDTH);
886
887         /* Button panel */
888         hbbox = gtk_hbutton_box_new();
889         gtk_button_box_set_layout(GTK_BUTTON_BOX(hbbox), GTK_BUTTONBOX_END);
890         gtk_button_box_set_spacing(GTK_BUTTON_BOX(hbbox), 2);
891         gtk_container_set_border_width(GTK_CONTAINER(hbbox), 4);
892         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
893
894 #if GTK_CHECK_VERSION(2, 6, 0)
895         edit_btn = gtk_button_new_from_stock(GTK_STOCK_EDIT);
896 #else
897         edit_btn = gtk_button_new_from_stock(GTK_STOCK_PROPERTIES);
898 #endif
899         GTK_WIDGET_SET_FLAGS(edit_btn, GTK_CAN_DEFAULT);
900         gtk_box_pack_start(GTK_BOX(hbbox), edit_btn, TRUE, TRUE, 0);
901         del_btn = gtk_button_new_from_stock(GTK_STOCK_DELETE);
902         GTK_WIDGET_SET_FLAGS(del_btn, GTK_CAN_DEFAULT);
903         gtk_box_pack_start(GTK_BOX(hbbox), del_btn, TRUE, TRUE, 0);
904         reg_btn = gtk_button_new_from_stock(GTK_STOCK_NEW);
905         GTK_WIDGET_SET_FLAGS(reg_btn, GTK_CAN_DEFAULT);
906         gtk_box_pack_start(GTK_BOX(hbbox), reg_btn, TRUE, TRUE, 0);
907
908
909         lup_btn = gtk_button_new_from_stock(GTK_STOCK_FIND);
910         GTK_WIDGET_SET_FLAGS(lup_btn, GTK_CAN_DEFAULT);
911         gtk_box_pack_start(GTK_BOX(hbox), lup_btn, TRUE, TRUE, 0);
912
913         g_signal_connect(G_OBJECT(edit_btn), "clicked",
914                          G_CALLBACK(addressbook_edit_clicked), NULL);
915         g_signal_connect(G_OBJECT(del_btn), "clicked",
916                          G_CALLBACK(addressbook_del_clicked), NULL);
917         g_signal_connect(G_OBJECT(reg_btn), "clicked",
918                          G_CALLBACK(addressbook_reg_clicked), NULL);
919         g_signal_connect(G_OBJECT(lup_btn), "clicked",
920                          G_CALLBACK(addressbook_lup_clicked), NULL);
921
922         to_btn = gtk_button_new_with_label
923                 (prefs_common.trans_hdr ? _("To:") : "To:");
924         GTK_WIDGET_SET_FLAGS(to_btn, GTK_CAN_DEFAULT);
925         gtk_box_pack_start(GTK_BOX(hbbox), to_btn, TRUE, TRUE, 0);
926         cc_btn = gtk_button_new_with_label
927                 (prefs_common.trans_hdr ? _("Cc:") : "Cc:");
928         GTK_WIDGET_SET_FLAGS(cc_btn, GTK_CAN_DEFAULT);
929         gtk_box_pack_start(GTK_BOX(hbbox), cc_btn, TRUE, TRUE, 0);
930         bcc_btn = gtk_button_new_with_label
931                 (prefs_common.trans_hdr ? _("Bcc:") : "Bcc:");
932         GTK_WIDGET_SET_FLAGS(bcc_btn, GTK_CAN_DEFAULT);
933         gtk_box_pack_start(GTK_BOX(hbbox), bcc_btn, TRUE, TRUE, 0);
934
935         close_btn = gtk_button_new_from_stock(GTK_STOCK_CLOSE);
936         GTK_WIDGET_SET_FLAGS(close_btn, GTK_CAN_DEFAULT);
937         gtk_box_pack_start(GTK_BOX(hbbox), close_btn, TRUE, TRUE, 0);
938
939         g_signal_connect(G_OBJECT(to_btn), "clicked",
940                          G_CALLBACK(addressbook_to_clicked),
941                          GINT_TO_POINTER(COMPOSE_TO));
942         g_signal_connect(G_OBJECT(cc_btn), "clicked",
943                          G_CALLBACK(addressbook_to_clicked),
944                          GINT_TO_POINTER(COMPOSE_CC));
945         g_signal_connect(G_OBJECT(bcc_btn), "clicked",
946                          G_CALLBACK(addressbook_to_clicked),
947                          GINT_TO_POINTER(COMPOSE_BCC));
948         g_signal_connect(G_OBJECT(close_btn), "clicked",
949                          G_CALLBACK(addressbook_close_clicked), NULL);
950
951         /* Build icons for interface */
952         stock_pixmap_gdk( window, STOCK_PIXMAP_INTERFACE,
953                           &interfacexpm, &interfacexpmmask );
954
955         /* Build control tables */
956         addrbookctl_build_map(window);
957         addrbookctl_build_iflist();
958         addrbookctl_build_ifselect();
959
960         /* Add each interface into the tree as a root level folder */
961         nodeIf = _addressInterfaceList_;
962         while( nodeIf ) {
963                 AdapterInterface *adapter = nodeIf->data;
964                 AddressInterface *iface = adapter->interface;
965                 nodeIf = g_list_next(nodeIf);
966
967                 if(iface->useInterface) {
968                         AddressTypeControlItem *atci = adapter->atci;
969                         text = atci->displayName;
970                         adapter->treeNode =
971                                 gtk_ctree_insert_node( GTK_CTREE(ctree),
972                                         NULL, NULL, &text, FOLDER_SPACING,
973                                         interfacexpm, interfacexpmmask,
974                                         interfacexpm, interfacexpmmask,
975                                         FALSE, FALSE );
976                         menu_set_sensitive( menu_factory, atci->menuCommand, adapter->haveLibrary );
977                         gtk_ctree_node_set_row_data_full(
978                                 GTK_CTREE(ctree), adapter->treeNode, adapter,
979                                 addressbook_free_treenode );
980                 }
981         }
982
983         /* Popup menu */
984         n_entries = sizeof(addressbook_tree_popup_entries) /
985                 sizeof(addressbook_tree_popup_entries[0]);
986         tree_popup = menu_create_items(addressbook_tree_popup_entries,
987                                        n_entries,
988                                        "<AddressBookTree>", &tree_factory,
989                                        NULL);
990         n_entries = sizeof(addressbook_list_popup_entries) /
991                 sizeof(addressbook_list_popup_entries[0]);
992         list_popup = menu_create_items(addressbook_list_popup_entries,
993                                        n_entries,
994                                        "<AddressBookList>", &list_factory,
995                                        NULL);
996
997         addrbook.window  = window;
998         addrbook.menubar = menubar;
999         addrbook.ctree   = ctree;
1000         addrbook.ctree_swin
1001                          = ctree_swin;
1002         addrbook.clist   = clist;
1003         addrbook.label   = label;
1004         addrbook.entry   = entry;
1005         addrbook.statusbar = statusbar;
1006         addrbook.status_cid = gtk_statusbar_get_context_id(
1007                         GTK_STATUSBAR(statusbar), "Addressbook Window" );
1008
1009         addrbook.edit_btn = edit_btn;
1010         addrbook.del_btn = del_btn;
1011         addrbook.reg_btn = reg_btn;
1012         addrbook.lup_btn = lup_btn;
1013         addrbook.to_btn  = to_btn;
1014         addrbook.cc_btn  = cc_btn;
1015         addrbook.bcc_btn = bcc_btn;
1016
1017         addrbook.tree_popup   = tree_popup;
1018         addrbook.list_popup   = list_popup;
1019         addrbook.tree_factory = tree_factory;
1020         addrbook.list_factory = list_factory;
1021         addrbook.menu_factory = menu_factory;
1022
1023         addrbook.listSelected = NULL;
1024         address_completion_start(window);
1025
1026         if (!geometry.min_height) {
1027                 geometry.min_width = ADDRESSBOOK_WIDTH;
1028                 geometry.min_height = ADDRESSBOOK_HEIGHT;
1029         }
1030
1031         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL, &geometry,
1032                                       GDK_HINT_MIN_SIZE);
1033         gtk_widget_set_size_request(window, prefs_common.addressbookwin_width,
1034                                     prefs_common.addressbookwin_height);
1035
1036         gtk_widget_show_all(window);
1037 }
1038
1039 /**
1040  * Close address book window and save to file(s).
1041  */
1042 static gint addressbook_close( void ) {
1043         gtk_widget_hide(addrbook.window);
1044         addressbook_export_to_file();
1045         return TRUE;
1046 }
1047
1048 /**
1049  * Display message in status line.
1050  * \param msg Message to display.
1051  */
1052 static void addressbook_status_show( gchar *msg ) {
1053         if( addrbook.statusbar != NULL ) {
1054                 gtk_statusbar_pop(
1055                         GTK_STATUSBAR(addrbook.statusbar),
1056                         addrbook.status_cid );
1057                 if( msg ) {
1058                         gtk_statusbar_push(
1059                                 GTK_STATUSBAR(addrbook.statusbar),
1060                                 addrbook.status_cid, msg );
1061                 }
1062         }
1063 }
1064
1065 static void addressbook_ds_status_message( AddressDataSource *ds, gchar *msg ) {
1066         *addressbook_msgbuf = '\0';
1067         if( ds ) {
1068                 gchar *name;
1069
1070                 name = addrindex_ds_get_name( ds );
1071                 g_snprintf( addressbook_msgbuf, sizeof(addressbook_msgbuf),
1072                             "%s: %s", name, msg );
1073         }
1074         else {
1075                 g_snprintf( addressbook_msgbuf, sizeof(addressbook_msgbuf),
1076                             "%s", msg );
1077         }
1078         addressbook_status_show( addressbook_msgbuf );
1079 }
1080
1081 static void addressbook_ds_show_message( AddressDataSource *ds ) {
1082         gint retVal;
1083         gchar *name;
1084         gchar *desc;
1085         *addressbook_msgbuf = '\0';
1086         if( ds ) {
1087                 name = addrindex_ds_get_name( ds );
1088                 retVal = addrindex_ds_get_status_code( ds );
1089                 if( retVal == MGU_SUCCESS ) {
1090                         g_snprintf( addressbook_msgbuf,
1091                                     sizeof(addressbook_msgbuf), "%s", name );
1092                 }
1093                 else {
1094                         desc = addressbook_err2string( _lutErrorsGeneral_, retVal );
1095                         g_snprintf( addressbook_msgbuf, 
1096                             sizeof(addressbook_msgbuf), "%s: %s", name, desc );
1097                 }
1098         }
1099         addressbook_status_show( addressbook_msgbuf );
1100 }
1101
1102 static void addressbook_button_set_sensitive(void)
1103 {
1104         gboolean to_sens  = FALSE;
1105         gboolean cc_sens  = FALSE;
1106         gboolean bcc_sens = FALSE;
1107
1108         if (!addrbook.window) return;
1109
1110         if (addrbook.target_compose) {
1111                 to_sens = TRUE;
1112                 cc_sens = TRUE;
1113 #ifndef CLAWS           
1114                 if (addrbook.target_compose->use_bcc)
1115 #endif                  
1116                         bcc_sens = TRUE;
1117         }
1118
1119         gtk_widget_set_sensitive(addrbook.to_btn, to_sens);
1120         gtk_widget_set_sensitive(addrbook.cc_btn, cc_sens);
1121         gtk_widget_set_sensitive(addrbook.bcc_btn, bcc_sens);
1122 }
1123
1124 static void addressbook_edit_clicked(GtkButton *button, gpointer data)
1125 {
1126         addressbook_edit_address_cb(NULL, 0, NULL);
1127 }
1128
1129 /*
1130 * Delete one or more objects from address list.
1131 */
1132 static void addressbook_del_clicked(GtkButton *button, gpointer data)
1133 {
1134         GtkCTree *clist = GTK_CTREE(addrbook.clist);
1135         GtkCTree *ctree = GTK_CTREE(addrbook.ctree);
1136         AddressObject *pobj;
1137         AdapterDSource *ads = NULL;
1138         GtkCTreeNode *nodeList;
1139         gboolean procFlag;
1140         AlertValue aval;
1141         AddressBookFile *abf = NULL;
1142         AddressDataSource *ds = NULL;
1143         AddressInterface *iface;
1144         AddrItemObject *aio;
1145         AddrSelectItem *item;
1146         GList *list, *node;
1147         gboolean refreshList = FALSE;
1148         
1149         pobj = gtk_ctree_node_get_row_data(ctree, addrbook.opened );
1150         g_return_if_fail(pobj != NULL);
1151
1152         /* Test whether anything selected for deletion */
1153         nodeList = addrbook.listSelected;
1154
1155         aio = gtk_ctree_node_get_row_data( clist, nodeList );
1156         if( aio == NULL) return;
1157         ds = addressbook_find_datasource( addrbook.treeSelected );
1158         if( ds == NULL ) return;
1159
1160         /* Test for read only */
1161         iface = ds->interface;
1162         if( iface->readOnly ) {
1163                 alertpanel( _("Delete address(es)"),
1164                         _("This address data is readonly and cannot be deleted."),
1165                         GTK_STOCK_CLOSE, NULL, NULL );
1166                 return;
1167         }
1168
1169         /* Test whether Ok to proceed */
1170         procFlag = FALSE;
1171         if( pobj->type == ADDR_DATASOURCE ) {
1172                 ads = ADAPTER_DSOURCE(pobj);
1173                 if( ads->subType == ADDR_BOOK ) procFlag = TRUE;
1174         }
1175         else if( pobj->type == ADDR_ITEM_FOLDER ) {
1176                 procFlag = TRUE;
1177         }
1178         else if( pobj->type == ADDR_ITEM_GROUP ) {
1179                 procFlag = TRUE;
1180         }
1181         if( ! procFlag ) return;
1182         abf = ds->rawDataSource;
1183         if( abf == NULL ) return;
1184
1185         /* Confirm deletion */
1186         aval = alertpanel( _("Delete address(es)"),
1187                         _("Really delete the address(es)?"),
1188                         GTK_STOCK_YES, GTK_STOCK_NO, NULL );
1189         if( aval != G_ALERTDEFAULT ) return;
1190
1191         /* Process deletions */
1192         if( pobj->type == ADDR_DATASOURCE || pobj->type == ADDR_ITEM_FOLDER ) {
1193                 /* Items inside folders */
1194                 list = addrselect_get_list( _addressSelect_ );
1195
1196                 node = list;
1197                 while( node ) {
1198                         item = node->data;
1199                         node = g_list_next( node );
1200                         aio = ( AddrItemObject * ) item->addressItem;
1201                         if( aio->type == ADDR_ITEM_GROUP ) {
1202                                 ItemGroup *item = ( ItemGroup * ) aio;
1203                                 GtkCTreeNode *nd = NULL;
1204
1205                                 nd = addressbook_find_group_node( addrbook.opened, item );
1206                                 item = addrbook_remove_group( abf, item );
1207                                 if( item ) {
1208                                         addritem_free_item_group( item );
1209                                 }
1210                                 /* Remove group from parent node */
1211                                 gtk_ctree_remove_node( ctree, nd );
1212                                 refreshList = TRUE;
1213                         }
1214                         else if( aio->type == ADDR_ITEM_PERSON ) {
1215                                 ItemPerson *item = ( ItemPerson * ) aio;
1216                                 addressbook_folder_remove_one_person( clist, item );
1217                                 if (pobj->type == ADDR_ITEM_FOLDER)
1218                                         addritem_folder_remove_person(ADAPTER_FOLDER(pobj)->itemFolder, item);
1219                                 item = addrbook_remove_person( abf, item );
1220                                 if( item ) {
1221                                         addritem_free_item_person( item );
1222                                 }
1223                         }
1224                         else if( aio->type == ADDR_ITEM_EMAIL ) {
1225                                 ItemEMail *item = ( ItemEMail * ) aio;
1226                                 ItemPerson *person = ( ItemPerson * ) ADDRITEM_PARENT(item);
1227                                 item = addrbook_person_remove_email( abf, person, item );
1228                                 if( item ) {
1229                                         addritem_free_item_email( item );
1230                                 }
1231                                 addressbook_folder_refresh_one_person( clist, person );
1232                         }
1233                 }
1234                 g_list_free( list );
1235                 addressbook_list_select_clear();
1236                 if( refreshList ) 
1237                         gtk_sctree_select( GTK_SCTREE(ctree), addrbook.opened);
1238                 addrbook_set_dirty(abf, TRUE);
1239                 addressbook_export_to_file();
1240                 addressbook_list_menu_setup();
1241                 return;
1242         }
1243         else if( pobj->type == ADDR_ITEM_GROUP ) {
1244                 /* Items inside groups */
1245                 list = addrselect_get_list( _addressSelect_ );
1246                 node = list;
1247                 while( node ) {
1248                         item = node->data;
1249                         node = g_list_next( node );
1250                         aio = ( AddrItemObject * ) item->addressItem;
1251                         if( aio->type == ADDR_ITEM_EMAIL ) {
1252                                 ItemEMail *item = ( ItemEMail * ) aio;
1253                                 ItemPerson *person = ( ItemPerson * ) ADDRITEM_PARENT(item);
1254                                 item = addrbook_person_remove_email( abf, person, item );
1255                                 if( item ) {
1256                                         addritem_free_item_email( item );
1257                                 }
1258                         }
1259                 }
1260                 g_list_free( list );
1261                 addressbook_list_select_clear();
1262                 gtk_sctree_select( GTK_SCTREE(ctree), addrbook.opened);
1263                 addrbook_set_dirty(abf, TRUE);
1264                 addressbook_export_to_file();
1265                 addressbook_list_menu_setup();
1266                 return;
1267         }
1268
1269         gtk_ctree_node_set_row_data( clist, nodeList, NULL );
1270         gtk_ctree_remove_node( clist, nodeList );
1271
1272 }
1273
1274 static void addressbook_reg_clicked(GtkButton *button, gpointer data)
1275 {
1276         addressbook_new_address_cb( NULL, 0, NULL );
1277 }
1278
1279 gchar *addressbook_format_address( AddrItemObject * aio ) {
1280         gchar *buf = NULL;
1281         gchar *name = NULL;
1282         gchar *address = NULL;
1283
1284         if( aio->type == ADDR_ITEM_EMAIL ) {
1285                 ItemPerson *person = NULL;
1286                 ItemEMail *email = ( ItemEMail * ) aio;
1287
1288                 person = ( ItemPerson * ) ADDRITEM_PARENT(email);
1289                 if( email->address ) {
1290                         if( ADDRITEM_NAME(email) ) {
1291                                 name = ADDRITEM_NAME(email);
1292                                 if( *name == '\0' ) {
1293                                         name = ADDRITEM_NAME(person);
1294                                 }
1295                         }
1296                         else if( ADDRITEM_NAME(person) ) {
1297                                 name = ADDRITEM_NAME(person);
1298                         }
1299                         else {
1300                                 buf = g_strdup( email->address );
1301                         }
1302                         address = email->address;
1303                 }
1304         }
1305         else if( aio->type == ADDR_ITEM_PERSON ) {
1306                 ItemPerson *person = ( ItemPerson * ) aio;
1307                 GList *node = person->listEMail;
1308
1309                 name = ADDRITEM_NAME(person);
1310                 if( node ) {
1311                         ItemEMail *email = ( ItemEMail * ) node->data;
1312                         address = email->address;
1313                 }
1314         }
1315         if( address ) {
1316                 if( name && name[0] != '\0' ) {
1317                         if( strchr_with_skip_quote( name, '"', ',' ) )
1318                                 buf = g_strdup_printf( "\"%s\" <%s>", name, address );
1319                         else
1320                                 buf = g_strdup_printf( "%s <%s>", name, address );
1321                 }
1322                 else {
1323                         buf = g_strdup( address );
1324                 }
1325         }
1326
1327         return buf;
1328 }
1329
1330 static void addressbook_to_clicked(GtkButton *button, gpointer data)
1331 {
1332         GList *list, *node;
1333         Compose *compose;
1334         AddrSelectItem *item;
1335         AddrItemObject *aio;
1336         gchar *addr;
1337
1338         compose = addrbook.target_compose;
1339         if( ! compose ) return;
1340
1341         /* Nothing selected, but maybe there is something in text entry */
1342         addr = (char *)gtk_entry_get_text( GTK_ENTRY( addrbook.entry) );
1343         if ( addr ) {
1344                 compose_entry_append(
1345                         compose, addr, (ComposeEntryType)data );
1346         }
1347
1348         /* Select from address list */
1349         list = addrselect_get_list( _addressSelect_ );
1350         node = list;
1351         while( node ) {
1352                 item = node->data;
1353                 node = g_list_next( node );
1354                 aio = item->addressItem;
1355                 if( aio->type == ADDR_ITEM_PERSON ||
1356                     aio->type == ADDR_ITEM_EMAIL ) {
1357                         addr = addressbook_format_address( aio );
1358                         compose_entry_append(
1359                                 compose, addr, (ComposeEntryType) data );
1360                         g_free( addr );
1361                 }
1362                 else if( aio->type == ADDR_ITEM_GROUP ) {
1363                         ItemGroup *group = ( ItemGroup * ) aio;
1364                         AddressDataSource *ds = NULL;
1365                         AddressBookFile *abf = NULL;
1366                         GList *nodeMail = group->listEMail;
1367                         if (nodeMail == NULL) {
1368                                 if(addrbook.treeSelected ) {
1369                                         ds = addressbook_find_datasource( addrbook.treeSelected );
1370                                         abf = ds->rawDataSource;
1371                                         if( abf != NULL )
1372                                                 nodeMail = addrbook_get_available_email_list( abf, group );
1373                                 }
1374                         }
1375                         while( nodeMail ) {
1376                                 ItemEMail *email = nodeMail->data;
1377
1378                                 addr = addressbook_format_address(
1379                                                 ( AddrItemObject * ) email );
1380                                 compose_entry_append(
1381                                         compose, addr, (ComposeEntryType) data );
1382                                 g_free( addr );
1383                                 nodeMail = g_list_next( nodeMail );
1384                         }
1385                 }
1386         }
1387         g_list_free( list );
1388 }
1389
1390 static void addressbook_menubar_set_sensitive( gboolean sensitive ) {
1391         menu_set_sensitive( addrbook.menu_factory, "/Book/Edit book",   sensitive );
1392         menu_set_sensitive( addrbook.menu_factory, "/Book/Delete book", sensitive );
1393         menu_set_sensitive( addrbook.menu_factory, "/Book/New Folder",  sensitive );
1394
1395         menu_set_sensitive( addrbook.menu_factory, "/Address/Cut",    sensitive );
1396         menu_set_sensitive( addrbook.menu_factory, "/Address/Copy",   sensitive );
1397         menu_set_sensitive( addrbook.menu_factory, "/Address/Paste",  sensitive );
1398
1399         menu_set_sensitive( addrbook.menu_factory, "/Address/New Address", sensitive );
1400         menu_set_sensitive( addrbook.menu_factory, "/Address/New Group",   sensitive );
1401         menu_set_sensitive( addrbook.menu_factory, "/Address/Mail To",     sensitive );
1402         gtk_widget_set_sensitive( addrbook.reg_btn, sensitive );
1403         gtk_widget_set_sensitive( addrbook.edit_btn, sensitive );
1404         gtk_widget_set_sensitive( addrbook.del_btn, sensitive );
1405 }
1406
1407 static void addressbook_menuitem_set_sensitive( AddressObject *obj, GtkCTreeNode *node ) {
1408         gboolean canEdit = FALSE;
1409         gboolean canDelete = TRUE;
1410         gboolean canAdd = FALSE;
1411         gboolean canEditTr = TRUE;
1412         gboolean editAddress = FALSE;
1413         gboolean canExport = TRUE;
1414         AddressTypeControlItem *atci = NULL;
1415         AddressDataSource *ds = NULL;
1416         AddressInterface *iface = NULL;
1417
1418         if( obj == NULL ) return;
1419         if( obj->type == ADDR_INTERFACE ) {
1420                 AdapterInterface *adapter = ADAPTER_INTERFACE(obj);
1421                 iface = adapter->interface;
1422                 if( iface ) {
1423                         if( iface->haveLibrary ) {
1424                                 /* Enable appropriate File / New command */
1425                                 atci = adapter->atci;
1426                                 menu_set_sensitive( addrbook.menu_factory, atci->menuCommand, TRUE );
1427                         }
1428                 }
1429                 canEditTr = canExport = FALSE;
1430         }
1431         else if( obj->type == ADDR_DATASOURCE ) {
1432                 AdapterDSource *ads = ADAPTER_DSOURCE(obj);
1433                 ds = ads->dataSource;
1434                 iface = ds->interface;
1435                 if( ! iface->readOnly ) {
1436                         canAdd = canEdit = editAddress = canDelete = TRUE;
1437                 }
1438                 if( ! iface->haveLibrary ) {
1439                         canAdd = canEdit = editAddress = canExport = canDelete = FALSE;
1440                 }
1441         }
1442         else if( obj->type == ADDR_ITEM_FOLDER ) {
1443                 ds = addressbook_find_datasource( addrbook.treeSelected );
1444                 if( ds ) {
1445                         iface = ds->interface;
1446                         if( iface->readOnly ) {
1447                                 canEditTr = FALSE;
1448                                 canDelete = FALSE;
1449                         }
1450                         else {
1451                                 canAdd = editAddress = TRUE;
1452                         }
1453                 }
1454         }
1455         else if( obj->type == ADDR_ITEM_GROUP ) {
1456                 ds = addressbook_find_datasource( addrbook.treeSelected );
1457                 if( ds ) {
1458                         iface = ds->interface;
1459                         if( ! iface->readOnly ) {
1460                                 editAddress = TRUE;
1461                         }
1462                 }
1463         }
1464
1465         if( addrbook.listSelected == NULL ) canEdit = FALSE;
1466
1467         /* Enable add */
1468         menu_set_sensitive( addrbook.menu_factory, "/Address/New Address", editAddress );
1469         menu_set_sensitive( addrbook.menu_factory, "/Address/New Group",   canAdd );
1470         menu_set_sensitive( addrbook.menu_factory, "/Book/New Folder",  canAdd );
1471         gtk_widget_set_sensitive( addrbook.reg_btn, editAddress );
1472
1473         /* Enable edit */
1474         menu_set_sensitive( addrbook.menu_factory, "/Address/Edit",   canEdit );
1475         menu_set_sensitive( addrbook.menu_factory, "/Address/Delete", canDelete );
1476         gtk_widget_set_sensitive( addrbook.edit_btn, canEdit );
1477         gtk_widget_set_sensitive( addrbook.del_btn, canDelete );
1478
1479         menu_set_sensitive( addrbook.menu_factory, "/Book/Edit book",      canEditTr );
1480         menu_set_sensitive( addrbook.menu_factory, "/Book/Delete book",    canEditTr );
1481
1482         /* Export data */
1483         menu_set_sensitive( addrbook.menu_factory, "/Tools/Export HTML...", canExport );
1484         menu_set_sensitive( addrbook.menu_factory, "/Tools/Export LDIF...", canExport );
1485 }
1486
1487 static void addressbook_list_menu_setup( void );
1488
1489 /**
1490  * Address book tree callback function that responds to selection of tree
1491  * items.
1492  *
1493  * \param ctree  Tree widget.
1494  * \param node   Node that was selected.
1495  * \param column Column number where selected occurred.
1496  * \param data   Pointer to user data.
1497  */
1498 static void addressbook_tree_selected(GtkCTree *ctree, GtkCTreeNode *node,
1499                                       gint column, gpointer data)
1500 {
1501         AddressObject *obj = NULL;
1502         AdapterDSource *ads = NULL;
1503         AddressDataSource *ds = NULL;
1504         ItemFolder *rootFolder = NULL;
1505         AddressObjectType aot;
1506
1507         addrbook.treeSelected = node;
1508         addrbook.listSelected = NULL;
1509         addressbook_status_show( "" );
1510         if( addrbook.entry != NULL ) gtk_entry_set_text(GTK_ENTRY(addrbook.entry), "");
1511
1512         if( node ) obj = gtk_ctree_node_get_row_data( ctree, node );
1513         if( obj == NULL ) {
1514                 addressbook_set_clist(NULL, TRUE);
1515                 return;
1516         }
1517         addrbook.opened = node;
1518
1519         if( obj->type == ADDR_DATASOURCE ) {
1520                 /* Read from file */
1521                 static gboolean tVal = TRUE;
1522
1523                 ads = ADAPTER_DSOURCE(obj);
1524                 if( ads == NULL ) return;
1525                 ds = ads->dataSource;
1526                 if( ds == NULL ) return;                
1527
1528                 if( addrindex_ds_get_modify_flag( ds ) ) {
1529                         addrindex_ds_read_data( ds );
1530                 }
1531
1532                 if( ! addrindex_ds_get_read_flag( ds ) ) {
1533                         addrindex_ds_read_data( ds );
1534                 }
1535                 addressbook_ds_show_message( ds );
1536
1537                 if( ! addrindex_ds_get_access_flag( ds ) ) {
1538                         /* Remove existing folders and groups */
1539                         gtk_clist_freeze( GTK_CLIST(ctree) );
1540                         addressbook_tree_remove_children( ctree, node );
1541                         gtk_clist_thaw( GTK_CLIST(ctree) );
1542
1543                         /* Load folders into the tree */
1544                         rootFolder = addrindex_ds_get_root_folder( ds );
1545                         if( ds->type == ADDR_IF_JPILOT ) {
1546                                 aot = ADDR_CATEGORY;
1547                         }
1548                         else if( ds->type == ADDR_IF_LDAP ) {
1549                                 aot = ADDR_LDAP_QUERY;
1550                         }
1551                         else {
1552                                 aot = ADDR_ITEM_FOLDER;
1553                         }
1554                         addressbook_node_add_folder( node, ds, rootFolder, aot );
1555                         addrindex_ds_set_access_flag( ds, &tVal );
1556                         gtk_ctree_expand( ctree, node );
1557                 }
1558         }
1559
1560         /* Update address list */
1561         g_signal_handlers_block_by_func
1562                 (G_OBJECT(ctree),
1563                  G_CALLBACK(addressbook_tree_selected), NULL);
1564         addressbook_set_clist( obj, FALSE );
1565         g_signal_handlers_unblock_by_func
1566                 (G_OBJECT(ctree),
1567                  G_CALLBACK(addressbook_tree_selected), NULL);
1568
1569         /* Setup main menu selections */
1570         addressbook_menubar_set_sensitive( FALSE );
1571         addressbook_list_menu_setup();
1572         addressbook_menuitem_set_sensitive( obj, node );
1573
1574         addressbook_list_select_clear();
1575         addressbook_list_menu_setup();
1576         return;
1577 }
1578
1579 /**
1580  * Setup address list popup menu items. Items are enabled or disabled as
1581  * required.
1582  */
1583 static void addressbook_list_menu_setup( void ) {
1584         GtkCTree *clist = NULL;
1585         AddressObject *pobj = NULL;
1586         AddressObject *obj = NULL;
1587         AdapterDSource *ads = NULL;
1588         AddressInterface *iface = NULL;
1589         AddressDataSource *ds = NULL;
1590         gboolean canEdit = FALSE;
1591         gboolean canDelete = FALSE;
1592         gboolean canCut = FALSE;
1593         gboolean canCopy = FALSE;
1594         gboolean canPaste = FALSE;
1595         gboolean canBrowse = FALSE;
1596
1597         pobj = gtk_ctree_node_get_row_data( GTK_CTREE(addrbook.ctree), addrbook.treeSelected );
1598         if( pobj == NULL ) return;
1599
1600         clist = GTK_CTREE(addrbook.clist);
1601         obj = gtk_ctree_node_get_row_data( clist, addrbook.listSelected );
1602         if( obj == NULL ) canEdit = FALSE;
1603
1604         menu_set_insensitive_all( GTK_MENU_SHELL(addrbook.list_popup) );
1605
1606         if( pobj->type == ADDR_DATASOURCE ) {
1607                 /* Parent object is a data source */
1608                 ads = ADAPTER_DSOURCE(pobj);
1609                 ds = ads->dataSource;
1610                 iface = ds->interface;
1611                 if( ! iface->readOnly ) {
1612                         menu_set_sensitive( addrbook.list_factory, "/New Address", TRUE );
1613                         menu_set_sensitive( addrbook.list_factory, "/New Group", TRUE );
1614                         gtk_widget_set_sensitive( addrbook.reg_btn, TRUE );
1615                         if( ! addrclip_is_empty( _clipBoard_ ) ) canPaste = TRUE;
1616                         if( ! addrselect_test_empty( _addressSelect_ ) ) canCut = TRUE;
1617                         if( obj ) canEdit = TRUE;
1618                 }
1619                 canDelete = canEdit;
1620         }
1621         else if( pobj->type != ADDR_INTERFACE ) {
1622                 /* Parent object is not an interface */
1623                 ds = addressbook_find_datasource( addrbook.treeSelected );
1624                 iface = ds->interface;
1625                 if( ! iface->readOnly ) {
1626                         /* Folder or group */
1627                         if( pobj->type == ADDR_ITEM_FOLDER || pobj->type == ADDR_ITEM_GROUP ) {
1628                                 menu_set_sensitive( addrbook.list_factory, "/New Address", TRUE );
1629                                 gtk_widget_set_sensitive( addrbook.reg_btn, TRUE );
1630                                 if( obj ) canEdit = TRUE;
1631                         }
1632                         /* Folder */
1633                         if( pobj->type == ADDR_ITEM_FOLDER ) {
1634                                 menu_set_sensitive( addrbook.list_factory, "/New Group", TRUE );
1635                                 if( obj ) canEdit = TRUE;
1636                         }
1637                         if( ! addrclip_is_empty( _clipBoard_ ) ) canPaste = TRUE;
1638                         if( ! addrselect_test_empty( _addressSelect_ ) ) canCut = TRUE;
1639                         canDelete = canEdit;
1640                 }
1641                 if( iface->type == ADDR_IF_LDAP ) {
1642                         if( obj ) canBrowse = TRUE;
1643                         canEdit = TRUE;
1644                         canDelete = FALSE;
1645                 }
1646         }
1647         if( ! addrselect_test_empty( _addressSelect_ ) ) canCopy = TRUE;
1648
1649         /* Disable edit or browse if more than one row selected */
1650         if( GTK_CLIST(clist)->selection && GTK_CLIST(clist)->selection->next ) {
1651                 canEdit = FALSE;
1652                 canBrowse = FALSE;
1653         }
1654
1655         /* Now go finalize menu items */
1656         menu_set_sensitive( addrbook.list_factory, "/Edit",   canEdit );
1657         menu_set_sensitive( addrbook.list_factory, "/Delete", canDelete );
1658
1659         menu_set_sensitive( addrbook.list_factory, "/Cut",           canCut );
1660         menu_set_sensitive( addrbook.list_factory, "/Copy",          canCopy );
1661         menu_set_sensitive( addrbook.list_factory, "/Paste",         canPaste );
1662 /*      menu_set_sensitive( addrbook.list_factory, "/Paste Address", canPaste );*/
1663
1664         menu_set_sensitive( addrbook.list_factory, "/Mail To",       canCopy );
1665
1666         menu_set_sensitive( addrbook.menu_factory, "/Address/Cut",           canCut );
1667         menu_set_sensitive( addrbook.menu_factory, "/Address/Copy",          canCopy );
1668         menu_set_sensitive( addrbook.menu_factory, "/Address/Paste",         canPaste );
1669 /*      menu_set_sensitive( addrbook.menu_factory, "/Edit/Paste Address", canPaste );*/
1670
1671         menu_set_sensitive( addrbook.tree_factory, "/Cut",             canCut );
1672         menu_set_sensitive( addrbook.tree_factory, "/Copy",            canCopy );
1673         menu_set_sensitive( addrbook.tree_factory, "/Paste",           canPaste );
1674
1675         menu_set_sensitive( addrbook.menu_factory, "/Address/Edit",    canEdit );
1676         menu_set_sensitive( addrbook.menu_factory, "/Address/Delete",  canDelete );
1677         menu_set_sensitive( addrbook.menu_factory, "/Address/Mail To", canCopy );
1678
1679         gtk_widget_set_sensitive( addrbook.edit_btn, canEdit );
1680         gtk_widget_set_sensitive( addrbook.del_btn, canDelete );
1681
1682 #ifdef USE_LDAP
1683         menu_set_sensitive( addrbook.list_factory, "/Browse Entry",    canBrowse );
1684 #endif
1685 }
1686
1687 static void addressbook_select_row_tree (GtkCTree       *ctree,
1688                                          GtkCTreeNode   *node,
1689                                          gint            column,
1690                                          gpointer        data)
1691 {
1692 }
1693
1694 /**
1695  * Add list of items into tree node below specified tree node.
1696  * \param treeNode  Tree node.
1697  * \param ds        Data source.
1698  * \param listItems List of items.
1699  */
1700 static void addressbook_treenode_add_list(
1701         GtkCTreeNode *treeNode, AddressDataSource *ds, GList *listItems )
1702 {
1703         GList *node;
1704
1705         node = listItems;
1706         while( node ) {
1707                 AddrItemObject *aio;
1708                 GtkCTreeNode *nn;
1709
1710                 aio = node->data;
1711                 if( ADDRESS_OBJECT_TYPE(aio) == ITEMTYPE_GROUP ) {
1712                         ItemGroup *group;
1713
1714                         group = ( ItemGroup * ) aio;
1715                         nn = addressbook_node_add_group( treeNode, ds, group );
1716                 }
1717                 else if( ADDRESS_OBJECT_TYPE(aio) == ITEMTYPE_FOLDER ) {
1718                         ItemFolder *folder;
1719
1720                         folder = ( ItemFolder * ) aio;
1721                         nn = addressbook_node_add_folder(
1722                                 treeNode, ds, folder, ADDR_ITEM_FOLDER );
1723                 }
1724                 node = g_list_next( node );
1725         }
1726 }
1727
1728 /**
1729  * Cut from address list widget.
1730  */
1731 static void addressbook_clip_cut_cb( void ) {
1732         _clipBoard_->cutFlag = TRUE;
1733         addrclip_clear( _clipBoard_ );
1734         addrclip_add( _clipBoard_, _addressSelect_ );
1735         /* addrclip_list_show( _clipBoard_, stdout ); */
1736 }
1737
1738 /**
1739  * Copy from address list widget.
1740  */
1741 static void addressbook_clip_copy_cb( void ) {
1742         _clipBoard_->cutFlag = FALSE;
1743         addrclip_clear( _clipBoard_ );
1744         addrclip_add( _clipBoard_, _addressSelect_ );
1745         /* addrclip_list_show( _clipBoard_, stdout ); */
1746 }
1747
1748 /**
1749  * Paste clipboard into address list widget.
1750  */
1751 static void addressbook_clip_paste_cb( void ) {
1752         GtkCTree *ctree = GTK_CTREE( addrbook.ctree );
1753         AddressObject *pobj = NULL;
1754         AddressDataSource *ds = NULL;
1755         AddressBookFile *abf = NULL;
1756         ItemFolder *folder = NULL;
1757         GList *folderGroup = NULL;
1758
1759         ds = addressbook_find_datasource( GTK_CTREE_NODE(addrbook.treeSelected) );
1760         if( ds == NULL ) return;
1761         if( addrindex_ds_get_readonly( ds ) ) {
1762                 addressbook_ds_status_message(
1763                         ds, _( "Cannot paste. Target address book is readonly." ) );
1764                 return;
1765         }
1766
1767         pobj = gtk_ctree_node_get_row_data( ctree, addrbook.treeSelected );
1768         if( pobj ) {
1769                 if( pobj->type == ADDR_ITEM_FOLDER ) {
1770                         folder = ADAPTER_FOLDER(pobj)->itemFolder;
1771                 }
1772                 else if( pobj->type == ADDR_ITEM_GROUP ) {
1773                         addressbook_ds_status_message(
1774                                 ds, _( "Cannot paste into an address group." ) );
1775                         return;
1776                 }
1777         }
1778
1779         /* Get an address book */
1780         abf = addressbook_get_book_file();
1781         if( abf == NULL ) return;
1782
1783         if( _clipBoard_->cutFlag ) {
1784                 /* Paste/Cut */
1785                 folderGroup = addrclip_paste_cut( _clipBoard_, abf, folder );
1786
1787                 /* Remove all groups and folders in clipboard from tree node */
1788                 addressbook_treenode_remove_item();
1789
1790                 /* Remove all "cut" items */
1791                 addrclip_delete_item( _clipBoard_ );
1792
1793                 /* Clear clipboard - cut items??? */
1794                 addrclip_clear( _clipBoard_ );
1795         }
1796         else {
1797                 /* Paste/Copy */
1798                 folderGroup = addrclip_paste_copy( _clipBoard_, abf, folder );
1799         }
1800
1801         /* addrclip_list_show( _clipBoard_, stdout ); */
1802         if( folderGroup ) {
1803                 /* Update tree by inserting node for each folder or group */
1804                 addressbook_treenode_add_list(
1805                         addrbook.treeSelected, ds, folderGroup );
1806                 gtk_ctree_expand( ctree, addrbook.treeSelected );
1807                 g_list_free( folderGroup );
1808                 folderGroup = NULL;
1809         }
1810
1811         /* Display items pasted */
1812         gtk_sctree_select( GTK_SCTREE(ctree), addrbook.opened );
1813
1814 }
1815
1816 #if 0
1817 /**
1818  * Paste clipboard email addresses only into address list widget.
1819  */
1820 static void addressbook_clip_paste_address_cb( void ) {
1821         GtkCTree *clist = GTK_CTREE(addrbook.clist);
1822         GtkCTree *ctree;
1823         AddressObject *pobj = NULL;
1824         AddressDataSource *ds = NULL;
1825         AddressBookFile *abf = NULL;
1826         ItemFolder *folder = NULL;
1827         AddrItemObject *aio;
1828         gint cnt;
1829
1830         if( addrbook.listSelected == NULL ) return;
1831
1832         ctree = GTK_CTREE( addrbook.ctree );
1833         ds = addressbook_find_datasource( GTK_CTREE_NODE(addrbook.treeSelected) );
1834         if( ds == NULL ) return;
1835         if( addrindex_ds_get_readonly( ds ) ) {
1836                 addressbook_ds_status_message(
1837                         ds, _( "Cannot paste. Target address book is readonly." ) );
1838                 return;
1839         }
1840
1841         pobj = gtk_ctree_node_get_row_data( ctree, addrbook.treeSelected );
1842         if( pobj ) {
1843                 if( pobj->type == ADDR_ITEM_FOLDER ) {
1844                         folder = ADAPTER_FOLDER(pobj)->itemFolder;
1845                 }
1846         }
1847
1848         abf = addressbook_get_book_file();
1849         if( abf == NULL ) return;
1850
1851         cnt = 0;
1852         aio = gtk_ctree_node_get_row_data( clist, addrbook.listSelected );
1853         if( aio->type == ADDR_ITEM_PERSON ) {
1854                 ItemPerson *person;
1855
1856                 person = ( ItemPerson * ) aio;
1857                 if( _clipBoard_->cutFlag ) {
1858                         /* Paste/Cut */
1859                         cnt = addrclip_paste_person_cut( _clipBoard_, abf, person );
1860
1861                         /* Remove all "cut" items */
1862                         addrclip_delete_address( _clipBoard_ );
1863
1864                         /* Clear clipboard */
1865                         addrclip_clear( _clipBoard_ );
1866                 }
1867                 else {
1868                         /* Paste/Copy */
1869                         cnt = addrclip_paste_person_copy( _clipBoard_, abf, person );
1870                 }
1871                 if( cnt > 0 ) {
1872                         addritem_person_set_opened( person, TRUE );
1873                 }
1874         }
1875
1876         /* Display items pasted */
1877         if( cnt > 0 ) {
1878                 gtk_sctree_select( GTK_SCTREE(ctree), addrbook.opened );
1879         }
1880 }
1881 #endif
1882
1883 /**
1884  * Add current treenode object to clipboard. Note that widget only allows
1885  * one entry from the tree list to be selected.
1886  */
1887 static void addressbook_treenode_to_clipboard( void ) {
1888         AddressObject *obj = NULL;
1889         AddressDataSource *ds = NULL;
1890         AddrSelectItem *item;
1891         GtkCTree *ctree = GTK_CTREE( addrbook.ctree );
1892         GtkCTreeNode *node;
1893
1894         node = addrbook.treeSelected;
1895         if( node == NULL ) return;
1896         obj = gtk_ctree_node_get_row_data( ctree, node );
1897         if( obj == NULL ) return;
1898
1899         ds = addressbook_find_datasource( node );
1900         if( ds == NULL ) return;
1901
1902         item = NULL;
1903         if( obj->type == ADDR_ITEM_FOLDER ) {
1904                 AdapterFolder *adapter = ADAPTER_FOLDER(obj);
1905                 ItemFolder *folder = adapter->itemFolder;
1906
1907                 item = addrselect_create_node( obj );
1908                 item->uid = g_strdup( ADDRITEM_ID(folder) );
1909         }
1910         else if( obj->type == ADDR_ITEM_GROUP ) {
1911                 AdapterGroup *adapter = ADAPTER_GROUP(obj);
1912                 ItemGroup *group = adapter->itemGroup;
1913
1914                 item = addrselect_create_node( obj );
1915                 item->uid = g_strdup( ADDRITEM_ID(group) );
1916         }
1917         else if( obj->type == ADDR_DATASOURCE ) {
1918                 /* Data source */
1919                 item = addrselect_create_node( obj );
1920                 item->uid = NULL;
1921         }
1922
1923         if( item ) {
1924                 /* Clear existing list and add item into list */
1925                 gchar *cacheID;
1926
1927                 addressbook_list_select_clear();
1928                 cacheID = addrindex_get_cache_id( _addressIndex_, ds );
1929                 addrselect_list_add( _addressSelect_, item, cacheID );
1930                 g_free( cacheID );
1931         }
1932 }
1933
1934 /**
1935  * Cut from tree widget.
1936  */
1937 static void addressbook_treenode_cut_cb( void ) {
1938         _clipBoard_->cutFlag = TRUE;
1939         addressbook_treenode_to_clipboard();
1940         addrclip_clear( _clipBoard_ );
1941         addrclip_add( _clipBoard_, _addressSelect_ );
1942         /* addrclip_list_show( _clipBoard_, stdout ); */
1943 }
1944
1945 /**
1946  * Copy from tree widget.
1947  */
1948 static void addressbook_treenode_copy_cb( void ) {
1949         _clipBoard_->cutFlag = FALSE;
1950         addressbook_treenode_to_clipboard();
1951         addrclip_clear( _clipBoard_ );
1952         addrclip_add( _clipBoard_, _addressSelect_ );
1953         /* addrclip_list_show( _clipBoard_, stdout ); */
1954 }
1955
1956 /**
1957  * Paste clipboard into address tree widget.
1958  */
1959 static void addressbook_treenode_paste_cb( void ) {
1960         addressbook_clip_paste_cb();
1961 }
1962
1963 /**
1964  * Clear selected entries in clipboard.
1965  */
1966 static void addressbook_list_select_clear( void ) {
1967         addrselect_list_clear( _addressSelect_ );
1968 }
1969
1970 /**
1971  * Add specified address item to selected address list.
1972  * \param aio Address item object.
1973  * \param ds  Datasource.
1974  */
1975 static void addressbook_list_select_add( AddrItemObject *aio, AddressDataSource *ds ) {
1976         gchar *cacheID;
1977
1978         if( ds == NULL ) return;
1979         cacheID = addrindex_get_cache_id( _addressIndex_, ds );
1980         addrselect_list_add_obj( _addressSelect_, aio, cacheID );
1981         g_free( cacheID );
1982 }
1983
1984 /**
1985  * Remove specified address item from selected address list.
1986  * \param aio Address item object.
1987  */
1988 static void addressbook_list_select_remove( AddrItemObject *aio ) {
1989         addrselect_list_remove( _addressSelect_, aio );
1990 }
1991
1992 /**
1993  * Invoke EMail compose window with addresses in selected address list.
1994  */
1995 static void addressbook_mail_to_cb( void ) {
1996         GList *listAddress;
1997
1998         if( ! addrselect_test_empty( _addressSelect_ ) ) {
1999                 listAddress = addrselect_build_list( _addressSelect_ );
2000                 compose_new_with_list( NULL, listAddress );
2001                 mgu_free_dlist( listAddress );
2002                 listAddress = NULL;
2003         }
2004 }
2005
2006 static void addressbook_list_row_selected( GtkCTree *clist,
2007                                            GtkCTreeNode *node,
2008                                            gint column,
2009                                            gpointer data )
2010 {
2011         GtkEntry *entry = GTK_ENTRY(addrbook.entry);
2012         AddrItemObject *aio = NULL;
2013         AddressObject *pobj = NULL;
2014         AdapterDSource *ads = NULL;
2015         AddressDataSource *ds = NULL;
2016
2017         gtk_entry_set_text( entry, "" );
2018         addrbook.listSelected = node;
2019
2020         pobj = gtk_ctree_node_get_row_data( GTK_CTREE(addrbook.ctree), addrbook.treeSelected );
2021         if( pobj == NULL ) return;
2022
2023         if( pobj->type == ADDR_DATASOURCE ) {
2024                 ads = ADAPTER_DSOURCE(pobj);
2025                 ds = ads->dataSource;
2026         }
2027         else if( pobj->type != ADDR_INTERFACE ) {
2028                 ds = addressbook_find_datasource( addrbook.treeSelected );
2029         }
2030
2031         aio = gtk_ctree_node_get_row_data( clist, node );
2032         if( aio ) {
2033                 /* printf( "list select: %d : '%s'\n", aio->type, aio->name ); */
2034                 addressbook_list_select_add( aio, ds );
2035         }
2036
2037         addressbook_list_menu_setup();
2038 }
2039
2040 static void addressbook_list_row_unselected( GtkCTree *ctree,
2041                                              GtkCTreeNode *node,
2042                                              gint column,
2043                                              gpointer data )
2044 {
2045         AddrItemObject *aio;
2046
2047         aio = gtk_ctree_node_get_row_data( ctree, node );
2048         if( aio != NULL ) {
2049                 /* printf( "list unselect: %d : '%s'\n", aio->type, aio->name ); */
2050                 addressbook_list_select_remove( aio );
2051         }
2052 }
2053
2054 /* from gdkevents.c */
2055 #define DOUBLE_CLICK_TIME 250
2056
2057 static gboolean addressbook_list_button_pressed(GtkWidget *widget,
2058                                                 GdkEventButton *event,
2059                                                 gpointer data)
2060 {
2061         static guint32 lasttime = 0;
2062         if( ! event ) return FALSE;
2063
2064         addressbook_list_menu_setup();
2065
2066         if( event->button == 3 ) {
2067                 gtk_menu_popup( GTK_MENU(addrbook.list_popup), NULL, NULL, NULL, NULL,
2068                        event->button, event->time );
2069         } else if (event->button == 1) {
2070                 if (event->time - lasttime < DOUBLE_CLICK_TIME) {
2071                         if (prefs_common.add_address_by_click &&
2072                             addrbook.target_compose)
2073                                 addressbook_to_clicked(NULL, GINT_TO_POINTER(COMPOSE_TO));
2074                         else
2075                                 addressbook_edit_address_cb(NULL, 0, NULL);
2076
2077                         lasttime = 0;
2078                 } else
2079                         lasttime = event->time;
2080         }
2081
2082         return FALSE;
2083 }
2084
2085 static gboolean addressbook_list_button_released(GtkWidget *widget,
2086                                                  GdkEventButton *event,
2087                                                  gpointer data)
2088 {
2089         return FALSE;
2090 }
2091
2092 static gboolean addressbook_tree_button_pressed(GtkWidget *ctree,
2093                                                 GdkEventButton *event,
2094                                                 gpointer data)
2095 {
2096         GtkCList *clist = GTK_CLIST(ctree);
2097         gint row, column;
2098         AddressObject *obj = NULL;
2099         AdapterDSource *ads = NULL;
2100         AddressInterface *iface = NULL;
2101         AddressDataSource *ds = NULL;
2102         gboolean canEdit = FALSE;
2103         gboolean canDelete = FALSE;
2104         gboolean canCut = FALSE;
2105         gboolean canCopy = FALSE;
2106         gboolean canPaste = FALSE;
2107         gboolean canTreeCut = FALSE;
2108         gboolean canTreeCopy = FALSE;
2109         gboolean canTreePaste = FALSE;
2110         gboolean canLookup = FALSE;
2111
2112         if( ! event ) return FALSE;
2113         addressbook_menubar_set_sensitive( FALSE );
2114
2115         if( gtk_clist_get_selection_info( clist, event->x, event->y, &row, &column ) ) {
2116                 gtkut_clist_set_focus_row(clist, row);
2117                 obj = gtk_clist_get_row_data( clist, row );
2118         }
2119
2120         menu_set_insensitive_all(GTK_MENU_SHELL(addrbook.tree_popup));
2121
2122         if( obj == NULL ) return FALSE;
2123
2124         if( ! addrclip_is_empty( _clipBoard_ ) ) {
2125                 canTreePaste = TRUE;
2126         }
2127
2128         if (obj->type == ADDR_DATASOURCE) {
2129                 ads = ADAPTER_DSOURCE(obj);
2130                 ds = ads->dataSource;
2131                 iface = ds->interface;
2132                 canEdit = TRUE;
2133                 canDelete = TRUE;
2134                 if( iface->readOnly ) {
2135                         canTreePaste = FALSE;
2136                 }
2137                 else {
2138                         menu_set_sensitive( addrbook.tree_factory, "/New Folder", TRUE );
2139                         gtk_widget_set_sensitive( addrbook.reg_btn, TRUE );
2140                 }
2141                 canTreeCopy = TRUE;
2142                 if( iface->externalQuery ) canLookup = TRUE;
2143         }
2144         else if (obj->type == ADDR_ITEM_FOLDER) {
2145                 ds = addressbook_find_datasource( addrbook.treeSelected );
2146                 iface = ds->interface;
2147                 if( iface->readOnly ) {
2148                         canTreePaste = FALSE;
2149                 }
2150                 else {
2151                         canEdit = TRUE;
2152                         canDelete = TRUE;
2153                         canTreeCut = TRUE;
2154                         menu_set_sensitive( addrbook.tree_factory, "/New Folder", TRUE );
2155                         gtk_widget_set_sensitive( addrbook.reg_btn, TRUE );
2156                 }
2157                 canTreeCopy = TRUE;
2158                 iface = ds->interface;
2159                 if( iface->externalQuery ) {
2160                         /* Enable deletion of LDAP folder */
2161                         canLookup = TRUE;
2162                         canDelete = TRUE;
2163                 }
2164         }
2165         else if (obj->type == ADDR_ITEM_GROUP) {
2166                 ds = addressbook_find_datasource( addrbook.treeSelected );
2167                 iface = ds->interface;
2168                 if( ! iface->readOnly ) {
2169                         canEdit = TRUE;
2170                         canDelete = TRUE;
2171                         menu_set_sensitive( addrbook.list_factory, "/New Address", TRUE );
2172                         gtk_widget_set_sensitive( addrbook.reg_btn, TRUE );
2173                 }
2174         }
2175         else if (obj->type == ADDR_INTERFACE) {
2176                 canTreePaste = FALSE;
2177         }
2178
2179         if( canEdit ) {
2180                 if( ! addrselect_test_empty( _addressSelect_ ) ) canCut = TRUE;
2181         }
2182         if( ! addrselect_test_empty( _addressSelect_ ) ) canCopy = TRUE;
2183         if( ! addrclip_is_empty( _clipBoard_ ) ) canPaste = TRUE;
2184
2185         /* Enable edit */
2186         menu_set_sensitive( addrbook.tree_factory, "/Edit",   canEdit );
2187         menu_set_sensitive( addrbook.tree_factory, "/Delete", canDelete );
2188         menu_set_sensitive( addrbook.tree_factory, "/Cut",    canTreeCut );
2189         menu_set_sensitive( addrbook.tree_factory, "/Copy",   canTreeCopy );
2190         menu_set_sensitive( addrbook.tree_factory, "/Paste",  canTreePaste );
2191
2192         menu_set_sensitive( addrbook.menu_factory, "/Book/Edit book",          canEdit );
2193         menu_set_sensitive( addrbook.menu_factory, "/Book/Delete book",        canEdit );
2194         menu_set_sensitive( addrbook.menu_factory, "/Address/Cut",           canCut );
2195         menu_set_sensitive( addrbook.menu_factory, "/Address/Copy",          canCopy );
2196         menu_set_sensitive( addrbook.menu_factory, "/Address/Paste",         canPaste );
2197 /*      menu_set_sensitive( addrbook.menu_factory, "/Edit/Paste Address", canPaste );*/
2198
2199         addressbook_show_buttons(addrbook.target_compose == NULL, canLookup, addrbook.target_compose != NULL);
2200         if( event->button == 3 ) {
2201                 gtk_menu_popup(GTK_MENU(addrbook.tree_popup), NULL, NULL, NULL, NULL,
2202                                event->button, event->time);
2203         }
2204
2205         return FALSE;
2206 }
2207
2208 static gboolean addressbook_tree_button_released(GtkWidget *ctree,
2209                                                  GdkEventButton *event,
2210                                                  gpointer data)
2211 {
2212         gtkut_ctree_set_focus_row(GTK_CTREE(addrbook.ctree), addrbook.opened);
2213         return FALSE;
2214 }
2215
2216 static void addressbook_new_folder_cb(gpointer data, guint action,
2217                                       GtkWidget *widget)
2218 {
2219         GtkCTree *ctree = GTK_CTREE(addrbook.ctree);
2220         AddressObject *obj = NULL;
2221         AddressDataSource *ds = NULL;
2222         AddressBookFile *abf = NULL;
2223         ItemFolder *parentFolder = NULL;
2224         ItemFolder *folder = NULL;
2225
2226         if( ! addrbook.treeSelected ) return;
2227         obj = gtk_ctree_node_get_row_data( ctree, addrbook.treeSelected );
2228         if( obj == NULL ) return;
2229         ds = addressbook_find_datasource( addrbook.treeSelected );
2230         if( ds == NULL ) return;
2231
2232         if( obj->type == ADDR_DATASOURCE ) {
2233                 if( ADAPTER_DSOURCE(obj)->subType != ADDR_BOOK ) return;
2234         }
2235         else if( obj->type == ADDR_ITEM_FOLDER ) {
2236                 parentFolder = ADAPTER_FOLDER(obj)->itemFolder;
2237         }
2238         else {
2239                 return;
2240         }
2241
2242         abf = ds->rawDataSource;
2243         if( abf == NULL ) return;
2244         folder = addressbook_edit_folder( abf, parentFolder, NULL );
2245         if( folder ) {
2246                 GtkCTreeNode *nn;
2247                 nn = addressbook_node_add_folder(
2248                         addrbook.treeSelected, ds, folder, ADDR_ITEM_FOLDER );
2249                 gtk_ctree_expand( ctree, addrbook.treeSelected );
2250                 if( addrbook.treeSelected == addrbook.opened )
2251                         addressbook_set_clist(obj, TRUE);
2252         }
2253
2254 }
2255
2256 static void addressbook_new_group_cb(gpointer data, guint action,
2257                                      GtkWidget *widget)
2258 {
2259         GtkCTree *ctree = GTK_CTREE(addrbook.ctree);
2260         AddressObject *obj = NULL;
2261         AddressDataSource *ds = NULL;
2262         AddressBookFile *abf = NULL;
2263         ItemFolder *parentFolder = NULL;
2264         ItemGroup *group = NULL;
2265
2266         if( ! addrbook.treeSelected ) return;
2267         obj = gtk_ctree_node_get_row_data(ctree, addrbook.treeSelected);
2268         if( obj == NULL ) return;
2269         ds = addressbook_find_datasource( addrbook.treeSelected );
2270         if( ds == NULL ) return;
2271
2272         if( obj->type == ADDR_DATASOURCE ) {
2273                 if( ADAPTER_DSOURCE(obj)->subType != ADDR_BOOK ) return;
2274         }
2275         else if( obj->type == ADDR_ITEM_FOLDER ) {
2276                 parentFolder = ADAPTER_FOLDER(obj)->itemFolder;
2277         }
2278         else {
2279                 return;
2280         }
2281
2282         abf = ds->rawDataSource;
2283         if( abf == NULL ) return;
2284         group = addressbook_edit_group( abf, parentFolder, NULL );
2285         if( group ) {
2286                 GtkCTreeNode *nn;
2287                 nn = addressbook_node_add_group( addrbook.treeSelected, ds, group );
2288                 gtk_ctree_expand( ctree, addrbook.treeSelected );
2289                 if( addrbook.treeSelected == addrbook.opened )
2290                         addressbook_set_clist(obj, TRUE);
2291         }
2292
2293 }
2294
2295 static void addressbook_change_node_name(GtkCTreeNode *node, const gchar *name)
2296 {
2297         GtkCTree *ctree = GTK_CTREE(addrbook.ctree);
2298         gchar *text[1];
2299         guint8 spacing;
2300         GdkPixmap *pix_cl, *pix_op;
2301         GdkBitmap *mask_cl, *mask_op;
2302         gboolean is_leaf, expanded;
2303
2304         gtk_ctree_get_node_info(ctree, node, text, &spacing,
2305                                 &pix_cl, &mask_cl, &pix_op, &mask_op,
2306                                 &is_leaf, &expanded);
2307         gtk_ctree_set_node_info(ctree, node, name, spacing,
2308                                 pix_cl, mask_cl, pix_op, mask_op,
2309                                 is_leaf, expanded);
2310 }
2311
2312 /**
2313  * Edit data source.
2314  * \param obj  Address object to edit.
2315  * \param node Node in tree.
2316  * \return New name of data source.
2317  */
2318 static gchar *addressbook_edit_datasource( AddressObject *obj, GtkCTreeNode *node ) {
2319         gchar *newName = NULL;
2320         AddressDataSource *ds = NULL;
2321         AddressInterface *iface = NULL;
2322         AdapterDSource *ads = NULL;
2323
2324         ds = addressbook_find_datasource( node );
2325         if( ds == NULL ) return NULL;
2326         iface = ds->interface;
2327         if( ! iface->haveLibrary ) return NULL;
2328
2329         /* Read data from data source */
2330         if( addrindex_ds_get_modify_flag( ds ) ) {
2331                 addrindex_ds_read_data( ds );
2332         }
2333
2334         if( ! addrindex_ds_get_read_flag( ds ) ) {
2335                 addrindex_ds_read_data( ds );
2336         }
2337
2338         /* Handle edit */
2339         ads = ADAPTER_DSOURCE(obj);
2340         if( ads->subType == ADDR_BOOK ) {
2341                 if( addressbook_edit_book( _addressIndex_, ads ) == NULL ) return NULL;
2342         }
2343         else if( ads->subType == ADDR_VCARD ) {
2344                 if( addressbook_edit_vcard( _addressIndex_, ads ) == NULL ) return NULL;
2345         }
2346 #ifdef USE_JPILOT
2347         else if( ads->subType == ADDR_JPILOT ) {
2348                 if( addressbook_edit_jpilot( _addressIndex_, ads ) == NULL ) return NULL;
2349         }
2350 #endif
2351 #ifdef USE_LDAP
2352         else if( ads->subType == ADDR_LDAP ) {
2353                 if( addressbook_edit_ldap( _addressIndex_, ads ) == NULL ) return NULL;
2354         }
2355 #endif
2356         else {
2357                 return NULL;
2358         }
2359         newName = obj->name;
2360         return newName;
2361 }
2362
2363 /*
2364 * Edit an object that is in the address tree area.
2365 */
2366 static void addressbook_treenode_edit_cb(gpointer data, guint action,
2367                                        GtkWidget *widget)
2368 {
2369         GtkCTree *ctree = GTK_CTREE(addrbook.ctree);
2370         AddressObject *obj;
2371         AddressDataSource *ds = NULL;
2372         AddressBookFile *abf = NULL;
2373         GtkCTreeNode *node = NULL, *parentNode = NULL;
2374         gchar *name = NULL;
2375
2376         if( ! addrbook.treeSelected ) return;
2377         node = addrbook.treeSelected;
2378         if( GTK_CTREE_ROW(node)->level == 1 ) return;
2379         obj = gtk_ctree_node_get_row_data( ctree, node );
2380         if( obj == NULL ) return;
2381         parentNode = GTK_CTREE_ROW(node)->parent;
2382
2383         ds = addressbook_find_datasource( node );
2384         if( ds == NULL ) return;
2385
2386         if( obj->type == ADDR_DATASOURCE ) {
2387                 name = addressbook_edit_datasource( obj, node );
2388                 if( name == NULL ) return;
2389         }
2390         else {
2391                 abf = ds->rawDataSource;
2392                 if( abf == NULL ) return;
2393                 if( obj->type == ADDR_ITEM_FOLDER ) {
2394                         AdapterFolder *adapter = ADAPTER_FOLDER(obj);
2395                         ItemFolder *item = adapter->itemFolder;
2396                         ItemFolder *parentFolder = NULL;
2397                         parentFolder = ( ItemFolder * ) ADDRITEM_PARENT(item);
2398                         if( addressbook_edit_folder( abf, parentFolder, item ) == NULL ) return;
2399                         name = ADDRITEM_NAME(item);
2400                 }
2401                 else if( obj->type == ADDR_ITEM_GROUP ) {
2402                         AdapterGroup *adapter = ADAPTER_GROUP(obj);
2403                         ItemGroup *item = adapter->itemGroup;
2404                         ItemFolder *parentFolder = NULL;
2405                         parentFolder = ( ItemFolder * ) ADDRITEM_PARENT(item);
2406                         if( addressbook_edit_group( abf, parentFolder, item ) == NULL ) return;
2407                         name = ADDRITEM_NAME(item);
2408                 }
2409         }
2410         if( name && parentNode ) {
2411                 /* Update node in tree view */
2412                 addressbook_change_node_name( node, name );
2413                 gtk_sctree_sort_node(ctree, parentNode);
2414                 gtk_ctree_expand( ctree, node );
2415                 gtk_sctree_select( GTK_SCTREE( ctree), node );
2416         }
2417 }
2418
2419 typedef enum {
2420         ADDRTREE_DEL_NONE,
2421         ADDRTREE_DEL_DATA,
2422         ADDRTREE_DEL_FOLDER_ONLY,
2423         ADDRTREE_DEL_FOLDER_ADDR
2424 } TreeItemDelType ;
2425
2426 /**
2427  * Delete an item from the tree widget.
2428  * \param data   Data passed in.
2429  * \param action Action.
2430  * \param widget Widget issuing callback.
2431  */
2432 static void addressbook_treenode_delete_cb(
2433                 gpointer data, guint action, GtkWidget *widget )
2434 {
2435         GtkCTree *ctree = GTK_CTREE(addrbook.ctree);
2436         GtkCTreeNode *node = NULL;
2437         AddressObject *obj;
2438         gchar *message;
2439         AlertValue aval;
2440         AddrBookBase *adbase;
2441         AddressCache *cache;
2442         AdapterDSource *ads = NULL;
2443         AddressInterface *iface = NULL;
2444         AddressDataSource *ds = NULL;
2445         gboolean remFlag = FALSE;
2446         TreeItemDelType delType;
2447
2448         if( ! addrbook.treeSelected ) return;
2449         node = addrbook.treeSelected;
2450         if( GTK_CTREE_ROW(node)->level == 1 ) return;
2451
2452         obj = gtk_ctree_node_get_row_data( ctree, node );
2453         g_return_if_fail(obj != NULL);
2454
2455         if( obj->type == ADDR_DATASOURCE ) {
2456                 ads = ADAPTER_DSOURCE(obj);
2457                 if( ads == NULL ) return;
2458                 ds = ads->dataSource;
2459                 if( ds == NULL ) return;
2460         }
2461         else {
2462                 /* Must be folder or something else */
2463                 ds = addressbook_find_datasource( node );
2464                 if( ds == NULL ) return;
2465
2466                 /* Only allow deletion from non-readOnly */
2467                 iface = ds->interface;
2468                 if( iface->readOnly ) {
2469                         /* Allow deletion of query results */
2470                         if( ! iface->externalQuery ) return;
2471                 }
2472         }
2473
2474         /* Confirm deletion */
2475         delType = ADDRTREE_DEL_NONE;
2476         if( obj->type == ADDR_ITEM_FOLDER ) {
2477                 if( iface->externalQuery ) {
2478                         message = g_strdup_printf( _(
2479                                 "Do you want to delete the query " \
2480                                 "results and addresses in '%s' ?" ),
2481                                 obj->name );
2482                         aval = alertpanel( _("Delete"), message,
2483                                 GTK_STOCK_YES, GTK_STOCK_NO, NULL );
2484                         g_free(message);
2485                         if( aval == G_ALERTDEFAULT ) {
2486                                 delType = ADDRTREE_DEL_FOLDER_ADDR;
2487                         }
2488                 }
2489                 else {
2490                         message = g_strdup_printf
2491                                 ( _( "Do you want to delete the folder AND all addresses in '%s' ?\n"
2492                                      "If deleting the folder only, addresses will be moved into parent folder." ),
2493                                  obj->name );
2494                         aval = alertpanel( _("Delete folder"), message,
2495                                 _("_Folder only"), _("Folder and _addresses"),
2496                                 GTK_STOCK_CANCEL );
2497                         g_free(message);
2498                         if( aval == G_ALERTDEFAULT ) {
2499                                 delType = ADDRTREE_DEL_FOLDER_ONLY;
2500                         }
2501                         else if( aval == G_ALERTALTERNATE ) {
2502                                 delType = ADDRTREE_DEL_FOLDER_ADDR;
2503                         }
2504                 }
2505         }
2506         else {
2507                 message = g_strdup_printf(_("Really delete '%s' ?"), obj->name);
2508                 aval = alertpanel(_("Delete"), message, GTK_STOCK_YES, GTK_STOCK_NO, NULL);
2509                 g_free(message);
2510                 if( aval == G_ALERTDEFAULT ) delType = ADDRTREE_DEL_DATA;
2511         }
2512         if( delType == ADDRTREE_DEL_NONE ) return;
2513
2514         /* Proceed with deletion */
2515         if( obj->type == ADDR_DATASOURCE ) {
2516                 /* Remove node from tree */
2517                 gtk_ctree_remove_node( ctree, node );
2518         
2519                 /* Remove data source. */
2520                 if( addrindex_index_remove_datasource( _addressIndex_, ds ) ) {
2521                         addrindex_free_datasource( ds );
2522                 }
2523                 return;
2524         }
2525
2526         /* Get reference to cache */
2527         adbase = ( AddrBookBase * ) ds->rawDataSource;
2528         if( adbase == NULL ) return;
2529         cache = adbase->addressCache;
2530
2531         /* Remove query results folder */
2532         if( iface->externalQuery ) {
2533                 AdapterFolder *adapter = ADAPTER_FOLDER(obj);
2534                 ItemFolder *folder = adapter->itemFolder;
2535
2536                 adapter->itemFolder = NULL;
2537                 /*
2538                 printf( "remove folder for ::%s::\n", obj->name );
2539                 printf( "      folder name ::%s::\n", ADDRITEM_NAME(folder) );
2540                 printf( "-------------- remove results\n" );
2541                 */
2542                 addrindex_remove_results( ds, folder );
2543                 /* printf( "-------------- remove node\n" ); */
2544                 gtk_ctree_remove_node( ctree, node );
2545                 return;
2546         }
2547
2548         /* Code below is valid for regular address book deletion */
2549         if( obj->type == ADDR_ITEM_FOLDER ) {
2550                 AdapterFolder *adapter = ADAPTER_FOLDER(obj);
2551                 ItemFolder *item = adapter->itemFolder;
2552
2553                 if( delType == ADDRTREE_DEL_FOLDER_ONLY ) {
2554                         /* Remove folder only */
2555                         item = addrcache_remove_folder( cache, item );
2556                         if( item ) {
2557                                 addritem_free_item_folder( item );
2558                                 addressbook_move_nodes_up( ctree, node );
2559                                 remFlag = TRUE;
2560                         }
2561                 }
2562                 else if( delType == ADDRTREE_DEL_FOLDER_ADDR ) {
2563                         /* Remove folder and addresses */
2564                         item = addrcache_remove_folder_delete( cache, item );
2565                         if( item ) {
2566                                 addritem_free_item_folder( item );
2567                                 remFlag = TRUE;
2568                         }
2569                 }
2570         }
2571         else if( obj->type == ADDR_ITEM_GROUP ) {
2572                 AdapterGroup *adapter = ADAPTER_GROUP(obj);
2573                 ItemGroup *item = adapter->itemGroup;
2574
2575                 item = addrcache_remove_group( cache, item );
2576                 if( item ) {
2577                         addritem_free_item_group( item );
2578                         remFlag = TRUE;
2579                 }
2580         }
2581
2582         if( remFlag ) {
2583                 /* Remove node. */
2584                 gtk_ctree_remove_node(ctree, node );
2585         }
2586 }
2587
2588 static void addressbook_new_address_cb( gpointer data, guint action, GtkWidget *widget ) {
2589         AddressObject *pobj = NULL;
2590         AddressDataSource *ds = NULL;
2591         AddressBookFile *abf = NULL;
2592
2593         pobj = gtk_ctree_node_get_row_data(GTK_CTREE(addrbook.ctree), addrbook.treeSelected);
2594         if( pobj == NULL ) return;
2595         ds = addressbook_find_datasource( GTK_CTREE_NODE(addrbook.treeSelected) );
2596         if( ds == NULL ) return;
2597
2598         abf = ds->rawDataSource;
2599         if( abf == NULL ) return;
2600
2601         if( pobj->type == ADDR_DATASOURCE ) {
2602                 if( ADAPTER_DSOURCE(pobj)->subType == ADDR_BOOK ) {
2603                         /* New address */
2604                         ItemPerson *person = addressbook_edit_person( abf, NULL, NULL, FALSE );
2605                         if( person && addrbook.treeSelected == addrbook.opened ) {
2606                                 gtk_clist_unselect_all( GTK_CLIST(addrbook.clist) );
2607                                 addressbook_folder_refresh_one_person(
2608                                         GTK_CTREE(addrbook.clist), person );
2609                         }
2610                 }
2611         }
2612         else if( pobj->type == ADDR_ITEM_FOLDER ) {
2613                 /* New address */
2614                 ItemFolder *folder = ADAPTER_FOLDER(pobj)->itemFolder;
2615                 ItemPerson *person = addressbook_edit_person( abf, folder, NULL, FALSE );
2616                 if( person ) {
2617                         if (addrbook.treeSelected == addrbook.opened) {
2618                                 gtk_sctree_select( GTK_SCTREE(addrbook.ctree), addrbook.opened );
2619                         }
2620                 }
2621         }
2622         else if( pobj->type == ADDR_ITEM_GROUP ) {
2623                 /* New address in group */
2624                 ItemGroup *group = ADAPTER_GROUP(pobj)->itemGroup;
2625                 if( addressbook_edit_group( abf, NULL, group ) == NULL ) return;
2626                 if (addrbook.treeSelected == addrbook.opened) {
2627                         /* Change node name in tree. */
2628                         addressbook_change_node_name( addrbook.treeSelected, ADDRITEM_NAME(group) );
2629                         gtk_sctree_select( GTK_SCTREE(addrbook.ctree), addrbook.opened );
2630                 }
2631         }
2632 }
2633
2634 /**
2635  * Search for specified child group node in address index tree.
2636  * \param parent Parent node.
2637  * \param group  Group to find.
2638  */
2639 static GtkCTreeNode *addressbook_find_group_node( GtkCTreeNode *parent, ItemGroup *group ) {
2640         GtkCTreeNode *node = NULL;
2641         GtkCTreeRow *currRow;
2642
2643         currRow = GTK_CTREE_ROW( parent );
2644         if( currRow ) {
2645                 node = currRow->children;
2646                 while( node ) {
2647                         AddressObject *obj;
2648
2649                         obj = gtk_ctree_node_get_row_data( GTK_CTREE(addrbook.ctree), node );
2650                         if( obj->type == ADDR_ITEM_GROUP ) {
2651                                 ItemGroup *g = ADAPTER_GROUP(obj)->itemGroup;
2652                                 if( g == group ) return node;
2653                         }
2654                         currRow = GTK_CTREE_ROW(node);
2655                         node = currRow->sibling;
2656                 }
2657         }
2658         return NULL;
2659 }
2660
2661 static AddressBookFile *addressbook_get_book_file() {
2662         AddressBookFile *abf = NULL;
2663         AddressDataSource *ds = NULL;
2664
2665         ds = addressbook_find_datasource( addrbook.treeSelected );
2666         if( ds == NULL ) return NULL;
2667         if( ds->type == ADDR_IF_BOOK ) abf = ds->rawDataSource;
2668         return abf;
2669 }
2670
2671 static AddressBookFile *addressbook_get_book_file_for_node(GtkCTreeNode *node) {
2672         AddressBookFile *abf = NULL;
2673         AddressDataSource *ds = NULL;
2674
2675         ds = addressbook_find_datasource( node );
2676         if( ds == NULL ) return NULL;
2677         if( ds->type == ADDR_IF_BOOK ) abf = ds->rawDataSource;
2678         return abf;
2679 }
2680
2681 static void addressbook_tree_remove_children( GtkCTree *ctree, GtkCTreeNode *parent ) {
2682         GtkCTreeNode *node;
2683         GtkCTreeRow *row;
2684
2685         /* Remove existing folders and groups */
2686         row = GTK_CTREE_ROW( parent );
2687         if( row ) {
2688                 while( (node = row->children) ) {
2689                         gtk_ctree_remove_node( ctree, node );
2690                 }
2691         }
2692 }
2693
2694 static void addressbook_move_nodes_up( GtkCTree *ctree, GtkCTreeNode *node ) {
2695         GtkCTreeNode *parent, *child;
2696         GtkCTreeRow *currRow;
2697         currRow = GTK_CTREE_ROW( node );
2698         if( currRow ) {
2699                 parent = currRow->parent;
2700                 while( (child = currRow->children) ) {
2701                         gtk_ctree_move( ctree, child, parent, node );
2702                 }
2703                 gtk_sctree_sort_node( ctree, parent );
2704         }
2705 }
2706
2707 static void addressbook_edit_address_cb( gpointer data, guint action, GtkWidget *widget ) {
2708         GtkCTree *clist = GTK_CTREE(addrbook.clist);
2709         GtkCTree *ctree;
2710         AddressObject *obj = NULL, *pobj = NULL;
2711         AddressDataSource *ds = NULL;
2712         GtkCTreeNode *node = NULL, *parentNode = NULL;
2713         gchar *name = NULL;
2714         AddressBookFile *abf = NULL;
2715
2716         if( addrbook.listSelected == NULL ) return;
2717         obj = gtk_ctree_node_get_row_data( clist, addrbook.listSelected );
2718         g_return_if_fail(obj != NULL);
2719
2720         ctree = GTK_CTREE( addrbook.ctree );
2721         pobj = gtk_ctree_node_get_row_data( ctree, addrbook.treeSelected );
2722         node = gtk_ctree_find_by_row_data( ctree, addrbook.treeSelected, obj );
2723
2724         ds = addressbook_find_datasource( GTK_CTREE_NODE(addrbook.treeSelected) );
2725         if( ds == NULL ) return;
2726
2727         abf = addressbook_get_book_file();
2728         
2729         if( obj->type == ADDR_ITEM_EMAIL ) {
2730                 ItemEMail *email = ( ItemEMail * ) obj;
2731                 if( email == NULL ) return;
2732                 if( pobj && pobj->type == ADDR_ITEM_GROUP ) {
2733                         /* Edit parent group */
2734                         AdapterGroup *adapter = ADAPTER_GROUP(pobj);
2735                         ItemGroup *itemGrp = adapter->itemGroup;
2736                         if( abf == NULL ) return;
2737                         if( addressbook_edit_group( abf, NULL, itemGrp ) == NULL ) return;
2738                         name = ADDRITEM_NAME(itemGrp);
2739                         node = addrbook.treeSelected;
2740                         parentNode = GTK_CTREE_ROW(node)->parent;
2741                 }
2742                 else {
2743                         /* Edit person - email page */
2744                         ItemPerson *person;
2745                         person = ( ItemPerson * ) ADDRITEM_PARENT(email);
2746                         if( addressbook_edit_person( abf, NULL, person, TRUE ) == NULL ) return;
2747                         addressbook_folder_refresh_one_person( clist, person );
2748                         invalidate_address_completion();
2749                         return;
2750                 }
2751         }
2752         else if( obj->type == ADDR_ITEM_PERSON ) {
2753                 /* Edit person - basic page */
2754                 ItemPerson *person = ( ItemPerson * ) obj;
2755                 if( addressbook_edit_person( abf, NULL, person, FALSE ) == NULL ) return;
2756                 invalidate_address_completion();
2757                 addressbook_folder_refresh_one_person( clist, person );
2758                 return;
2759         }
2760         else if( obj->type == ADDR_ITEM_GROUP ) {
2761                 ItemGroup *itemGrp = ( ItemGroup * ) obj;
2762                 if( addressbook_edit_group( abf, NULL, itemGrp ) == NULL ) return;
2763                 parentNode = addrbook.treeSelected;
2764                 node = addressbook_find_group_node( parentNode, itemGrp );
2765                 name = ADDRITEM_NAME(itemGrp);
2766         }
2767         else {
2768                 return;
2769         }
2770
2771         /* Update tree node with node name */
2772         if( node == NULL ) return;
2773         addressbook_change_node_name( node, name );
2774         gtk_sctree_sort_node( ctree, parentNode );
2775         gtk_sctree_select( GTK_SCTREE(ctree), addrbook.opened ); 
2776 }
2777
2778 static void addressbook_delete_address_cb(gpointer data, guint action,
2779                                           GtkWidget *widget)
2780 {
2781         addressbook_del_clicked(NULL, NULL);
2782 }
2783
2784 static void close_cb(gpointer data, guint action, GtkWidget *widget)
2785 {
2786         addressbook_close();
2787 }
2788
2789 static void addressbook_file_save_cb( gpointer data, guint action, GtkWidget *widget ) {
2790         addressbook_export_to_file();
2791 }
2792
2793 static void addressbook_person_expand_node( GtkCTree *ctree, GList *node, gpointer *data ) {
2794         if( node ) {
2795                 ItemPerson *person = gtk_ctree_node_get_row_data( ctree, GTK_CTREE_NODE(node) );
2796                 if( person ) addritem_person_set_opened( person, TRUE );
2797         }
2798 }
2799
2800 static void addressbook_person_collapse_node( GtkCTree *ctree, GList *node, gpointer *data ) {
2801         if( node ) {
2802                 ItemPerson *person = gtk_ctree_node_get_row_data( ctree, GTK_CTREE_NODE(node) );
2803                 if( person ) addritem_person_set_opened( person, FALSE );
2804         }
2805 }
2806
2807 static gchar *addressbook_format_item_clist( ItemPerson *person, ItemEMail *email ) {
2808         gchar *str = NULL;
2809         gchar *eMailAlias = ADDRITEM_NAME(email);
2810         if( eMailAlias && *eMailAlias != '\0' ) {
2811                 if( person ) {
2812                         str = g_strdup_printf( "%s - %s", ADDRITEM_NAME(person), eMailAlias );
2813                 }
2814                 else {
2815                         str = g_strdup( eMailAlias );
2816                 }
2817         }
2818         return str;
2819 }
2820
2821 static void addressbook_load_group( GtkCTree *clist, ItemGroup *itemGroup ) {
2822         GList *items = itemGroup->listEMail;
2823         AddressTypeControlItem *atci = addrbookctl_lookup( ADDR_ITEM_EMAIL );
2824         for( ; items != NULL; items = g_list_next( items ) ) {
2825                 GtkCTreeNode *nodeEMail = NULL;
2826                 gchar *text[N_LIST_COLS];
2827                 ItemEMail *email = items->data;
2828                 ItemPerson *person;
2829                 gchar *str = NULL;
2830
2831                 if( ! email ) continue;
2832
2833                 person = ( ItemPerson * ) ADDRITEM_PARENT(email);
2834                 str = addressbook_format_item_clist( person, email );
2835                 if( str ) {
2836                         text[COL_NAME] = str;
2837                 }
2838                 else {
2839                         text[COL_NAME] = ADDRITEM_NAME(person);
2840                 }
2841                 text[COL_ADDRESS] = email->address;
2842                 text[COL_REMARKS] = email->remarks;
2843                 nodeEMail = gtk_ctree_insert_node(
2844                                 clist, NULL, NULL,
2845                                 text, FOLDER_SPACING,
2846                                 atci->iconXpm, atci->maskXpm,
2847                                 atci->iconXpmOpen, atci->maskXpmOpen,
2848                                 FALSE, FALSE );
2849                 gtk_ctree_node_set_row_data( clist, nodeEMail, email );
2850                 g_free( str );
2851                 str = NULL;
2852         }
2853 }
2854
2855 static void addressbook_folder_load_one_person(
2856                 GtkCTree *clist, ItemPerson *person,
2857                 AddressTypeControlItem *atci,
2858                 AddressTypeControlItem *atciMail )
2859 {
2860         GtkCTreeNode *nodePerson = NULL;
2861         GtkCTreeNode *nodeEMail = NULL;
2862         gchar *text[N_LIST_COLS];
2863         gboolean flgFirst = TRUE, haveAddr = FALSE;
2864         GList *node;
2865
2866         if( person == NULL ) return;
2867
2868         text[COL_NAME] = NULL;
2869         node = person->listEMail;
2870         while( node ) {
2871                 ItemEMail *email = node->data;
2872                 gchar *eMailAddr = NULL;
2873                 node = g_list_next( node );
2874
2875                 text[COL_ADDRESS] = email->address;
2876                 text[COL_REMARKS] = email->remarks;
2877                 eMailAddr = ADDRITEM_NAME(email);
2878                 if( eMailAddr && *eMailAddr == '\0' ) eMailAddr = NULL;
2879                 if( flgFirst ) {
2880                         /* First email belongs with person */
2881                         gchar *str = addressbook_format_item_clist( person, email );
2882                         if( str ) {
2883                                 text[COL_NAME] = str;
2884                         }
2885                         else {
2886                                 text[COL_NAME] = ADDRITEM_NAME(person);
2887                         }
2888                         nodePerson = gtk_ctree_insert_node(
2889                                         clist, NULL, NULL,
2890                                         text, FOLDER_SPACING,
2891                                         atci->iconXpm, atci->maskXpm,
2892                                         atci->iconXpmOpen, atci->maskXpmOpen,
2893                                         FALSE, person->isOpened );
2894                         g_free( str );
2895                         str = NULL;
2896                         gtk_ctree_node_set_row_data(clist, nodePerson, person );
2897                 }
2898                 else {
2899                         /* Subsequent email is a child node of person */
2900                         text[COL_NAME] = ADDRITEM_NAME(email);
2901                         nodeEMail = gtk_ctree_insert_node(
2902                                         clist, nodePerson, NULL,
2903                                         text, FOLDER_SPACING,
2904                                         atciMail->iconXpm, atciMail->maskXpm,
2905                                         atciMail->iconXpmOpen, atciMail->maskXpmOpen,
2906                                         FALSE, TRUE );
2907                         gtk_ctree_node_set_row_data(clist, nodeEMail, email );
2908                 }
2909                 flgFirst = FALSE;
2910                 haveAddr = TRUE;
2911         }
2912         if( ! haveAddr ) {
2913                 /* Have name without EMail */
2914                 text[COL_NAME] = ADDRITEM_NAME(person);
2915                 text[COL_ADDRESS] = NULL;
2916                 text[COL_REMARKS] = NULL;
2917                 nodePerson = gtk_ctree_insert_node(
2918                                 clist, NULL, NULL,
2919                                 text, FOLDER_SPACING,
2920                                 atci->iconXpm, atci->maskXpm,
2921                                 atci->iconXpmOpen, atci->maskXpmOpen,
2922                                 FALSE, person->isOpened );
2923                 gtk_ctree_node_set_row_data(clist, nodePerson, person );
2924         }
2925         return;
2926 }
2927
2928 static void addressbook_folder_load_person( GtkCTree *clist, ItemFolder *itemFolder ) {
2929         GList *items;
2930         AddressTypeControlItem *atci = addrbookctl_lookup( ADDR_ITEM_PERSON );
2931         AddressTypeControlItem *atciMail = addrbookctl_lookup( ADDR_ITEM_EMAIL );
2932
2933         if( atci == NULL ) return;
2934         if( atciMail == NULL ) return;
2935
2936         /* Load email addresses */
2937         items = addritem_folder_get_person_list( itemFolder );
2938         for( ; items != NULL; items = g_list_next( items ) ) {
2939                 addressbook_folder_load_one_person( clist, items->data, atci, atciMail );
2940         }
2941         /* Free up the list */
2942         mgu_clear_list( items );
2943         g_list_free( items );
2944 }
2945
2946 static void addressbook_folder_remove_node( GtkCTree *clist, GtkCTreeNode *node ) { 
2947         addrbook.listSelected = NULL;
2948         gtk_ctree_remove_node( clist, node );
2949         addressbook_menubar_set_sensitive( FALSE );
2950         addressbook_menuitem_set_sensitive(
2951                 gtk_ctree_node_get_row_data(
2952                         GTK_CTREE(clist), addrbook.treeSelected ),
2953                 addrbook.treeSelected );
2954 }
2955
2956 static void addressbook_folder_refresh_one_person( GtkCTree *clist, ItemPerson *person ) {
2957         AddressTypeControlItem *atci = addrbookctl_lookup( ADDR_ITEM_PERSON );
2958         AddressTypeControlItem *atciMail = addrbookctl_lookup( ADDR_ITEM_EMAIL );
2959         GtkCTreeNode *node;
2960         if( atci == NULL ) return;
2961         if( atciMail == NULL ) return;
2962         if( person == NULL ) return;
2963         /* unload the person */
2964         
2965         node = gtk_ctree_find_by_row_data( clist, NULL, person );
2966         if( node )
2967                 addressbook_folder_remove_node( clist, node );
2968         addressbook_folder_load_one_person( clist, person, atci, atciMail );
2969         gtk_sctree_sort_node( clist, NULL );
2970         node = gtk_ctree_find_by_row_data( clist, NULL, person );
2971         if( node ) {
2972                 gtk_sctree_select( GTK_SCTREE(clist), node );
2973                 if (!gtk_ctree_node_is_visible( clist, node ) ) 
2974                         gtk_ctree_node_moveto( clist, node, 0, 0, 0 );
2975         }
2976 }
2977
2978 static void addressbook_folder_remove_one_person( GtkCTree *clist, ItemPerson *person ) {
2979         GtkCTreeNode *node;
2980         gint row;
2981         
2982         if( person == NULL ) return;
2983         node = gtk_ctree_find_by_row_data( clist, NULL, person );
2984         row  = gtk_clist_find_row_from_data( GTK_CLIST(clist), person );
2985         if( node ) {
2986                 addressbook_folder_remove_node( clist, node );
2987         }
2988 }
2989
2990 static void addressbook_folder_load_group( GtkCTree *clist, ItemFolder *itemFolder ) {
2991         GList *items;
2992         AddressTypeControlItem *atci =  addrbookctl_lookup( ADDR_ITEM_GROUP );
2993
2994         /* Load any groups */
2995         if( ! atci ) return;
2996         items = addritem_folder_get_group_list( itemFolder );
2997         for( ; items != NULL; items = g_list_next( items ) ) {
2998                 GtkCTreeNode *nodeGroup = NULL;
2999                 gchar *text[N_LIST_COLS];
3000                 ItemGroup *group = items->data;
3001                 if( group == NULL ) continue;
3002                 text[COL_NAME] = ADDRITEM_NAME(group);
3003                 text[COL_ADDRESS] = NULL;
3004                 text[COL_REMARKS] = NULL;
3005                 nodeGroup = gtk_ctree_insert_node(clist, NULL, NULL,
3006                                       text, FOLDER_SPACING,
3007                                       atci->iconXpm, atci->maskXpm,
3008                                       atci->iconXpmOpen, atci->maskXpmOpen,
3009                                       FALSE, FALSE);
3010                 gtk_ctree_node_set_row_data(clist, nodeGroup, group );
3011                 gtk_sctree_sort_node(clist, NULL);
3012         }
3013         /* Free up the list */
3014         mgu_clear_list( items );
3015         g_list_free( items );
3016 }
3017
3018 /**
3019  * Search ctree widget callback function.
3020  * \param  pA Pointer to node.
3021  * \param  pB Pointer to data item being sought.
3022  * \return Zero (0) if group found.
3023  */
3024 static int addressbook_treenode_find_group_cb( gconstpointer pA, gconstpointer pB ) {
3025         AddressObject *aoA;
3026
3027         aoA = ( AddressObject * ) pA;
3028         if( aoA->type == ADDR_ITEM_GROUP ) {
3029                 ItemGroup *group, *grp;
3030
3031                 grp = ADAPTER_GROUP(aoA)->itemGroup;
3032                 group = ( ItemGroup * ) pB;
3033                 if( grp == group ) return 0;    /* Found group */
3034         }
3035         return 1;
3036 }
3037
3038 /**
3039  * Search ctree widget callback function.
3040  * \param  pA Pointer to node.
3041  * \param  pB Pointer to data item being sought.
3042  * \return Zero (0) if folder found.
3043  */
3044 static int addressbook_treenode_find_folder_cb( gconstpointer pA, gconstpointer pB ) {
3045         AddressObject *aoA;
3046
3047         aoA = ( AddressObject * ) pA;
3048         if( aoA->type == ADDR_ITEM_FOLDER ) {
3049                 ItemFolder *folder, *fld;
3050
3051                 fld = ADAPTER_FOLDER(aoA)->itemFolder;
3052                 folder = ( ItemFolder * ) pB;
3053                 if( fld == folder ) return 0;   /* Found folder */
3054         }
3055         return 1;
3056 }
3057
3058 /*
3059 * Remove folder and group nodes from tree widget for items contained ("cut")
3060 * in clipboard.
3061 */
3062 static void addressbook_treenode_remove_item( void ) {
3063         GList *node;
3064         AddrSelectItem *cutItem;
3065         AddressCache *cache;
3066         AddrItemObject *aio;
3067         GtkCTree *ctree = GTK_CTREE( addrbook.ctree );
3068         GtkCTreeNode *tn;
3069
3070         node = _clipBoard_->objectList;
3071         while( node ) {
3072                 cutItem = node->data;
3073                 node = g_list_next( node );
3074                 cache = addrindex_get_cache(
3075                         _clipBoard_->addressIndex, cutItem->cacheID );
3076                 if( cache == NULL ) continue;
3077                 aio = addrcache_get_object( cache, cutItem->uid );
3078                 if( aio ) {
3079                         tn = NULL;
3080                         if( ADDRITEM_TYPE(aio) == ITEMTYPE_FOLDER ) {
3081                                 ItemFolder *folder;
3082
3083                                 folder = ( ItemFolder * ) aio;
3084                                 tn = gtk_ctree_find_by_row_data_custom(
3085                                         ctree, NULL, folder,
3086                                         addressbook_treenode_find_folder_cb );
3087                         }
3088                         else if( ADDRITEM_TYPE(aio) == ITEMTYPE_GROUP ) {
3089                                 ItemGroup *group;
3090
3091                                 group = ( ItemGroup * ) aio;
3092                                 tn = gtk_ctree_find_by_row_data_custom(
3093                                         ctree, NULL, group,
3094                                         addressbook_treenode_find_group_cb );
3095                         }
3096
3097                         if( tn ) {
3098                                 /* Free up adapter and remove node. */
3099                                 gtk_ctree_remove_node( ctree, tn );
3100                         }
3101                 }
3102         }
3103 }
3104
3105 /**
3106  * Find parent datasource for specified tree node.
3107  * \param  node Node to test.
3108  * \return Data source, or NULL if not found.
3109  */
3110 static AddressDataSource *addressbook_find_datasource( GtkCTreeNode *node ) {
3111         AddressDataSource *ds = NULL;
3112         AddressObject *ao;
3113
3114         g_return_val_if_fail(addrbook.ctree != NULL, NULL);
3115
3116         while( node ) {
3117                 if( GTK_CTREE_ROW(node)->level < 2 ) return NULL;
3118                 ao = gtk_ctree_node_get_row_data( GTK_CTREE(addrbook.ctree), node );
3119                 if( ao ) {
3120                         /* printf( "ao->type = %d\n", ao->type ); */
3121                         if( ao->type == ADDR_DATASOURCE ) {
3122                                 AdapterDSource *ads = ADAPTER_DSOURCE(ao);
3123                                 /* printf( "found it\n" ); */
3124                                 ds = ads->dataSource;
3125                                 break;
3126                         }
3127                 }
3128                 node = GTK_CTREE_ROW(node)->parent;
3129         }
3130         return ds;
3131 }
3132
3133 /**
3134  * Load address list widget with children of specified object.
3135  * \param obj Parent object to be loaded.
3136  */
3137 static void addressbook_set_clist( AddressObject *obj, gboolean refresh ) {
3138         GtkCTree *ctreelist = GTK_CTREE(addrbook.clist);
3139         GtkCList *clist = GTK_CLIST(addrbook.clist);
3140         AddressDataSource *ds = NULL;
3141         AdapterDSource *ads = NULL;
3142         static AddressObject *last_obj = NULL;
3143
3144         if (obj == last_obj && !refresh)
3145                 return;
3146
3147         last_obj = obj;
3148         if( obj == NULL ) {
3149                 gtk_clist_clear(clist);
3150                 return;
3151         }
3152
3153         if( obj->type == ADDR_INTERFACE ) {
3154                 /* printf( "set_clist: loading datasource...\n" ); */
3155                 /* addressbook_node_load_datasource( GTK_CTREE(clist), obj ); */
3156                 return;
3157         }
3158
3159         gtk_clist_freeze(clist);
3160         gtk_clist_clear(clist);
3161
3162         if( obj->type == ADDR_DATASOURCE ) {
3163                 ads = ADAPTER_DSOURCE(obj);
3164                 ds = ADAPTER_DSOURCE(obj)->dataSource;
3165                 if( ds ) {
3166                         /* Load root folder */
3167                         ItemFolder *rootFolder = NULL;
3168                         rootFolder = addrindex_ds_get_root_folder( ds );
3169                         addressbook_folder_load_person(
3170                                 ctreelist, addrindex_ds_get_root_folder( ds ) );
3171                         addressbook_folder_load_group(
3172                                 ctreelist, addrindex_ds_get_root_folder( ds ) );
3173                 }
3174         }
3175         else {
3176                 if( obj->type == ADDR_ITEM_GROUP ) {
3177                         /* Load groups */
3178                         ItemGroup *itemGroup = ADAPTER_GROUP(obj)->itemGroup;
3179                         addressbook_load_group( ctreelist, itemGroup );
3180                 }
3181                 else if( obj->type == ADDR_ITEM_FOLDER ) {
3182                         /* Load folders */
3183                         ItemFolder *itemFolder = ADAPTER_FOLDER(obj)->itemFolder;
3184                         addressbook_folder_load_person( ctreelist, itemFolder );
3185                         addressbook_folder_load_group( ctreelist, itemFolder );
3186                 }
3187         }
3188         gtk_sctree_sort_node(GTK_CTREE(clist), NULL);
3189         gtk_clist_thaw(clist);
3190 }
3191
3192 /**
3193  * Call back function to free adaptor. Call back is setup by function
3194  * gtk_ctree_node_set_row_data_full() when node is populated. This function is
3195  * called when the address book tree widget node is removed by calling
3196  * function gtk_ctree_remove_node().
3197  * 
3198  * \param data Tree node's row data.
3199  */
3200 static void addressbook_free_treenode( gpointer data ) {
3201         AddressObject *ao;
3202
3203         ao = ( AddressObject * ) data;
3204         if( ao == NULL ) return;
3205         if( ao->type == ADDR_INTERFACE ) {
3206                 AdapterInterface *ai = ADAPTER_INTERFACE(ao);
3207                 addrbookctl_free_interface( ai );
3208         }
3209         else if( ao->type == ADDR_DATASOURCE ) {
3210                 AdapterDSource *ads = ADAPTER_DSOURCE(ao);
3211                 addrbookctl_free_datasource( ads );
3212         }
3213         else if( ao->type == ADDR_ITEM_FOLDER ) {
3214                 AdapterFolder *af = ADAPTER_FOLDER(ao);
3215                 addrbookctl_free_folder( af );
3216         }
3217         else if( ao->type == ADDR_ITEM_GROUP ) {
3218                 AdapterGroup *ag = ADAPTER_GROUP(ao);
3219                 addrbookctl_free_group( ag );
3220         }
3221 }
3222
3223 /*
3224 * Create new adaptor for specified data source.
3225 */
3226 AdapterDSource *addressbook_create_ds_adapter( AddressDataSource *ds,
3227                                 AddressObjectType otype, gchar *name )
3228 {
3229         AdapterDSource *adapter = g_new0( AdapterDSource, 1 );
3230         ADDRESS_OBJECT(adapter)->type = ADDR_DATASOURCE;
3231         ADDRESS_OBJECT_NAME(adapter) = g_strdup( name );
3232         adapter->dataSource = ds;
3233         adapter->subType = otype;
3234         return adapter;
3235 }
3236
3237 void addressbook_ads_set_name( AdapterDSource *adapter, gchar *value ) {
3238         ADDRESS_OBJECT_NAME(adapter) =
3239                 mgu_replace_string( ADDRESS_OBJECT_NAME(adapter), value );
3240 }
3241
3242 /*
3243  * Load tree from address index with the initial data.
3244  */
3245 static void addressbook_load_tree( void ) {
3246         GtkCTree *ctree = GTK_CTREE( addrbook.ctree );
3247         GList *nodeIf, *nodeDS;
3248         AdapterInterface *adapter;
3249         AddressInterface *iface;
3250         AddressTypeControlItem *atci;
3251         AddressDataSource *ds;
3252         AdapterDSource *ads;
3253         GtkCTreeNode *node, *newNode;
3254         gchar *name;
3255
3256         nodeIf = _addressInterfaceList_;
3257         while( nodeIf ) {
3258                 adapter = nodeIf->data;
3259                 node = adapter->treeNode;
3260                 iface = adapter->interface;
3261                 atci = adapter->atci;
3262                 if( iface ) {
3263                         if( iface->useInterface ) {
3264                                 /* Load data sources below interface node */
3265                                 nodeDS = iface->listSource;
3266                                 while( nodeDS ) {
3267                                         ds = nodeDS->data;
3268                                         newNode = NULL;
3269                                         name = addrindex_ds_get_name( ds );
3270                                         ads = addressbook_create_ds_adapter(
3271                                                         ds, atci->objectType, name );
3272                                         newNode = addressbook_add_object(
3273                                                         node, ADDRESS_OBJECT(ads) );
3274                                         nodeDS = g_list_next( nodeDS );
3275                                 }
3276                                 gtk_ctree_expand( ctree, node );
3277                         }
3278                 }
3279                 nodeIf = g_list_next( nodeIf );
3280         }
3281 }
3282
3283 /*
3284  * Convert the old address book to new format.
3285  */
3286 static gboolean addressbook_convert( AddressIndex *addrIndex ) {
3287         gboolean retVal = FALSE;
3288         gboolean errFlag = TRUE;
3289         gchar *msg = NULL;
3290
3291         /* Read old address book, performing conversion */
3292         debug_print( "Reading and converting old address book...\n" );
3293         addrindex_set_file_name( addrIndex, ADDRESSBOOK_OLD_FILE );
3294         addrindex_read_data( addrIndex );
3295         if( addrIndex->retVal == MGU_NO_FILE ) {
3296                 /* We do not have a file - new user */
3297                 debug_print( "New user... create new books...\n" );
3298                 addrindex_create_new_books( addrIndex );
3299                 if( addrIndex->retVal == MGU_SUCCESS ) {
3300                         /* Save index file */
3301                         addrindex_set_file_name( addrIndex, ADDRESSBOOK_INDEX_FILE );
3302                         addrindex_save_data( addrIndex );
3303                         if( addrIndex->retVal == MGU_SUCCESS ) {
3304                                 retVal = TRUE;
3305                                 errFlag = FALSE;
3306                         }
3307                         else {
3308                                 msg = _( "New user, could not save index file." );
3309                         }
3310                 }
3311                 else {
3312                         msg = _( "New user, could not save address book files." );
3313                 }
3314         }
3315         else {
3316                 /* We have an old file */
3317                 if( addrIndex->wasConverted ) {
3318                         /* Converted successfully - save address index */
3319                         addrindex_set_file_name( addrIndex, ADDRESSBOOK_INDEX_FILE );
3320                         addrindex_save_data( addrIndex );
3321                         if( addrIndex->retVal == MGU_SUCCESS ) {
3322                                 msg = _( "Old address book converted successfully." );
3323                                 retVal = TRUE;
3324                                 errFlag = FALSE;
3325                         }
3326                         else {
3327                                 msg = _("Old address book converted,\n"
3328                                         "could not save new address index file" );
3329                         }
3330                 }
3331                 else {
3332                         /* File conversion failed - just create new books */
3333                         debug_print( "File conversion failed... just create new books...\n" );
3334                         addrindex_create_new_books( addrIndex );
3335                         if( addrIndex->retVal == MGU_SUCCESS ) {
3336                                 /* Save index */
3337                                 addrindex_set_file_name( addrIndex, ADDRESSBOOK_INDEX_FILE );
3338                                 addrindex_save_data( addrIndex );
3339                                 if( addrIndex->retVal == MGU_SUCCESS ) {
3340                                         msg = _("Could not convert address book,\n"
3341                                                 "but created empty new address book files." );
3342                                         retVal = TRUE;
3343                                         errFlag = FALSE;
3344                                 }
3345                                 else {
3346                                         msg = _("Could not convert address book,\n"
3347                                                 "could not create new address book files." );
3348                                 }
3349                         }
3350                         else {
3351                                 msg = _("Could not convert address book\n"
3352                                         "and could not create new address book files." );
3353                         }
3354                 }
3355         }
3356         if( errFlag ) {
3357                 debug_print( "Error\n%s\n", msg );
3358                 alertpanel_full(_("Addressbook conversion error"), msg,
3359                                 GTK_STOCK_CLOSE, NULL, NULL, FALSE,
3360                                 NULL, ALERT_ERROR, G_ALERTDEFAULT);
3361         }
3362         else if( msg ) {
3363                 debug_print( "Warning\n%s\n", msg );
3364                 alertpanel_full(_("Addressbook conversion error"), msg,
3365                                 GTK_STOCK_CLOSE, NULL, NULL, FALSE,
3366                                 NULL, ALERT_WARNING, G_ALERTDEFAULT);
3367         }
3368
3369         return retVal;
3370 }
3371
3372 void addressbook_read_file( void ) {
3373         AddressIndex *addrIndex = NULL;
3374
3375         debug_print( "Reading address index...\n" );
3376         if( _addressIndex_ ) {
3377                 debug_print( "address book already read!!!\n" );
3378                 return;
3379         }
3380
3381         addrIndex = addrindex_create_index();
3382         addrindex_initialize();
3383
3384         /* Use new address book index. */
3385         addrindex_set_file_path( addrIndex, get_rc_dir() );
3386         addrindex_set_file_name( addrIndex, ADDRESSBOOK_INDEX_FILE );
3387         addrindex_read_data( addrIndex );
3388         if( addrIndex->retVal == MGU_NO_FILE ) {
3389                 /* Conversion required */
3390                 debug_print( "Converting...\n" );
3391                 if( addressbook_convert( addrIndex ) ) {
3392                         _addressIndex_ = addrIndex;
3393                 }
3394         }
3395         else if( addrIndex->retVal == MGU_SUCCESS ) {
3396                 _addressIndex_ = addrIndex;
3397         }
3398         else {
3399                 /* Error reading address book */
3400                 debug_print( "Could not read address index.\n" );
3401                 addrindex_print_index( addrIndex, stdout );
3402                 alertpanel_full(_("Addressbook Error"),
3403                                 _("Could not read address index"),
3404                                 GTK_STOCK_CLOSE, NULL, NULL, FALSE,
3405                                 NULL, ALERT_ERROR, G_ALERTDEFAULT);
3406         }
3407         debug_print( "done.\n" );
3408 }
3409
3410 /*
3411 * Add object into the address index tree widget.
3412 * Enter: node   Parent node.
3413 *        obj    Object to add.
3414 * Return: Node that was added, or NULL if object not added.
3415 */
3416 static GtkCTreeNode *addressbook_add_object(GtkCTreeNode *node,
3417                                             AddressObject *obj)
3418 {
3419         GtkCTree *ctree = GTK_CTREE(addrbook.ctree);
3420         GtkCTreeNode *added;
3421         AddressObject *pobj;
3422         AddressObjectType otype;
3423         AddressTypeControlItem *atci = NULL;
3424
3425         g_return_val_if_fail(node != NULL, NULL);
3426         g_return_val_if_fail(obj  != NULL, NULL);
3427
3428         pobj = gtk_ctree_node_get_row_data(ctree, node);
3429         g_return_val_if_fail(pobj != NULL, NULL);
3430
3431         /* Determine object type to be displayed */
3432         if( obj->type == ADDR_DATASOURCE ) {
3433                 otype = ADAPTER_DSOURCE(obj)->subType;
3434         }
3435         else {
3436                 otype = obj->type;
3437         }
3438
3439         /* Handle any special conditions. */
3440         added = node;
3441         atci = addrbookctl_lookup( otype );
3442         if( atci ) {
3443                 if( atci->showInTree ) {
3444                         /* Add object to tree */
3445                         gchar **name;
3446                         name = &obj->name;
3447                         added = gtk_ctree_insert_node( ctree, node, NULL, name, FOLDER_SPACING,
3448                                 atci->iconXpm, atci->maskXpm, atci->iconXpmOpen, atci->maskXpmOpen,
3449                                 atci->treeLeaf, atci->treeExpand );
3450                         gtk_ctree_node_set_row_data_full( ctree, added, obj,
3451                                 addressbook_free_treenode );
3452                 }
3453         }
3454
3455         gtk_sctree_sort_node(ctree, node);
3456
3457         return added;
3458 }
3459
3460 /**
3461  * Add group into the address index tree.
3462  * \param  node      Parent node.
3463  * \param  ds        Data source.
3464  * \param  itemGroup Group to add.
3465  * \return Inserted node.
3466  */
3467 static GtkCTreeNode *addressbook_node_add_group(
3468                 GtkCTreeNode *node, AddressDataSource *ds,
3469                 ItemGroup *itemGroup )
3470 {
3471         GtkCTree *ctree = GTK_CTREE(addrbook.ctree);
3472         GtkCTreeNode *newNode;
3473         AdapterGroup *adapter;
3474         AddressTypeControlItem *atci = NULL;
3475         gchar **name;
3476
3477         if( ds == NULL ) return NULL;
3478         if( node == NULL || itemGroup == NULL ) return NULL;
3479
3480         name = &itemGroup->obj.name;
3481
3482         atci = addrbookctl_lookup( ADDR_ITEM_GROUP );
3483
3484         adapter = g_new0( AdapterGroup, 1 );
3485         ADDRESS_OBJECT_TYPE(adapter) = ADDR_ITEM_GROUP;
3486         ADDRESS_OBJECT_NAME(adapter) = g_strdup( ADDRITEM_NAME(itemGroup) );
3487         adapter->itemGroup = itemGroup;
3488
3489         newNode = gtk_ctree_insert_node( ctree, node, NULL, name, FOLDER_SPACING,
3490                         atci->iconXpm, atci->maskXpm, atci->iconXpm, atci->maskXpm,
3491                         atci->treeLeaf, atci->treeExpand );
3492         gtk_ctree_node_set_row_data_full( ctree, newNode, adapter,
3493                 addressbook_free_treenode );
3494         gtk_sctree_sort_node( ctree, node );
3495         return newNode;
3496 }
3497
3498 /**
3499  * Add folder into the address index tree. Only visible folders are loaded into
3500  * the address index tree. Note that the root folder is not inserted into the
3501  * tree.
3502  *
3503  * \param  node       Parent node.
3504  * \param  ds         Data source.
3505  * \param  itemFolder Folder to add.
3506  * \param  otype      Object type to display.
3507  * \return Inserted node for the folder.
3508 */
3509 static GtkCTreeNode *addressbook_node_add_folder(
3510                 GtkCTreeNode *node, AddressDataSource *ds,
3511                 ItemFolder *itemFolder, AddressObjectType otype )
3512 {
3513         GtkCTree *ctree = GTK_CTREE(addrbook.ctree);
3514         GtkCTreeNode *newNode = NULL;
3515         AdapterFolder *adapter;
3516         AddressTypeControlItem *atci = NULL;
3517         GList *listItems = NULL;
3518         gchar *name;
3519         ItemFolder *rootFolder;
3520
3521         /* Only visible folders */
3522         if( itemFolder->isHidden ) return NULL;
3523
3524         if( ds == NULL ) return NULL;
3525         if( node == NULL || itemFolder == NULL ) return NULL;
3526
3527         /* Determine object type */
3528         atci = addrbookctl_lookup( otype );
3529         if( atci == NULL ) return NULL;
3530
3531         rootFolder = addrindex_ds_get_root_folder( ds );
3532         if( itemFolder == rootFolder ) {
3533                 newNode = node;
3534         }
3535         else {
3536                 adapter = g_new0( AdapterFolder, 1 );
3537                 ADDRESS_OBJECT_TYPE(adapter) = ADDR_ITEM_FOLDER;
3538                 ADDRESS_OBJECT_NAME(adapter) = g_strdup( ADDRITEM_NAME(itemFolder) );
3539                 adapter->itemFolder = itemFolder;
3540
3541                 name = ADDRITEM_NAME(itemFolder);
3542                 newNode = gtk_ctree_insert_node( ctree, node, NULL, &name, FOLDER_SPACING,
3543                                 atci->iconXpm, atci->maskXpm, atci->iconXpm, atci->maskXpm,
3544                                 atci->treeLeaf, atci->treeExpand );
3545                 if( newNode ) {
3546                         gtk_ctree_node_set_row_data_full( ctree, newNode, adapter,
3547                                 addressbook_free_treenode );
3548                 }
3549         }
3550
3551         listItems = itemFolder->listFolder;
3552         while( listItems ) {
3553                 ItemFolder *item = listItems->data;
3554                 addressbook_node_add_folder( newNode, ds, item, otype );
3555                 listItems = g_list_next( listItems );
3556         }
3557         listItems = itemFolder->listGroup;
3558         while( listItems ) {
3559                 ItemGroup *item = listItems->data;
3560                 addressbook_node_add_group( newNode, ds, item );
3561                 listItems = g_list_next( listItems );
3562         }
3563         gtk_sctree_sort_node( ctree, node );
3564         return newNode;
3565 }
3566
3567 void addressbook_export_to_file( void ) {
3568         if( _addressIndex_ ) {
3569                 /* Save all new address book data */
3570                 debug_print( "Saving address books...\n" );
3571                 addrindex_save_all_books( _addressIndex_ );
3572
3573                 debug_print( "Exporting addressbook to file...\n" );
3574                 addrindex_save_data( _addressIndex_ );
3575                 if( _addressIndex_->retVal != MGU_SUCCESS ) {
3576                         addrindex_print_index( _addressIndex_, stdout );
3577                 }
3578
3579                 /* Notify address completion of new data */
3580                 invalidate_address_completion();
3581         }
3582 }
3583
3584 static gboolean addressbook_entry_key_pressed(GtkWidget *widget, GdkEventKey *event, gpointer data)
3585 {
3586         if (event && event->keyval == GDK_Return)
3587                 addressbook_lup_clicked(NULL, NULL);
3588         return FALSE;
3589 }
3590
3591 /*
3592 * Comparison using cell contents (text in first column). Used for sort
3593 * address index widget.
3594 */
3595 static gint addressbook_treenode_compare_func(
3596         GtkCList *clist, gconstpointer ptr1, gconstpointer ptr2 )
3597 {
3598         GtkCell *cell1 = ((GtkCListRow *)ptr1)->cell;
3599         GtkCell *cell2 = ((GtkCListRow *)ptr2)->cell;
3600         gchar *name1 = NULL, *name2 = NULL;
3601         if( cell1 ) name1 = cell1->u.text;
3602         if( cell2 ) name2 = cell2->u.text;
3603         if( ! name1 ) return ( name2 != NULL );
3604         if( ! name2 ) return -1;
3605         return g_utf8_collate( name1, name2 );
3606 }
3607
3608 /*
3609 * Comparison using object names and types.
3610 */
3611 static gint addressbook_list_compare_func(
3612         GtkCList *clist, gconstpointer ptr1, gconstpointer ptr2 )
3613 {
3614         AddrItemObject *aio1 = ((GtkCListRow *)ptr1)->data;
3615         AddrItemObject *aio2 = ((GtkCListRow *)ptr2)->data;
3616         gchar *name1 = NULL, *name2 = NULL;
3617
3618         /* Order by cell contents */
3619         name1 = ADDRITEM_NAME( aio1 );
3620         name2 = ADDRITEM_NAME( aio2 );
3621
3622         if( aio1->type == aio2->type ) {
3623                 /* Order by name */
3624                 if( ! name1 ) return ( name2 != NULL );
3625                 if( ! name2 ) return -1;
3626                 return g_utf8_collate( name1, name2 );
3627         }
3628         else {
3629                 /* Order groups before person */
3630                 if( aio1->type == ITEMTYPE_GROUP ) {
3631                         return -1;
3632                 }
3633                 else if( aio2->type == ITEMTYPE_GROUP ) {
3634                         return 1;
3635                 }
3636                 return 0;
3637         }
3638 }
3639
3640 static void addressbook_new_book_cb( gpointer data, guint action, GtkWidget *widget ) {
3641         AdapterDSource *ads;
3642         AdapterInterface *adapter;
3643         GtkCTreeNode *newNode;
3644
3645         adapter = addrbookctl_find_interface( ADDR_IF_BOOK );
3646         if( adapter == NULL ) return;
3647         ads = addressbook_edit_book( _addressIndex_, NULL );
3648         if( ads ) {
3649                 newNode = addressbook_add_object( adapter->treeNode, ADDRESS_OBJECT(ads) );
3650                 if( newNode ) {
3651                         gtk_sctree_select( GTK_SCTREE(addrbook.ctree), newNode );
3652                         addrbook.treeSelected = newNode;
3653                 }
3654         }
3655 }
3656
3657 static void addressbook_new_vcard_cb( gpointer data, guint action, GtkWidget *widget ) {
3658         AdapterDSource *ads;
3659         AdapterInterface *adapter;
3660         GtkCTreeNode *newNode;
3661
3662         adapter = addrbookctl_find_interface( ADDR_IF_VCARD );
3663         if( adapter == NULL ) return;
3664         ads = addressbook_edit_vcard( _addressIndex_, NULL );
3665         if( ads ) {
3666                 newNode = addressbook_add_object( adapter->treeNode, ADDRESS_OBJECT(ads) );
3667                 if( newNode ) {
3668                         gtk_sctree_select( GTK_SCTREE(addrbook.ctree), newNode );
3669                         addrbook.treeSelected = newNode;
3670                 }
3671         }
3672 }
3673
3674 #ifdef USE_JPILOT
3675 static void addressbook_new_jpilot_cb( gpointer data, guint action, GtkWidget *widget ) {
3676         AdapterDSource *ads;
3677         AdapterInterface *adapter;
3678         AddressInterface *iface;
3679         GtkCTreeNode *newNode;
3680
3681         adapter = addrbookctl_find_interface( ADDR_IF_JPILOT );
3682         if( adapter == NULL ) return;
3683         iface = adapter->interface;
3684         if( ! iface->haveLibrary ) return;
3685         ads = addressbook_edit_jpilot( _addressIndex_, NULL );
3686         if( ads ) {
3687                 newNode = addressbook_add_object( adapter->treeNode, ADDRESS_OBJECT(ads) );
3688                 if( newNode ) {
3689                         gtk_sctree_select( GTK_SCTREE(addrbook.ctree), newNode );
3690                         addrbook.treeSelected = newNode;
3691                 }
3692         }
3693 }
3694 #endif
3695
3696 #ifdef USE_LDAP
3697 static void addressbook_new_ldap_cb( gpointer data, guint action, GtkWidget *widget ) {
3698         AdapterDSource *ads;
3699         AdapterInterface *adapter;
3700         AddressInterface *iface;
3701         GtkCTreeNode *newNode;
3702
3703         adapter = addrbookctl_find_interface( ADDR_IF_LDAP );
3704         if( adapter == NULL ) return;
3705         iface = adapter->interface;
3706         if( ! iface->haveLibrary ) return;
3707         ads = addressbook_edit_ldap( _addressIndex_, NULL );
3708         if( ads ) {
3709                 newNode = addressbook_add_object( adapter->treeNode, ADDRESS_OBJECT(ads) );
3710                 if( newNode ) {
3711                         gtk_sctree_select( GTK_SCTREE(addrbook.ctree), newNode );
3712                         addrbook.treeSelected = newNode;
3713                 }
3714         }
3715 }
3716 #endif
3717
3718 /**
3719  * Display address search status message.
3720  * \param queryType Query type.
3721  * \param status    Status/Error code.
3722  */
3723 static void addressbook_search_message( gint queryType, gint sts ) {
3724         gchar *desc = NULL;
3725         *addressbook_msgbuf = '\0';
3726
3727         if( sts != MGU_SUCCESS ) {
3728                 if( queryType == ADDRQUERY_LDAP ) {
3729 #ifdef USE_LDAP                 
3730                         desc = addressbook_err2string( _lutErrorsLDAP_, sts );
3731 #endif
3732                 }
3733         }
3734         if( desc ) {
3735                 g_snprintf( addressbook_msgbuf,
3736                         sizeof(addressbook_msgbuf), "%s", desc );
3737                 addressbook_status_show( addressbook_msgbuf );
3738         }
3739         else {
3740                 addressbook_status_show( "" );
3741         }
3742 }
3743
3744 /**
3745  * Refresh addressbook by forcing refresh of current selected object in
3746  * tree.
3747  */
3748 static void addressbook_refresh_current( void ) {
3749         AddressObject *obj;
3750         GtkCTree *ctree;
3751
3752         ctree = GTK_CTREE(addrbook.ctree);
3753         obj = gtk_ctree_node_get_row_data( ctree, addrbook.treeSelected );
3754         if( obj == NULL ) return;
3755         addressbook_set_clist( obj, TRUE );
3756 }
3757
3758 /**
3759  * Message that is displayed whilst a query is executing in a background
3760  * thread.
3761  */
3762 static gchar *_tempMessage_ = N_( "Busy searching..." );
3763
3764 /**
3765  * Address search idle function. This function is called during UI idle time
3766  * while a search is in progress.
3767  *
3768  * \param data Idler data.
3769  */
3770 static void addressbook_search_idle( gpointer data ) {
3771         /*
3772         gint queryID;
3773
3774         queryID = GPOINTER_TO_INT( data );
3775         printf( "addressbook_ldap_idle... queryID=%d\n", queryID );
3776         */
3777 }
3778
3779 /**
3780  * Search completion callback function. This removes the query from the idle
3781  * list.
3782  *
3783  * \param queryID Query ID of search request.
3784  */
3785 void addressbook_clear_idler( gint queryID ) {
3786         gpointer ptrQID;
3787
3788         /* Remove idler function */
3789         /* printf( "addressbook_clear_idler::%d::\n", queryID ); */
3790         ptrQID = GINT_TO_POINTER( queryID );
3791         if( ptrQID ) {
3792                 gtk_idle_remove_by_data( ptrQID );
3793         }
3794 }
3795
3796 /**
3797  * Search completion callback function. This removes the query from the idle
3798  * list.
3799  *
3800  * \param sender  Sender of query.
3801  * \param queryID Query ID of search request.
3802  * \param status  Search status.
3803  * \param data    Query data.
3804  */
3805 static void addressbook_search_callback_end(
3806                 gpointer sender, gint queryID, gint status, gpointer data )
3807 {
3808         gpointer ptrQID;
3809         QueryRequest *req;
3810         AddrQueryObject *aqo;
3811
3812         /* Remove idler function */
3813         ptrQID = GINT_TO_POINTER( queryID );
3814         if( ptrQID ) {
3815                 gtk_idle_remove_by_data( ptrQID );
3816         }
3817
3818         /* Refresh addressbook contents */
3819         addressbook_refresh_current();
3820         req = qrymgr_find_request( queryID );
3821         if( req != NULL ) {
3822                 aqo = ( AddrQueryObject * ) req->queryList->data;
3823                 addressbook_search_message( aqo->queryType, status );
3824         }
3825
3826         /* Stop the search */
3827         addrindex_stop_search( queryID );
3828 }
3829
3830 /**
3831  * Label (a format string) that is used to name each folder.
3832  */
3833 static gchar *_queryFolderLabel_ = N_( "Search '%s'" );
3834
3835 /**
3836  * Perform search.
3837  *
3838  * \param ds         Data source to search.
3839  * \param searchTerm String to lookup.
3840  * \param pNode      Parent data source node.
3841  */
3842 static void addressbook_perform_search(
3843                 AddressDataSource *ds, gchar *searchTerm,
3844                 GtkCTreeNode *pNode )
3845 {
3846         AddrBookBase *adbase;
3847         AddressCache *cache;
3848         ItemFolder *folder;
3849         GtkCTree *ctree;
3850         GtkCTreeNode *nNode;
3851         gchar *name;
3852         gint queryID;
3853         guint idleID;
3854         AddressObjectType aoType = ADDR_NONE;
3855
3856         /* Setup a query */
3857         if( *searchTerm == '\0' || strlen( searchTerm ) < 1 ) return;
3858
3859         if( ds->type == ADDR_IF_LDAP ) {
3860 #if USE_LDAP
3861                 aoType = ADDR_LDAP_QUERY;
3862 #endif
3863         }
3864         else {
3865                 return;
3866         }
3867
3868         /* Get reference to address cache */    
3869         adbase = ( AddrBookBase * ) ds->rawDataSource;
3870         cache = adbase->addressCache;
3871
3872         /* Create a folder for the search results */
3873         folder = addrcache_add_new_folder( cache, NULL