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