summaryrefslogtreecommitdiff
path: root/menudriver.c
blob: 63fed3292ac78fd41d98688692e5bd1f65825648 (plain)
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
/* general purpose menu driver */
/* alternatively there is an equivalent shell script, menudriver.sh */

/**************************************************************************
 * Copyright (C) Research Software Limited 1985-90.  All rights reserved. *
 * The Miranda system is distributed as free software under the terms in  *
 * the file "COPYING" which is included in the distribution.              *
 *                                                                        *
 * Revised to C11 standard and made 64bit compatible, January 2020        *
 *------------------------------------------------------------------------*/

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>

#ifndef PATH_MAX
#ifdef _XOPEN_PATH_MAX
#define PATH_MAX _XOPEN_PATH_MAX
#else
#define PATH_MAX _POSIX_PATH_MAX
#endif
#endif

char *menuviewer;
char *viewer = "less";

#define VIEWERPAUSESATEND .
/* this modifies default behaviour of menudriver to return straight to menu
   after displaying section, to avoid two layers of prompt;
   choice can be overriden by environment variable RETURNTOMENU=YES/NO */

#ifdef VIEWERPAUSESATEND
int fastback = 1;
#else
int fastback = 0;
#endif

void callshell(char[]);
void clrscr(void);
void menudrive(char *);
void pushlast(void);
void poplast(void);
void settings(void);
void singleton(char *);
int subdir(void);

char next[40] = "", cmd[80], last[40] = ".";
int val, ok = 0;

#include <string.h>
#define index(s,c) strchr(s,c)

int main(int argc, char *argv[])
{
  char *v = getenv("VIEWER");
  char *fb = getenv("RETURNTOMENU");
  menuviewer = getenv("MENUVIEWER");

  if (argc > 2) {
    fprintf(stderr, "menudriver: wrong number of args\n");
    exit(1);
  }

  if (!menuviewer) {
    menuviewer = "cat";
  }

  if (v) {
    viewer = v;
  }

  if (fb) {
    fastback = !(*fb == 'N' || *fb == 'n');
  }

#ifdef CURSES
  setupterm(0, 1, &ok);
  if (ok != 1) {
    fprintf(stderr, "warning: cannot find terminfo entry\n");
  }
#endif

  menudrive(argc == 1 ? "." : argv[1]);
}

/* checks if last is a number (and if so leaves value in val) */
int lastval(void)
{
  /* special case, have just entered subdir */
  if (strcmp(last, ".") == 0 && subdir()) {
    poplast();

    if (sscanf(last, "%d", &val) == 1) {
      chdir("..");
      return (1);
    }

    pushlast();
    return 0;
  }

  return (sscanf(last, "%d", &val) == 1);
}

void menudrive(char *dir)
{
  char *np;
  int c;
  int bad = 0;
  if (chdir(dir) == -1) {
    singleton(dir);		/* apparently not a directory */
  }

  struct stat st;
  while (stat("contents", &st) == 0) {
    if (next[0] == '\0' || bad) {
      clrscr();

      /* invalid selection notified here, after clearing screen */
      if (bad) {
	if (strcmp(next, ".") == 0) {
	  printf("no previous selection to substitute for \".\"\n");
	} else {
	  printf("selection \"%s\" not valid\n", next);
        }
	bad = 0;
      }

      strcpy(cmd, menuviewer);
      strcat(cmd, " ");
      strcat(cmd, "contents");
      system(cmd);
      printf("::please type selection number (or return to exit):");

      /* read remainder of line into next, less leading white space */
      np = next;
      c = getchar();
      while (c == ' ' || c == '\t') {
	c = getchar();
      }

      while (c != '\n' && c != EOF) {
	*np++ = c, c = getchar();
      }

      if (c == EOF) {
	exit(0);
      }

      /* remove trailing white space */
      if (next[0] != '!') {
	while (np[-1] == ' ' || np[-1] == '\t') {
	  np--;
        }
      }
      *np = '\0';
    }

    if (next[0] == '\0') {
      chdir("..");
      poplast();
      continue;
    }

    if (strcmp(next, ".") == 0) {
      strcpy(next, last);	/* repeat last option */
    }

    if (strcmp(next, "+") == 0 && lastval()) {
      (void)sprintf(next, "%d", val + 1);
    }

    if (strcmp(next, "-") == 0 && lastval()) {
      (void)sprintf(next, "%d", val - 1);
    }

    if (stat(next, &st) == 0) {
      if (strcmp(next, ".") == 0 || strcmp(next, "..") == 0 || index(next, '/')) {
	bad = 1;
	continue;
      }				/* no pathnames - see below */

      if (S_ISDIR(st.st_mode)) {	/* directory */
	char hold[PATH_MAX];
	if (!getcwd(hold, sizeof(hold))) {
	  fprintf(stderr, "panic: cwd too long\n"), exit(1);
        }

	if (chdir(next) == -1 || stat("contents", &st)) {
	  bad = 1, chdir(hold);
	} else {
	  strcpy(last, next), pushlast(), next[0] = '\0';
        }

      } else if (S_ISREG(st.st_mode)) {	/* regular file */
	clrscr();

#ifndef UWIN
	if (st.st_mode & S_IXUSR)	/* executable (by owner) */
#else
	if (strcmp(next, "99") == 0)
#endif
	{
	  strcpy(cmd, "./");
	  strcat(cmd, next);
	  system(cmd);
	  if (fastback) {
	    printf("[Hit return to continue]");
	    while (getchar() != '\n') ;
	  }

	} else {
	  strcpy(cmd, viewer);
	  strcat(cmd, " ");
	  strcat(cmd, next);
	  system(cmd);
	}

	if (fastback) {
	  strcpy(last, next);
	  next[0] = '\0';
	} else {
	  printf("::next selection (or return to go back to menu, or q to quit):");
	  /* read remainder of line into next, less leading white space */
	  strcpy(last, next);
	  np = next;

	  c = getchar();
	  while (c == ' ' || c == '\t') {
	    c = getchar();
          }

	  while (c != '\n' && c != EOF) {
	    *np++ = c, c = getchar();
          }

	  if (c == EOF) {
	    exit(0);
          }

	  /* remove trailing white space */
	  if (next[0] != '!') {
	    while (np[-1] == ' ' || np[-1] == '\t') {
	      np--;
            }
          }
	  *np = '\0';
	}
      }
    } else if (strcmp(next, "???") == 0) {	/* ask to see menudriver settings */
      settings();
      printf("[Hit return to continue]");
      while (getchar() != '\n') {
        /* keep reading until new-line */
      }

      next[0] = '\0';

    } else if (strcmp(next, "q") == 0 || strcmp(next, "/q") == 0) {
      exit(0);

    } else if (next[0] == '!') {
      /* shell escape - handy for editing manual! */
      static char syscm[80];
      if (next[1] == '\0' || next[1] == '!') {
	if (syscm[0]) {
	  if (next[1] == '!') {
	    strcat(syscm, next + 2);
          }
	  printf("!%s\n", syscm);
	} else {
	  printf("no previous shell command to substitute for \"!\"\n");
        }
      } else {
	strcpy(syscm, next + 1);
      }

      if (syscm[0]) {
	callshell(syscm);	/* `system' always gets /bin/sh */
      }

      printf("[Hit return to continue]");
      while (getchar() != '\n') ;
      next[0] = '\0';

    } else {
      bad = 1;
    }
  }
}

/* possibly a bug - can retreat above original dir, if parent contains a
   "contents" file - difficult to detect this in a general way, however */
/* pathnames banned because 
   (i) upward pathname will not return correctly if a directory (see above)
   (ii) direct selection of a grandchild directory leads to
        (a) returns via child, instead of directly
        (b) meaning of "." is screwed up while in (a)                  */
/* could fix all this by - rewrite handling of subdirectory to hold=getwd()
   and exit by chdir(hold) instead of chdir("..") - will need to make this
   recursive, or else have stack of holdwd's */

void singleton(char *fil)
{
  struct stat st;
  if (stat(fil, &st) == 0 && S_ISREG(st.st_mode)) {	/* regular file */
    clrscr();

#ifndef UWIN
    if (st.st_mode & S_IXUSR) {	/* executable (by owner) */
      strcpy(cmd, "./");
      strcat(cmd, fil);
      system(cmd);
      fastback = 0;
    } else
#endif
    {
      strcpy(cmd, viewer);
      strcat(cmd, " ");
      strcat(cmd, fil);
      system(cmd);
    }

    if (!fastback) {
      printf("[Hit return to continue]");
      while (getchar() != '\n') ;
    }

    exit(0);

  } else {
    fprintf(stderr, "menudriver: cannot access \"%s\"\n", fil), exit(1);
  }
}

void callshell(char v[])
{
  static char *shell = NULL;
  int pid;

  if (!shell) {
    shell = getenv("SHELL");
    if (!shell) {
      shell = "/bin/sh";
    }
  }

  void (*oldsig)(int) = signal(SIGINT, SIG_IGN);
  if ((pid = fork())) {		/* parent */
    if (pid == -1) {
      perror("UNIX error - cannot create process");
    }

    wait(0);
    (void)signal(SIGINT, oldsig);

  } else {
    execl(shell, shell, "-c", v, (char *)0);
  }
}

void settings(void)
{
  printf("current values of menudriver internal variables are\n\n");
  printf("        VIEWER=%s\n", viewer);
  printf("        MENUVIEWER=%s\n", menuviewer);
  printf("        RETURNTOMENU=%s\n", fastback ? "YES" : "NO");
  printf("\n\
These can be modified by setting environment variables of the same names\n\n\
VIEWER is the program used to display individual sections\n\n\
MENUVIEWER is the program used to display contents pages\n\n\
RETURNTOMENU=NO/YES  causes  a second prompt to be given/not given after\n\
displaying section (ie before returning to contents page).  It should be\n\
`YES' if VIEWER is a program that pauses for input at end  of  file,  or\n\
`NO' if VIEWER is a program that quits silently at end of file.\n\n");
}

/*
Symptoms  of  a  wrong  setting  are  (i)  bottom part of manual section\n\
disappears from screen before you have had a chance to read it - to cure\n\
this  set  RETURNTOMENU=NO; or (ii) having to quit through two layers of\n\
prompt at bottom of a manual section before getting back to the contents\n\
page - to cure this set RETURNTOMENU=YES;\n\n");
*/

char lastvec[100], *lastp = lastvec + 1;
int giveup = 0;

int subdir(void)
{
  return (lastp > lastvec + 1);
}

void pushlast(void)
{
  int n = strlen(last);
  if (last[0] == '.') {
    /* pathological cases */
    if (last[1] == '\0') {
      return;
    } else if (last[1] == '.' && last[2] == '\0') {
      poplast();
      return;
    }
  }

  if (lastp + n > lastvec + 100) {	/* overflow */
    giveup = 1;
    return;
  }

  /* suppressed 'cos interferes with special case in lastval() */
  strcpy(lastp, last), lastp += n + 1, strcpy(last, ".");
}

void poplast(void)
{
  strcpy(lastp, last);		/* just in case we come back immediately */
  lastp--;

  if (giveup || lastp <= lastvec) {
    return;			/* underflow */
  }

  while (*--lastp) {
    /* what does this empty loop do? */
  }

  strcpy(last, ++lastp);
}

#ifndef CURSES

/* to clear screen */
void clrscr(void)
{
  printf("\x1b[2J\x1b[H");
  fflush(stdout);
}

#else
/* alternative method needs curses lib, compile with -DCURSES, or -DUWIN
   and -lncurses */

#ifdef UWIN
#include <ncurses/curses.h>
#include <ncurses/term.h>
#else
#include <curses.h>
#include <term.h>
#endif

void clrscr(void)
{
  if (ok != 1) {
    return;
  }

  putp(clear_screen);
  fflush(stdout);
}

/* end of clrscr method using curses */
#endif