]> git.deb.at Git - pkg/abook.git/blob - edit.c
Display dates according to current locale (as defined by LC_TIME).
[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                         /* put raw representation of date in buf */
254                         find_field_number(cur->field->key, &nb);
255                         if((str = db_fget_byid(item, nb)) != NULL)
256                                 strncpy(buf, str, sizeof(buf));
257
258                         if(str && parse_date_string(buf, &day, &month, &year)) {
259                                 /* put locale representation of date in buf */
260                                 locale_date(buf, sizeof(buf), year, month, day);
261                                 mvwaddnstr(editw, y, TAB_COLON_POS + 2, buf,
262                                         bytes2width(buf, FIELD_MAX_WIDTH));
263                         }
264                 } else {
265                         find_field_number(cur->field->key, &nb);
266                         str = safe_str(db_fget_byid(item, nb));
267                         mvwaddnstr(editw, y, TAB_COLON_POS + 2, str,
268                                 bytes2width(str, FIELD_MAX_WIDTH));
269                 }
270
271                 j++;
272         }
273 }
274
275 /*
276  * function: change_field
277  *
278  * parameters:
279  *  (char *msg)
280  *   message to display as a prompt
281  *  (char **field)
282  *   a pointer to a pointer which will point a new string. if the latter
283  *   pointer != NULL it will be freed (if user doesn't cancel)
284  *  (size_t max_len)
285  *   maximum length of field to read from user
286  *
287  * returns (int)
288  *  a nonzero value if user has cancelled and zero if user has typed a
289  *  valid string
290  */
291 static int
292 change_field(char *msg, char **field, size_t max_len)
293 {
294         char *old;
295         int ret = 0;
296
297         old = *field;
298
299         *field = ui_readline(msg, old, max_len - 1, 0);
300
301         if(*field) {
302                 xfree(old);
303                 if(!**field)
304                         xfree(*field);
305         } else {
306                 *field = old;
307                 ret = 1;
308         }
309
310         clear_statusline();
311         refresh_statusline();
312
313         return ret;
314 }
315
316 static int
317 change_name_field(char *msg, char **field, size_t max_len)
318 {
319         char *tmp;
320         int ret;
321
322         tmp = xstrdup(*field);
323         ret = change_field(msg, field, max_len);
324
325         if(*field == NULL || ! **field) {
326                 xfree(*field);
327                 *field = xstrdup(tmp);
328         }
329
330         xfree(tmp);
331
332         return ret;
333 }
334
335 static void
336 fix_email_str(char *str)
337 {
338         for(; *str; str++)
339                 *str = *str == ',' ? '_' : *str;
340 }
341
342 static void
343 edit_list(int item, int nb, int isemail)
344 {
345         char *field, *msg, *keys;
346         abook_list *list, *e;
347         int choice = 1, elem_count;
348
349         list = csv_to_abook_list(db_fget_byid(item, nb));
350
351         for(e = list, elem_count = 0; e; e = e->next, elem_count++)
352                 ;
353
354         if(elem_count) {
355                 keys = xstrndup(S_("keybindings_new_123456789|n123456789"),
356                                 elem_count + 1);
357                 msg = strdup_printf(_("Choose %s to modify (<1>%s%c%s%s."),
358                                 isemail ? _("email") : _("item"),
359                                 (elem_count > 1) ? "-<" : "",
360                                 (elem_count > 1) ?  '0' + elem_count : ')',
361                                 (elem_count > 1) ? ">)" : "",
362                                 (elem_count < MAX_LIST_ITEMS) ?
363                                         _(" or <n>ew") : ""
364                                 );
365                 choice = statusline_askchoice(
366                                 msg,
367                                 keys,
368                                 (elem_count < MAX_LIST_ITEMS) ? 1 : 2
369                                 );
370                 free(keys);
371                 free(msg);
372         }
373
374         if(choice == 0)
375                 return;
376
377         field = (choice > 1) ?
378                 xstrdup(abook_list_get(list, choice - 2)->data) :
379                 NULL;
380
381         if(change_field(isemail ? _("E-mail: ") : _("Item: "),
382                                 &field, MAX_EMAIL_LEN))
383                 return; /* user cancelled ( C-g ) */
384
385         /* TODO if list item contains commas, should use quotes instead */
386         if(field)
387                 fix_email_str(field);
388
389         if(choice == 1)
390                 abook_list_append(&list, field);
391         else
392                 abook_list_replace(&list, choice - 2, field);
393
394         if(field)
395                 xfree(field);
396
397         field = abook_list_to_csv(list);
398         db_fput_byid(item, nb, field ? field : xstrdup(""));
399         abook_list_free(&list);
400 }
401
402 /*
403  * str is a buffer of max length str_len, which, after calling, will
404  * contain a representation of the given [y, m, d] date using the
405  * current locale (as defined by LC_TIME).
406  *
407  * Default is an ISO 8601 representation.
408  *
409  * %-sequences available to translators: %y, %Y, %m, %M, %d, %D represent
410  * year, month, and day (the uppercase version telling to fill with leading
411  * zeros if necessary)
412  */
413 static void
414 locale_date(char *str, size_t str_len, int year, int month, int day)
415 {
416         char *s = str, *fmt;
417         size_t len;
418
419 #if defined(HAVE_LOCALE_H) && defined(HAVE_SETLOCALE)
420         fmt = year ?    dcgettext(PACKAGE, "%Y-%M-%D", LC_TIME) :
421                         dcgettext(PACKAGE, "--%M-%D", LC_TIME);
422 #else
423         if(year)
424                 snprintf(str, str_len, "%04d-%02d-%02d", year, month, day);
425         else
426                 snprintf(str, str_len, "--%02d-%02d", month, day);
427         return;
428 #endif
429
430         while(*fmt && (s - str + 1 < str_len)) {
431                 if(*fmt != '%') {
432                         *s++ = *fmt++;
433                         continue;
434                 }
435
436                 len = str_len - (str - s);
437                 switch(*++fmt) {
438                         case 'y': s += snprintf(s, len, "%d", year); break;
439                         case 'Y': s += snprintf(s, len, "%04d", year); break;
440                         case 'm': s += snprintf(s, len, "%d", month); break;
441                         case 'M': s += snprintf(s, len, "%02d", month); break;
442                         case 'd': s += snprintf(s, len, "%d", day); break;
443                         case 'D': s += snprintf(s, len, "%02d", day); break;
444                         case '%': /* fall through */
445                         default:
446                                 *s++ = '%';
447                                 *s++ = *fmt;
448                                 break;
449                 }
450                 fmt++;
451         }
452         *++s = 0;
453 }
454
455 static int is_valid_date(const int day, const int month, const int year)
456 {
457         int valid = 1;
458         int month_length[13] =
459                 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
460
461         /*
462          * leap year
463          */
464         if ((!(year % 4)) && ((year % 100) || !(year % 400)))
465                 month_length[2] = 29;
466
467         if (month < 1 || month > 12)
468                 valid = 0;
469         else if (day < 1 || day > month_length[month])
470                 valid = 0;
471         else if (year < 0) /* we don't accept negative year numbers */
472                 valid = 0;
473
474         return valid;
475 }
476
477 int
478 parse_date_string(char *s, int *day, int *month, int *year)
479 {
480         int i = 0;
481         char *p = s;
482         assert(s && day && month && year);
483
484         if(*s == '-' && *s++ == '-') { /* omitted year */
485                 *year = 0;
486                 p = ++s;
487                 i++;
488         }
489
490         while(*s) {
491                 if(isdigit(*s)) {
492                         s++;
493                         continue;
494                 } else if(*s == '-') {
495                         if(++i > 3)
496                                 return FALSE;
497                         *s++ = '\0';
498                         switch(i) {
499                                 case 1: *year = safe_atoi(p); break;
500                                 case 2: *month = safe_atoi(p); break;
501                         }
502                         p = s;
503                 } else
504                 return FALSE;
505         }
506
507         if (i != 2 || !*p)
508                 return FALSE;
509
510         *day = atoi(p);
511
512         return is_valid_date(*day, *month, *year);
513 }
514
515 static void
516 edit_date(int item, int nb)
517 {
518         int i, date[3], old = FALSE;
519         char buf[12], *s = db_fget_byid(item, nb);
520         char *field[] = { N_("Day: "), N_("Month: "), N_("Year (optional): ") };
521
522         if(s) {
523                 strncpy(buf, s, sizeof(buf));
524                 old = parse_date_string(buf, &date[0], &date[1], &date[2]);
525         }
526
527         for(i = 0; i < 3; i++) {
528                 s = (old && date[i]) ? strdup_printf("%d", date[i]) : NULL;
529                 if(change_field(gettext(field[i]), &s, 5))
530                         return; /* user aborted with ^G */
531
532                 date[i] = (s && is_number(s)) ? atoi(s) : 0;
533
534                 if(!s) {
535                         switch(i) {
536                                 case 0: db_fput_byid(item, nb, NULL); /*delete*/
537                                 case 1: /* fall through */ return;
538                         }
539                 } else
540                         xfree(s);
541         }
542
543         /* ISO 8601 date, of the YYYY-MM-DD or --MM-DD format */
544         if(is_valid_date(date[0], date[1], date[2])) {
545                 if(date[2])
546                         s = strdup_printf("%04d-%02d-%02d",
547                                 date[2], date[1], date[0]);
548                 else
549                         s = strdup_printf("--%02d-%02d", date[1], date[0]);
550
551                 db_fput_byid(item, nb, xstrdup(s));
552         } else
553                 statusline_msg(_("Invalid date"));
554 }
555
556 /* input range: 1-9A-Z
557  * output range: 0-34 */
558 static int
559 key_to_field_number(char c)
560 {
561         int n = c - '1';
562         if(n >= 0 && n < 9)
563                 return n;
564
565         n = c - 'A' + 9;
566         if(n > 8 && n < 35)
567                 return n;
568
569         return -1;
570 }
571
572 static void
573 edit_field(int tab, char c, int item_number)
574 {
575         int i = 0, number, idx;
576         char *msg;
577         abook_field_list *f;
578         list_item item;
579
580         if((number = key_to_field_number(c)) < 0)
581                 return;
582
583         edit_undo(item_number, BACKUP_ITEM);
584
585         view_info(tab, NULL, &f);
586
587         while(1) {
588                 if(!f)
589                         return;
590
591                 if(i == number)
592                         break;
593
594                 f = f->next;
595                 i++;
596         }
597
598         find_field_number(f->field->key, &idx);
599         
600         switch(f->field->type) {
601                 case FIELD_STRING:
602                         msg = strdup_printf("%s: ", f->field->name);
603                         item = db_item_get(item_number);
604                         if(strcmp(f->field->key, "name") == 0)
605                                 change_name_field(msg,&item[idx],MAX_FIELD_LEN);
606                         else
607                                 change_field(msg,&item[idx],MAX_FIELD_LEN);
608                         free(msg);
609                         break;
610                 case FIELD_LIST:
611                         edit_list(item_number, idx, 0);
612                         break;
613                 case FIELD_EMAILS:
614                         edit_list(item_number, idx, 1);
615                         break;
616                 case FIELD_DATE:
617                         edit_date(item_number, idx);
618                         return;
619                 default:
620                         assert(0);
621         }
622 }
623
624 static int
625 edit_loop(int item)
626 {
627         static int tab = 0; /* first tab */
628         int c;
629
630         werase(editw);
631         headerline(gettext(EDITOR_HELPLINE));
632         refresh_statusline();
633         print_editor_header(item);
634         editor_tab(tab);
635         editor_print_data(tab, item);
636         wmove(editw, EDITW_LINES - 1, EDITW_COLS - 1);
637
638         refresh();
639         wrefresh(editw);
640
641         c = getch();
642         if(c == '\033') {
643                 statusline_addstr("ESC-");
644                 c = getch();
645                 clear_statusline();
646
647                 /* Escaped bindings */
648                 switch(c) {
649                         case 'r': roll_emails(item, ROTATE_RIGHT); break;
650                         default: break;
651                 }
652
653                 return item;
654         }
655
656         /* No uppercase nor numeric key should be used in this menu,
657          * as they are reserved for field selection */
658         switch(c) {
659                 case 'h':
660                 case KEY_LEFT: tab = tab == 0 ? views_count - 1 : tab - 1;
661                                break;
662                 case 'l':
663                 case KEY_RIGHT: tab = tab == views_count - 1 ? 0 : tab + 1;
664                                 break;
665                 case KEY_UP:
666                 case '<':
667                 case 'k': if(is_valid_item(item - 1)) item--; break;
668                 case KEY_DOWN:
669                 case '>':
670                 case 'j': if(is_valid_item(item + 1)) item++; break;
671                 case 'r': roll_emails(item, ROTATE_LEFT); break;
672                 case '?': display_help(HELP_EDITOR); break;
673                 case 'u': item = edit_undo(item, RESTORE_ITEM); break;
674                 case 'm': launch_mutt(item); clearok(stdscr, 1); break;
675                 case 'v': launch_wwwbrowser(item); clearok(stdscr, 1); break;
676                 case 12 : clearok(stdscr, 1); break; /* ^L (refresh screen) */
677                 case 'q': return -1;
678                 default: edit_field(tab, c, item);
679         }
680
681         return item;
682 }
683
684 void
685 edit_item(int item)
686 {
687         if(item < 0) {
688                 if(list_get_curitem() < 0)
689                         return;
690                 else
691                         item = list_get_curitem();
692         }
693
694         init_editor();
695
696         while((item = edit_loop(item)) >= 0)
697                 list_set_curitem(item); /* this is not very clean way to go */
698
699         close_editor();
700 }
701
702 void
703 add_item()
704 {
705         char *field = NULL;
706         list_item item = item_create();
707
708         change_field(_("Name: "), &field, MAX_FIELD_LEN);
709
710         if( field == NULL )
711                 return;
712
713         item_fput(item, NAME, field);
714
715         add_item2database(item);
716         item_free(&item);
717
718         list_set_curitem(last_item());
719
720         edit_item(last_item());
721 }
722