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