File: edit.c

package info (click to toggle)
abook 0.6.0~pre2-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 2,384 kB
  • ctags: 2,011
  • sloc: ansic: 16,787; sh: 4,310; cpp: 956; makefile: 528; yacc: 288; python: 256; perl: 97
file content (667 lines) | stat: -rw-r--r-- 13,372 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667

/*
 * $Id: edit.c,v 1.55 2006/09/06 02:46:44 cduval Exp $
 *
 * by JH <jheinonen@users.sourceforge.net>
 *
 * Copyright (C) Jaakko Heinonen
 */

#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
#include "abook_curses.h"
#include "ui.h"
#include "abook.h"
#include "database.h"
#include "gettext.h"
#include "list.h"
#include "edit.h"
#include "misc.h"
#include "views.h"
#include "xmalloc.h"
#ifdef HAVE_CONFIG_H
#	include "config.h"
#endif

/*
 * some extern variables
 */

extern int views_count;

WINDOW *editw;


static void
editor_tab(const int tab)
{
	int i, j;
	int x_pos = 2; /* current x pos */
	char *tab_name;

	mvwhline(editw, TABLINE + 1, 0, UI_HLINE_CHAR, EDITW_COLS);

	for(i = 0; i < views_count; i++) {
		view_info(i, &tab_name, NULL);
		int width = strwidth(tab_name) + 5;

		if(x_pos + width + 1 > EDITW_COLS) {
			statusline_addstr(_("Tab name too wide for screen"));
			break;
		}

		mvwaddch(editw,  TABLINE + 1, x_pos,  UI_TEE_CHAR);
		mvwaddch(editw,  TABLINE + 1, x_pos + width - 2, UI_TEE_CHAR);

		mvwaddch(editw,  TABLINE, x_pos,  UI_ULCORNER_CHAR);
		mvwaddch(editw,  TABLINE, x_pos + 1,  UI_LBOXLINE_CHAR);
		mvwaddstr(editw, TABLINE, x_pos + 2,  tab_name);
		mvwaddch(editw,  TABLINE, x_pos + width - 3, UI_RBOXLINE_CHAR);
		mvwaddch(editw,  TABLINE, x_pos + width - 2, UI_URCORNER_CHAR);

		if(i == tab) {
			mvwaddch(editw,  TABLINE + 1, x_pos, UI_LRCORNER_CHAR);
			for(j = 0; j < width - 3; j++)
				mvwaddstr(editw,
					TABLINE + 1, x_pos + j + 1, " ");
			mvwaddch(editw,  TABLINE + 1, x_pos + width - 2,
				UI_LLCORNER_CHAR);
		}
		x_pos += width;
	}
}

void
get_first_email(char *str, int item)
{
	char *tmp, *emails = db_email_get(item);

	if(!*emails) {
		*str = 0;
		return;
	}

	strncpy(str, emails, MAX_EMAIL_LEN);
	free(emails);
	if( (tmp = strchr(str, ',')) )
		*tmp = 0;
	else
		str[MAX_EMAIL_LEN - 1] = 0;
}

/* This only rolls emails from the 'email' field, not emails from any
 * field of type FIELD_EMAILS.
 * TODO: expand to ask for which field to roll if several are present? */
static void
roll_emails(int item, enum rotate_dir dir)
{
	abook_list *emails = csv_to_abook_list(db_fget(item, EMAIL));

	if(!emails)
		return;

	free(db_fget(item, EMAIL));
	abook_list_rotate(&emails, dir);
	db_fput(item, EMAIL, abook_list_to_csv(emails));
	abook_list_free(&emails);
}

static void
init_editor()
{
	clear();
	editw = newwin(EDITW_LINES, EDITW_COLS, EDITW_TOP, EDITW_X);
	notimeout(editw, TRUE); /* handling of escape key */

	refresh_statusline();
}

enum {
	BACKUP_ITEM,
	RESTORE_ITEM,
	CLEAR_UNDO
};

static int
edit_undo(int item, int mode)
{
	static list_item backup = NULL;
	static int backed_up_item = -1;

	switch(mode) {
		case CLEAR_UNDO:
			if(backup) {
				item_empty(backup);
				item_free(&backup);
			}
			break;
		case BACKUP_ITEM:
			if(backup) {
				item_empty(backup);
				item_free(&backup);
			}
			backup = item_create();
			item_duplicate(backup, db_item_get(item));
			backed_up_item = item;
			break;
		case RESTORE_ITEM:
			if(backup) {
				item_empty(db_item_get(backed_up_item));
				item_copy(db_item_get(backed_up_item), backup);
				item_free(&backup);
				return backed_up_item;
			}
			break;
		default:
			assert(0);
	}
	return item;
}

static void
close_editor()
{
	edit_undo(-1, CLEAR_UNDO);
	delwin(editw);
	refresh_screen();
}

static void
print_editor_header(int item)
{
	char *header;
	char email[MAX_EMAIL_LEN];

	if((header = xmalloc(EDITW_COLS)) == NULL)
		return;

	get_first_email(email, item);

	if(*email)
		snprintf(header, EDITW_COLS, "%s <%s>",
				db_name_get(item),
				email);
	else
		snprintf(header, EDITW_COLS, "%s", db_name_get(item));

	mvwaddstr(editw, 0, (EDITW_COLS - strwidth(header)) / 2, header);

	free(header);
}

static void
editor_print_data(int tab, int item)
{
	int j = 1, nb;
	int y, x;
	abook_field_list *cur;
	char *str;

	view_info(tab, NULL, &cur);

	for(; cur; cur = cur->next) {

		if(j > 1) {
			getyx(editw, y, x);
			y++;
		} else
			y = FIELDS_START_Y;

		mvwprintw(editw, y, FIELDS_START_X, "%c - ",
				(j < 10) ? '0' + j : 'A' + j - 10);
		mvwaddnstr(editw, y, FIELDS_START_X + 4, cur->field->name,
				bytes2width(cur->field->name,
					FIELDNAME_MAX_WIDTH));
		mvwaddch(editw, y, TAB_COLON_POS, ':');

		if((cur->field->type == FIELD_EMAILS) ||
				(cur->field->type == FIELD_LIST)) {
			abook_list *emails, *e;
			
			find_field_number(cur->field->key, &nb);
			emails = csv_to_abook_list(db_fget_byid(item, nb));

			for(e = emails; e; e = e->next) {
				getyx(editw, y, x);
				mvwaddnstr(editw, y + 1, TAB_COLON_POS + 2,
						e->data,
						bytes2width(e->data,
							FIELD_MAX_WIDTH));
				mvwaddch(editw, y + 1, TAB_COLON_POS,
						UI_VLINE_CHAR);
			}
			if(emails) {
				mvwaddch(editw, y + 2, TAB_COLON_POS,
						UI_LLCORNER_CHAR);
				mvwhline(editw, y + 2, TAB_COLON_POS + 1,
						UI_HLINE_CHAR,
						EDITW_COLS - TAB_COLON_POS - 2);
			}
			abook_list_free(&emails);
		} else if(cur->field->type == FIELD_DATE) {
			int day, month, year;
			char buf[12];

			find_field_number(cur->field->key, &nb);
			if((str = db_fget_byid(item, nb)) != NULL)
				strncpy(buf, str, sizeof(buf));

			if(str && parse_date_string(buf, &day, &month, &year)) {
				if(year)
					str = strdup_printf("%04d-%02d-%02d",
						year, month, day);
				else
					str = strdup_printf("--%02d-%02d",
						month, day);
				mvwaddnstr(editw, y, TAB_COLON_POS + 2, str,
					bytes2width(str, FIELD_MAX_WIDTH));
				free(str);
			}
		} else {
			find_field_number(cur->field->key, &nb);
			str = safe_str(db_fget_byid(item, nb));
			mvwaddnstr(editw, y, TAB_COLON_POS + 2, str,
				bytes2width(str, FIELD_MAX_WIDTH));
		}

		j++;
	}
}

/*
 * function: change_field
 *
 * parameters:
 *  (char *msg)
 *   message to display as a prompt
 *  (char **field)
 *   a pointer to a pointer which will point a new string. if the latter
 *   pointer != NULL it will be freed (if user doesn't cancel)
 *  (size_t max_len)
 *   maximum length of field to read from user
 *
 * returns (int)
 *  a nonzero value if user has cancelled and zero if user has typed a
 *  valid string
 */
static int
change_field(char *msg, char **field, size_t max_len)
{
	char *old;
	int ret = 0;

	old = *field;

	*field = ui_readline(msg, old, max_len - 1, 0);

	if(*field) {
		xfree(old);
		if(!**field)
			xfree(*field);
	} else {
		*field = old;
		ret = 1;
	}

	clear_statusline();
	refresh_statusline();

	return ret;
}

static int
change_name_field(char *msg, char **field, size_t max_len)
{
	char *tmp;
	int ret;

	tmp = xstrdup(*field);
	ret = change_field(msg, field, max_len);

	if(*field == NULL || ! **field) {
		xfree(*field);
		*field = xstrdup(tmp);
	}

	xfree(tmp);

	return ret;
}

static void
fix_email_str(char *str)
{
	for(; *str; str++)
		*str = *str == ',' ? '_' : *str;
}

static void
edit_list(int item, int nb, int isemail)
{
	char *field, *msg, *keys;
	abook_list *list, *e;
	int choice = 1, elem_count;

	list = csv_to_abook_list(db_fget_byid(item, nb));

	for(e = list, elem_count = 0; e; e = e->next, elem_count++)
		;

	if(elem_count) {
		keys = xstrndup(S_("keybindings_new_123456789|n123456789"),
				elem_count + 1);
		msg = strdup_printf(_("Choose %s to modify (<1>%s%c%s%s."),
				isemail ? _("email") : _("item"),
				(elem_count > 1) ? "-<" : "",
				(elem_count > 1) ?  '0' + elem_count : ')',
				(elem_count > 1) ? ">)" : "",
				(elem_count < MAX_LIST_ITEMS) ?
					_(" or <n>ew") : ""
				);
		choice = statusline_askchoice(
				msg,
				keys,
				(elem_count < MAX_LIST_ITEMS) ? 1 : 2
				);
		free(keys);
		free(msg);
	}

	if(choice == 0)
		return;

	field = (choice > 1) ?
		xstrdup(abook_list_get(list, choice - 2)->data) :
		NULL;

	if(change_field(isemail ? _("E-mail: ") : _("Item: "),
				&field, MAX_EMAIL_LEN))
		return; /* user cancelled ( C-g ) */

	/* TODO if list item contains commas, should use quotes instead */
	if(field)
		fix_email_str(field);

	if(choice == 1)
		abook_list_append(&list, field);
	else
		abook_list_replace(&list, choice - 2, field);

	if(field)
		xfree(field);

	field = abook_list_to_csv(list);
	db_fput_byid(item, nb, field ? field : xstrdup(""));
	abook_list_free(&list);
}

static int is_valid_date(const int day, const int month, const int year)
{
	int valid = 1;
	int month_length[13] =
		{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

	/*
	 * leap year
	 */
	if ((!(year % 4)) && ((year % 100) || !(year % 400)))
		month_length[2] = 29;

	if (month < 1 || month > 12)
		valid = 0;
	else if (day < 1 || day > month_length[month])
		valid = 0;
	else if (year < 0) /* we don't accept negative year numbers */
		valid = 0;

	return valid;
}

int
parse_date_string(char *s, int *day, int *month, int *year)
{
	int i = 0;
	char *p = s;
	assert(s && day && month && year);

	if(*s == '-' && *s++ == '-') { /* omitted year */
		*year = 0;
		p = ++s;
		i++;
	}

	while(*s) {
		if(isdigit(*s)) {
			s++;
			continue;
		} else if(*s == '-') {
			if(++i > 3)
				return FALSE;
			*s++ = '\0';
			switch(i) {
				case 1: *year = safe_atoi(p); break;
				case 2: *month = safe_atoi(p); break;
			}
			p = s;
		} else
		return FALSE;
	}

	if (i != 2 || !*p)
		return FALSE;

	*day = atoi(p);

	return is_valid_date(*day, *month, *year);
}

static void
edit_date(int item, int nb)
{
	int i, date[3], old = FALSE;
	char buf[12], *s = db_fget_byid(item, nb);
	char *field[] = { N_("Day: "), N_("Month: "), N_("Year (optional): ") };

	if(s) {
		strncpy(buf, s, sizeof(buf));
		old = parse_date_string(buf, &date[0], &date[1], &date[2]);
	}

	for(i = 0; i < 3; i++) {
		s = (old && date[i]) ? strdup_printf("%d", date[i]) : NULL;
		if(change_field(gettext(field[i]), &s, 5))
			return; /* user aborted with ^G */

		date[i] = (s && is_number(s)) ? atoi(s) : 0;

		if(!s) {
			switch(i) {
				case 0:	db_fput_byid(item, nb, NULL); /*delete*/
				case 1: /* fall through */ return;
			}
		} else
			xfree(s);
	}

	/* ISO 8601 date, of the YYYY-MM-DD or --MM-DD format */
	if(is_valid_date(date[0], date[1], date[2])) {
		if(date[2])
			s = strdup_printf("%04d-%02d-%02d",
				date[2], date[1], date[0]);
		else
			s = strdup_printf("--%02d-%02d", date[1], date[0]);

		db_fput_byid(item, nb, xstrdup(s));
	} else
		statusline_msg(_("Invalid date"));
}

/* input range: 1-9A-Z
 * output range: 0-34 */
static int
key_to_field_number(char c)
{
	int n = c - '1';
	if(n >= 0 && n < 9)
		return n;

	n = c - 'A' + 9;
	if(n > 8 && n < 35)
		return n;

	return -1;
}

static void
edit_field(int tab, char c, int item_number)
{
	int i = 0, number, idx;
	char *msg;
	abook_field_list *f;
	list_item item;

	if((number = key_to_field_number(c)) < 0)
		return;

	edit_undo(item_number, BACKUP_ITEM);

	view_info(tab, NULL, &f);

	while(1) {
		if(!f)
			return;

		if(i == number)
			break;

		f = f->next;
		i++;
	}

	find_field_number(f->field->key, &idx);
	
	switch(f->field->type) {
		case FIELD_STRING:
			msg = strdup_printf("%s: ", f->field->name);
			item = db_item_get(item_number);
			if(strcmp(f->field->key, "name") == 0)
				change_name_field(msg,&item[idx],MAX_FIELD_LEN);
			else
				change_field(msg,&item[idx],MAX_FIELD_LEN);
			free(msg);
			break;
		case FIELD_LIST:
			edit_list(item_number, idx, 0);
			break;
		case FIELD_EMAILS:
			edit_list(item_number, idx, 1);
			break;
		case FIELD_DATE:
			edit_date(item_number, idx);
			return;
		default:
			assert(0);
	}
}

static int
edit_loop(int item)
{
	static int tab = 0; /* first tab */
	int c;

	werase(editw);
	headerline(gettext(EDITOR_HELPLINE));
	refresh_statusline();
	print_editor_header(item);
	editor_tab(tab);
	editor_print_data(tab, item);
	wmove(editw, EDITW_LINES - 1, EDITW_COLS - 1);

	refresh();
	wrefresh(editw);

	c = getch();
	if(c == '\033') {
		statusline_addstr("ESC-");
		c = getch();
		clear_statusline();

		/* Escaped bindings */
		switch(c) {
			case 'r': roll_emails(item, ROTATE_RIGHT); break;
			default: break;
		}

		return item;
	}

	/* No uppercase nor numeric key should be used in this menu,
	 * as they are reserved for field selection */
	switch(c) {
		case 'h':
		case KEY_LEFT: tab = tab == 0 ? views_count - 1 : tab - 1;
			       break;
		case 'l':
		case KEY_RIGHT: tab = tab == views_count - 1 ? 0 : tab + 1;
				break;
		case KEY_UP:
		case '<':
		case 'k': if(is_valid_item(item - 1)) item--; break;
		case KEY_DOWN:
		case '>':
		case 'j': if(is_valid_item(item + 1)) item++; break;
		case 'r': roll_emails(item, ROTATE_LEFT); break;
		case '?': display_help(HELP_EDITOR); break;
		case 'u': item = edit_undo(item, RESTORE_ITEM); break;
		case 'm': launch_mutt(item); clearok(stdscr, 1); break;
		case 'v': launch_wwwbrowser(item); clearok(stdscr, 1); break;
		case 12 : clearok(stdscr, 1); break; /* ^L (refresh screen) */
		case 'q': return -1;
		default: edit_field(tab, c, item);
	}

	return item;
}

void
edit_item(int item)
{
	if(item < 0) {
		if(list_get_curitem() < 0)
			return;
		else
			item = list_get_curitem();
	}

	init_editor();

	while((item = edit_loop(item)) >= 0)
		list_set_curitem(item); /* this is not very clean way to go */

	close_editor();
}

void
add_item()
{
	char *field = NULL;
	list_item item = item_create();

	change_field(_("Name: "), &field, MAX_FIELD_LEN);

	if( field == NULL )
		return;

	item_fput(item, NAME, field);

	add_item2database(item);
	item_free(&item);

	list_set_curitem(last_item());

	edit_item(last_item());
}