]> git.deb.at Git - pkg/abook.git/blob - edit.c
* parse_date_string(): don't modify string argument in place, since most
[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  * str is a buffer of max length str_len, which, after calling, will
402  * contain a representation of the given [y, m, d] date using the
403  * current locale (as defined by LC_TIME).
404  *
405  * Default is an ISO 8601 representation.
406  *
407  * %-sequences available to translators: %y, %Y, %m, %M, %d, %D represent
408  * year, month, and day (the uppercase version telling to fill with leading
409  * zeros if necessary)
410  */
411 static void
412 locale_date(char *str, size_t str_len, int year, int month, int day)
413 {
414         char *s = str, *fmt;
415         size_t len;
416
417 #if defined(HAVE_LOCALE_H) && defined(HAVE_SETLOCALE)
418         fmt = year ?    dcgettext(PACKAGE, "%Y-%M-%D", LC_TIME) :
419                         dcgettext(PACKAGE, "--%M-%D", LC_TIME);
420 #else
421         if(year)
422                 snprintf(str, str_len, "%04d-%02d-%02d", year, month, day);
423         else
424                 snprintf(str, str_len, "--%02d-%02d", month, day);
425         return;
426 #endif
427
428         while(*fmt && (s - str + 1 < str_len)) {
429                 if(*fmt != '%') {
430                         *s++ = *fmt++;
431                         continue;
432                 }
433
434                 len = str_len - (str - s);
435                 switch(*++fmt) {
436                         case 'y': s += snprintf(s, len, "%d", year); break;
437                         case 'Y': s += snprintf(s, len, "%04d", year); break;
438                         case 'm': s += snprintf(s, len, "%d", month); break;
439                         case 'M': s += snprintf(s, len, "%02d", month); break;
440                         case 'd': s += snprintf(s, len, "%d", day); break;
441                         case 'D': s += snprintf(s, len, "%02d", day); break;
442                         case '%': /* fall through */
443                         default:
444                                 *s++ = '%';
445                                 *s++ = *fmt;
446                                 break;
447                 }
448                 fmt++;
449         }
450         *++s = 0;
451 }
452
453 static int is_valid_date(const int day, const int month, const int year)
454 {
455         int valid = 1;
456         int month_length[13] =
457                 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
458
459         /*
460          * leap year
461          */
462         if ((!(year % 4)) && ((year % 100) || !(year % 400)))
463                 month_length[2] = 29;
464
465         if (month < 1 || month > 12)
466                 valid = 0;
467         else if (day < 1 || day > month_length[month])
468                 valid = 0;
469         else if (year < 0) /* we don't accept negative year numbers */
470                 valid = 0;
471
472         return valid;
473 }
474
475 int
476 parse_date_string(char *str, int *day, int *month, int *year)
477 {
478         int i = 0;
479         char buf[12], *s, *p;
480
481         assert(day && month && year);
482
483         if(!str || !*str)
484                 return FALSE;
485
486         p = s = strncpy(buf, str, sizeof(buf));
487
488         if(*s == '-' && *s++ == '-') { /* omitted year */
489                 *year = 0;
490                 p = ++s;
491                 i++;
492         }
493
494         while(*s) {
495                 if(isdigit(*s)) {
496                         s++;
497                         continue;
498                 } else if(*s == '-') {
499                         if(++i > 3)
500                                 return FALSE;
501                         *s++ = '\0';
502                         switch(i) {
503                                 case 1: *year = safe_atoi(p); break;
504                                 case 2: *month = safe_atoi(p); break;
505                         }
506                         p = s;
507                 } else
508                         return FALSE;
509         }
510
511         if (i != 2 || !*p)
512                 return FALSE;
513
514         *day = atoi(p);
515
516         return is_valid_date(*day, *month, *year);
517 }
518
519 static void
520 edit_date(int item, int nb)
521 {
522         int i, date[3], old;
523         char *s = db_fget_byid(item, nb);
524         char *field[] = { N_("Day: "), N_("Month: "), N_("Year (optional): ") };
525
526         old = parse_date_string(s, &date[0], &date[1], &date[2]);
527
528         for(i = 0; i < 3; i++) {
529                 s = (old && date[i]) ? strdup_printf("%d", date[i]) : NULL;
530                 if(change_field(gettext(field[i]), &s, 5))
531                         return; /* user aborted with ^G */
532
533                 date[i] = (s && is_number(s)) ? atoi(s) : 0;
534
535                 if(!s) {
536                         switch(i) {
537                                 case 0: db_fput_byid(item, nb, NULL); /*delete*/
538                                 case 1: /* fall through */ return;
539                         }
540                 } else
541                         xfree(s);
542         }
543
544         /* ISO 8601 date, of the YYYY-MM-DD or --MM-DD format */
545         if(is_valid_date(date[0], date[1], date[2])) {
546                 if(date[2])
547                         s = strdup_printf("%04d-%02d-%02d",
548                                 date[2], date[1], date[0]);
549                 else
550                         s = strdup_printf("--%02d-%02d", date[1], date[0]);
551
552                 db_fput_byid(item, nb, xstrdup(s));
553         } else
554                 statusline_msg(_("Invalid date"));
555 }
556
557 /* input range: 1-9A-Z
558  * output range: 0-34 */
559 static int
560 key_to_field_number(char c)
561 {
562         int n = c - '1';
563         if(n >= 0 && n < 9)
564                 return n;
565
566         n = c - 'A' + 9;
567         if(n > 8 && n < 35)
568                 return n;
569
570         return -1;
571 }
572
573 static void
574 edit_field(int tab, char c, int item_number)
575 {
576         int i = 0, number, idx;
577         char *msg;
578         abook_field_list *f;
579         list_item item;
580
581         if((number = key_to_field_number(c)) < 0)
582                 return;
583
584         edit_undo(item_number, BACKUP_ITEM);
585
586         view_info(tab, NULL, &f);
587
588         while(1) {
589                 if(!f)
590                         return;
591
592                 if(i == number)
593                         break;
594
595                 f = f->next;
596                 i++;
597         }
598
599         find_field_number(f->field->key, &idx);
600         
601         switch(f->field->type) {
602                 case FIELD_STRING:
603                         msg = strdup_printf("%s: ", f->field->name);
604                         item = db_item_get(item_number);
605                         if(strcmp(f->field->key, "name") == 0)
606                                 change_name_field(msg,&item[idx],MAX_FIELD_LEN);
607                         else
608                                 change_field(msg,&item[idx],MAX_FIELD_LEN);
609                         free(msg);
610                         break;
611                 case FIELD_LIST:
612                         edit_list(item_number, idx, 0);
613                         break;
614                 case FIELD_EMAILS:
615                         edit_list(item_number, idx, 1);
616                         break;
617                 case FIELD_DATE:
618                         edit_date(item_number, idx);
619                         return;
620                 default:
621                         assert(0);
622         }
623 }
624
625 static int
626 edit_loop(int item)
627 {
628         static int tab = 0; /* first tab */
629         int c;
630
631         werase(editw);
632         headerline(gettext(EDITOR_HELPLINE));
633         refresh_statusline();
634         print_editor_header(item);
635         editor_tab(tab);
636         editor_print_data(tab, item);
637         wmove(editw, EDITW_LINES - 1, EDITW_COLS - 1);
638
639         refresh();
640         wrefresh(editw);
641
642         c = getch();
643         if(c == '\033') {
644                 statusline_addstr("ESC-");
645                 c = getch();
646                 clear_statusline();
647
648                 /* Escaped bindings */
649                 switch(c) {
650                         case 'r': roll_emails(item, ROTATE_RIGHT); break;
651                         default: break;
652                 }
653
654                 return item;
655         }
656
657         /* No uppercase nor numeric key should be used in this menu,
658          * as they are reserved for field selection */
659         switch(c) {
660                 case 'h':
661                 case KEY_LEFT: tab = tab == 0 ? views_count - 1 : tab - 1;
662                                break;
663                 case 'l':
664                 case KEY_RIGHT: tab = tab == views_count - 1 ? 0 : tab + 1;
665                                 break;
666                 case KEY_UP:
667                 case '<':
668                 case 'k': if(is_valid_item(item - 1)) item--; break;
669                 case KEY_DOWN:
670                 case '>':
671                 case 'j': if(is_valid_item(item + 1)) item++; break;
672                 case 'r': roll_emails(item, ROTATE_LEFT); break;
673                 case '?': display_help(HELP_EDITOR); break;
674                 case 'u': item = edit_undo(item, RESTORE_ITEM); break;
675                 case 'm': launch_mutt(item); clearok(stdscr, 1); break;
676                 case 'v': launch_wwwbrowser(item); clearok(stdscr, 1); break;
677                 case 12 : clearok(stdscr, 1); break; /* ^L (refresh screen) */
678                 case 'q': return -1;
679                 default: edit_field(tab, c, item);
680         }
681
682         return item;
683 }
684
685 void
686 edit_item(int item)
687 {
688         if(item < 0) {
689                 if(list_get_curitem() < 0)
690                         return;
691                 else
692                         item = list_get_curitem();
693         }
694
695         init_editor();
696
697         while((item = edit_loop(item)) >= 0)
698                 list_set_curitem(item); /* this is not very clean way to go */
699
700         close_editor();
701 }
702
703 void
704 add_item()
705 {
706         char *field = NULL;
707         list_item item = item_create();
708
709         change_field(_("Name: "), &field, MAX_FIELD_LEN);
710
711         if( field == NULL )
712                 return;
713
714         item_fput(item, NAME, field);
715
716         add_item2database(item);
717         item_free(&item);
718
719         list_set_curitem(last_item());
720
721         edit_item(last_item());
722 }
723