Removed curses fullscreen mode in the text client, in preparation for something even...
[citadel.git] / citadel / textclient / commands.c
1 /*
2  * This file contains functions which implement parts of the
3  * text-mode user interface.
4  *
5  * Copyright (c) 1987-2009 by the citadel.org team
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 3 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "sysdep.h"
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <stdio.h>
26 #include <fcntl.h>
27 #include <ctype.h>
28 #include <string.h>
29 #include <sys/types.h>
30
31 #if TIME_WITH_SYS_TIME
32 # include <sys/time.h>
33 # include <time.h>
34 #else
35 # if HAVE_SYS_TIME_H
36 #  include <sys/time.h>
37 # else
38 #  include <time.h>
39 # endif
40 #endif
41
42 #ifdef HAVE_TERMIOS_H
43 #include <termios.h>
44 #else
45 #include <sgtty.h>
46 #endif
47
48 #ifdef HAVE_SYS_SELECT_H
49 #include <sys/select.h>
50 #endif
51
52 #ifdef THREADED_CLIENT
53 #include <pthread.h>
54 #endif
55
56 #include <signal.h>
57 #include <errno.h>
58 #include <stdarg.h>
59 #include <libcitadel.h>
60 #include "citadel.h"
61 #include "citadel_ipc.h"
62 #include "commands.h"
63 #include "messages.h"
64 #include "citadel_decls.h"
65 #include "routines.h"
66 #include "routines2.h"
67 #include "rooms.h"
68 #include "client_chat.h"
69 #include "citadel_dirs.h"
70 #ifndef HAVE_SNPRINTF
71 #include "snprintf.h"
72 #endif
73 #include "screen.h"
74 #include "ecrash.h"
75
76 struct citcmd {
77         struct citcmd *next;
78         int c_cmdnum;
79         int c_axlevel;
80         char c_keys[5][64];
81 };
82
83 #define IFNEXPERT if ((userflags&US_EXPERT)==0)
84
85
86 int rc_exp_beep;
87 char rc_exp_cmd[1024];
88 int rc_allow_attachments;
89 int rc_display_message_numbers;
90 int rc_force_mail_prompts;
91 int rc_remember_passwords;
92 int rc_ansi_color;
93 int rc_color_use_bg;
94 int rc_prompt_control = 0;
95 time_t rc_idle_threshold = (time_t)900;
96 char rc_url_cmd[SIZ];
97 char rc_open_cmd[SIZ];
98 char rc_gotmail_cmd[SIZ];
99
100 char *gl_string;
101 int next_lazy_cmd = 5;
102
103 int lines_printed = 0;          /* line count for paginator */
104 extern int screenwidth, screenheight;
105 extern int termn8;
106 extern CtdlIPC *ipc_for_signal_handlers;        /* KLUDGE cover your eyes */
107
108 struct citcmd *cmdlist = NULL;
109
110
111 /* these variables are local to this module */
112 char keepalives_enabled = KA_YES;       /* send NOOPs to server when idle */
113 int ok_to_interrupt = 0;                /* print instant msgs asynchronously */
114 time_t AnsiDetect;                      /* when did we send the detect code? */
115 int enable_color = 0;                   /* nonzero for ANSI color */
116
117
118
119
120 /*
121  * If an interesting key has been pressed, return its value, otherwise 0
122  */
123 char was_a_key_pressed(void) {
124         fd_set rfds;
125         struct timeval tv;
126         int the_character;
127         int retval;
128
129         FD_ZERO(&rfds);
130         FD_SET(0, &rfds);
131         tv.tv_sec = 0;
132         tv.tv_usec = 0;
133         retval = select(1, &rfds, NULL, NULL, &tv); 
134
135         /* Careful!  Disable keepalives during keyboard polling; we're probably
136          * in the middle of a data transfer from the server, in which case
137          * sending a NOOP would throw the client protocol out of sync.
138          */
139         if (FD_ISSET(0, &rfds)) {
140                 set_keepalives(KA_NO);
141                 the_character = inkey();
142                 set_keepalives(KA_YES);
143         }
144         else {
145                 the_character = 0;
146         }
147         return(the_character);
148 }
149
150
151
152
153
154 /*
155  * Check to see if we need to pause at the end of a screen.
156  * If we do, we have to switch to half keepalives during the pause because
157  * we are probably in the middle of a server operation and the NOOP command
158  * would confuse everything.
159  */
160 int checkpagin(int lp, unsigned int pagin, unsigned int height)
161 {
162         int thekey;
163
164         if (sigcaught) return(lp);
165         thekey = was_a_key_pressed();
166         if (thekey == 'q' || thekey == 'Q' || thekey == 's' || thekey == 'S')
167                 thekey = STOP_KEY;
168         if (thekey == 'n' || thekey == 'N')
169                 thekey = NEXT_KEY;
170         if ( (thekey == NEXT_KEY) || (thekey == STOP_KEY)) sigcaught = thekey;
171         if (sigcaught) return(lp);
172
173         if (!pagin) return(0);
174         if (lp>=(height-1)) {
175                 set_keepalives(KA_HALF);
176                 hit_any_key(ipc_for_signal_handlers);   /* Cheating -IO */
177                 set_keepalives(KA_YES);
178                 return(0);
179         }
180         return(lp);
181 }
182
183
184
185
186 /*
187  * pprintf()  ...   paginated version of printf()
188  */
189 void pprintf(const char *format, ...) {   
190         va_list arg_ptr;
191         static char buf[4096];  /* static for performance, change if needed */
192         int i;
193
194         /* If sigcaught is nonzero, a keypress has interrupted this and we
195          * should just drain output.
196          */
197         if (sigcaught) return;
198  
199         /* Otherwise, start spewing... */ 
200         va_start(arg_ptr, format);   
201         vsnprintf(buf, sizeof(buf), format, arg_ptr);   
202         va_end(arg_ptr);   
203
204         for (i=0; !IsEmptyStr(&buf[i]); ++i) {
205                 scr_putc(buf[i]);
206                 if (buf[i]==10) {
207                         ++lines_printed;
208                         lines_printed = checkpagin(lines_printed,
209                                 (userflags & US_PAGINATOR),
210                                 screenheight);
211                 }
212         }
213 }   
214
215
216
217 /*
218  * print_instant()  -  print instant messages if there are any
219  */
220 void print_instant(void)
221 {
222         char buf[1024];
223         FILE *outpipe;
224         time_t timestamp;
225         struct tm stamp;
226         int flags = 0;
227         char sender[64];
228         char node[64];
229         char *listing = NULL;
230         int r;                  /* IPC result code */
231
232         if (instant_msgs == 0)
233                 return;
234
235         if (rc_exp_beep) {
236                 ctdl_beep();
237         }
238         if (IsEmptyStr(rc_exp_cmd)) {
239                 color(BRIGHT_RED);
240                 scr_printf("\r---");
241         }
242         
243         while (instant_msgs != 0) {
244                 r = CtdlIPCGetInstantMessage(ipc_for_signal_handlers, &listing, buf);
245                 if (r / 100 != 1)
246                         return;
247         
248                 instant_msgs = extract_int(buf, 0);
249                 timestamp = extract_long(buf, 1);
250                 flags = extract_int(buf, 2);
251                 extract_token(sender, buf, 3, '|', sizeof sender);
252                 extract_token(node, buf, 4, '|', sizeof node);
253                 strcpy(last_paged, sender);
254         
255                 localtime_r(&timestamp, &stamp);
256
257                 /* If the page is a Logoff Request, honor it. */
258                 if (flags & 2) {
259                         termn8 = 1;
260                         return;
261                 }
262         
263                 if (!IsEmptyStr(rc_exp_cmd)) {
264                         outpipe = popen(rc_exp_cmd, "w");
265                         if (outpipe != NULL) {
266                                 /* Header derived from flags */
267                                 if (flags & 2)
268                                         fprintf(outpipe,
269                                                "Please log off now, as requested ");
270                                 else if (flags & 1)
271                                         fprintf(outpipe, "Broadcast message ");
272                                 else if (flags & 4)
273                                         fprintf(outpipe, "Chat request ");
274                                 else
275                                         fprintf(outpipe, "Message ");
276                                 /* Timestamp.  Can this be improved? */
277                                 if (stamp.tm_hour == 0 || stamp.tm_hour == 12)
278                                         fprintf(outpipe, "at 12:%02d%cm",
279                                                 stamp.tm_min, 
280                                                 stamp.tm_hour ? 'p' : 'a');
281                                 else if (stamp.tm_hour > 12)            /* pm */
282                                         fprintf(outpipe, "at %d:%02dpm",
283                                                 stamp.tm_hour - 12,
284                                                 stamp.tm_min);
285                                 else                                    /* am */
286                                         fprintf(outpipe, "at %d:%02dam",
287                                                 stamp.tm_hour, stamp.tm_min);
288                                 fprintf(outpipe, " from %s", sender);
289                                 if (strncmp(ipc_for_signal_handlers->ServInfo.nodename, node, 32))
290                                         fprintf(outpipe, " @%s", node);
291                                 fprintf(outpipe, ":\n%s\n", listing);
292                                 pclose(outpipe);
293                                 if (instant_msgs == 0)
294                                         return;
295                                 continue;
296                         }
297                 }
298                 /* fall back to built-in instant message display */
299                 scr_printf("\n");
300                 lines_printed++;
301
302                 /* Header derived from flags */
303                 if (flags & 2)
304                         scr_printf("Please log off now, as requested ");
305                 else if (flags & 1)
306                         scr_printf("Broadcast message ");
307                 else if (flags & 4)
308                         scr_printf("Chat request ");
309                 else
310                         scr_printf("Message ");
311         
312                 /* Timestamp.  Can this be improved? */
313                 if (stamp.tm_hour == 0 || stamp.tm_hour == 12)/* 12am/12pm */
314                         scr_printf("at 12:%02d%cm", stamp.tm_min, 
315                                 stamp.tm_hour ? 'p' : 'a');
316                 else if (stamp.tm_hour > 12)                    /* pm */
317                         scr_printf("at %d:%02dpm",
318                                 stamp.tm_hour - 12, stamp.tm_min);
319                 else                                            /* am */
320                         scr_printf("at %d:%02dam", stamp.tm_hour, stamp.tm_min);
321                 
322                 /* Sender */
323                 scr_printf(" from %s", sender);
324         
325                 /* Remote node, if any */
326                 if (strncmp(ipc_for_signal_handlers->ServInfo.nodename, node, 32))
327                         scr_printf(" @%s", node);
328         
329                 scr_printf(":\n");
330                 lines_printed++;
331                 fmout(screenwidth, NULL, listing, NULL, 1, screenheight, -1, 0);
332                 free(listing);
333
334                 lines_printed = 0;
335         }
336         scr_printf("\n---\n");
337         color(BRIGHT_WHITE);
338
339
340 }
341
342
343 void set_keepalives(int s)
344 {
345         keepalives_enabled = (char) s;
346 }
347
348 /* 
349  * This loop handles the "keepalive" messages sent to the server when idling.
350  */
351
352 static time_t idlet = 0;
353 static void really_do_keepalive(void) {
354         int r;                          /* IPC response code */
355
356         time(&idlet);
357
358         /* This may sometimes get called before we are actually connected
359          * to the server.  Don't do anything if we aren't connected. -IO
360          */
361         if (!ipc_for_signal_handlers)
362                 return;
363
364         /* If full keepalives are enabled, send a NOOP to the server and
365          * wait for a response.
366          */
367         if (keepalives_enabled == KA_YES) {
368                 r = CtdlIPCNoop(ipc_for_signal_handlers);
369                 if (instant_msgs > 0) {
370                         if (ok_to_interrupt == 1) {
371                                 scr_printf("\r%64s\r", "");
372                                 print_instant();
373                                 scr_printf("%s%c ", room_name,
374                                        room_prompt(room_flags));
375                                 scr_flush();
376                         }
377                 }
378         }
379
380         /* If half keepalives are enabled, send a QNOP to the server (if the
381          * server supports it) and then do nothing.
382          */
383         if ( (keepalives_enabled == KA_HALF)
384            && (ipc_for_signal_handlers->ServInfo.supports_qnop > 0) ) {
385                 CtdlIPC_chat_send(ipc_for_signal_handlers, "QNOP");
386         }
387 }
388
389 /* threaded nonblocking keepalive stuff starts here. I'm going for a simple
390    encapsulated interface; in theory there should be no need to touch these
391    globals outside of the async_ka_* functions. */
392
393 #ifdef THREADED_CLIENT
394 static pthread_t ka_thr_handle;
395 static int ka_thr_active = 0;
396 static int async_ka_enabled = 0;
397
398 static void *ka_thread(void *arg)
399 {
400 #ifdef HAVE_BACKTRACE
401         char threadName[256];
402
403         // Set up our name
404         sprintf(threadName, "ka_Thread n");
405
406         // Register for tracing
407         eCrash_RegisterThread(threadName, 0);
408 #endif
409         really_do_keepalive();
410         pthread_detach(ka_thr_handle);
411         ka_thr_active = 0;
412         
413 #ifdef HAVE_BACKTRACE
414         eCrash_UnregisterThread();
415 #endif
416         return NULL;
417 }
418
419 /* start up a thread to handle a keepalive in the background */
420 static void async_ka_exec(void)
421 {
422         if (!ka_thr_active) {
423                 ka_thr_active = 1;
424                 if (pthread_create(&ka_thr_handle, NULL, ka_thread, NULL)) {
425                         perror("pthread_create");
426                         exit(1);
427                 }
428         }
429 }
430 #endif /* THREADED_CLIENT */
431
432 /* I changed this from static to not because I need to call it from
433    screen.c, either that or make something in screen.c not static.
434    Fix it how you like. Why all the staticness? stu */
435    
436 void do_keepalive(void)
437 {
438         time_t now;
439
440         time(&now);
441         if ((now - idlet) < ((long) S_KEEPALIVE))
442                 return;
443
444         /* Do a space-backspace to keep telnet sessions from idling out */
445         scr_printf(" %c", 8);
446         scr_flush();
447
448 #ifdef THREADED_CLIENT
449         if (async_ka_enabled)
450                 async_ka_exec();
451         else
452 #endif
453                 really_do_keepalive();
454 }
455
456
457 /* Now the actual async-keepalve API that we expose to higher levels:
458    async_ka_start() and async_ka_end(). These do nothing when we don't have
459    threading enabled, so we avoid sprinkling ifdef's throughout the code. */
460
461 /* wait for a background keepalive to complete. this must be done before
462    attempting any further server requests! */
463 void async_ka_end(void)
464 {
465 #ifdef THREADED_CLIENT
466         if (ka_thr_active)
467                 pthread_join(ka_thr_handle, NULL);
468
469         async_ka_enabled--;
470 #endif
471 }
472
473 /* tell do_keepalive() that keepalives are asynchronous. */
474 void async_ka_start(void)
475 {
476 #ifdef THREADED_CLIENT
477         async_ka_enabled++;
478 #endif
479 }
480
481
482 int inkey(void)
483 {                               /* get a character from the keyboard, with   */
484         int a;                  /* the watchdog timer in effect if necessary */
485         fd_set rfds;
486         struct timeval tv;
487         time_t start_time;
488
489         scr_flush();
490         lines_printed = 0;
491         time(&start_time);
492
493         do {
494                 /* This loop waits for keyboard input.  If the keepalive
495                  * timer expires, it sends a keepalive to the server if
496                  * necessary and then waits again.
497                  */
498                 do {
499                         scr_set_windowsize(ipc_for_signal_handlers);
500                         do_keepalive();
501                         scr_set_windowsize(ipc_for_signal_handlers);
502
503                         FD_ZERO(&rfds);
504                         FD_SET(0, &rfds);
505                         tv.tv_sec = S_KEEPALIVE;
506                         tv.tv_usec = 0;
507
508                         select(1, &rfds, NULL, NULL, &tv);
509                 } while (!FD_ISSET(0, &rfds));
510
511                 /* At this point, there's input, so fetch it.
512                  * (There's a hole in the bucket...)
513                  */
514                 a = scr_getc(SCR_BLOCK);
515                 if (a == 127) {
516                         a = 8;
517                 }
518                 if (a == 13) {
519                         a = 10;
520                 }
521 /* not so fast there dude, we have to handle UTF-8 and ISO-8859-1...
522                 if (a > 126) {
523                         a = 0;
524                 }
525                 if (((a != 23) && (a != 4) && (a != 10) && (a != 8) && (a != NEXT_KEY) && (a != STOP_KEY))
526                     && ((a < 32) || (a > 126))) {
527                         a = 0;
528                 }
529  */
530
531 #ifndef DISABLE_CURSES
532 #if defined(HAVE_CURSES_H) || defined(HAVE_NCURSES_H)
533                 if (a == ERR) {
534                         logoff(NULL, 3);
535                 }
536 #endif
537 #endif
538
539         } while (a == 0);
540         return (a);
541 }
542
543
544 int yesno(void)
545 {                               /* Returns 1 for yes, 0 for no */
546         int a;
547         while (1) {
548                 a = inkey();
549                 a = tolower(a);
550                 if (a == 'y') {
551                         scr_printf("Yes\n");
552                         return (1);
553                 }
554                 if (a == 'n') {
555                         scr_printf("No\n");
556                         return (0);
557                 }
558         }
559 }
560
561 /* Returns 1 for yes, 0 for no, arg is default value */
562 int yesno_d(int d)
563 {
564         int a;
565         while (1) {
566                 a = inkey();
567                 a = tolower(a);
568                 if (a == 10)
569                         a = (d ? 'y' : 'n');
570                 if (a == 'y') {
571                         scr_printf("Yes\n");
572                         return (1);
573                 }
574                 if (a == 'n') {
575                         scr_printf("No\n");
576                         return (0);
577                 }
578         }
579 }
580
581
582
583
584 /* Gets a line from the terminal */
585 /* string == Pointer to string buffer */
586 /* lim == Maximum length - if negative, no-show */
587 void ctdl_getline(char *string, int lim) 
588 {
589         int a, b;
590         char flag = 0;
591
592         if (lim < 0) {
593                 lim = (0 - lim);
594                 flag = 1;
595         }
596         strcpy(string, "");
597         gl_string = string;
598         async_ka_start();
599
600 GLA:    a = inkey();
601         /* a = (a & 127); ** commented out because it isn't just an ASCII world anymore */
602         if ((a == 8 || a == 23) && (IsEmptyStr(string)))
603                 goto GLA;
604         if ((a != 10) && (a != 8) && (strlen(string) == lim))
605                 goto GLA;
606         if ((a == 8) && (string[0] != 0)) {
607                 string[strlen(string) - 1] = 0;
608                 scr_putc(8); scr_putc(32); scr_putc(8);
609                 goto GLA;
610         }
611         if ((a == 23) && (string[0] != 0)) {
612                 do {
613                         string[strlen(string) - 1] = 0;
614                         scr_putc(8); scr_putc(32); scr_putc(8);
615                 } while (!IsEmptyStr(string) && string[strlen(string) - 1] != ' ');
616                 goto GLA;
617         }
618         if ((a == 10)) {
619                 scr_putc(10);
620                 async_ka_end();
621                 return;
622         }
623         if (a < 32)
624                 a = '.';
625         b = strlen(string);
626         string[b] = a;
627         string[b + 1] = 0;
628         if (flag == 0)
629                 scr_putc(a);
630         if (flag == 1)
631                 scr_putc('*');
632         goto GLA;
633 }
634
635
636 /*
637  * strprompt()  -  prompt for a string, print the existing value and
638  *                 allow the user to press return to keep it...
639  */
640 void strprompt(char *prompt, char *str, int len)
641 {
642         int i;
643         char buf[128];
644
645         print_instant();
646         color(DIM_WHITE);
647         scr_printf("%s ", prompt);
648         color(DIM_MAGENTA);
649         scr_printf("[");
650         color(BRIGHT_MAGENTA);
651
652         if (len >= 0) {
653                 scr_printf("%s", str);
654         }
655         else {
656                 for (i=0; !IsEmptyStr(&str[i]); ++i) {
657                         scr_printf("*");
658                 }
659         }
660
661         color(DIM_MAGENTA);
662         scr_printf("]");
663         color(DIM_WHITE);
664         scr_printf(": ");
665         color(BRIGHT_CYAN);
666         ctdl_getline(buf, len);
667         if (buf[0] != 0)
668                 strcpy(str, buf);
669         color(DIM_WHITE);
670 }
671
672 /*
673  * boolprompt()  -  prompt for a yes/no, print the existing value and
674  *                  allow the user to press return to keep it...
675  */
676 int boolprompt(char *prompt, int prev_val)
677 {
678         int r;
679
680         color(DIM_WHITE);
681         scr_printf("%s ", prompt);
682         color(DIM_MAGENTA);
683         scr_printf("[");
684         color(BRIGHT_MAGENTA);
685         scr_printf("%s", (prev_val ? "Yes" : "No"));
686         color(DIM_MAGENTA);
687         scr_printf("]: ");
688         color(BRIGHT_CYAN);
689         r = (yesno_d(prev_val));
690         color(DIM_WHITE);
691         return r;
692 }
693
694 /* 
695  * intprompt()  -  like strprompt(), except for an integer
696  *                 (note that it RETURNS the new value!)
697  */
698 int intprompt(char *prompt, int ival, int imin, int imax)
699 {
700         char buf[16];
701         int i;
702         int p;
703
704         do {
705                 i = ival;
706                 snprintf(buf, sizeof buf, "%d", i);
707                 strprompt(prompt, buf, 15);
708                 i = atoi(buf);
709                 for (p=0; !IsEmptyStr(&buf[p]); ++p) {
710                         if ( (!isdigit(buf[p]))
711                            && ( (buf[p]!='-') || (p!=0) )  )
712                                 i = imin - 1;
713                 }
714                 if (i < imin)
715                         scr_printf("*** Must be no less than %d.\n", imin);
716                 if (i > imax)
717                         scr_printf("*** Must be no more than %d.\n", imax);
718         } while ((i < imin) || (i > imax));
719         return (i);
720 }
721
722 /* 
723  * newprompt()  -  prompt for a string with no existing value
724  *                 (clears out string buffer first)
725  */
726 void newprompt(char *prompt, char *str, int len)
727 {
728         color(BRIGHT_MAGENTA);
729         scr_printf("%s", prompt);
730         color(DIM_MAGENTA);
731         ctdl_getline(str, len);
732         color(DIM_WHITE);
733 }
734
735
736 int lkey(void)
737 {                               /* returns a lower case value */
738         int a;
739         a = inkey();
740         if (isupper(a))
741                 a = tolower(a);
742         return (a);
743 }
744
745 /*
746  * parse the citadel.rc file
747  */
748 void load_command_set(void)
749 {
750         FILE *ccfile;
751         char buf[1024];
752         char editor_key[100];
753         struct citcmd *cptr;
754         struct citcmd *lastcmd = NULL;
755         int a, d;
756         int b = 0;
757         int i;
758
759
760         /* first, set up some defaults for non-required variables */
761
762         for (i = 0; i < MAX_EDITORS; i++)
763                 strcpy(editor_paths[i], "");
764         strcpy(printcmd, "");
765         strcpy(imagecmd, "");
766         strcpy(rc_username, "");
767         strcpy(rc_password, "");
768         rc_floor_mode = 0;
769         rc_exp_beep = 1;
770         rc_allow_attachments = 0;
771         rc_remember_passwords = 0;
772         strcpy(rc_exp_cmd, "");
773         rc_display_message_numbers = 0;
774         rc_force_mail_prompts = 0;
775         rc_ansi_color = 0;
776         rc_color_use_bg = 0;
777         strcpy(rc_url_cmd, "");
778         strcpy(rc_open_cmd, "");
779         strcpy(rc_gotmail_cmd, "");
780 #ifdef HAVE_OPENSSL
781         rc_encrypt = RC_DEFAULT;
782 #endif
783 #if defined(HAVE_CURSES_H) && !defined(DISABLE_CURSES)
784         rc_screen = RC_DEFAULT;
785 #endif
786         rc_alt_semantics = 0;
787
788         /* now try to open the citadel.rc file */
789
790         ccfile = NULL;
791         if (getenv("HOME") != NULL) {
792                 snprintf(buf, sizeof buf, "%s/.citadelrc", getenv("HOME"));
793                 ccfile = fopen(buf, "r");
794         }
795         if (ccfile == NULL) {
796                 ccfile = fopen(file_citadel_rc, "r");
797         }
798         if (ccfile == NULL) {
799                 ccfile = fopen("/etc/citadel.rc", "r");
800         }
801         if (ccfile == NULL) {
802                 ccfile = fopen("./citadel.rc", "r");
803         }
804         if (ccfile == NULL) {
805                 perror("commands: cannot open citadel.rc");
806                 logoff(NULL, 3);
807         }
808         while (fgets(buf, sizeof buf, ccfile) != NULL) {
809                 while ((!IsEmptyStr(buf)) ? (isspace(buf[strlen(buf) - 1])) : 0)
810                         buf[strlen(buf) - 1] = 0;
811
812                 if (!strncasecmp(buf, "encrypt=", 8)) {
813                         if (!strcasecmp(&buf[8], "yes")) {
814 #ifdef HAVE_OPENSSL
815                                 rc_encrypt = RC_YES;
816 #else
817                                 fprintf(stderr, "citadel.rc requires encryption support but citadel is not compiled with OpenSSL");
818                                 logoff(NULL, 3);
819 #endif
820                         }
821 #ifdef HAVE_OPENSSL
822                         else if (!strcasecmp(&buf[8], "no")) {
823                                 rc_encrypt = RC_NO;
824                         }
825                         else if (!strcasecmp(&buf[8], "default")) {
826                                 rc_encrypt = RC_DEFAULT;
827                         }
828 #endif
829                 }
830
831 #if defined(HAVE_CURSES_H) && !defined(DISABLE_CURSES)
832                 if (!strncasecmp(buf, "fullscreen=", 11)) {
833                         if (!strcasecmp(&buf[11], "yes"))
834                                 rc_screen = RC_YES;
835                         else if (!strcasecmp(&buf[11], "no"))
836                                 rc_screen = RC_NO;
837                 }
838 #endif
839
840                 if (!strncasecmp(buf, "editor=", 7))
841                         strcpy(editor_paths[0], &buf[7]);
842
843                 for (i = 0; i < MAX_EDITORS; i++)
844                 {
845                         sprintf(editor_key, "editor%d=", i);
846                         if (!strncasecmp(buf, editor_key, strlen(editor_key)))
847                                 strcpy(editor_paths[i], &buf[strlen(editor_key)]);
848                 }
849
850                 if (!strncasecmp(buf, "printcmd=", 9))
851                         strcpy(printcmd, &buf[9]);
852
853                 if (!strncasecmp(buf, "imagecmd=", 9))
854                         strcpy(imagecmd, &buf[9]);
855
856                 if (!strncasecmp(buf, "expcmd=", 7))
857                         strcpy(rc_exp_cmd, &buf[7]);
858
859                 if (!strncasecmp(buf, "local_screen_dimensions=", 24))
860                         have_xterm = (char) atoi(&buf[24]);
861
862                 if (!strncasecmp(buf, "use_floors=", 11)) {
863                         if (!strcasecmp(&buf[11], "yes"))
864                                 rc_floor_mode = RC_YES;
865                         if (!strcasecmp(&buf[11], "no"))
866                                 rc_floor_mode = RC_NO;
867                         if (!strcasecmp(&buf[11], "default"))
868                                 rc_floor_mode = RC_DEFAULT;
869                 }
870                 if (!strncasecmp(buf, "beep=", 5)) {
871                         rc_exp_beep = atoi(&buf[5]);
872                 }
873                 if (!strncasecmp(buf, "allow_attachments=", 18)) {
874                         rc_allow_attachments = atoi(&buf[18]);
875                 }
876                 if (!strncasecmp(buf, "idle_threshold=", 15)) {
877                         rc_idle_threshold = atol(&buf[15]);
878                 }
879                 if (!strncasecmp(buf, "remember_passwords=", 19)) {
880                         rc_remember_passwords = atoi(&buf[19]);
881                 }
882                 if (!strncasecmp(buf, "display_message_numbers=", 24)) {
883                         rc_display_message_numbers = atoi(&buf[24]);
884                 }
885                 if (!strncasecmp(buf, "force_mail_prompts=", 19)) {
886                         rc_force_mail_prompts = atoi(&buf[19]);
887                 }
888                 if (!strncasecmp(buf, "ansi_color=", 11)) {
889                         if (!strncasecmp(&buf[11], "on", 2))
890                                 rc_ansi_color = 1;
891                         if (!strncasecmp(&buf[11], "auto", 4))
892                                 rc_ansi_color = 2;      /* autodetect */
893                         if (!strncasecmp(&buf[11], "user", 4))
894                                 rc_ansi_color = 3;      /* user config */
895                 }
896                 if (!strncasecmp(buf, "use_background=", 15)) {
897                         if (!strncasecmp(&buf[15], "on", 2))
898                                 rc_color_use_bg = 9;
899                 }
900                 if (!strncasecmp(buf, "prompt_control=", 15)) {
901                         if (!strncasecmp(&buf[15], "on", 2))
902                                 rc_prompt_control = 1;
903                         if (!strncasecmp(&buf[15], "user", 4))
904                                 rc_prompt_control = 3;  /* user config */
905                 }
906                 if (!strncasecmp(buf, "username=", 9))
907                         strcpy(rc_username, &buf[9]);
908
909                 if (!strncasecmp(buf, "password=", 9))
910                         strcpy(rc_password, &buf[9]);
911
912                 if (!strncasecmp(buf, "urlcmd=", 7))
913                         strcpy(rc_url_cmd, &buf[7]);
914
915                 if (!strncasecmp(buf, "opencmd=", 7))
916                         strcpy(rc_open_cmd, &buf[8]);
917
918                 if (!strncasecmp(buf, "gotmailcmd=", 11))
919                         strcpy(rc_gotmail_cmd, &buf[11]);
920
921                 if (!strncasecmp(buf, "alternate_semantics=", 20)) {
922                         if (!strncasecmp(&buf[20], "yes", 3)) {
923                                 rc_alt_semantics = 1;
924                         }
925                         else {
926                                 rc_alt_semantics = 0;
927                         }
928                 }
929
930                 if (!strncasecmp(buf, "cmd=", 4)) {
931                         strcpy(buf, &buf[4]);
932
933                         cptr = (struct citcmd *) malloc(sizeof(struct citcmd));
934
935                         cptr->c_cmdnum = atoi(buf);
936                         for (d = strlen(buf); d >= 0; --d)
937                                 if (buf[d] == ',')
938                                         b = d;
939                         strcpy(buf, &buf[b + 1]);
940
941                         cptr->c_axlevel = atoi(buf);
942                         for (d = strlen(buf); d >= 0; --d)
943                                 if (buf[d] == ',')
944                                         b = d;
945                         strcpy(buf, &buf[b + 1]);
946
947                         for (a = 0; a < 5; ++a)
948                                 cptr->c_keys[a][0] = 0;
949
950                         a = 0;
951                         b = 0;
952                         buf[strlen(buf) + 1] = 0;
953                         while (!IsEmptyStr(buf)) {
954                                 b = strlen(buf);
955                                 for (d = strlen(buf); d >= 0; --d)
956                                         if (buf[d] == ',')
957                                                 b = d;
958                                 strncpy(cptr->c_keys[a], buf, b);
959                                 cptr->c_keys[a][b] = 0;
960                                 if (buf[b] == ',')
961                                         strcpy(buf, &buf[b + 1]);
962                                 else
963                                         strcpy(buf, "");
964                                 ++a;
965                         }
966
967                         cptr->next = NULL;
968                         if (cmdlist == NULL)
969                                 cmdlist = cptr;
970                         else
971                                 lastcmd->next = cptr;
972                         lastcmd = cptr;
973                 }
974         }
975         fclose(ccfile);
976 }
977
978
979
980 /*
981  * return the key associated with a command
982  */
983 char keycmd(char *cmdstr)
984 {
985         int a;
986
987         for (a = 0; !IsEmptyStr(&cmdstr[a]); ++a)
988                 if (cmdstr[a] == '&')
989                         return (tolower(cmdstr[a + 1]));
990         return (0);
991 }
992
993
994 /*
995  * Output the string from a key command without the ampersand
996  * "mode" should be set to 0 for normal or 1 for <C>ommand key highlighting
997  */
998 char *cmd_expand(char *strbuf, int mode)
999 {
1000         int a;
1001         static char exp[64];
1002         char buf[1024];
1003
1004         strcpy(exp, strbuf);
1005
1006         for (a = 0; exp[a]; ++a) {
1007                 if (strbuf[a] == '&') {
1008
1009                         /* dont echo these non mnemonic command keys */
1010                         int noecho = strbuf[a+1] == '<' || strbuf[a+1] == '>' || strbuf[a+1] == '+' || strbuf[a+1] == '-';
1011
1012                         if (mode == 0) {
1013                                 strcpy(&exp[a], &exp[a + 1 + noecho]);
1014                         }
1015                         if (mode == 1) {
1016                                 exp[a] = '<';
1017                                 strcpy(buf, &exp[a + 2]);
1018                                 exp[a + 2] = '>';
1019                                 exp[a + 3] = 0;
1020                                 strcat(exp, buf);
1021                         }
1022                 }
1023                 if (!strncmp(&exp[a], "^r", 2)) {
1024                         strcpy(buf, exp);
1025                         strcpy(&exp[a], room_name);
1026                         strcat(exp, &buf[a + 2]);
1027                 }
1028                 if (!strncmp(&exp[a], "^c", 2)) {
1029                         exp[a] = ',';
1030                         strcpy(&exp[a + 1], &exp[a + 2]);
1031                 }
1032         }
1033
1034         return (exp);
1035 }
1036
1037
1038
1039 /*
1040  * Comparison function to determine if entered commands match a
1041  * command loaded from the config file.
1042  */
1043 int cmdmatch(char *cmdbuf, struct citcmd *cptr, int ncomp)
1044 {
1045         int a;
1046         int cmdax;
1047
1048         cmdax = 0;
1049         if (is_room_aide)
1050                 cmdax = 1;
1051         if (axlevel >= 6)
1052                 cmdax = 2;
1053
1054         for (a = 0; a < ncomp; ++a) {
1055                 if ((tolower(cmdbuf[a]) != keycmd(cptr->c_keys[a]))
1056                     || (cptr->c_axlevel > cmdax))
1057                         return (0);
1058         }
1059         return (1);
1060 }
1061
1062
1063 /*
1064  * This function returns 1 if a given command requires a string input
1065  */
1066 int requires_string(struct citcmd *cptr, int ncomp)
1067 {
1068         int a;
1069         char buf[64];
1070
1071         strcpy(buf, cptr->c_keys[ncomp - 1]);
1072         for (a = 0; !IsEmptyStr(&buf[a]); ++a) {
1073                 if (buf[a] == ':')
1074                         return (1);
1075         }
1076         return (0);
1077 }
1078
1079
1080 /*
1081  * Input a command at the main prompt.
1082  * This function returns an integer command number.  If the command prompts
1083  * for a string then it is placed in the supplied buffer.
1084  */
1085 int getcmd(CtdlIPC *ipc, char *argbuf)
1086 {
1087         char cmdbuf[5];
1088         int cmdspaces[5];
1089         int cmdpos;
1090         int ch;
1091         int a;
1092         int got;
1093         int this_lazy_cmd;
1094         struct citcmd *cptr;
1095
1096         /*
1097          * Starting a new command now, so set sigcaught to 0.  This variable
1098          * is set to nonzero (usually NEXT_KEY or STOP_KEY) if a command has
1099          * been interrupted by a keypress.
1100          */
1101         sigcaught = 0;
1102
1103         /* Switch color support on or off if we're in user mode */
1104         if (rc_ansi_color == 3) {
1105                 if (userflags & US_COLOR)
1106                         enable_color = 1;
1107                 else
1108                         enable_color = 0;
1109         }
1110         /* if we're running in idiot mode, display a cute little menu */
1111         IFNEXPERT formout(ipc, "mainmenu");
1112
1113         print_instant();
1114         strcpy(argbuf, "");
1115         cmdpos = 0;
1116         for (a = 0; a < 5; ++a)
1117                 cmdbuf[a] = 0;
1118         /* now the room prompt... */
1119         ok_to_interrupt = 1;
1120         color(BRIGHT_WHITE);
1121         scr_printf("\n%s", room_name);
1122         color(DIM_WHITE);
1123         scr_printf("%c ", room_prompt(room_flags));
1124         scr_flush();
1125
1126         while (1) {
1127                 ch = inkey();
1128                 ok_to_interrupt = 0;
1129
1130                 /* Handle the backspace key, but only if there's something
1131                  * to backspace over...
1132                  */
1133                 if ((ch == 8) && (cmdpos > 0)) {
1134                         back(cmdspaces[cmdpos - 1] + 1);
1135                         cmdbuf[cmdpos] = 0;
1136                         --cmdpos;
1137                 }
1138                 /* Spacebar invokes "lazy traversal" commands */
1139                 if ((ch == 32) && (cmdpos == 0)) {
1140                         this_lazy_cmd = next_lazy_cmd;
1141                         if (this_lazy_cmd == 13)
1142                                 next_lazy_cmd = 5;
1143                         if (this_lazy_cmd == 5)
1144                                 next_lazy_cmd = 13;
1145                         for (cptr = cmdlist; cptr != NULL; cptr = cptr->next) {
1146                                 if (cptr->c_cmdnum == this_lazy_cmd) {
1147                                         for (a = 0; a < 5; ++a)
1148                                                 if (cptr->c_keys[a][0] != 0)
1149                                                         scr_printf("%s ", cmd_expand(
1150                                                                                         cptr->c_keys[a], 0));
1151                                         scr_printf("\n");
1152                                         return (this_lazy_cmd);
1153                                 }
1154                         }
1155                         scr_printf("\n");
1156                         return (this_lazy_cmd);
1157                 }
1158                 /* Otherwise, process the command */
1159                 cmdbuf[cmdpos] = tolower(ch);
1160
1161                 for (cptr = cmdlist; cptr != NULL; cptr = cptr->next) {
1162                         if (cmdmatch(cmdbuf, cptr, cmdpos + 1)) {
1163
1164                                 scr_printf("%s", cmd_expand(cptr->c_keys[cmdpos], 0));
1165                                 cmdspaces[cmdpos] = strlen(
1166                                     cmd_expand(cptr->c_keys[cmdpos], 0));
1167                                 if (cmdpos < 4)
1168                                         if ((cptr->c_keys[cmdpos + 1]) != 0)
1169                                                 scr_putc(' ');
1170                                 ++cmdpos;
1171                         }
1172                 }
1173
1174                 for (cptr = cmdlist; cptr != NULL; cptr = cptr->next) {
1175                         if (cmdmatch(cmdbuf, cptr, 5)) {
1176                                 /* We've found our command. */
1177                                 if (requires_string(cptr, cmdpos)) {
1178                                         ctdl_getline(argbuf, 64);
1179                                 } else {
1180                                         scr_printf("\n");
1181                                 }
1182
1183                                 /* If this command is one that changes rooms,
1184                                  * then the next lazy-command (space bar)
1185                                  * should be "read new" instead of "goto"
1186                                  */
1187                                 if ((cptr->c_cmdnum == 5)
1188                                     || (cptr->c_cmdnum == 6)
1189                                     || (cptr->c_cmdnum == 47)
1190                                     || (cptr->c_cmdnum == 52)
1191                                     || (cptr->c_cmdnum == 16)
1192                                     || (cptr->c_cmdnum == 20))
1193                                         next_lazy_cmd = 13;
1194
1195                                 /* If this command is "read new"
1196                                  * then the next lazy-command (space bar)
1197                                  * should be "goto"
1198                                  */
1199                                 if (cptr->c_cmdnum == 13)
1200                                         next_lazy_cmd = 5;
1201
1202                                 return (cptr->c_cmdnum);
1203
1204                         }
1205                 }
1206
1207                 if (ch == '?') {
1208                         pprintf("\rOne of ...                         \n");
1209                         for (cptr = cmdlist; cptr != NULL; cptr = cptr->next) {
1210                                 if (cmdmatch(cmdbuf, cptr, cmdpos)) {
1211                                         for (a = 0; a < 5; ++a) {
1212                                            keyopt(cmd_expand(cptr->c_keys[a], 1));
1213                                    pprintf(" ");
1214                                         }
1215                                         pprintf("\n");
1216                                 }
1217                         }
1218                 sigcaught = 0;
1219
1220                         pprintf("\n%s%c ", room_name, room_prompt(room_flags));
1221                         got = 0;
1222                         for (cptr = cmdlist; cptr != NULL; cptr = cptr->next) {
1223                                 if ((got == 0) && (cmdmatch(cmdbuf, cptr, cmdpos))) {
1224                                         for (a = 0; a < cmdpos; ++a) {
1225                                                 pprintf("%s ",
1226                                                        cmd_expand(cptr->c_keys[a], 0));
1227                                         }
1228                                         got = 1;
1229                                 }
1230                         }
1231                 }
1232         }
1233
1234 }
1235
1236
1237
1238
1239
1240 /*
1241  * set tty modes.  commands are:
1242  * 
1243  * 01- set to Citadel mode
1244  * 2 - save current settings for later restoral
1245  * 3 - restore saved settings
1246  */
1247 #ifdef HAVE_TERMIOS_H
1248 void stty_ctdl(int cmd)
1249 {                               /* SysV version of stty_ctdl() */
1250         struct termios live;
1251         static struct termios saved_settings;
1252         static int last_cmd = 0;
1253
1254         if (cmd == SB_LAST)
1255                 cmd = last_cmd;
1256         else
1257                 last_cmd = cmd;
1258
1259         if ((cmd == 0) || (cmd == 1)) {
1260                 tcgetattr(0, &live);
1261                 live.c_iflag = ISTRIP | IXON | IXANY;
1262                 live.c_oflag = OPOST | ONLCR;
1263                 live.c_lflag = ISIG | NOFLSH;
1264
1265                 live.c_cc[VINTR] = 0;
1266                 live.c_cc[VQUIT] = 0;
1267
1268 #ifdef hpux
1269                 live.c_cc[VMIN] = 0;
1270                 live.c_cc[VTIME] = 0;
1271 #endif
1272
1273                 /* do we even need this stuff anymore? */
1274                 /* live.c_line=0; */
1275                 live.c_cc[VERASE] = 8;
1276                 live.c_cc[VKILL] = 24;
1277                 live.c_cc[VEOF] = 1;
1278                 live.c_cc[VEOL] = 255;
1279                 live.c_cc[VEOL2] = 0;
1280                 live.c_cc[VSTART] = 0;
1281                 tcsetattr(0, TCSADRAIN, &live);
1282         }
1283         if (cmd == 2) {
1284                 tcgetattr(0, &saved_settings);
1285         }
1286         if (cmd == 3) {
1287                 tcsetattr(0, TCSADRAIN, &saved_settings);
1288         }
1289
1290 }
1291 #else
1292 void stty_ctdl(int cmd)
1293 {                               /* BSD version of stty_ctdl() */
1294         struct sgttyb live;
1295         static struct sgttyb saved_settings;
1296         static int last_cmd = 0;
1297
1298         if (cmd == SB_LAST)
1299                 cmd = last_cmd;
1300         else
1301                 last_cmd = cmd;
1302
1303         if ((cmd == 0) || (cmd == 1)) {
1304                 gtty(0, &live);
1305                 live.sg_flags |= CBREAK;
1306                 live.sg_flags |= CRMOD;
1307                 live.sg_flags |= NL1;
1308                 live.sg_flags &= ~ECHO;
1309                 if (cmd == 1)
1310                         live.sg_flags |= NOFLSH;
1311                 stty(0, &live);
1312         }
1313         if (cmd == 2) {
1314                 gtty(0, &saved_settings);
1315         }
1316         if (cmd == 3) {
1317                 stty(0, &saved_settings);
1318         }
1319 }
1320 #endif
1321
1322
1323 /*
1324  * display_help()  -  help file viewer
1325  */
1326 void display_help(CtdlIPC *ipc, char *name)
1327 {
1328         formout(ipc, name);
1329 }
1330
1331
1332 /*
1333  * fmout() - Citadel text formatter and paginator
1334  */
1335 int fmout(
1336         int width,      /* screen width to use */
1337         FILE *fpin,     /* file to read from, or NULL to format given text */
1338         char *text,     /* text to be formatted (when fpin is NULL */
1339         FILE *fpout,    /* file to write to, or NULL to write to screen */
1340         char pagin,     /* nonzero if we should use the paginator */
1341         int height,     /* screen height to use */
1342         int starting_lp,/* starting value for lines_printed, -1 for global */
1343         int subst)      /* nonzero if we should use hypertext mode */
1344 {
1345         char *buffer = NULL;    /* The current message */
1346         char *word = NULL;      /* What we are about to actually print */
1347         char *e;                /* Pointer to position in text */
1348         char old = 0;           /* The previous character */
1349         int column = 0;         /* Current column */
1350         size_t i;               /* Generic counter */
1351
1352         /* Space for a single word, which can be at most screenwidth */
1353         word = (char *)calloc(1, width);
1354         if (!word) {
1355                 err_printf("Can't alloc memory to print message: %s!\n",
1356                                 strerror(errno));
1357                 logoff(NULL, 3);
1358         }
1359
1360         /* Read the entire message body into memory */
1361         if (fpin) {
1362                 buffer = load_message_from_file(fpin);
1363                 if (!buffer) {
1364                         err_printf("Can't print message: %s!\n",
1365                                         strerror(errno));
1366                         logoff(NULL, 3);
1367                 }
1368         } else {
1369                 buffer = text;
1370         }
1371         e = buffer;
1372
1373         if (starting_lp >= 0)
1374                 lines_printed = starting_lp;
1375
1376         /* Run the message body */
1377         while (*e) {
1378                 /* Catch characters that shouldn't be there at all */
1379                 if (*e == '\r') {
1380                         e++;
1381                         continue;
1382                 }
1383                 /* First, are we looking at a newline? */
1384                 if (*e == '\n') {
1385                         e++;
1386                         if (*e == ' ') {        /* Paragraph */
1387                                 if (fpout) {
1388                                         fprintf(fpout, "\n");
1389                                 } else {
1390                                         scr_printf("\n");
1391                                         ++lines_printed;
1392                                         lines_printed = checkpagin(lines_printed, pagin, height);
1393                                 }
1394                                 column = 0;
1395                         } else if (old != ' ') {/* Don't print two spaces */
1396                                 if (fpout) {
1397                                         fprintf(fpout, " ");
1398                                 } else {
1399                                         scr_printf(" ");
1400                                 }
1401                                 column++;
1402                         }
1403                         old = '\n';
1404                         continue;
1405                 }
1406
1407                 /* Are we looking at a nonprintable?
1408                  * (This section is now commented out because we could be displaying
1409                  * a character set like UTF-8 or ISO-8859-1.)
1410                 if ( (*e < 32) || (*e > 126) ) {
1411                         e++;
1412                         continue;
1413                 } */
1414
1415                 /* Or are we looking at a space? */
1416                 if (*e == ' ') {
1417                         e++;
1418                         if (column >= width - 1) {
1419                                 /* Are we in the rightmost column? */
1420                                 if (fpout) {
1421                                         fprintf(fpout, "\n");
1422                                 } else {
1423                                         scr_printf("\n");
1424                                         ++lines_printed;
1425                                         lines_printed = checkpagin(lines_printed, pagin, height);
1426                                 }
1427                                 column = 0;
1428                         } else if (!(column == 0 && old == ' ')) {
1429                                 /* Eat only the first space on a line */
1430                                 if (fpout) {
1431                                         fprintf(fpout, " ");
1432                                 } else {
1433                                         scr_printf(" ");
1434                                 }
1435                                 column++;
1436                         }
1437                         /* ONLY eat the FIRST space on a line */
1438                         old = ' ';
1439                         continue;
1440                 }
1441                 old = *e;
1442
1443                 /* Read a word, slightly messy */
1444                 i = 0;
1445                 while (e[i]) {
1446                         if (!isprint(e[i]) && !isspace(e[i]))
1447                                 e[i] = ' ';
1448                         if (isspace(e[i]))
1449                                 break;
1450                         i++;
1451                 }
1452
1453                 /* We should never see these, but... slightly messy */
1454                 if (e[i] == '\t' || e[i] == '\f' || e[i] == '\v')
1455                         e[i] = ' ';
1456
1457                 /* Break up really long words */
1458                 /* TODO: auto-hyphenation someday? */
1459                 if (i >= width) 
1460                         i = width - 1;
1461                 strncpy(word, e, i);
1462                 word[i] = 0;
1463
1464                 /* Decide where to print the word */
1465                 if (column + i >= width) {
1466                         /* Wrap to the next line */
1467                         if (fpout) {
1468                                 fprintf(fpout, "\n");
1469                         } else {
1470                                 scr_printf("\n");
1471                                 ++lines_printed;
1472                                 lines_printed = checkpagin(lines_printed, pagin, height);
1473                         }
1474                         column = 0;
1475                 }
1476
1477                 /* Print the word */
1478                 if (fpout) {
1479                         fprintf(fpout, "%s", word);
1480                 } else {
1481                         scr_printf("%s", word);
1482                 }
1483                 column += i;
1484                 e += i;         /* Start over with the whitepsace! */
1485         }
1486
1487         free(word);
1488         if (fpin)               /* We allocated this, remember? */
1489                 free(buffer);
1490
1491         /* Is this necessary?  It makes the output kind of spacey. */
1492         if (fpout) {
1493                 fprintf(fpout, "\n");
1494         } else {
1495                 scr_printf("\n");
1496                 ++lines_printed;
1497                 lines_printed = checkpagin(lines_printed, pagin, height);
1498         }
1499
1500         return sigcaught;
1501 }
1502
1503
1504 /*
1505  * support ANSI color if defined
1506  */
1507 void color(int colornum)
1508 {
1509         static int hold_color;
1510         static int current_color;
1511
1512         if (colornum == COLOR_PUSH) {
1513                 hold_color = current_color;
1514                 return;
1515         }
1516
1517         if (colornum == COLOR_POP) {
1518                 color(hold_color);
1519                 return;
1520         }
1521
1522         current_color = colornum;
1523         if (enable_color) {
1524 #if defined(HAVE_CURSES_H) && !defined(DISABLE_CURSES)
1525                 if (scr_color(colornum))
1526                         return;
1527 #endif
1528                 /* When switching to dim white, actually output an 'original
1529                  * pair' sequence -- this looks better on black-on-white
1530                  * terminals. - Changed to ORIGINAL_PAIR as this actually
1531                  * wound up looking horrible on black-on-white terminals, not
1532                  * to mention transparent terminals.
1533                  */
1534                 if (colornum == ORIGINAL_PAIR)
1535                         printf("\033[0;39;49m");
1536                 else
1537                         printf("\033[%d;3%d;4%dm", 
1538                                         (colornum & 8) ? 1 : 0,
1539                                         (colornum & 7),
1540                                         rc_color_use_bg);
1541
1542                 scr_flush();
1543         }
1544 }
1545
1546 void cls(int colornum)
1547 {
1548         if (enable_color) {
1549                 printf("\033[4%dm\033[2J\033[H\033[0m",
1550                                 colornum ? colornum : rc_color_use_bg);
1551                 scr_flush();
1552         }
1553 }
1554
1555
1556 /*
1557  * Detect whether ANSI color is available (answerback)
1558  */
1559 void send_ansi_detect(void)
1560 {
1561         if (rc_ansi_color == 2) {
1562                 printf("\033[c");
1563                 scr_flush();
1564                 time(&AnsiDetect);
1565         }
1566 }
1567
1568 void look_for_ansi(void)
1569 {
1570         fd_set rfds;
1571         struct timeval tv;
1572         char abuf[512];
1573         time_t now;
1574         int a, rv;
1575
1576         if (rc_ansi_color == 0) {
1577                 enable_color = 0;
1578         } else if (rc_ansi_color == 1) {
1579                 enable_color = 1;
1580         } else if (rc_ansi_color == 2) {
1581
1582                 /* otherwise, do the auto-detect */
1583
1584                 strcpy(abuf, "");
1585
1586                 time(&now);
1587                 if ((now - AnsiDetect) < 2)
1588                         sleep(1);
1589
1590                 do {
1591                         FD_ZERO(&rfds);
1592                         FD_SET(0, &rfds);
1593                         tv.tv_sec = 0;
1594                         tv.tv_usec = 1;
1595
1596                         select(1, &rfds, NULL, NULL, &tv);
1597                         if (FD_ISSET(0, &rfds)) {
1598                                 abuf[strlen(abuf) + 1] = 0;
1599                                 rv = read(0, &abuf[strlen(abuf)], 1);
1600                         }
1601                 } while (FD_ISSET(0, &rfds));
1602
1603                 for (a = 0; !IsEmptyStr(&abuf[a]); ++a) {
1604                         if ((abuf[a] == 27) && (abuf[a + 1] == '[')
1605                             && (abuf[a + 2] == '?')) {
1606                                 enable_color = 1;
1607                         }
1608                 }
1609         }
1610 }
1611
1612
1613 /*
1614  * Display key options (highlight hotkeys inside angle brackets)
1615  */
1616 void keyopt(char *buf) {
1617         int i;
1618
1619         color(DIM_WHITE);
1620         for (i=0; !IsEmptyStr(&buf[i]); ++i) {
1621                 if (buf[i]=='<') {
1622                         pprintf("%c", buf[i]);
1623                         color(BRIGHT_MAGENTA);
1624                 } else {
1625                         if (buf[i]=='>'&& buf[i+1] != '>') {
1626                                 color(DIM_WHITE);
1627                         }
1628                         pprintf("%c", buf[i]);
1629                 }
1630         }
1631         color(DIM_WHITE);
1632 }
1633
1634
1635
1636 /*
1637  * Present a key-menu line choice type of thing
1638  */
1639 char keymenu(char *menuprompt, char *menustring) {
1640         int i, c, a;
1641         int choices;
1642         int do_prompt = 0;
1643         char buf[1024];
1644         int ch;
1645         int display_prompt = 1;
1646
1647         choices = num_tokens(menustring, '|');
1648
1649         if (menuprompt != NULL) do_prompt = 1;
1650         if ((menuprompt != NULL) && (IsEmptyStr(menuprompt))) do_prompt = 0;
1651
1652         while (1) {
1653                 if (display_prompt) {
1654                         if (do_prompt) {
1655                                 scr_printf("%s ", menuprompt);
1656                         } 
1657                         else {
1658                                 for (i=0; i<choices; ++i) {
1659                                         extract_token(buf, menustring, i, '|', sizeof buf);
1660                                         keyopt(buf);
1661                                         scr_printf(" ");
1662                                 }
1663                         }
1664                         scr_printf("-> ");
1665                         display_prompt = 0;
1666                 }
1667                 ch = lkey();
1668         
1669                 if ( (do_prompt) && (ch=='?') ) {
1670                         scr_printf("\rOne of...                               ");
1671                         scr_printf("                                      \n");
1672                         for (i=0; i<choices; ++i) {
1673                                 extract_token(buf, menustring, i, '|', sizeof buf);
1674                                 scr_printf("   ");
1675                                 keyopt(buf);
1676                                 scr_printf("\n");
1677                         }
1678                         scr_printf("\n");
1679                         display_prompt = 1;
1680                 }
1681
1682                 for (i=0; i<choices; ++i) {
1683                         extract_token(buf, menustring, i, '|', sizeof buf);
1684                         for (c=1; !IsEmptyStr(&buf[c]); ++c) {
1685                                 if ( (ch == tolower(buf[c]))
1686                                    && (buf[c-1]=='<')
1687                                    && (buf[c+1]=='>') ) {
1688                                         for (a=0; !IsEmptyStr(&buf[a]); ++a) {
1689                                                 if ( (a!=(c-1)) && (a!=(c+1))) {
1690                                                         scr_putc(buf[a]);
1691                                                 }
1692                                         }
1693                                         scr_printf("\n");
1694                                         return ch;
1695                                 }
1696                         }
1697                 }
1698         }
1699 }