Fix compiler warnings (missing #includes etc) thrown up by RedHat.
[sgt/tweak] / main.c
1 /*
2 * TODO before releasable quality:
3 *
4 * - Thorough testing.
5 *
6 * - Half decent build system.
7 *
8 * TODO possibly after that:
9 *
10 * - Need to handle >2Gb files! Up the `filesize' type to long
11 * long and use it everywhere.
12 *
13 * - Multiple buffers, multiple on-screen windows.
14 * + ^X^F to open new file
15 * + ^X^R to open new file RO
16 * + ^X b to switch buffers in a window
17 * + ^X o to switch windows
18 * + ^X 2 to split a window
19 * + ^X 1 to destroy all windows but this
20 * + ^X 0 to destroy this window
21 * + ^X ^ to enlarge this window by one line
22 * + width settings vary per buffer (aha, _that's_ why I wanted
23 * a buffer structure surrounding the raw B-tree)
24 * + hex-editor-style minibuffer for entering search terms,
25 * rather than the current rather crap one; in particular
26 * this enables pasting into the search string.
27 * + er, how exactly do we deal with the problem of saving over
28 * a file which we're maintaining references to?
29 *
30 * - Undo!
31 * + this actually doesn't seem _too_ horrid. For a start, one
32 * simple approach would be to clone the entire buffer B-tree
33 * every time we perform an operation! That's actually not
34 * _too_ expensive, if we maintain a limit on the number of
35 * operations we may undo.
36 * + I had also thought of cloning the tree we insert for each
37 * buf_insert_data and cloning the one removed for each
38 * buf_delete_data (both must be cloned for an overwrite),
39 * but I'm not convinced that simply cloning the entire thing
40 * isn't a superior option.
41 *
42 * - Reverse search.
43 * + need to construct a reverse DFA.
44 * + probably should construct both every time, so that you can
45 * search forward for a thing and then immediately change
46 * your mind and search backward for the same thing.
47 *
48 * - In-place editing.
49 * + this is an extra option when running in Fix mode. It
50 * causes a change of semantics when saving: instead of
51 * constructing a new backup file and writing it over the old
52 * one, we simply seek within the original file and write out
53 * all the pieces that have changed.
54 * + Primarily useful for editing disk devices directly
55 * (yikes!).
56 * + I had intended to suggest that in Fix mode this would be
57 * nice and easy, since every element of the buffer tree is
58 * either a literal block (needs writing) or a from-file
59 * block denoting the same file _in the same position_.
60 * However, this is not in fact the case because you can cut
61 * and paste, so it's not that easy.
62 * + So I'm forced to the conclusion that when operating in
63 * this mode, it becomes illegal to cut and paste from-file
64 * blocks: they must be loaded in full at some point.
65 * * Thinking ahead about multiple-buffer operation: it
66 * would be a bad idea to keep a from-file block
67 * referencing /dev/hda and paste it into another ordinary
68 * buffer. But _also_ it would be a bad idea to paste a
69 * from-file block referencing a file stored _on_ /dev/hda
70 * into the in-place buffer dealing with /dev/hda itself.
71 * * So I'm forced to another odd conclusion, which is that
72 * from-file blocks must be eliminated in _two_ places:
73 * when copying a cut buffer _from_ an in-place buffer,
74 * _and_ when pasting a cut buffer _into_ one.
75 */
76
77 #include <stdio.h>
78 #include <stdlib.h>
79 #include <string.h>
80 #include <ctype.h>
81 #include <assert.h>
82
83 #if defined(unix) && !defined(GO32)
84 #include <signal.h>
85 #include <sys/ioctl.h>
86 #include <termios.h>
87 #elif defined(MSDOS)
88 #include <dos.h>
89 #include <process.h>
90 #endif
91
92 #include "tweak.h"
93
94 static void init(void);
95 static void done(void);
96 static void load_file (char *);
97
98 char toprint[256]; /* LUT: printable versions of chars */
99 char hex[256][3]; /* LUT: binary to hex, 1 byte */
100
101 char message[80];
102
103 char decstatus[] = "%s TWEAK "VER": %-18.18s %s posn=%-10d size=%-10d";
104 char hexstatus[] = "%s TWEAK "VER": %-18.18s %s posn=0x%-8X size=0x%-8X";
105 char *statfmt = hexstatus;
106
107 char last_char;
108 char *pname;
109 char *filename = NULL;
110 buffer *filedata, *cutbuffer = NULL;
111 int fix_mode = FALSE;
112 int look_mode = FALSE;
113 int eager_mode = FALSE;
114 int insert_mode = FALSE;
115 int edit_type = 1; /* 1,2 are hex digits, 0=ascii */
116 int finished = FALSE;
117 int marking = FALSE;
118 int modified = FALSE;
119 int new_file = FALSE; /* shouldn't need initialisation -
120 * but let's not take chances :-) */
121 int width = 16;
122 int realoffset = 0, offset = 16;
123
124 int ascii_enabled = TRUE;
125
126 long file_size = 0, top_pos = 0, cur_pos = 0, mark_point = 0;
127
128 int scrlines;
129
130 /*
131 * Main program
132 */
133 int main(int argc, char **argv) {
134 int newoffset = -1, newwidth = -1;
135
136 /*
137 * Parse command line arguments
138 */
139 pname = *argv; /* program name */
140 if (argc < 2) {
141 fprintf(stderr,
142 "usage: %s [-f] [-l] [-e] filename\n"
143 " or %s -D to write default tweak.rc to stdout\n",
144 pname, pname);
145 return 0;
146 }
147
148 while (--argc > 0) {
149 char c, *p = *++argv, *value;
150
151 if (*p == '-') {
152 p++;
153 while (*p) switch (c = *p++) {
154 case 'o': case 'O':
155 case 'w': case 'W':
156 /*
157 * these parameters require arguments
158 */
159 if (*p)
160 value = p, p = "";
161 else if (--argc)
162 value = *++argv;
163 else {
164 fprintf(stderr, "%s: option `-%c' requires an argument\n",
165 pname, c);
166 return 1;
167 }
168 switch (c) {
169 case 'o': case 'O':
170 newoffset = strtol(value, NULL, 0); /* allow `0xXX' */
171 break;
172 case 'w': case 'W':
173 newwidth = strtol(value, NULL, 0);
174 break;
175 }
176 break;
177 case 'f': case 'F':
178 fix_mode = TRUE;
179 break;
180 case 'l': case 'L':
181 look_mode = TRUE;
182 break;
183 case 'e': case 'E':
184 eager_mode = TRUE;
185 break;
186 case 'D':
187 write_default_rc();
188 return 0;
189 break;
190 }
191 } else {
192 if (filename) {
193 fprintf(stderr, "%s: multiple filenames specified\n", pname);
194 return 1;
195 }
196 filename = p;
197 }
198 }
199
200 if (!filename) {
201 fprintf(stderr, "%s: no filename specified\n", pname);
202 return 1;
203 }
204
205 read_rc();
206 if (newoffset != -1)
207 realoffset = newoffset;
208 if (newwidth != -1)
209 width = newwidth;
210 load_file (filename);
211 init();
212 fix_offset();
213 do {
214 draw_scr ();
215 proc_key ();
216 } while (!finished);
217 done();
218
219 return 0;
220 }
221
222 /*
223 * Fix up `offset' to match `realoffset'. Also, while we're here,
224 * enable or disable ASCII mode and sanity-check the width.
225 */
226 void fix_offset(void) {
227 if (3*width+11 > display_cols) {
228 width = (display_cols-11) / 3;
229 sprintf (message, "Width reduced to %d to fit on the screen", width);
230 }
231 if (4*width+14 > display_cols) {
232 ascii_enabled = FALSE;
233 if (edit_type == 0)
234 edit_type = 1; /* force to hex mode */
235 } else
236 ascii_enabled = TRUE;
237 offset = realoffset % width;
238 if (!offset)
239 offset = width;
240 }
241
242 /*
243 * Initialise stuff at the beginning of the program: mostly the
244 * display.
245 */
246 static void init(void) {
247 int i;
248
249 display_setup();
250
251 display_define_colour(COL_BUFFER, 7, 0);
252 display_define_colour(COL_SELECT, 0, 7);
253 display_define_colour(COL_STATUS, 11, 4);
254 display_define_colour(COL_ESCAPE, 9, 0);
255 display_define_colour(COL_INVALID, 11, 0);
256
257 for (i=0; i<256; i++) {
258 sprintf(hex[i], "%02X", i);
259 toprint[i] = (i>=32 && i<127 ? i : '.');
260 }
261 }
262
263 /*
264 * Clean up all the stuff that init() did.
265 */
266 static void done(void) {
267 display_cleanup();
268 }
269
270 /*
271 * Load the file specified on the command line.
272 */
273 static void load_file (char *fname) {
274 FILE *fp;
275
276 file_size = 0;
277 if ( (fp = fopen (fname, "rb")) ) {
278 if (eager_mode) {
279 long len;
280 static char buffer[4096];
281
282 filedata = buf_new_empty();
283
284 file_size = 0;
285
286 /*
287 * We've opened the file. Load it.
288 */
289 while ( (len = fread (buffer, 1, sizeof(buffer), fp)) > 0 ) {
290 buf_insert_data (filedata, buffer, len, file_size);
291 file_size += len;
292 }
293 fclose (fp);
294 assert(file_size == buf_length(filedata));
295 sprintf(message, "loaded %s (size %ld == 0x%lX).",
296 fname, file_size, file_size);
297 } else {
298 filedata = buf_new_from_file(fp);
299 file_size = buf_length(filedata);
300 sprintf(message, "opened %s (size %ld == 0x%lX).",
301 fname, file_size, file_size);
302 }
303 new_file = FALSE;
304 } else {
305 if (look_mode || fix_mode) {
306 fprintf(stderr, "%s: file %s not found, and %s mode active\n",
307 pname, fname, (look_mode ? "LOOK" : "FIX"));
308 exit (1);
309 }
310 filedata = buf_new_empty();
311 sprintf(message, "New file %s.", fname);
312 new_file = TRUE;
313 }
314 }
315
316 /*
317 * Save the file. Return TRUE on success, FALSE on error.
318 */
319 int save_file (void) {
320 FILE *fp;
321 long pos = 0;
322
323 if (look_mode)
324 return FALSE; /* do nothing! */
325
326 if ( (fp = fopen (filename, "wb")) ) {
327 static char buffer[SAVE_BLKSIZ];
328
329 while (pos < file_size) {
330 long size = file_size - pos;
331 if (size > SAVE_BLKSIZ)
332 size = SAVE_BLKSIZ;
333
334 buf_fetch_data (filedata, buffer, size, pos);
335 if (size != fwrite (buffer, 1, size, fp)) {
336 fclose (fp);
337 return FALSE;
338 }
339 pos += size;
340 }
341 } else
342 return FALSE;
343 fclose (fp);
344 return TRUE;
345 }
346
347 /*
348 * Make a backup of the file, if such has not already been done.
349 * Return TRUE on success, FALSE on error.
350 */
351 int backup_file (void) {
352 char backup_name[FILENAME_MAX];
353
354 if (new_file)
355 return TRUE; /* unnecessary - pretend it's done */
356 strcpy (backup_name, filename);
357 #if defined(unix) && !defined(GO32)
358 strcat (backup_name, ".bak");
359 #elif defined(MSDOS)
360 {
361 char *p, *q;
362
363 q = NULL;
364 for (p = backup_name; *p; p++) {
365 if (*p == '\\')
366 q = NULL;
367 else if (*p == '.')
368 q = p;
369 }
370 if (!q)
371 q = p;
372 strcpy (q, ".BAK");
373 }
374 #endif
375 remove (backup_name); /* don't care if this fails */
376 return !rename (filename, backup_name);
377 }
378
379 static unsigned char *scrbuf = NULL;
380 static int scrbuflines = 0;
381
382 /*
383 * Draw the screen, for normal usage.
384 */
385 void draw_scr (void) {
386 int scrsize, scroff, llen, i, j;
387 long currpos;
388 int marktop, markbot, mark;
389 char *p;
390 unsigned char c, *q;
391 char *linebuf;
392
393 scrlines = display_rows - 2;
394 if (scrlines > scrbuflines) {
395 scrbuf = (scrbuf ?
396 realloc(scrbuf, scrlines*width) :
397 malloc(scrlines*width));
398 if (!scrbuf) {
399 done();
400 fprintf(stderr, "%s: out of memory!\n", pname);
401 exit (2);
402 }
403 scrbuflines = scrlines;
404 }
405
406 linebuf = malloc(width*4+20);
407 if (!linebuf) {
408 done();
409 fprintf(stderr, "%s: out of memory!\n", pname);
410 exit (2);
411 }
412 memset (linebuf, ' ', width*4+13);
413 linebuf[width*4+13] = '\0';
414
415 if (top_pos == 0)
416 scroff = width - offset;
417 else
418 scroff = 0;
419 scrsize = scrlines * width - scroff;
420 if (scrsize > file_size - top_pos)
421 scrsize = file_size - top_pos;
422
423 buf_fetch_data (filedata, scrbuf, scrsize, top_pos);
424
425 scrsize += scroff; /* hack but it'll work */
426
427 mark = marking && (cur_pos != mark_point);
428 if (mark) {
429 if (cur_pos > mark_point)
430 marktop = mark_point, markbot = cur_pos;
431 else
432 marktop = cur_pos, markbot = mark_point;
433 } else
434 marktop = markbot = 0; /* placate gcc */
435
436 currpos = top_pos;
437 q = scrbuf;
438
439 for (i=0; i<scrlines; i++) {
440 display_moveto (i, 0);
441 if (currpos<=cur_pos || currpos<file_size) {
442 p = hex[(currpos >> 24) & 0xFF];
443 linebuf[0]=p[0];
444 linebuf[1]=p[1];
445 p = hex[(currpos >> 16) & 0xFF];
446 linebuf[2]=p[0];
447 linebuf[3]=p[1];
448 p = hex[(currpos >> 8) & 0xFF];
449 linebuf[4]=p[0];
450 linebuf[5]=p[1];
451 p = hex[currpos & 0xFF];
452 linebuf[6]=p[0];
453 linebuf[7]=p[1];
454 for (j=0; j<width; j++) {
455 if (scrsize > 0) {
456 if (currpos == 0 && j < width-offset)
457 p = " ", c = ' ';
458 else
459 p = hex[*q], c = *q++;
460 scrsize--;
461 } else {
462 p = " ", c = ' ';
463 }
464 linebuf[11+3*j]=p[0];
465 linebuf[12+3*j]=p[1];
466 linebuf[13+3*width+j]=toprint[c];
467 }
468 llen = (currpos ? width : offset);
469 if (mark && currpos<markbot && currpos+llen>marktop) {
470 /*
471 * Some of this line is marked. Maybe all. Whatever
472 * the precise details, there will be two regions
473 * requiring highlighting: a hex bit and an ascii
474 * bit.
475 */
476 int localstart= (currpos<marktop?marktop:currpos) - currpos;
477 int localstop = (currpos+llen>markbot ? markbot :
478 currpos+llen) - currpos;
479 localstart += width-llen;
480 localstop += width-llen;
481 display_write_chars(linebuf, 11+3*localstart);
482 display_set_colour(COL_SELECT);
483 display_write_chars(linebuf+11+3*localstart,
484 3*(localstop-localstart)-1);
485 display_set_colour(COL_BUFFER);
486 if (ascii_enabled) {
487 display_write_chars(linebuf+10+3*localstop,
488 3+3*width+localstart-3*localstop);
489 display_set_colour(COL_SELECT);
490 display_write_chars(linebuf+13+3*width+localstart,
491 localstop-localstart);
492 display_set_colour(COL_BUFFER);
493 display_write_chars(linebuf+13+3*width+localstop,
494 width-localstop);
495 } else {
496 display_write_chars(linebuf+10+3*localstop,
497 2+3*width-3*localstop);
498 }
499 } else
500 display_write_chars(linebuf,
501 ascii_enabled ? 13+4*width : 10+3*width);
502 }
503 currpos += (currpos ? width : offset);
504 display_clear_to_eol();
505 }
506
507 {
508 char status[80];
509 int slen;
510 display_moveto (display_rows-2, 0);
511 display_set_colour(COL_STATUS);
512 sprintf(status, statfmt,
513 (modified ? "**" : " "),
514 filename,
515 (insert_mode ? "(Insert)" :
516 look_mode ? "(LOOK) " :
517 fix_mode ? "(FIX) " : "(Ovrwrt)"),
518 cur_pos, file_size);
519 slen = strlen(status);
520 if (slen > display_cols)
521 slen = display_cols;
522 display_write_chars(status, slen);
523 while (slen++ < display_cols)
524 display_write_str(" ");
525 display_set_colour(COL_BUFFER);
526 }
527
528 display_moveto (display_rows-1, 0);
529 display_write_str (message);
530 display_clear_to_eol();
531 message[0] = '\0';
532
533 i = cur_pos - top_pos;
534 if (top_pos == 0)
535 i += width - offset;
536 j = (edit_type ? (i%width)*3+10+edit_type : (i%width)+13+3*width);
537 if (j >= display_cols)
538 j = display_cols-1;
539 free (linebuf);
540 display_moveto (i/width, j);
541 display_refresh ();
542 }
543
544 /*
545 * Get a string, in the "minibuffer". Return TRUE on success, FALSE
546 * on break. Possibly syntax-highlight the entered string for
547 * backslash-escapes, depending on the "highlight" parameter.
548 */
549 int get_str (char *prompt, char *buf, int highlight) {
550 int maxlen = 79 - strlen(prompt); /* limit to 80 - who cares? :) */
551 int len = 0;
552 int c;
553
554 for (EVER) {
555 display_moveto (display_rows-1, 0);
556 display_set_colour (COL_MINIBUF);
557 display_write_str (prompt);
558 if (highlight) {
559 char *q, *p = buf, *r = buf+len;
560 while (p<r) {
561 q = p;
562 if (*p == '\\') {
563 p++;
564 if (p<r && *p == '\\')
565 p++, display_set_colour(COL_ESCAPE);
566 else if (p>=r || !isxdigit (*p))
567 display_set_colour(COL_INVALID);
568 else if (p+1>=r || !isxdigit (p[1]))
569 p++, display_set_colour(COL_INVALID);
570 else
571 p+=2, display_set_colour(COL_ESCAPE);
572 } else {
573 while (p<r && *p != '\\')
574 p++;
575 display_set_colour (COL_MINIBUF);
576 }
577 display_write_chars (q, p-q);
578 }
579 } else
580 display_write_chars (buf, len);
581 display_set_colour (COL_MINIBUF);
582 display_clear_to_eol();
583 display_refresh();
584 if (update_required)
585 update();
586 safe_update = TRUE;
587 c = display_getkey();
588 safe_update = FALSE;
589 if (c == 13 || c == 10) {
590 buf[len] = '\0';
591 return TRUE;
592 } else if (c == 27 || c == 7) {
593 display_beep();
594 display_post_error();
595 strcpy (message, "User Break!");
596 return FALSE;
597 }
598
599 if (c >= 32 && c <= 126) {
600 if (len < maxlen)
601 buf[len++] = c;
602 else
603 display_beep();
604 }
605
606 if ((c == 127 || c == 8) && len > 0)
607 len--;
608
609 if (c == 'U'-'@') /* ^U kill line */
610 len = 0;
611 }
612 }
613
614 /*
615 * Take a buffer containing possible backslash-escapes, and return
616 * a buffer containing a (binary!) string. Since the string is
617 * binary, it cannot be null terminated: hence the length is
618 * returned from the function. The string is processed in place.
619 *
620 * Escapes are simple: a backslash followed by two hex digits
621 * represents that character; a doubled backslash represents a
622 * backslash itself; a backslash followed by anything else is
623 * invalid. (-1 is returned if an invalid sequence is detected.)
624 */
625 int parse_quoted (char *buffer) {
626 char *p, *q;
627
628 p = q = buffer;
629 while (*p) {
630 while (*p && *p != '\\')
631 *q++ = *p++;
632 if (*p == '\\') {
633 p++;
634 if (*p == '\\')
635 *q++ = *p++;
636 else if (p[1] && isxdigit(*p) && isxdigit(p[1])) {
637 char buf[3];
638 buf[0] = *p++;
639 buf[1] = *p++;
640 buf[2] = '\0';
641 *q++ = strtol(buf, NULL, 16);
642 } else
643 return -1;
644 }
645 }
646 return q - buffer;
647 }
648
649 /*
650 * Suspend program. (Or shell out, depending on OS, of course.)
651 */
652 void suspend(void) {
653 #if defined(unix) && !defined(GO32)
654 done();
655 raise (SIGTSTP);
656 init();
657 #elif defined(MSDOS)
658 done();
659 spawnl (P_WAIT, getenv("COMSPEC"), "", NULL);
660 init();
661 #else
662 display_beep();
663 strcpy(message, "Suspend function not yet implemented.");
664 #endif
665 }
666
667 volatile int safe_update, update_required;
668
669 void update (void) {
670 display_recheck_size();
671 fix_offset ();
672 draw_scr ();
673 }
674
675 void schedule_update(void) {
676 if (safe_update)
677 update();
678 else
679 update_required = TRUE;
680 }
681
682 long parse_num (char *buffer, int *error) {
683 if (error)
684 *error = FALSE;
685 if (!buffer[strspn(buffer, "0123456789")]) {
686 /* interpret as decimal */
687 return atoi(buffer);
688 } else if (buffer[0]=='0' && (buffer[1]=='X' || buffer[1]=='x') &&
689 !buffer[2+strspn(buffer+2,"0123456789ABCDEFabcdef")]) {
690 return strtol(buffer+2, NULL, 16);
691 } else if (buffer[0]=='$' &&
692 !buffer[1+strspn(buffer+1,"0123456789ABCDEFabcdef")]) {
693 return strtol(buffer+1, NULL, 16);
694 } else {
695 return 0;
696 if (error)
697 *error = TRUE;
698 }
699 }