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