]> git.deb.at Git - pkg/abook.git/blob - edit.c
* Reorganized code.
[pkg/abook.git] / edit.c
1
2 /*
3  * $Id$
4  *
5  * by JH <jheinonen@users.sourceforge.net>
6  *
7  * Copyright (C) Jaakko Heinonen
8  */
9
10 #include <string.h>
11 #include <stdlib.h>
12 #include <ctype.h>
13 #include <assert.h>
14 #include "abook_curses.h"
15 #include "ui.h"
16 #include "abook.h"
17 #include "database.h"
18 #include "gettext.h"
19 #include "list.h"
20 #include "edit.h"
21 #include "misc.h"
22 #include "views.h"
23 #include "xmalloc.h"
24 #ifdef HAVE_CONFIG_H
25 #       include "config.h"
26 #endif
27 #if defined(HAVE_LOCALE_H) && defined(HAVE_SETLOCALE)
28 #       include <locale.h>
29 #endif 
30
31
32 static void locale_date(char *str, size_t str_len, int year, int month, int day);
33
34 /*
35  * some extern variables
36  */
37
38 extern int views_count;
39
40 WINDOW *editw;
41
42
43 static void
44 editor_tab(const int tab)
45 {
46         int i, j;
47         int x_pos = 2; /* current x pos */
48         char *tab_name;
49
50         mvwhline(editw, TABLINE + 1, 0, UI_HLINE_CHAR, EDITW_COLS);
51
52         for(i = 0; i < views_count; i++) {
53                 view_info(i, &tab_name, NULL);
54                 int width = strwidth(tab_name) + 5;
55
56                 if(x_pos + width + 1 > EDITW_COLS) {
57                         statusline_addstr(_("Tab name too wide for screen"));
58                         break;
59                 }
60
61                 mvwaddch(editw,  TABLINE + 1, x_pos,  UI_TEE_CHAR);
62                 mvwaddch(editw,  TABLINE + 1, x_pos + width - 2, UI_TEE_CHAR);
63
64                 mvwaddch(editw,  TABLINE, x_pos,  UI_ULCORNER_CHAR);
65                 mvwaddch(editw,  TABLINE, x_pos + 1,  UI_LBOXLINE_CHAR);
66                 mvwaddstr(editw, TABLINE, x_pos + 2,  tab_name);
67                 mvwaddch(editw,  TABLINE, x_pos + width - 3, UI_RBOXLINE_CHAR);
68                 mvwaddch(editw,  TABLINE, x_pos + width - 2, UI_URCORNER_CHAR);
69
70                 if(i == tab) {
71                         mvwaddch(editw,  TABLINE + 1, x_pos, UI_LRCORNER_CHAR);
72                         for(j = 0; j < width - 3; j++)
73                                 mvwaddstr(editw,
74                                         TABLINE + 1, x_pos + j + 1, " ");
75                         mvwaddch(editw,  TABLINE + 1, x_pos + width - 2,
76                                 UI_LLCORNER_CHAR);
77                 }
78                 x_pos += width;
79         }
80 }
81
82 void
83 get_first_email(char *str, int item)
84 {
85         char *tmp, *emails = db_email_get(item);
86
87         if(!*emails) {
88                 *str = 0;
89                 return;
90         }
91
92         strncpy(str, emails, MAX_EMAIL_LEN);
93         free(emails);
94         if( (tmp = strchr(str, ',')) )
95                 *tmp = 0;
96         else
97                 str[MAX_EMAIL_LEN - 1] = 0;
98 }
99
100 /* This only rolls emails from the 'email' field, not emails from any
101  * field of type FIELD_EMAILS.
102  * TODO: expand to ask for which field to roll if several are present? */
103 static void
104 roll_emails(int item, enum rotate_dir dir)
105 {
106         abook_list *emails = csv_to_abook_list(db_fget(item, EMAIL));
107
108         if(!emails)
109                 return;
110
111         free(db_fget(item, EMAIL));
112         abook_list_rotate(&emails, dir);
113         db_fput(item, EMAIL, abook_list_to_csv(emails));
114         abook_list_free(&emails);
115 }
116
117 static void
118 init_editor()
119 {
120         clear();
121         editw = newwin(EDITW_LINES, EDITW_COLS, EDITW_TOP, EDITW_X);
122         notimeout(editw, TRUE); /* handling of escape key */
123
124         refresh_statusline();
125 }
126
127 enum {
128         BACKUP_ITEM,
129         RESTORE_ITEM,
130         CLEAR_UNDO
131 };
132
133 static int
134 edit_undo(int item, int mode)
135 {
136         static list_item backup = NULL;
137         static int backed_up_item = -1;
138
139         switch(mode) {
140                 case CLEAR_UNDO:
141                         if(backup) {
142                                 item_empty(backup);
143                                 item_free(&backup);
144                         }
145                         break;
146                 case BACKUP_ITEM:
147                         if(backup) {
148                                 item_empty(backup);
149                                 item_free(&backup);
150                         }
151                         backup = item_create();
152                         item_duplicate(backup, db_item_get(item));
153                         backed_up_item = item;
154                         break;
155                 case RESTORE_ITEM:
156                         if(backup) {
157                                 item_empty(db_item_get(backed_up_item));
158                                 item_copy(db_item_get(backed_up_item), backup);
159                                 item_free(&backup);
160                                 return backed_up_item;
161                         }
162                         break;
163                 default:
164                         assert(0);
165         }
166         return item;
167 }
168
169 static void
170 close_editor()
171 {
172         edit_undo(-1, CLEAR_UNDO);
173         delwin(editw);
174         refresh_screen();
175 }
176
177 static void
178 print_editor_header(int item)
179 {
180         char *header;
181         char email[MAX_EMAIL_LEN];
182
183         if((header = xmalloc(EDITW_COLS)) == NULL)
184                 return;
185
186         get_first_email(email, item);
187
188         if(*email)
189                 snprintf(header, EDITW_COLS, "%s <%s>",
190                                 db_name_get(item),
191                                 email);
192         else
193                 snprintf(header, EDITW_COLS, "%s", db_name_get(item));
194
195         mvwaddstr(editw, 0, (EDITW_COLS - strwidth(header)) / 2, header);
196
197         free(header);
198 }
199
200 static void
201 editor_print_data(int tab, int item)
202 {
203         int j = 1, nb;
204         int y, x;
205         abook_field_list *cur;
206         char *str;
207
208         view_info(tab, NULL, &cur);
209
210         for(; cur; cur = cur->next) {
211
212                 if(j > 1) {
213                         getyx(editw, y, x);
214                         y++;
215                 } else
216                         y = FIELDS_START_Y;
217
218                 mvwprintw(editw, y, FIELDS_START_X, "%c - ",
219                                 (j < 10) ? '0' + j : 'A' + j - 10);
220                 mvwaddnstr(editw, y, FIELDS_START_X + 4, cur->field->name,
221                                 bytes2width(cur->field->name,
222                                         FIELDNAME_MAX_WIDTH));
223                 mvwaddch(editw, y, TAB_COLON_POS, ':');
224
225                 if((cur->field->type == FIELD_EMAILS) ||
226                                 (cur->field->type == FIELD_LIST)) {
227                         abook_list *emails, *e;
228                         
229                         find_field_number(cur->field->key, &nb);
230                         emails = csv_to_abook_list(db_fget_byid(item, nb));
231
232                         for(e = emails; e; e = e->next) {
233                                 getyx(editw, y, x);
234                                 mvwaddnstr(editw, y + 1, TAB_COLON_POS + 2,
235                                                 e->data,
236                                                 bytes2width(e->data,
237                                                         FIELD_MAX_WIDTH));
238                                 mvwaddch(editw, y + 1, TAB_COLON_POS,
239                                                 UI_VLINE_CHAR);
240                         }
241                         if(emails) {
242                                 mvwaddch(editw, y + 2, TAB_COLON_POS,
243                                                 UI_LLCORNER_CHAR);
244                                 mvwhline(editw, y + 2, TAB_COLON_POS + 1,
245                                                 UI_HLINE_CHAR,
246                                                 EDITW_COLS - TAB_COLON_POS - 2);
247                         }
248                         abook_list_free(&emails);
249                 } else if(cur->field->type == FIELD_DATE) {
250                         int day, month, year;
251                         char buf[64];
252
253                         find_field_number(cur->field->key, &nb);
254                         str = db_fget_byid(item, nb);
255                         
256                         if(parse_date_string(str, &day, &month, &year)) {
257                                 /* put locale representation of date in buf */
258                                 locale_date(buf, sizeof(buf), year, month, day);
259                                 mvwaddnstr(editw, y, TAB_COLON_POS + 2, buf,
260                                         bytes2width(buf, FIELD_MAX_WIDTH));
261                         }
262                 } else {
263                         find_field_number(cur->field->key, &nb);
264                         str = safe_str(db_fget_byid(item, nb));
265                         mvwaddnstr(editw, y, TAB_COLON_POS + 2, str,
266                                 bytes2width(str, FIELD_MAX_WIDTH));
267                 }
268
269                 j++;
270         }
271 }
272
273 /*
274  * function: change_field
275  *
276  * parameters:
277  *  (char *msg)
278  *   message to display as a prompt
279  *  (char **field)
280  *   a pointer to a pointer which will point a new string. if the latter
281  *   pointer != NULL it will be freed (if user doesn't cancel)
282  *  (size_t max_len)
283  *   maximum length of field to read from user
284  *
285  * returns (int)
286  *  a nonzero value if user has cancelled and zero if user has typed a
287  *  valid string
288  */
289 static int
290 change_field(char *msg, char **field, size_t max_len)
291 {
292         char *old;
293         int ret = 0;
294
295         old = *field;
296
297         *field = ui_readline(msg, old, max_len - 1, 0);
298
299         if(*field) {
300                 xfree(old);
301                 if(!**field)
302                         xfree(*field);
303         } else {
304                 *field = old;
305                 ret = 1;
306         }
307
308         clear_statusline();
309         refresh_statusline();
310
311         return ret;
312 }
313
314 static int
315 change_name_field(char *msg, char **field, size_t max_len)
316 {
317         char *tmp;
318         int ret;
319
320         tmp = xstrdup(*field);
321         ret = change_field(msg, field, max_len);
322
323         if(*field == NULL || ! **field) {
324                 xfree(*field);
325                 *field = xstrdup(tmp);
326         }
327
328         xfree(tmp);
329
330         return ret;
331 }
332
333 static void
334 fix_email_str(char *str)
335 {
336         for(; *str; str++)
337                 *str = *str == ',' ? '_' : *str;
338 }
339
340 static void
341 edit_list(int item, int nb, int isemail)
342 {
343         char *field, *msg, *keys;
344         abook_list *list, *e;
345         int choice = 1, elem_count;
346
347         list = csv_to_abook_list(db_fget_byid(item, nb));
348
349         for(e = list, elem_count = 0; e; e = e->next, elem_count++)
350                 ;
351
352         if(elem_count) {
353                 keys = xstrndup(S_("keybindings_new_123456789|n123456789"),
354                                 elem_count + 1);
355                 msg = strdup_printf(_("Choose %s to modify (<1>%s%c%s%s."),
356                                 isemail ? _("email") : _("item"),
357                                 (elem_count > 1) ? "-<" : "",
358                                 (elem_count > 1) ?  '0' + elem_count : ')',
359                                 (elem_count > 1) ? ">)" : "",
360                                 (elem_count < MAX_LIST_ITEMS) ?
361                                         _(" or <n>ew") : ""
362                                 );
363                 choice = statusline_askchoice(
364                                 msg,
365                                 keys,
366                                 (elem_count < MAX_LIST_ITEMS) ? 1 : 2
367                                 );
368                 free(keys);
369                 free(msg);
370         }
371
372         if(choice == 0)
373                 return;
374
375         field = (choice > 1) ?
376                 xstrdup(abook_list_get(list, choice - 2)->data) :
377                 NULL;
378
379         if(change_field(isemail ? _("E-mail: ") : _("Item: "),
380                                 &field, MAX_EMAIL_LEN))
381                 return; /* user cancelled ( C-g ) */
382
383         /* TODO if list item contains commas, should use quotes instead */
384         if(field)
385                 fix_email_str(field);
386
387         if(choice == 1)
388                 abook_list_append(&list, field);
389         else
390                 abook_list_replace(&list, choice - 2, field);
391
392         if(field)
393                 xfree(field);
394
395         field = abook_list_to_csv(list);
396         db_fput_byid(item, nb, field ? field : xstrdup(""));
397         abook_list_free(&list);
398 }
399
400 /*
401  * available %-sequences:
402  *   - %y, %Y, %m, %M, %d, %D represent year, month, and day
403  *     (the uppercase version telling to fill with leading zeros
404  *     if necessary)
405  *   - %I for ISO 8601 representation
406  */
407 static size_t
408 format_date(char *str, size_t str_len, char *fmt, int year, int month, int day)
409 {
410         char *s = str;
411         size_t len;
412
413         while(*fmt && (s - str + 1 < str_len)) {
414                 if(*fmt != '%') {
415                         *s++ = *fmt++;
416                         continue;
417                 }
418
419                 len = str_len - (str - s);
420                 switch(*++fmt) {
421                         case 'y': s += snprintf(s, len, "%d", year); break;
422                         case 'Y': s += snprintf(s, len, "%04d", year); break;
423                         case 'm': s += snprintf(s, len, "%d", month); break;
424                         case 'M': s += snprintf(s, len, "%02d", month); break;
425                         case 'd': s += snprintf(s, len, "%d", day); break;
426                         case 'D': s += snprintf(s, len, "%02d", day); break;
427                         case 'I': s += format_date(s, len,
428                                                   year ? "%Y-%M-%D" : "--%M-%D",
429                                                   year, month, day);
430                                   break;
431                         case '%': *s++ = '%'; break;
432                         default: *s++ = '%'; *s++ = *fmt; break;
433                 }
434                 fmt++;
435         }
436         *s = 0;
437         return s - str;
438 }
439
440 /*
441  * str is a buffer of max length str_len, which, after calling, will
442  * contain a representation of the given [y, m, d] date using the
443  * current locale (as defined by LC_TIME).
444  *
445  * In the absence of any localization, use an ISO 8601 representation.
446  */
447 static void
448 locale_date(char *str, size_t str_len, int year, int month, int day)
449 {
450         char *fmt;
451
452 #if defined(HAVE_LOCALE_H) && defined(HAVE_SETLOCALE)
453         fmt = year ?    dcgettext(PACKAGE, "%Y-%M-%D", LC_TIME) :
454                         dcgettext(PACKAGE, "--%M-%D", LC_TIME);
455 #else
456         fmt = "%I";
457 #endif
458         format_date(str, str_len, fmt, year, month, day);
459 }
460
461 static int is_valid_date(const int day, const int month, const int year)
462 {
463         int valid = 1;
464         int month_length[13] =
465                 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
466
467         /*
468          * leap year
469          */
470         if ((!(year % 4)) && ((year % 100) || !(year % 400)))
471                 month_length[2] = 29;
472
473         if (month < 1 || month > 12)
474                 valid = 0;
475         else if (day < 1 || day > month_length[month])
476                 valid = 0;
477         else if (year < 0) /* we don't accept negative year numbers */
478                 valid = 0;
479
480         return valid;
481 }
482
483 int
484 parse_date_string(char *str, int *day, int *month, int *year)
485 {
486         int i = 0;
487         char buf[12], *s, *p;
488
489         assert(day && month && year);
490
491         if(!str || !*str)
492                 return FALSE;
493
494         p = s = strncpy(buf, str, sizeof(buf));
495
496         if(*s == '-' && *s++ == '-') { /* omitted year */
497                 *year = 0;
498                 p = ++s;
499                 i++;
500         }
501
502         while(*s) {
503                 if(isdigit(*s)) {
504                         s++;
505                         continue;
506                 } else if(*s == '-') {
507                         if(++i > 3)
508                                 return FALSE;
509                         *s++ = '\0';
510                         switch(i) {
511                                 case 1: *year = safe_atoi(p); break;
512                                 case 2: *month = safe_atoi(p); break;
513                         }
514                         p = s;
515                 } else
516                         return FALSE;
517         }
518
519         if (i != 2 || !*p)
520                 return FALSE;
521
522         *day = atoi(p);
523
524         return is_valid_date(*day, *month, *year);
525 }
526
527 static void
528 edit_date(int item, int nb)
529 {
530         int i, date[3], old;
531         char *s = db_fget_byid(item, nb);
532         char *field[] = { N_("Day: "), N_("Month: "), N_("Year (optional): ") };
533
534         old = parse_date_string(s, &date[0], &date[1], &date[2]);
535
536         for(i = 0; i < 3; i++) {
537                 s = (old && date[i]) ? strdup_printf("%d", date[i]) : NULL;
538                 if(change_field(gettext(field[i]), &s, 5))
539                         return; /* user aborted with ^G */
540
541                 date[i] = (s && is_number(s)) ? atoi(s) : 0;
542
543                 if(!s) {
544                         switch(i) {
545                                 case 0: db_fput_byid(item, nb, NULL); /*delete*/
546                                 case 1: /* fall through */ return;
547                         }
548                 } else
549                         xfree(s);
550         }
551
552         /* ISO 8601 date, of the YYYY-MM-DD or --MM-DD format */
553         if(is_valid_date(date[0], date[1], date[2])) {
554                 if(date[2])
555                         s = strdup_printf("%04d-%02d-%02d",
556                                 date[2], date[1], date[0]);
557                 else
558                         s = strdup_printf("--%02d-%02d", date[1], date[0]);
559
560                 db_fput_byid(item, nb, xstrdup(s));
561         } else
562                 statusline_msg(_("Invalid date"));
563 }
564
565 /* input range: 1-9A-Z
566  * output range: 0-34 */
567 static int
568 key_to_field_number(char c)
569 {
570         int n = c - '1';
571         if(n >= 0 && n < 9)
572                 return n;
573
574         n = c - 'A' + 9;
575         if(n > 8 && n < 35)
576                 return n;
577
578         return -1;
579 }
580
581 static void
582 edit_field(int tab, char c, int item_number)
583 {
584         int i = 0, number, idx;
585         char *msg;
586         abook_field_list *f;
587         list_item item;
588
589         if((number = key_to_field_number(c)) < 0)
590                 return;
591
592         edit_undo(item_number, BACKUP_ITEM);
593
594         view_info(tab, NULL, &f);
595
596         while(1) {
597                 if(!f)
598                         return;
599
600                 if(i == number)
601                         break;
602
603                 f = f->next;
604                 i++;
605         }
606
607         find_field_number(f->field->key, &idx);
608         
609         switch(f->field->type) {
610                 case FIELD_STRING:
611                         msg = strdup_printf("%s: ", f->field->name);
612                         item = db_item_get(item_number);
613                         if(strcmp(f->field->key, "name") == 0)
614                                 change_name_field(msg,&item[idx],MAX_FIELD_LEN);
615                         else
616                                 change_field(msg,&item[idx],MAX_FIELD_LEN);
617                         free(msg);
618                         break;
619                 case FIELD_LIST:
620                         edit_list(item_number, idx, 0);
621                         break;
622                 case FIELD_EMAILS:
623                         edit_list(item_number, idx, 1);
624                         break;
625                 case FIELD_DATE:
626                         edit_date(item_number, idx);
627                         return;
628                 default:
629                         assert(0);
630         }
631 }
632
633 static int
634 edit_loop(int item)
635 {
636         static int tab = 0; /* first tab */
637         int c;
638
639         werase(editw);
640         headerline(gettext(EDITOR_HELPLINE));
641         refresh_statusline();
642         print_editor_header(item);
643         editor_tab(tab);
644         editor_print_data(tab, item);
645         wmove(editw, EDITW_LINES - 1, EDITW_COLS - 1);
646
647         refresh();
648         wrefresh(editw);
649
650         c = getch();
651         if(c == '\033') {
652                 statusline_addstr("ESC-");
653                 c = getch();
654                 clear_statusline();
655
656                 /* Escaped bindings */
657                 switch(c) {
658                         case 'r': roll_emails(item, ROTATE_RIGHT); break;
659                         default: break;
660                 }
661
662                 return item;
663         }
664
665         /* No uppercase nor numeric key should be used in this menu,
666          * as they are reserved for field selection */
667         switch(c) {
668                 case 'h':
669                 case KEY_LEFT: tab = tab == 0 ? views_count - 1 : tab - 1;
670                                break;
671                 case 'l':
672                 case KEY_RIGHT: tab = tab == views_count - 1 ? 0 : tab + 1;
673                                 break;
674                 case KEY_UP:
675                 case '<':
676                 case 'k': if(is_valid_item(item - 1)) item--; break;
677                 case KEY_DOWN:
678                 case '>':
679                 case 'j': if(is_valid_item(item + 1)) item++; break;
680                 case 'r': roll_emails(item, ROTATE_LEFT); break;
681                 case '?': display_help(HELP_EDITOR); break;
682                 case 'u': item = edit_undo(item, RESTORE_ITEM); break;
683                 case 'm': launch_mutt(item); clearok(stdscr, 1); break;
684                 case 'v': launch_wwwbrowser(item); clearok(stdscr, 1); break;
685                 case 12 : clearok(stdscr, 1); break; /* ^L (refresh screen) */
686                 case 'q': return -1;
687                 default: edit_field(tab, c, item);
688         }
689
690         return item;
691 }
692
693 void
694 edit_item(int item)
695 {
696         if(item < 0) {
697                 if(list_get_curitem() < 0)
698                         return;
699                 else
700                         item = list_get_curitem();
701         }
702
703         init_editor();
704
705         while((item = edit_loop(item)) >= 0)
706                 list_set_curitem(item); /* this is not very clean way to go */
707
708         close_editor();
709 }
710
711 void
712 add_item()
713 {
714         char *field = NULL;
715         list_item item = item_create();
716
717         change_field(_("Name: "), &field, MAX_FIELD_LEN);
718
719         if( field == NULL )
720                 return;
721
722         item_fput(item, NAME, field);
723
724         add_item2database(item);
725         item_free(&item);
726
727         list_set_curitem(last_item());
728
729         edit_item(last_item());
730 }
731