ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/root-tail/root-tail.c
(Generate patch)

Comparing root-tail/root-tail.c (file contents):
Revision 1.3 by pcg, Sun May 5 19:10:39 2002 UTC vs.
Revision 1.43 by chris_moore, Wed Mar 31 17:07:02 2004 UTC

1/* 1/*
2 * Copyright 2001 by Marco d'Itri <md@linux.it> 2 * Copyright 2001 by Marco d'Itri <md@linux.it>
3 * 3 * Copyright 2000,2001,2002,2003,2004
4 * Original version by Mike Baker, then maintained by pcg@goof.com. 4 * Marc Lehmann <pcg@goof.com>,
5 * and many others, see README
6 *
7 * Original version by Mike Baker.
5 * 8 *
6 * This program is free software; you can redistribute it and/or modify 9 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by 10 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or 11 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version. 12 * (at your option) any later version.
28#include <fcntl.h> 31#include <fcntl.h>
29#include <errno.h> 32#include <errno.h>
30#include <sys/time.h> 33#include <sys/time.h>
31#include <sys/stat.h> 34#include <sys/stat.h>
32#include <sys/types.h> 35#include <sys/types.h>
36#include <locale.h>
37#include <ctype.h>
38#include <stdarg.h>
39#include <X11/Xlib.h>
40#include <X11/Xatom.h>
41#include <X11/Xutil.h>
42
33#if HAS_REGEX 43#if HAS_REGEX
34#include <regex.h> 44#include <regex.h>
35#endif 45#endif
36#include <X11/Xlib.h> 46
37#include <X11/Xutil.h> 47#define SHADE_X 2
48#define SHADE_Y 2
38 49
39/* data structures */ 50/* data structures */
40struct logfile_entry { 51struct logfile_entry
41 char *fname; /* name of file */ 52{
42 char *desc; /* alternative description */
43 FILE *fp; /* FILE struct associated with file */
44 ino_t inode; /* inode of the file opened */
45 off_t last_size; /* file size at the last check */
46 unsigned long color; /* color to be used for printing */
47 struct logfile_entry *next; 53 struct logfile_entry *next;
54
55 char *fname; /* name of file */
56 char *desc; /* alternative description */
57 char *buf; /* text read but not yet displayed */
58 FILE *fp; /* FILE struct associated with file */
59 ino_t inode; /* inode of the file opened */
60 off_t last_size; /* file size at the last check */
61 unsigned long color; /* color to be used for printing */
62 int partial; /* true if the last line isn't complete */
63 int lastpartial; /* true if the previous output wasn't complete */
64 int index; /* index into linematrix of a partial line */
65 int modified; /* true if line is modified & needs displaying */
48}; 66};
49 67
50struct linematrix { 68struct linematrix
69{
51 char *line; 70 char *line;
71 int len;
52 unsigned long color; 72 unsigned long color;
53}; 73};
54 74
75struct displaymatrix
76{
77 char *line;
78 int len;
79 int buffer_size;
80 unsigned long color;
81};
55 82
56/* global variables */ 83/* global variables */
57unsigned int width = STD_WIDTH, listlen = STD_HEIGHT; 84struct linematrix *lines;
85struct displaymatrix *display;
86int width = STD_WIDTH, height = STD_HEIGHT, listlen;
58int win_x = LOC_X, win_y = LOC_Y; 87int win_x = LOC_X, win_y = LOC_Y;
59int w = -1, h = -1, font_width, font_height, font_descent; 88int font_ascent, font_height;
89int effect_x_space, effect_y_space; /* how much space does shading / outlining take up */
90int effect_x_offset, effect_y_offset; /* and how does it offset the usable space */
60int do_reopen; 91int do_reopen;
61struct timeval interval = { 2, 400000 }; /* see Knuth */ 92struct timeval interval = { 2, 400000 };
93XFontSet fontset;
62 94
63/* command line options */ 95/* command line options */
64int opt_noinitial, opt_shade, opt_frame, opt_reverse=0, opt_nofilename, 96int opt_noinitial, opt_shade, opt_frame, opt_reverse, opt_nofilename,
97 opt_outline, opt_noflicker, opt_whole, opt_update, opt_wordwrap,
65 geom_mask, reload = 3600; 98 geom_mask, reload = 0;
66const char *command = NULL, 99const char *command = NULL,
67 *fontname = USE_FONT, *dispname = NULL, *def_color = DEF_COLOR; 100 *fontname = USE_FONT, *dispname = NULL, *def_color = DEF_COLOR,
101 *continuation = "[+]";
68 102
69struct logfile_entry *loglist = NULL, *loglist_tail = NULL; 103struct logfile_entry *loglist = NULL, *loglist_tail = NULL;
70 104
71Display *disp; 105Display *disp;
72Window root; 106Window root;
73GC WinGC; 107GC WinGC;
74 108
75#if HAS_REGEX 109#if HAS_REGEX
76struct re_list { 110struct re_list
111{
77 regex_t from; 112 regex_t from;
78 const char *to; 113 const char *to;
79 struct re_list *next; 114 struct re_list *next;
80}; 115};
81struct re_list *re_head, *re_tail; 116struct re_list *re_head, *re_tail;
117char *transform_to = NULL;
118regex_t *transformre;
82#endif 119#endif
83 120
84 121
85/* prototypes */ 122/* prototypes */
86void list_files(int); 123void list_files (int);
87void force_reopen(int); 124void force_reopen (int);
88void force_refresh(int); 125void force_refresh (int);
89void blank_window(int); 126void blank_window (int);
90 127
91void InitWindow(void); 128void InitWindow (void);
92unsigned long GetColor(const char *); 129unsigned long GetColor (const char *);
93void redraw(void); 130void redraw (int);
94void refresh(struct linematrix *, int, int); 131void refresh (int, int, int, int);
95 132
96void transform_line(char *s); 133void transform_line (char *s);
97int lineinput(char *, int, FILE *); 134int lineinput (struct logfile_entry *);
98void reopen(void); 135void reopen (void);
99void check_open_files(void); 136void check_open_files (void);
100FILE *openlog(struct logfile_entry *); 137FILE *openlog (struct logfile_entry *);
101void main_loop(void); 138static void main_loop (void);
102 139
103void display_version(void); 140void display_version (void);
104void display_help(char *); 141void display_help (char *);
105void install_signal(int, void (*)(int)); 142void install_signal (int, void (*)(int));
106void *xstrdup(const char *); 143void *xstrdup (const char *);
107void *xmalloc(size_t); 144void *xmalloc (size_t);
145void *xrealloc (void *, size_t);
108int daemonize(void); 146int daemonize (void);
109 147
110/* signal handlers */ 148/* signal handlers */
149void
111void list_files(int dummy) 150list_files (int dummy)
112{ 151{
113 struct logfile_entry *e; 152 struct logfile_entry *e;
114 153
115 fprintf(stderr, "Files opened:\n"); 154 fprintf (stderr, "Files opened:\n");
116 for (e = loglist; e; e = e->next) 155 for (e = loglist; e; e = e->next)
117 fprintf(stderr, "\t%s (%s)\n", e->fname, e->desc); 156 fprintf (stderr, "\t%s (%s)\n", e->fname, e->desc);
118} 157}
119 158
159void
120void force_reopen(int dummy) 160force_reopen (int dummy)
121{ 161{
122 do_reopen = 1; 162 do_reopen = 1;
123} 163}
124 164
165void
125void force_refresh(int dummy) 166force_refresh (int dummy)
126{ 167{
127 XClearWindow(disp, root);
128 redraw(); 168 redraw (1);
129} 169}
130 170
171void
131void blank_window(int dummy) 172blank_window (int dummy)
132{ 173{
133 XClearWindow(disp, root); 174 XClearArea (disp, root, win_x - 2, win_y - 2, width + 5, height + 5, False);
134 XFlush(disp); 175 XFlush (disp);
135 exit(0); 176 exit (0);
136} 177}
137 178
138/* X related functions */ 179/* X related functions */
180unsigned long
139unsigned long GetColor(const char *ColorName) 181GetColor (const char *ColorName)
140{ 182{
141 XColor Color; 183 XColor Color;
142 XWindowAttributes Attributes; 184 XWindowAttributes Attributes;
143 185
144 XGetWindowAttributes(disp, root, &Attributes); 186 XGetWindowAttributes (disp, root, &Attributes);
145 Color.pixel = 0; 187 Color.pixel = 0;
188
146 if (!XParseColor(disp, Attributes.colormap, ColorName, &Color)) 189 if (!XParseColor (disp, Attributes.colormap, ColorName, &Color))
147 fprintf(stderr, "can't parse %s\n", ColorName); 190 fprintf (stderr, "can't parse %s\n", ColorName);
148 else if (!XAllocColor(disp, Attributes.colormap, &Color)) 191 else if (!XAllocColor (disp, Attributes.colormap, &Color))
149 fprintf(stderr, "can't allocate %s\n", ColorName); 192 fprintf (stderr, "can't allocate %s\n", ColorName);
193
150 return Color.pixel; 194 return Color.pixel;
151} 195}
152 196
153void InitWindow(void) 197static Window
198root_window (Display * display, int screen_number)
154{ 199{
155 XGCValues gcv; 200 Atom SWM_VROOT = XInternAtom (display, "__SWM_VROOT", False);
156 Font font; 201 Window real_root_window = RootWindow (display, screen_number);
157 unsigned long gcm;
158 XFontStruct *info;
159 int screen, ScreenWidth, ScreenHeight;
160 202
161 if (!(disp = XOpenDisplay(dispname))) { 203 if (root) /* root window set via option */
162 fprintf(stderr, "Can't open display %s.\n", dispname); 204 return root;
163 exit(1); 205
206 if (SWM_VROOT != None)
164 } 207 {
165 screen = DefaultScreen(disp); 208 Window unused, *windows;
166 ScreenHeight = DisplayHeight(disp, screen); 209 unsigned int count;
167 ScreenWidth = DisplayWidth(disp, screen);
168 root = RootWindow(disp, screen);
169 gcm = GCBackground;
170 gcv.graphics_exposures = True;
171 WinGC = XCreateGC(disp, root, gcm, &gcv);
172 XMapWindow(disp, root);
173 XSetForeground(disp, WinGC, GetColor(DEF_COLOR));
174 210
175 font = XLoadFont(disp, fontname); 211 if (XQueryTree (display, real_root_window, &unused, &unused, &windows,
176 XSetFont(disp, WinGC, font); 212 &count))
177 info = XQueryFont(disp, font);
178 font_width = info->max_bounds.width;
179 font_descent = info->max_bounds.descent;
180 font_height = info->max_bounds.ascent + font_descent;
181
182 w = width * font_width;
183 h = listlen * font_height;
184 if (geom_mask & XNegative)
185 win_x = win_x + ScreenWidth - w;
186 if (geom_mask & YNegative)
187 win_y = win_y + ScreenHeight - h;
188
189 XSelectInput(disp, root, ExposureMask|FocusChangeMask);
190}
191
192char *
193detabificate (char *s)
194{
195 char * out;
196 int i, j;
197
198 out = malloc (8 * strlen (s) + 1);
199
200 for(i = 0, j = 0; s[i]; i++)
201 {
202 if (s[i] == '\t')
203 do 213 {
204 out[j++] = ' '; 214 int i;
205 while (j % 8); 215
216 for (i = 0; i < count; i++)
217 {
218 Atom type;
219 int format;
220 unsigned long nitems, bytes_after_return;
221 unsigned char *virtual_root_window;
222
223 if (XGetWindowProperty (display, windows[i], SWM_VROOT,
224 0, 1, False, XA_WINDOW, &type, &format,
225 &nitems, &bytes_after_return,
226 &virtual_root_window) == Success)
227 {
228 if (type != None)
229 {
230 if (type == XA_WINDOW)
231 {
232 XFree (windows);
233 return (Window) virtual_root_window;
234 }
235 else
236 fprintf (stderr,
237 "__SWM_VROOT property type mismatch");
238 }
239 }
240 else
241 fprintf (stderr,
242 "failed to get __SWM_VROOT property on window 0x%lx",
243 windows[i]);
244 }
245
246 if (count)
247 XFree (windows);
248 }
206 else 249 else
207 out[j++] = s[i]; 250 fprintf (stderr, "Can't query tree on root window 0x%lx",
251 real_root_window);
252 }
253 else
254 /* This shouldn't happen. The Xlib documentation is wrong BTW. */
255 fprintf (stderr, "Can't intern atom __SWM_VROOT");
256
257 return real_root_window;
258}
259
260void
261InitWindow (void)
262{
263 XGCValues gcv;
264 unsigned long gcm;
265 int screen, ScreenWidth, ScreenHeight;
266
267 if (!(disp = XOpenDisplay (dispname)))
268 {
269 fprintf (stderr, "Can't open display %s.\n", dispname);
270 exit (1);
271 }
272
273 screen = DefaultScreen (disp);
274 ScreenHeight = DisplayHeight (disp, screen);
275 ScreenWidth = DisplayWidth (disp, screen);
276
277 root = root_window (disp, screen);
278
279 gcm = GCBackground;
280 gcv.graphics_exposures = True;
281 WinGC = XCreateGC (disp, root, gcm, &gcv);
282 XMapWindow (disp, root);
283 XSetForeground (disp, WinGC, GetColor (DEF_COLOR));
284
285 {
286 char **missing_charset_list;
287 int missing_charset_count;
288 char *def_string;
289
290 fontset = XCreateFontSet (disp, fontname,
291 &missing_charset_list, &missing_charset_count,
292 &def_string);
293
294 if (missing_charset_count)
295 {
296 fprintf (stderr,
297 "Missing charsets in String to FontSet conversion (%s)\n",
298 missing_charset_list[0]);
299 XFreeStringList (missing_charset_list);
208 } 300 }
301 }
302
303 if (!fontset)
304 {
305 fprintf (stderr, "unable to create fontset, exiting.\n");
306 exit (1);
307 }
308
309 {
310 XFontSetExtents *xfe = XExtentsOfFontSet (fontset);
311
312 font_height = xfe->max_logical_extent.height;
313 font_ascent = -xfe->max_logical_extent.y;
314 }
315
316 if (geom_mask & XNegative)
317 win_x = win_x + ScreenWidth - width;
318 if (geom_mask & YNegative)
319 win_y = win_y + ScreenHeight - height;
320
321 if (opt_outline)
322 {
323 /* adding outline increases the total width and height by 2
324 pixels each, and offsets the text one pixel right and one
325 pixel down */
326 effect_x_space = effect_y_space = 2;
327 effect_x_offset = effect_y_offset = 1;
328 }
329 else if (opt_shade)
330 {
331 /* adding a shadow increases the space used */
332 effect_x_space = abs(SHADE_X);
333 effect_y_space = abs(SHADE_Y);
334 /* if the shadow is to the right and below then we don't need
335 * to move the text to make space for it, but shadows to the left
336 * and above need accomodating */
337 effect_x_offset = SHADE_X > 0 ? 0 : -SHADE_X;
338 effect_y_offset = SHADE_Y > 0 ? 0 : -SHADE_Y;
339 }
340 else
341 {
342 effect_x_space = effect_y_space = 0;
343 effect_x_offset = effect_y_offset = 0;
344 }
345
346 /* if we are using -shade or -outline, there will be less usable
347 * space for output */
348 listlen = (height - effect_y_space) / font_height;
349
350 if (!listlen)
351 {
352 fprintf (stderr, "height too small for a single line, setting to %d\n",
353 font_height);
354 listlen = 1;
355 }
356
357 /* leave the height how the user requested it. it might not all be
358 * used, but this will allow the geometry to be tuned more accurately
359 * (with the -frame option)
360 * the old code did this:
361 * height = listlen * font_height + effect_y_space; */
209 362
210 out[j] = '\0'; 363 XSelectInput (disp, root, ExposureMask | FocusChangeMask);
211 return out;
212} 364}
213 365
214/* 366/*
215 * redraw does a complete redraw, rather than an update (i.e. the area 367 * if redraw() is passwd a non-zero argument, it does a complete
216 * gets cleared first) 368 * redraw, rather than an update. if the argument is zero (and
369 * -noflicker is in effect) then only the lines which have changed
370 * since the last draw are redrawn.
371 *
217 * the rest is handled by regular refresh()'es 372 * the rest is handled by regular refresh()'es
218 */ 373 */
219void redraw(void) 374void
375redraw (int redraw_all)
220{ 376{
221 XClearArea(disp, root, win_x, win_y, w, h + font_descent + 2, True); 377 XSetClipMask (disp, WinGC, None);
378 refresh (0, 32768, 1, redraw_all);
222} 379}
223 380
224/* Just redraw everything without clearing (i.e. after an EXPOSE event) */ 381/* Just redraw everything without clearing (i.e. after an EXPOSE event) */
225void refresh(struct linematrix *lines, int miny, int maxy) 382void
383refresh (int miny, int maxy, int clear, int refresh_all)
226{ 384{
227 int lin; 385 int lin;
228 int offset = (listlen + 1) * font_height; 386 int offset = listlen * font_height + font_ascent + effect_y_offset;
229 unsigned long black_color = GetColor("black"); 387 unsigned long black_color = GetColor ("black");
230 388
231 miny -= win_y + font_height; 389 miny -= win_y + font_height;
232 maxy -= win_y - font_height; 390 maxy -= win_y - font_height;
233 391
392 if (clear && !opt_noflicker)
393 XClearArea (disp, root, win_x, win_y, width, height, False);
394
234 for (lin = listlen; lin--;) 395 for (lin = listlen; lin--;)
396 {
397 struct linematrix *line = lines + (opt_reverse ? listlen - lin - 1 : lin);
398 struct displaymatrix *display_line = display + lin;
399
400 offset -= font_height;
401
402 if (offset < miny || offset > maxy)
403 continue;
404
405 /* if this line is a different than it was, then it
406 * needs displaying */
407 if (!opt_noflicker
408 || refresh_all
409 || display_line->len != line->len
410 || display_line->color != line->color
411 || memcmp (display_line->line, line->line, line->len))
235 { 412 {
236 char *temp; 413 /* don't bother updating the record of what has been
414 * displayed if -noflicker isn't in effect, since we redraw
415 * the whole display every time anyway */
416 if (opt_noflicker)
417 {
418 /* update the record of what has been displayed;
419 * first make sure the buffer is big enough */
420 if (display_line->buffer_size <= line->len)
421 {
422 display_line->buffer_size = line->len;
423 display_line->line = xrealloc (display_line->line, display_line->buffer_size);
424 }
425
426 display_line->len = line->len;
427 display_line->color = line->color;
428 memcpy (display_line->line, line->line, line->len);
429
430 if (clear)
431 XClearArea (disp, root, win_x, win_y + offset - font_ascent,
432 width + effect_x_space, font_height + effect_y_space, False);
433 }
434
435 if (opt_outline)
436 {
437 int x, y;
438 XSetForeground (disp, WinGC, black_color);
439
440 for (x = -1; x <= 1; x += 2)
441 for (y = -1; y <= 1; y += 2)
442 XmbDrawString (disp, root, fontset, WinGC,
443 win_x + effect_x_offset + x,
444 win_y + y + offset,
445 line->line, line->len);
446 }
447 else if (opt_shade)
448 {
449 XSetForeground (disp, WinGC, black_color);
450 XmbDrawString (disp, root, fontset, WinGC,
451 win_x + effect_x_offset + SHADE_X,
452 win_y + offset + SHADE_Y,
453 line->line, line->len);
454 }
455
456 XSetForeground (disp, WinGC, line->color);
457 XmbDrawString (disp, root, fontset, WinGC,
458 win_x + effect_x_offset,
459 win_y + offset,
460 line->line, line->len);
461 }
462 }
463
464 if (opt_frame)
465 {
466 XSetForeground (disp, WinGC, GetColor (def_color));
467 XDrawRectangle (disp, root, WinGC, win_x - 0, win_y - 0, width - 1, height - 1);
468 }
469}
470
471#if HAS_REGEX
472void
473transform_line (char *s)
474{
475#ifdef I_AM_Md
476 int i;
477 if (1)
478 {
479 for (i = 16; s[i]; i++)
480 s[i] = s[i + 11];
481 }
482 s[i + 1] = '\0';
483#endif
484
485 if (transformre)
486 {
487 int i;
488 regmatch_t matched[16];
489
490 i = regexec (transformre, s, 16, matched, 0);
491 if (i == 0)
492 { /* matched */
493 int match_start = matched[0].rm_so;
494 int match_end = matched[0].rm_eo;
495 int old_len = match_end - match_start;
496 int new_len = strlen (transform_to);
497 int old_whole_len = strlen (s);
498
499 printf ("regexp was matched by '%s' - replace with '%s'\n", s, transform_to);
500 printf ("match is from %d to %d\n", match_start, match_end);
501 if (new_len > old_len)
502 s = xrealloc(s, old_whole_len + new_len - old_len);
503
504 if (new_len != old_len)
505 {
506 memcpy(s + match_end + new_len - old_len,
507 s + match_end,
508 old_whole_len - match_end);
509 s[old_whole_len + new_len - old_len] = '\0';
510 }
511
512 memcpy (s + match_start,
513 transform_to,
514 new_len);
515 printf ("transformed to '%s'\n", s);
516 }
517 else
518 {
519 printf ("regexp was not matched by '%s'\n", s);
520 }
521 }
522}
523#endif
524
525char *
526concat_line (const char *p1, const char *p2)
527{
528 int l1 = p1 ? strlen (p1) : 0;
529 int l2 = strlen (p2);
530 char *r = xmalloc (l1 + l2 + 1);
531
532 memcpy (r, p1, l1);
533 memcpy (r + l1, p2, l2);
534 r[l1 + l2] = 0;
535
536 return r;
537}
538
539/*
540 * This routine can read a line of any length if it is called enough times.
541 */
542int
543lineinput (struct logfile_entry *logfile)
544{
545 char buff[1024], *p = buff;
546 int ch;
547 /* HACK-2: add on the length of any partial line which we will be appending to */
548 int ofs = logfile->buf ? strlen (logfile->buf) : 0;
549
550 do
551 {
552 ch = fgetc (logfile->fp);
553
554 if (ch == '\n' || ch == EOF)
555 break;
556 else if (ch == '\r')
557 continue; /* skip */
558 else if (ch == '\t')
559 {
560 do
561 {
562 *p++ = ' ';
563 ofs++;
564 }
565 while (ofs & 7);
566 }
567 else
568 {
569 *p++ = ch;
570 ofs++;
571 }
572 }
573 while (p < buff + (sizeof buff) - 8 - 1);
574
575 if (p == buff && ch == EOF)
576 return 0;
577
578 *p = 0;
579
580 p = concat_line (logfile->buf, buff);
581 free (logfile->buf); logfile->buf = p;
582
583 logfile->lastpartial = logfile->partial;
584 /* there are 3 ways we could have exited the loop: reading '\n',
585 * reaching EOF, or filling the buffer; the 2nd and 3rd of these
586 * both result in a partial line */
587 logfile->partial = ch != '\n';
237 588
238 offset -= font_height; 589 if (logfile->partial && opt_whole)
239 590 return 0;
240 if (offset < miny || offset > maxy)
241 continue;
242
243 if (opt_reverse)
244 temp = detabificate (lines[listlen-lin-1].line);
245 else
246 temp = detabificate (lines[lin].line);
247
248 if (opt_shade)
249 {
250 XSetForeground (disp, WinGC, black_color);
251 XDrawString (disp, root, WinGC, win_x + 2, win_y + offset + 2,
252 temp, strlen (temp));
253 }
254
255 XSetForeground (disp, WinGC, lines[lin].color);
256 XDrawString (disp, root, WinGC, win_x, win_y + offset,
257 temp, strlen (temp));
258
259 free (temp);
260 }
261
262 if (opt_frame) {
263 int bot_y = win_y + h + font_descent + 2;
264
265 XDrawLine(disp, root, WinGC, win_x, win_y, win_x + w, win_y);
266 XDrawLine(disp, root, WinGC, win_x + w, win_y, win_x + w, bot_y);
267 XDrawLine(disp, root, WinGC, win_x + w, bot_y, win_x, bot_y);
268 XDrawLine(disp, root, WinGC, win_x, bot_y, win_x, win_y);
269 }
270}
271 591
272#if HAS_REGEX 592#if HAS_REGEX
273void transform_line(char *s) 593 transform_line (logfile->buf);
274{
275#ifdef I_AM_Md
276 int i;
277 if (1) {
278 for (i = 16; s[i]; i++)
279 s[i] = s[i + 11];
280 }
281 s[i + 1] = '\0';
282#endif 594#endif
283
284 if (transformre) {
285 int i;
286 regmatch_t matched[16];
287
288 i = regexec(&transformre, string, 16, matched, 0);
289 if (i == 0) { /* matched */
290 }
291 }
292}
293#endif
294
295
296/*
297 * This routine should read 'width' characters and not more. However,
298 * we really want to read width + 1 charachters if the last char is a '\n',
299 * which we should remove afterwards. So, read width+1 chars and ungetc
300 * the last character if it's not a newline. This means 'string' must be
301 * width + 2 wide!
302 */
303int lineinput(char *string, int slen, FILE *f)
304{
305 int len;
306
307 do {
308 if (fgets(string, slen, f) == NULL) /* EOF or Error */
309 return 0; 595 return 1;
310
311 len = strlen(string);
312 } while (len == 0);
313
314 if (string[len - 1] == '\n')
315 string[len - 1] = '\0'; /* erase newline */
316 else if (len >= slen - 1) {
317 ungetc(string[len - 1], f);
318 string[len - 1] = '\0';
319 }
320
321#if HAS_REGEX
322 transform_line(string);
323#endif
324 return len;
325} 596}
326 597
327/* input: reads file->fname 598/* input: reads file->fname
328 * output: fills file->fp, file->inode 599 * output: fills file->fp, file->inode
329 * returns file->fp 600 * returns file->fp
330 * in case of error, file->fp is NULL 601 * in case of error, file->fp is NULL
331 */ 602 */
603FILE *
332FILE *openlog(struct logfile_entry *file) 604openlog (struct logfile_entry * file)
333{ 605{
334 struct stat stats; 606 struct stat stats;
335 607
336 if ((file->fp = fopen(file->fname, "r")) == NULL) { 608 if ((file->fp = fopen (file->fname, "r")) == NULL)
609 {
337 file->fp = NULL; 610 file->fp = NULL;
338 return NULL; 611 return NULL;
339 } 612 }
340 613
341 fstat(fileno(file->fp), &stats); 614 fstat (fileno (file->fp), &stats);
342 if (S_ISFIFO(stats.st_mode)) { 615 if (S_ISFIFO (stats.st_mode))
616 {
343 if (fcntl(fileno(file->fp), F_SETFL, O_NONBLOCK) < 0) 617 if (fcntl (fileno (file->fp), F_SETFL, O_NONBLOCK) < 0)
344 perror("fcntl"), exit(1); 618 perror ("fcntl"), exit (1);
345 file->inode = 0; 619 file->inode = 0;
620 }
346 } else 621 else
347 file->inode = stats.st_ino; 622 file->inode = stats.st_ino;
348 623
349 if (opt_noinitial) 624 if (opt_noinitial)
350 fseek (file->fp, 0, SEEK_END); 625 fseek (file->fp, 0, SEEK_END);
351 else if (stats.st_size > (listlen + 1) * width) 626 else if (stats.st_size > (listlen + 1) * width)
627 fseek (file->fp, -((listlen + 2) * width), SEEK_END);
628
629 file->last_size = stats.st_size;
630 return file->fp;
631}
632
633void
634reopen (void)
635{
636 struct logfile_entry *e;
637
638 for (e = loglist; e; e = e->next)
639 {
640 if (!e->inode)
641 continue; /* skip stdin */
642
643 if (e->fp)
644 fclose (e->fp);
645 /* if fp is NULL we will try again later */
646 openlog (e);
647 }
648
649 do_reopen = 0;
650}
651
652void
653check_open_files (void)
654{
655 struct logfile_entry *e;
656 struct stat stats;
657
658 for (e = loglist; e; e = e->next)
659 {
660 if (!e->inode)
661 continue; /* skip stdin */
662
663 if (stat (e->fname, &stats) < 0)
664 { /* file missing? */
665 sleep (1);
666 if (e->fp)
667 fclose (e->fp);
668 if (openlog (e) == NULL)
669 continue;
670 if (fstat (fileno (e->fp), &stats) < 0)
671 continue;
672 }
673
674 if (stats.st_ino != e->inode)
675 { /* file renamed? */
676 if (e->fp)
677 fclose (e->fp);
678 if (openlog (e) == NULL)
679 continue;
680 if (fstat (fileno (e->fp), &stats) < 0)
681 continue;
682 }
683
684 if (stats.st_size < e->last_size)
685 { /* file truncated? */
686 fseek (e->fp, 0, SEEK_SET);
687 e->last_size = stats.st_size;
688 }
689 }
690}
691
692/*
693 * insert a single physical line (that must be short enough to fit)
694 * at position "idx" by pushing up lines above it. the caller
695 * MUST then fill in lines[idx] with valid data.
696 */
697static void
698insert_line (int idx)
699{
700 int cur_line;
701 struct logfile_entry *current;
702
703 free (lines[0].line);
704
705 for (cur_line = 0; cur_line < idx; cur_line++)
706 lines[cur_line] = lines[cur_line + 1];
707
708 for (current = loglist; current; current = current->next)
709 if (current->index <= idx)
710 current->index--;
711}
712
713/*
714 * remove a single physical line at position "idx" by moving the lines above it
715 * down and inserting a "~" line at the top.
716 */
717static void
718delete_line (int idx)
719{
720 int cur_line;
721 struct logfile_entry *current;
722
723 for (cur_line = idx; cur_line > 0; cur_line--)
724 lines[cur_line] = lines[cur_line - 1];
725
726 lines[0].line = xstrdup ("~");
727
728 for (current = loglist; current; current = current->next)
729 if (current->index >= 0 && current->index <= idx)
730 current->index++;
731}
732
733/*
734 * takes a logical log file line and splits it into multiple physical
735 * screen lines by splitting it whenever a part becomes too long.
736 * lal lines will be inserted at position "idx".
737 */
738static void
739split_line (int idx, const char *str, unsigned long color)
740{
741 int l = strlen (str);
742 int last_wrapped = 0;
743 const char *p = str;
744 static int continuation_width = -1;
745 static int continuation_length;
746
747 /* only calculate the continuation's width once */
748 if (continuation_width == -1)
749 {
750 continuation_length = strlen (continuation);
751 continuation_width = XmbTextEscapement (fontset, continuation, continuation_length);
752 }
753
754 do
755 {
756 const char *beg = p;
757 int w = last_wrapped ? continuation_width : 0;
758 int wrapped = 0;
759 const char *break_p = NULL;
760
761 while (*p)
762 {
763 /* find the length in bytes of the next multibyte character */
764 int len = mblen (p, l);
765 if (len <= 0)
766 len = 1; /* ignore (don't skip) illegal character sequences */
767
768 /* find the width in pixels of the next character */
769 int cw = XmbTextEscapement (fontset, p, len);
770 if (cw + w > width - effect_x_space)
771 {
772 if (p == beg)
773 {
774 fprintf (stderr, "we can't even fit a single character onto the line\n");
775 if (len == 1) fprintf (stderr, "(the character we couldn't fit was '%c')\n", *p);
776 exit (1);
777 }
778
779 wrapped = 1;
780 break;
781 }
782
783 if (opt_wordwrap && len == 1 && p[0] == ' ')
784 break_p = p;
785
786 w += cw;
787 p += len;
788 l -= len;
789 }
790
791 /* if we're wrapping at spaces, and the line is long enough to
792 * wrap, and we've seen a space already, and the space wasn't
793 * the first character on the line, then wrap at the space */
794 if (opt_wordwrap && wrapped && break_p && break_p != beg)
795 {
796 l += p - break_p;
797 p = break_p;
798 }
799
352 { 800 {
353 char dummy[255]; 801 int len = p - beg + (last_wrapped ? continuation_length : 0);
802 char *s = xmalloc (len + 1);
803 if (last_wrapped)
804 {
805 memcpy (s, continuation, continuation_length);
806 memcpy (s + continuation_length, beg, p - beg);
807 }
808 else
809 memcpy (s, beg, len);
354 810
355 fseek(file->fp, -((listlen + 2) * width), SEEK_END); 811 s[len] = 0;
356 /* the pointer might point halfway some line. Let's 812 insert_line (idx);
357 be nice and skip this damaged line */ 813 lines[idx].line = s;
358 lineinput(dummy, sizeof(dummy), file->fp); 814 lines[idx].len = len;
815 lines[idx].color = color;
359 } 816 }
360 817
361 file->last_size = stats.st_size; 818 /* if we wrapped at a space, don't display the space */
362 return file->fp; 819 if (opt_wordwrap && wrapped && break_p && break_p != beg)
363} 820 {
364 821 l--;
365void reopen(void) 822 p++;
366{
367 struct logfile_entry *e;
368
369 for (e = loglist; e; e = e->next) {
370 if (!e->inode)
371 continue; /* skip stdin */
372
373 if (e->fp)
374 fclose(e->fp);
375 /* if fp is NULL we will try again later */
376 openlog(e);
377 }
378
379 do_reopen = 0;
380}
381
382void check_open_files(void)
383{
384 struct logfile_entry *e;
385 struct stat stats;
386
387 for (e = loglist; e; e = e->next) {
388 if (!e->inode)
389 continue; /* skip stdin */
390
391 if (stat(e->fname, &stats) < 0) { /* file missing? */
392 sleep(1);
393 if (e->fp)
394 fclose(e->fp);
395 if (openlog(e) == NULL)
396 break;
397 } 823 }
398 824
399 if (stats.st_ino != e->inode) { /* file renamed? */ 825 last_wrapped = wrapped;
400 if (e->fp) 826 }
401 fclose(e->fp); 827 while (l);
828}
829
830/*
831 * append something to an existing physical line. this is done
832 * by deleting the file on-screen, concatenating the new data to it
833 * and splitting it again.
834 */
835static void
836append_line (int idx, const char *str)
837{
838 unsigned long color = lines[idx].color;
839 char *old = lines[idx].line;
840 char *new = concat_line (old, str);
841
842 free (old);
843
844 delete_line (idx);
845 split_line (idx, new, color);
846}
847
848static void
849main_loop (void)
850{
851 lines = xmalloc (sizeof (struct linematrix) * listlen);
852 display = xmalloc (sizeof (struct displaymatrix) * listlen);
853 int lin;
854 time_t lastreload;
855 Region region = XCreateRegion ();
856 XEvent xev;
857 struct logfile_entry *lastprinted = NULL;
858 struct logfile_entry *current;
859 int need_update = 1;
860
861 lastreload = time (NULL);
862
863 /* Initialize linematrix */
864 for (lin = 0; lin < listlen; lin++)
865 {
866 lines[lin].line = xstrdup ("~");
867 lines[lin].len = 1;
868 display[lin].line = xstrdup("");
869 display[lin].len = 0;
870 display[lin].buffer_size = 0;
871 lines[lin].color = GetColor (def_color);
872 }
873
874 for (;;)
875 {
876 /* read logs */
877 for (current = loglist; current; current = current->next)
878 {
879 if (!current->fp)
880 continue; /* skip missing files */
881
882 clearerr (current->fp);
883
884 while (lineinput (current))
885 {
886 need_update = 1;
887 /* if we're trying to update old partial lines in
888 * place, and the last time this file was updated the
889 * output was partial, and that partial line is not
890 * too close to the top of the screen, then update
891 * that partial line */
892 if (opt_update && current->lastpartial && current->index >= 0)
893 {
894 int idx = current->index;
895 append_line (idx, current->buf);
896 current->index = idx;
897 free (current->buf), current->buf = 0;
898 continue;
899 }
900
901 /* print filename if any, and if last line was from
902 * different file */
903 if (!opt_nofilename && lastprinted != current && current->desc[0])
904 {
905 split_line (listlen - 1, "[", current->color);
906 append_line (listlen - 1, current->desc);
907 append_line (listlen - 1, "]");
908 }
909
910 /* if we're dealing with partial lines, and the last
911 * time we showed the line it wasn't finished ... */
912 if (!opt_whole && current->lastpartial)
913 {
914 /* if this is the same file we showed last then
915 append to the last line shown */
916 if (lastprinted == current)
917 append_line (listlen - 1, current->buf);
918 else
919 {
920 /* but if a different file has been shown in the
921 * mean time, make a new line, starting with the
922 * continuation string */
923 split_line (listlen - 1, continuation, current->color);
924 append_line (listlen - 1, current->buf);
925 }
926 }
927 else
928 /* otherwise just make a plain and simple new line */
929 split_line (listlen - 1, current->buf, current->color);
930
931 free (current->buf), current->buf = 0;
932 current->index = listlen - 1;
933 lastprinted = current;
934 }
935 }
936
937 if (need_update)
938 {
939 redraw (0);
940 need_update = 0;
941 }
942 else
943 {
944 XFlush (disp);
945
946 if (!XPending (disp))
947 {
948 fd_set fdr;
949 struct timeval to = interval;
950
951 FD_ZERO (&fdr);
952 FD_SET (ConnectionNumber (disp), &fdr);
953 select (ConnectionNumber (disp) + 1, &fdr, 0, 0, &to);
954 }
955 }
956
957 check_open_files ();
958
959 if (do_reopen)
960 reopen ();
961
962 /* we ignore possible errors due to window resizing &c */
963 while (XPending (disp))
964 {
965 XNextEvent (disp, &xev);
966
967 switch (xev.type)
968 {
969 case Expose:
970 {
971 XRectangle r;
972
973 r.x = xev.xexpose.x;
974 r.y = xev.xexpose.y;
975 r.width = xev.xexpose.width;
976 r.height = xev.xexpose.height;
977
978 XUnionRectWithRegion (&r, region, region);
979 }
980 break;
981 default:
982#ifdef DEBUGMODE
983 fprintf (stderr, "PANIC! Unknown event %d\n", xev.type);
984#endif
985 break;
986 }
987 }
988
989 /* reload if requested */
990 if (reload && lastreload + reload < time (NULL))
991 {
992 if (command && command[0])
993 system (command);
994
995 reopen ();
996 lastreload = time (NULL);
997 }
998
999 if (!XEmptyRegion (region))
1000 {
1001 XRectangle r;
1002
1003 XSetRegion (disp, WinGC, region);
1004 XClipBox (region, &r);
1005
1006 refresh (r.y, r.y + r.height, 0, 1);
1007
1008 XDestroyRegion (region);
1009 region = XCreateRegion ();
1010 }
1011 }
1012}
1013
1014
1015int
1016main (int argc, char *argv[])
1017{
1018 int i;
1019 int opt_daemonize = 0;
1020 int opt_partial = 0, file_count = 0;
1021#if HAS_REGEX
1022 char *transform = NULL;
1023#endif
1024
1025 setlocale (LC_CTYPE, ""); /* try to initialize the locale. */
1026
1027 /* window needs to be initialized before colorlookups can be done */
1028 /* just a dummy to get the color lookups right */
1029 geom_mask = NoValue;
1030 InitWindow ();
1031
1032 for (i = 1; i < argc; i++)
1033 {
1034 const char *arg = argv[i];
1035
1036 if (arg[0] == '-' && arg[1] != '\0' && arg[1] != ',')
1037 {
1038 if (arg[1] == '-')
1039 arg++;
1040
1041 if (!strcmp (arg, "-?") ||
1042 !strcmp (arg, "-help") || !strcmp (arg, "-h"))
1043 display_help (argv[0]);
1044 else if (!strcmp (arg, "-V"))
1045 display_version ();
1046 else if (!strcmp (arg, "-g") || !strcmp (arg, "-geometry"))
1047 geom_mask =
1048 XParseGeometry (argv[++i], &win_x, &win_y, &width, &height);
1049 else if (!strcmp (arg, "-display"))
1050 dispname = argv[++i];
1051 else if (!strcmp (arg, "-cont"))
1052 continuation = argv[++i];
1053 else if (!strcmp (arg, "-font") || !strcmp (arg, "-fn"))
1054 fontname = argv[++i];
1055#if HAS_REGEX
1056 else if (!strcmp (arg, "-t"))
1057 {
1058 transform = argv[++i];
1059 transform_to = argv[++i];
1060 printf("transform: '%s' to '%s'\n", transform, transform_to);
1061 }
1062#endif
1063 else if (!strcmp (arg, "-fork") || !strcmp (arg, "-f"))
1064 opt_daemonize = 1;
1065 else if (!strcmp (arg, "-reload"))
1066 {
1067 reload = atoi (argv[++i]);
1068 command = argv[++i];
1069 }
1070 else if (!strcmp (arg, "-shade"))
1071 opt_shade = 1;
1072 else if (!strcmp (arg, "-outline"))
1073 opt_outline = 1;
1074 else if (!strcmp (arg, "-noflicker"))
1075 opt_noflicker = 1;
1076 else if (!strcmp (arg, "-frame"))
1077 opt_frame = 1;
1078 else if (!strcmp (arg, "-no-filename"))
1079 opt_nofilename = 1;
1080 else if (!strcmp (arg, "-reverse"))
1081 opt_reverse = 1;
1082 else if (!strcmp (arg, "-whole"))
1083 opt_whole = 1;
1084 else if (!strcmp (arg, "-partial"))
1085 opt_partial = 1;
1086 else if (!strcmp (arg, "-update"))
1087 opt_update = opt_partial = 1;
1088 else if (!strcmp (arg, "-wordwrap"))
1089 opt_wordwrap = 1;
1090 else if (!strcmp (arg, "-color"))
1091 def_color = argv[++i];
1092 else if (!strcmp (arg, "-noinitial"))
1093 opt_noinitial = 1;
1094 else if (!strcmp (arg, "-id"))
1095 root = atoi (argv[++i]);
1096 else if (!strcmp (arg, "-interval") || !strcmp (arg, "-i"))
1097 {
1098 double iv = atof (argv[++i]);
1099
1100 interval.tv_sec = (int) iv;
1101 interval.tv_usec = (iv - interval.tv_sec) * 1e6;
1102 }
1103 else
1104 {
1105 fprintf (stderr, "Unknown option '%s'.\n"
1106 "Try --help for more information.\n", arg);
1107 exit (1);
1108 }
1109 }
1110 else
1111 { /* it must be a filename */
1112 struct logfile_entry *e;
1113 const char *fname, *desc, *fcolor = def_color;
1114 char *p;
1115
1116 file_count++;
1117
1118 /* this is not foolproof yet (',' in filenames are not allowed) */
1119 fname = desc = arg;
1120 if ((p = strchr (arg, ',')))
1121 {
1122 *p = '\0';
1123 fcolor = p + 1;
1124
1125 if ((p = strchr (fcolor, ',')))
1126 {
1127 *p = '\0';
1128 desc = p + 1;
1129 }
1130 }
1131
1132 e = xmalloc (sizeof (struct logfile_entry));
1133 e->partial = 0;
1134 e->buf = 0;
1135 e->index = -1;
1136
1137 if (arg[0] == '-' && arg[1] == '\0')
1138 {
1139 if ((e->fp = fdopen (0, "r")) == NULL)
1140 perror ("fdopen"), exit (1);
1141 if (fcntl (0, F_SETFL, O_NONBLOCK) < 0)
1142 perror ("fcntl"), exit (1);
1143
1144 e->fname = NULL;
1145 e->inode = 0;
1146 e->desc = xstrdup ("stdin");
1147 }
1148 else
1149 {
1150 e->fname = xstrdup (fname);
1151
402 if (openlog(e) == NULL) 1152 if (openlog (e) == NULL)
403 break; 1153 perror (fname), exit (1);
1154
1155 e->desc = xstrdup (desc);
1156 }
1157
1158 e->color = GetColor (fcolor);
1159 e->partial = 0;
1160 e->next = NULL;
1161
1162 if (!loglist)
1163 loglist = e;
1164 if (loglist_tail)
1165 loglist_tail->next = e;
1166
1167 loglist_tail = e;
1168 }
1169 }
1170
1171 if (!loglist)
1172 {
1173 fprintf (stderr, "You did not specify any files to tail\n"
1174 "use %s --help for help\n", argv[0]);
1175 exit (1);
1176 }
1177
1178 if (opt_update && opt_whole)
1179 {
1180 fprintf (stderr, "Specify at most one of -update and -whole\n");
1181 exit (1);
1182 }
1183 else if (opt_partial && opt_whole)
1184 {
1185 fprintf (stderr, "Specify at most one of -partial and -whole\n");
1186 exit (1);
1187 }
1188
1189 /* HACK-7: do we want to allow both -shade and -outline? */
1190 if (opt_shade && opt_outline)
1191 {
1192 fprintf (stderr, "Specify at most one of -shade and -outline\n");
1193 exit (1);
1194 }
1195
1196 if (opt_partial)
1197 /* if we specifically requested to see partial lines then don't insist on whole lines */
1198 opt_whole = 0;
1199 else if (file_count > 1)
1200 /* otherwise, if we're viewing multiple files, default to showing whole lines */
1201 opt_whole = 1;
1202
1203#if HAS_REGEX
1204 if (transform)
1205 {
1206 int i;
1207
1208 printf("compiling regexp '%s'\n", transform);
1209 transformre = xmalloc (sizeof (regex_t));
1210 i = regcomp (transformre, transform, REG_EXTENDED);
1211 if (i != 0)
1212 {
1213 char buf[512];
1214
1215 regerror (i, transformre, buf, sizeof (buf));
1216 fprintf (stderr, "Cannot compile regular expression: %s\n", buf);
1217 }
1218 else
1219 {
1220 printf("compiled '%s' OK to %x\n", transform, (int)transformre);
404 } 1221 }
405
406 if (stats.st_size < e->last_size) { /* file truncated? */
407 fseek(e->fp, 0, SEEK_SET);
408 e->last_size = stats.st_size;
409 }
410 }
411}
412
413#define SCROLL_UP(lines, listlen) \
414{ \
415 int cur_line; \
416 for (cur_line = 0; cur_line < (listlen - 1); cur_line++) { \
417 strcpy(lines[cur_line].line, lines[cur_line + 1].line); \
418 lines[cur_line].color = lines[cur_line + 1].color; \
419 } \
420}
421
422void main_loop(void)
423{
424 struct linematrix *lines = xmalloc(sizeof(struct linematrix) * listlen);
425 int lin, miny, maxy, buflen;
426 char *buf;
427 time_t lastreload;
428 Region region = XCreateRegion();
429 XEvent xev;
430
431 maxy = 0;
432 miny = win_y + h;
433 buflen = width + 2;
434 buf = xmalloc(buflen);
435 lastreload = time(NULL);
436
437 /* Initialize linematrix */
438 for (lin = 0; lin < listlen; lin++) {
439 lines[lin].line = xmalloc(buflen);
440 strcpy(lines[lin].line, "~");
441 lines[lin].color = GetColor(def_color);
442 }
443
444 if (!opt_noinitial)
445 while (lineinput(buf, buflen, loglist->fp) != 0) {
446 SCROLL_UP(lines, listlen);
447 /* print the next line */
448 strcpy(lines[listlen - 1].line, buf);
449 }
450
451 for (;;) {
452 int need_update = 0;
453 struct logfile_entry *current;
454 static struct logfile_entry *lastprinted = NULL;
455
456 /* read logs */
457 for (current = loglist; current; current = current->next) {
458 if (!current->fp)
459 continue; /* skip missing files */
460
461 clearerr(current->fp);
462
463 while (lineinput(buf, buflen, current->fp) != 0) {
464 /* print filename if any, and if last line was from
465 different file */
466 if (!opt_nofilename &&
467 !(lastprinted && lastprinted == current) &&
468 current->desc[0]) {
469 SCROLL_UP(lines, listlen);
470 sprintf(lines[listlen - 1].line, "[%s]", current->desc);
471 lines[listlen - 1].color = current->color;
472 }
473
474 SCROLL_UP(lines, listlen);
475 strcpy(lines[listlen - 1].line, buf);
476 lines[listlen - 1].color = current->color;
477
478 lastprinted = current;
479 need_update = 1;
480 } 1222 }
481 }
482
483 if (need_update)
484 redraw();
485 else {
486 XFlush(disp);
487 if (!XPending(disp)) {
488 fd_set fdr;
489 struct timeval to = interval;
490
491 FD_ZERO(&fdr);
492 FD_SET(ConnectionNumber(disp), &fdr);
493 select(ConnectionNumber(disp) + 1, &fdr, 0, 0, &to);
494 }
495 }
496
497 check_open_files();
498
499 if (do_reopen)
500 reopen();
501
502 /* we ignore possible errors due to window resizing &c */
503 while (XPending(disp)) {
504 XNextEvent(disp, &xev);
505 switch (xev.type) {
506 case Expose:
507 {
508 XRectangle r;
509
510 r.x = xev.xexpose.x;
511 r.y = xev.xexpose.y;
512 r.width = xev.xexpose.width;
513 r.height = xev.xexpose.height;
514 XUnionRectWithRegion(&r, region, region);
515 if (miny > r.y)
516 miny = r.y;
517 if (maxy < r.y + r.height)
518 maxy = r.y + r.height;
519 }
520 break;
521 default:
522#ifdef DEBUGMODE
523 fprintf(stderr, "PANIC! Unknown event %d\n", xev.type);
524#endif 1223#endif
525 break;
526 }
527 }
528 1224
529 /* reload if requested */
530 if (reload && lastreload + reload < time(NULL)) {
531 if (command)
532 system(command);
533
534 reopen();
535 lastreload = time(NULL);
536 }
537
538 if (!XEmptyRegion(region)) {
539 XSetRegion(disp, WinGC, region);
540 refresh(lines, miny, maxy);
541 XDestroyRegion(region);
542 region = XCreateRegion();
543 maxy = 0;
544 miny = win_y + h;
545 }
546 }
547}
548
549
550int main(int argc, char *argv[])
551{
552 int i;
553 int opt_daemonize = 0;
554#if HAS_REGEX
555 char *transform = NULL;
556#endif
557
558 /* window needs to be initialized before colorlookups can be done */
559 /* just a dummy to get the color lookups right */
560 geom_mask = NoValue;
561 InitWindow(); 1225 InitWindow ();
562 1226
563 for (i = 1; i < argc; i++) {
564 if (argv[i][0] == '-' && argv[i][1] != '\0' && argv[i][1] != ',') {
565 if (!strcmp(argv[i], "--?") ||
566 !strcmp(argv[i], "--help") || !strcmp(argv[i], "-h"))
567 display_help(argv[0]);
568 else if (!strcmp(argv[i], "-V"))
569 display_version();
570 else if (!strcmp(argv[i], "-g") || !strcmp(argv[i], "-geometry"))
571 geom_mask = XParseGeometry(argv[++i],
572 &win_x, &win_y, &width, &listlen);
573 else if (!strcmp(argv[i], "-display"))
574 dispname = argv[++i];
575 else if (!strcmp(argv[i], "-font") || !strcmp(argv[i], "-fn"))
576 fontname = argv[++i];
577#if HAS_REGEX
578 else if (!strcmp(argv[i], "-t"))
579 transform = argv[++i];
580#endif
581 else if (!strcmp(argv[i], "-fork") || !strcmp(argv[i], "-f"))
582 opt_daemonize = 1;
583 else if (!strcmp(argv[i], "-reload")) {
584 reload = atoi(argv[++i]);
585 command = argv[++i];
586 }
587 else if (!strcmp(argv[i], "-shade"))
588 opt_shade = 1;
589 else if (!strcmp(argv[i], "-frame"))
590 opt_frame = 1;
591 else if (!strcmp(argv[i], "-no-filename"))
592 opt_nofilename = 1;
593 else if (!strcmp(argv[i], "-reverse"))
594 opt_reverse = 1;
595 else if (!strcmp(argv[i], "-color"))
596 def_color = argv[++i];
597 else if (!strcmp(argv[i], "-noinitial"))
598 opt_noinitial = 1;
599 else if (!strcmp(argv[i], "-interval") || !strcmp(argv[i], "-i")) {
600 double iv = atof(argv[++i]);
601
602 interval.tv_sec = (int) iv;
603 interval.tv_usec = (iv - interval.tv_sec) * 1e6;
604 } else {
605 fprintf(stderr, "Unknown option '%s'.\n"
606 "Try --help for more information.\n", argv[i]);
607 exit(1);
608 }
609 } else { /* it must be a filename */
610 struct logfile_entry *e;
611 const char *fname, *desc, *fcolor = def_color;
612 char *p;
613
614 /* this is not foolproof yet (',' in filenames are not allowed) */
615 fname = desc = argv[i];
616 if ((p = strchr(argv[i], ','))) {
617 *p = '\0';
618 fcolor = p + 1;
619
620 if ((p = strchr(fcolor, ','))) {
621 *p = '\0';
622 desc = p + 1;
623 }
624 }
625
626 e = xmalloc(sizeof(struct logfile_entry));
627 if (argv[i][0] == '-' && argv[i][1] == '\0') {
628 if ((e->fp = fdopen(0, "r")) == NULL)
629 perror("fdopen"), exit(1);
630 if (fcntl(0, F_SETFL, O_NONBLOCK) < 0)
631 perror("fcntl"), exit(1);
632 e->fname = NULL;
633 e->inode = 0;
634 e->desc = xstrdup("stdin");
635 } else {
636 int l;
637
638 e->fname = xstrdup(fname);
639 if (openlog(e) == NULL)
640 perror(fname), exit(1);
641
642 l = strlen(desc);
643 if (l > width - 2) /* must account for [ ] */
644 l = width - 2;
645 e->desc = xmalloc(l + 1);
646 memcpy(e->desc, desc, l);
647 *(e->desc + l) = '\0';
648 }
649
650 e->color = GetColor(fcolor);
651 e->next = NULL;
652
653 if (!loglist)
654 loglist = e;
655 if (loglist_tail)
656 loglist_tail->next = e;
657 loglist_tail = e;
658 }
659 }
660
661 if (!loglist) {
662 fprintf(stderr, "You did not specify any files to tail\n"
663 "use %s --help for help\n", argv[0]);
664 exit(1);
665 }
666
667#if HAS_REGEX
668 if (transform) {
669 int i;
670
671 transformre = xmalloc(sizeof(transformre));
672 i = regcomp(&transformre, transform, REG_EXTENDED);
673 if (i != 0) {
674 char buf[512];
675
676 regerror(i, &transformre, buf, sizeof(buf));
677 fprintf(stderr, "Cannot compile regular expression: %s\n", buf);
678 }
679 }
680#endif
681
682 InitWindow();
683
684 install_signal(SIGINT, blank_window); 1227 install_signal (SIGINT, blank_window);
685 install_signal(SIGQUIT, blank_window); 1228 install_signal (SIGQUIT, blank_window);
686 install_signal(SIGTERM, blank_window); 1229 install_signal (SIGTERM, blank_window);
687 install_signal(SIGHUP, force_reopen); 1230 install_signal (SIGHUP, force_reopen);
688 install_signal(SIGUSR1, list_files); 1231 install_signal (SIGUSR1, list_files);
689 install_signal(SIGUSR2, force_refresh); 1232 install_signal (SIGUSR2, force_refresh);
690 1233
691 if (opt_daemonize) 1234 if (opt_daemonize)
692 daemonize(); 1235 daemonize ();
693 1236
694 main_loop(); 1237 main_loop ();
695 1238
696 exit(1); /* to make gcc -Wall stop complaining */ 1239 exit (1); /* to make gcc -Wall stop complaining */
697} 1240}
698 1241
1242void
699void install_signal(int sig, void (*handler)(int)) 1243install_signal (int sig, void (*handler) (int))
700{ 1244{
701 struct sigaction action; 1245 struct sigaction action;
702 1246
703 action.sa_handler = handler; 1247 action.sa_handler = handler;
704 sigemptyset(&action.sa_mask); 1248 sigemptyset (&action.sa_mask);
705 action.sa_flags = SA_RESTART; 1249 action.sa_flags = SA_RESTART;
1250
706 if (sigaction(sig, &action, NULL) < 0) 1251 if (sigaction (sig, &action, NULL) < 0)
707 fprintf(stderr, "sigaction(%d): %s\n", sig, strerror(errno)), exit(1); 1252 fprintf (stderr, "sigaction(%d): %s\n", sig, strerror (errno)), exit (1);
708} 1253}
709 1254
1255void *
710void *xstrdup(const char *string) 1256xstrdup (const char *string)
711{ 1257{
712 void *p; 1258 void *p;
713 1259
714 while ((p = strdup(string)) == NULL) { 1260 while ((p = strdup (string)) == NULL)
1261 {
715 fprintf(stderr, "Memory exausted."); 1262 fprintf (stderr, "Memory exausted.");
716 sleep(10); 1263 sleep (10);
717 } 1264 }
1265
718 return p; 1266 return p;
719} 1267}
720 1268
1269void *
721void *xmalloc(size_t size) 1270xmalloc (size_t size)
722{ 1271{
723 void *p; 1272 void *p;
724 1273
725 while ((p = malloc(size)) == NULL) { 1274 while ((p = malloc (size)) == NULL)
1275 {
726 fprintf(stderr, "Memory exausted."); 1276 fprintf (stderr, "Memory exausted.");
727 sleep(10); 1277 sleep (10);
728 } 1278 }
1279
729 return p; 1280 return p;
730} 1281}
731 1282
1283void *
1284xrealloc (void *ptr, size_t size)
1285{
1286 void *p;
1287
1288 while ((p = realloc (ptr, size)) == NULL)
1289 {
1290 fprintf (stderr, "Memory exausted.");
1291 sleep (10);
1292 }
1293
1294 return p;
1295}
1296
1297void
732void display_help(char *myname) 1298display_help (char *myname)
733{ 1299{
734 printf("Usage: %s [options] file1[,color[,desc]] " 1300 printf ("Usage: %s [options] file1[,color[,desc]] "
735 "[file2[,color[,desc]] ...]\n", myname); 1301 "[file2[,color[,desc]] ...]\n", myname);
736 printf(" -g | -geometry geometry -g WIDTHxHEIGHT+X+Y\n" 1302 printf (" -g | -geometry geometry -g WIDTHxHEIGHT+X+Y\n"
737 " -color color use color $color as default\n" 1303 " -color color use color $color as default\n"
738 " -reload sec command reload after $sec and run command\n" 1304 " -reload sec command reload after $sec and run command\n"
739 " by default -- 3 mins\n" 1305 " -id id window id to use instead of the root window\n"
740 " -font FONTSPEC (-fn) font to use\n" 1306 " -font FONTSPEC (-fn) font to use\n"
741 " -f | -fork fork into background\n" 1307 " -f | -fork fork into background\n"
742 " -reverse print new lines at the top\n" 1308 " -reverse print new lines at the top\n"
1309 " -whole wait for \\n before showing a line\n"
1310 " -partial show lines even if they don't end with a \\n\n"
1311 " -update allow updates to old partial lines\n"
1312 " -cont string to prefix continued partial lines with\n"
1313 " -wordwrap wrap long lines at spaces to avoid breaking words\n"
1314 " defaults to \"[+]\"\n"
743 " -shade add shading to font\n" 1315 " -shade add shading to font\n"
744 " -noinitial don't display the last file lines on\n" 1316 " -noinitial don't display the last file lines on\n"
745 " startup\n" 1317 " startup\n"
746 " -i | -interval seconds interval between checks (fractional\n" 1318 " -i | -interval seconds interval between checks (fractional\n"
747 " values o.k.). Default 3\n" 1319 " values o.k.). Default 2.4 seconds\n"
748 " -V display version information and exit\n" 1320 " -V display version information and exit\n"
749 "\n"); 1321 "\n");
750 printf("Example:\n%s -g 80x25+100+50 -font fixed /var/log/messages,green " 1322 printf ("Example:\n%s -g 80x25+100+50 -font fixed /var/log/messages,green "
751 "/var/log/secure,red,'ALERT'\n", myname); 1323 "/var/log/secure,red,'ALERT'\n", myname);
752 exit(0); 1324 exit (0);
753} 1325}
754 1326
1327void
755void display_version(void) { 1328display_version (void)
1329{
756 printf("root-tail version " VERSION "\n"); 1330 printf ("root-tail version " VERSION "\n");
757 exit(0); 1331 exit (0);
758} 1332}
759 1333
1334int
760int daemonize(void) { 1335daemonize (void)
1336{
1337 pid_t pid;
1338
761 switch (fork()) { 1339 switch (pid = fork ())
1340 {
762 case -1: 1341 case -1:
763 return -1; 1342 return -1;
764 case 0: 1343 case 0:
765 break; 1344 break;
766 default: 1345 default:
767 _exit(0); 1346 /*printf("%d\n", pid);*/
1347 exit (0);
768 } 1348 }
769 1349
770 if (setsid() == -1) 1350 if (setsid () == -1)
771 return -1; 1351 return -1;
772 1352
773 return 0; 1353 return 0;
774} 1354}
775

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines