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