1/*
2 *  $Id: tailbox.c,v 1.72 2018/06/19 22:57:01 tom Exp $
3 *
4 *  tailbox.c -- implements the tail box
5 *
6 *  Copyright 2000-2012,2018	Thomas E. Dickey
7 *
8 *  This program is free software; you can redistribute it and/or modify
9 *  it under the terms of the GNU Lesser General Public License, version 2.1
10 *  as published by the Free Software Foundation.
11 *
12 *  This program is distributed in the hope that it will be useful, but
13 *  WITHOUT ANY WARRANTY; without even the implied warranty of
14 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 *  Lesser General Public License for more details.
16 *
17 *  You should have received a copy of the GNU Lesser General Public
18 *  License along with this program; if not, write to
19 *	Free Software Foundation, Inc.
20 *	51 Franklin St., Fifth Floor
21 *	Boston, MA 02110, USA.
22 *
23 *  An earlier version of this program lists as authors
24 *	Pasquale De Marco (demarco_p@abramo.it)
25 */
26
27#include <dialog.h>
28#include <dlg_keys.h>
29#include <sys/stat.h>
30
31typedef struct {
32    DIALOG_CALLBACK obj;
33    WINDOW *text;
34    const char **buttons;
35    int hscroll;
36    int old_hscroll;
37    char line[MAX_LEN + 2];
38    off_t last_pos;
39} MY_OBJ;
40
41/*
42 * Return current line of text.
43 */
44static char *
45get_line(MY_OBJ * obj)
46{
47    FILE *fp = obj->obj.input;
48    int col = -(obj->hscroll);
49    int j, tmpint, ch;
50
51    do {
52	if (((ch = getc(fp)) == EOF) && !feof(fp))
53	    dlg_exiterr("Error moving file pointer in get_line().");
54	else if (!feof(fp) && (ch != '\n')) {
55	    if ((ch == TAB) && (dialog_vars.tab_correct)) {
56		tmpint = dialog_state.tab_len
57		    - ((col + obj->hscroll) % dialog_state.tab_len);
58		for (j = 0; j < tmpint; j++) {
59		    if (col >= 0 && col < MAX_LEN)
60			obj->line[col] = ' ';
61		    ++col;
62		}
63	    } else {
64		if (col >= 0)
65		    obj->line[col] = (char) ch;
66		++col;
67	    }
68	    if (col >= MAX_LEN)
69		break;
70	}
71    } while (!feof(fp) && (ch != '\n'));
72
73    if (col < 0)
74	col = 0;
75    obj->line[col] = '\0';
76
77    return obj->line;
78}
79
80/*
81 * Print a new line of text.
82 */
83static void
84print_line(MY_OBJ * obj, WINDOW *win, int row, int width)
85{
86    int i, y, x;
87    char *line = get_line(obj);
88
89    (void) wmove(win, row, 0);	/* move cursor to correct line */
90    (void) waddch(win, ' ');
91    (void) waddnstr(win, line, MIN((int) strlen(line), width - 2));
92
93    getyx(win, y, x);
94    (void) y;
95    /* Clear 'residue' of previous line */
96    for (i = 0; i < width - x; i++)
97	(void) waddch(win, ' ');
98}
99
100/*
101 * Go back 'target' lines in text file.  BUFSIZ has to be in 'size_t' range.
102 */
103static void
104last_lines(MY_OBJ * obj, int target)
105{
106    FILE *fp = obj->obj.input;
107    size_t inx;
108    int count = 0;
109    char buf[BUFSIZ + 1];
110    size_t size_to_read;
111    size_t size_as_read;
112    long offset = 0;
113    long fpos = 0;
114
115    if (fseek(fp, 0L, SEEK_END) == -1
116	|| (fpos = ftell(fp)) < 0)
117	dlg_exiterr("Error moving file pointer in last_lines().");
118
119    if (fpos != 0) {
120	++target;
121	for (;;) {
122	    if (fpos >= BUFSIZ) {
123		size_to_read = BUFSIZ;
124	    } else {
125		size_to_read = (size_t) fpos;
126	    }
127	    fpos = fpos - (long) size_to_read;
128	    if (fseek(fp, fpos, SEEK_SET) == -1)
129		dlg_exiterr("Error moving file pointer in last_lines().");
130	    size_as_read = fread(buf, sizeof(char), size_to_read, fp);
131	    if (ferror(fp))
132		dlg_exiterr("Error reading file in last_lines().");
133
134	    if (size_as_read == 0) {
135		fpos = 0;
136		offset = 0;
137		break;
138	    }
139
140	    offset += (long) size_as_read;
141	    for (inx = size_as_read - 1; inx != 0; --inx) {
142		if (buf[inx] == '\n') {
143		    if (++count > target)
144			break;
145		    offset = (long) (inx + 1);
146		}
147	    }
148
149	    if (count > target) {
150		break;
151	    } else if (fpos == 0) {
152		offset = 0;
153		break;
154	    }
155	}
156
157	if (fseek(fp, fpos + offset, SEEK_SET) == -1)
158	    dlg_exiterr("Error moving file pointer in last_lines().");
159    }
160}
161
162/*
163 * Print a new page of text.
164 */
165static void
166print_page(MY_OBJ * obj, int height, int width)
167{
168    int i;
169
170    for (i = 0; i < height; i++) {
171	print_line(obj, obj->text, i, width);
172    }
173    (void) wnoutrefresh(obj->text);
174}
175
176static void
177print_last_page(MY_OBJ * obj)
178{
179    int high = getmaxy(obj->obj.win) - (2 * MARGIN + (obj->obj.bg_task ? 1 : 3));
180    int wide = getmaxx(obj->text);
181
182    last_lines(obj, high);
183    print_page(obj, high, wide);
184}
185
186static void
187repaint_text(MY_OBJ * obj)
188{
189    FILE *fp = obj->obj.input;
190    int cur_y, cur_x;
191
192    getyx(obj->obj.win, cur_y, cur_x);
193    obj->old_hscroll = obj->hscroll;
194
195    print_last_page(obj);
196    obj->last_pos = ftell(fp);
197
198    (void) wmove(obj->obj.win, cur_y, cur_x);	/* Restore cursor position */
199    wrefresh(obj->obj.win);
200}
201
202static bool
203handle_input(DIALOG_CALLBACK * cb)
204{
205    MY_OBJ *obj = (MY_OBJ *) cb;
206    FILE *fp = obj->obj.input;
207    struct stat sb;
208
209    if (fstat(fileno(fp), &sb) == 0
210	&& sb.st_size != obj->last_pos) {
211	repaint_text(obj);
212    }
213
214    return TRUE;
215}
216
217static bool
218valid_callback(DIALOG_CALLBACK * cb)
219{
220    bool valid = FALSE;
221    DIALOG_CALLBACK *p;
222    for (p = dialog_state.getc_callbacks; p != 0; p = p->next) {
223	if (p == cb) {
224	    valid = TRUE;
225	    break;
226	}
227    }
228    return valid;
229}
230
231static bool
232handle_my_getc(DIALOG_CALLBACK * cb, int ch, int fkey, int *result)
233{
234    MY_OBJ *obj = (MY_OBJ *) cb;
235    bool done = FALSE;
236
237    if (!valid_callback(cb))
238	return FALSE;
239
240    if (!fkey && dlg_char_to_button(ch, obj->buttons) == 0) {
241	ch = DLGK_ENTER;
242	fkey = TRUE;
243    }
244
245    if (fkey) {
246	switch (ch) {
247	case DLGK_ENTER:
248	    *result = DLG_EXIT_OK;
249	    done = TRUE;
250	    break;
251	case DLGK_BEGIN:	/* Beginning of line */
252	    obj->hscroll = 0;
253	    break;
254	case DLGK_GRID_LEFT:	/* Scroll left */
255	    if (obj->hscroll > 0) {
256		obj->hscroll -= 1;
257	    }
258	    break;
259	case DLGK_GRID_RIGHT:	/* Scroll right */
260	    if (obj->hscroll < MAX_LEN)
261		obj->hscroll += 1;
262	    break;
263	default:
264	    beep();
265	    break;
266	}
267	if ((obj->hscroll != obj->old_hscroll))
268	    repaint_text(obj);
269    } else {
270	switch (ch) {
271	case ERR:
272	    clearerr(cb->input);
273	    ch = getc(cb->input);
274	    (void) ungetc(ch, cb->input);
275	    if (ch != EOF) {
276		handle_input(cb);
277	    }
278	    break;
279	case ESC:
280	    done = TRUE;
281	    *result = DLG_EXIT_ESC;
282	    break;
283	default:
284	    beep();
285	    break;
286	}
287    }
288
289    return !done;
290}
291
292/*
293 * Display text from a file in a dialog box, like in a "tail -f".
294 */
295int
296dialog_tailbox(const char *title,
297	       const char *filename,
298	       int height,
299	       int width,
300	       int bg_task)
301{
302    /* *INDENT-OFF* */
303    static DLG_KEYS_BINDING binding[] = {
304	HELPKEY_BINDINGS,
305	ENTERKEY_BINDINGS,
306	DLG_KEYS_DATA( DLGK_BEGIN,      '0' ),
307	DLG_KEYS_DATA( DLGK_BEGIN,      KEY_BEG ),
308	DLG_KEYS_DATA( DLGK_GRID_LEFT,  'H' ),
309	DLG_KEYS_DATA( DLGK_GRID_LEFT,  'h' ),
310	DLG_KEYS_DATA( DLGK_GRID_LEFT,  KEY_LEFT ),
311	DLG_KEYS_DATA( DLGK_GRID_RIGHT, 'L' ),
312	DLG_KEYS_DATA( DLGK_GRID_RIGHT, 'l' ),
313	DLG_KEYS_DATA( DLGK_GRID_RIGHT, KEY_RIGHT ),
314	END_KEYS_BINDING
315    };
316    /* *INDENT-ON* */
317
318#ifdef KEY_RESIZE
319    int old_height = height;
320    int old_width = width;
321#endif
322    int fkey;
323    int x, y, result, thigh;
324    WINDOW *dialog, *text;
325    const char **buttons = 0;
326    MY_OBJ *obj;
327    FILE *fd;
328    int min_width = 12;
329
330    DLG_TRACE(("# tailbox args:\n"));
331    DLG_TRACE2S("title", title);
332    DLG_TRACE2S("filename", filename);
333    DLG_TRACE2N("height", height);
334    DLG_TRACE2N("width", width);
335    DLG_TRACE2N("bg_task", bg_task);
336
337    /* Open input file for reading */
338    if ((fd = fopen(filename, "rb")) == NULL)
339	dlg_exiterr("Can't open input file in dialog_tailbox().");
340
341#ifdef KEY_RESIZE
342  retry:
343#endif
344    dlg_auto_sizefile(title, filename, &height, &width, 2, min_width);
345    dlg_print_size(height, width);
346    dlg_ctl_size(height, width);
347
348    x = dlg_box_x_ordinate(width);
349    y = dlg_box_y_ordinate(height);
350    thigh = height - ((2 * MARGIN) + (bg_task ? 0 : 2));
351
352    dialog = dlg_new_window(height, width, y, x);
353
354    dlg_mouse_setbase(x, y);
355
356    /* Create window for text region, used for scrolling text */
357    text = dlg_sub_window(dialog,
358			  thigh,
359			  width - (2 * MARGIN),
360			  y + MARGIN,
361			  x + MARGIN);
362
363    dlg_draw_box2(dialog, 0, 0, height, width, dialog_attr, border_attr, border2_attr);
364    dlg_draw_bottom_box2(dialog, border_attr, border2_attr, dialog_attr);
365    dlg_draw_title(dialog, title);
366    dlg_draw_helpline(dialog, FALSE);
367
368    if (!bg_task) {
369	buttons = dlg_exit_label();
370	dlg_button_layout(buttons, &min_width);
371	dlg_draw_buttons(dialog, height - (2 * MARGIN), 0, buttons, FALSE,
372			 FALSE, width);
373    }
374
375    (void) wmove(dialog, thigh, (MARGIN + 1));
376    (void) wnoutrefresh(dialog);
377
378    obj = dlg_calloc(MY_OBJ, 1);
379    assert_ptr(obj, "dialog_tailbox");
380
381    obj->obj.input = fd;
382    obj->obj.win = dialog;
383    obj->obj.handle_getc = handle_my_getc;
384    obj->obj.handle_input = bg_task ? handle_input : 0;
385    obj->obj.keep_bg = bg_task && dialog_vars.cant_kill;
386    obj->obj.bg_task = bg_task;
387    obj->text = text;
388    obj->buttons = buttons;
389    dlg_add_callback(&(obj->obj));
390
391    dlg_register_window(dialog, "tailbox", binding);
392    dlg_register_buttons(dialog, "tailbox", buttons);
393
394    /* Print last page of text */
395    dlg_attr_clear(text, thigh, getmaxx(text), dialog_attr);
396    repaint_text(obj);
397
398    dlg_trace_win(dialog);
399    if (bg_task) {
400	result = DLG_EXIT_OK;
401    } else {
402	int ch;
403	do {
404	    ch = dlg_getc(dialog, &fkey);
405#ifdef KEY_RESIZE
406	    if (fkey && ch == KEY_RESIZE) {
407		dlg_will_resize(dialog);
408		/* reset data */
409		height = old_height;
410		width = old_width;
411		/* repaint */
412		dlg_clear();
413		dlg_del_window(dialog);
414		refresh();
415		dlg_mouse_free_regions();
416		dlg_button_layout(buttons, &min_width);
417		goto retry;
418	    }
419#endif
420	}
421	while (handle_my_getc(&(obj->obj), ch, fkey, &result));
422    }
423    dlg_mouse_free_regions();
424    return result;
425}
426