]> icculus.org git repositories - btb/d2x.git/blob - main/console.c
unused
[btb/d2x.git] / main / console.c
1 /*
2  *  Code for controlling the console
3  *  Based on an early version of SDL_Console
4  *
5  *  Written By: Garrett Banuk <mongoose@mongeese.org>
6  *  Code Cleanup and heavily extended by: Clemens Wacha <reflex-2000@gmx.net>
7  *  Ported to use native Descent interfaces by: Bradley Bell <btb@icculus.org>
8  *
9  *  This is free, just be sure to give us credit when using it
10  *  in any of your programs.
11  */
12
13 #ifdef HAVE_CONFIG_H
14 #include <conf.h>
15 #endif
16
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <stdarg.h>
21 #ifndef _WIN32_WCE
22 #include <fcntl.h>
23 #endif
24 #include <ctype.h>
25 #include <unistd.h>
26
27 #include "inferno.h"
28 #include "u_mem.h"
29 #include "gr.h"
30 #include "key.h"
31 #include "timer.h"
32 #include "pstypes.h"
33 #include "error.h"
34 #include "cfile.h"
35
36
37 #ifndef __MSDOS__
38 int text_console_enabled = 1;
39 #else
40 int isvga();
41 #define text_console_enabled (!isvga())
42 #endif
43
44
45 /* How discriminating we are about which messages are displayed */
46 cvar_t con_threshold = {"con_threshold", "0",};
47
48 #define CON_BG_HIRES (cfexist("scoresb.pcx")?"scoresb.pcx":"scores.pcx")
49 #define CON_BG_LORES (cfexist("scores.pcx")?"scores.pcx":"scoresb.pcx") // Mac datafiles only have scoresb.pcx
50 #define CON_BG ((SWIDTH>=640)?CON_BG_HIRES:CON_BG_LORES)
51
52 #define CON_NUM_LINES           128
53 // Cut the buffer line if it becomes longer than this
54 #define CON_CHARS_PER_LINE      128
55 // Border in pixels from the most left to the first letter
56 #define CON_CHAR_BORDER         4
57 // Spacing in pixels between lines
58 #define CON_LINE_SPACE          1
59 // Scroll this many lines at a time (when pressing PGUP or PGDOWN)
60 #define CON_LINE_SCROLL         2
61 // Indicator showing that you scrolled up the history
62 #define CON_SCROLL_INDICATOR    "^"
63 // Defines the default hide key (Hide() the console if pressed)
64 #define CON_DEFAULT_HIDEKEY     KEY_LAPOSTRO
65 // Defines the opening/closing speed
66 #define CON_OPENCLOSE_SPEED 50
67
68
69 /* The console's data */
70 static int Visible;             // Enum that tells which visible state we are in CON_HIDE, CON_SHOW, CON_RAISE, CON_LOWER
71 static int RaiseOffset;         // Offset used when scrolling in the console
72 static int HideKey;             // The key that can hide the console
73 static char **ConsoleLines;     // List of all the past lines
74 static int TotalConsoleLines;   // Total number of lines in the console
75 static int ConsoleScrollBack;   // How much the user scrolled back in the console
76 static int LineBuffer;          // The number of visible lines in the console (autocalculated)
77 static int VChars;              // The number of visible characters in one console line (autocalculated)
78 static grs_canvas *ConsoleSurface;  // Canvas of the console
79 static grs_bitmap *BackgroundImage; // Background image for the console
80 static grs_bitmap *InputBackground; // Dirty rectangle to draw over behind the users background
81
82 /* console is ready to be written to */
83 static int con_initialized;
84
85
86 /* Internals */
87 static void con_update_offset(void);
88 /* Frees all the memory loaded by the console */
89 static void con_free(void);
90 static int con_background(grs_bitmap *image);
91 /* Sets font info for the console */
92 static void con_font(grs_font *font, int fg, int bg);
93 /* makes newline (same as printf("\n") or CON_Out("\n") ) */
94 static void con_newline(void);
95 /* updates console after resize etc. */
96 static void con_update(void);
97 /* Called if you press Ctrl-L (deletes the History) */
98 static void con_clear(void);
99
100
101 /* Takes keys from the keyboard and inputs them to the console
102  * If the event was not handled (i.e. WM events or unknown ctrl-shift
103  * sequences) the function returns the event for further processing. */
104 int con_key_handler(int key)
105 {
106         unsigned char character = key_to_ascii(key);
107
108         if (!con_is_visible())
109                 return key;
110
111         if (key == HideKey) {
112                 // deactivate Console
113                 con_hide();
114                 return 0;
115         }
116
117         switch (key) {
118                 case KEY_SHIFTED + KEY_ESC:
119                         con_hide();
120                         break;
121                 case KEY_CTRLED + KEY_L:
122                         con_clear();
123                         con_update();
124                         break;
125                 case KEY_SHIFTED + KEY_HOME:
126                         ConsoleScrollBack = LineBuffer-1;
127                         con_update();
128                         break;
129                 case KEY_SHIFTED + KEY_END:
130                         ConsoleScrollBack = 0;
131                         con_update();
132                         break;
133                 case KEY_PAGEUP:
134                         ConsoleScrollBack += CON_LINE_SCROLL;
135                         if(ConsoleScrollBack > LineBuffer-1)
136                                 ConsoleScrollBack = LineBuffer-1;
137                         con_update();
138                         break;
139                 case KEY_PAGEDOWN:
140                         ConsoleScrollBack -= CON_LINE_SCROLL;
141                         if(ConsoleScrollBack < 0)
142                                 ConsoleScrollBack = 0;
143                         con_update();
144                         break;
145                 case KEY_CTRLED + KEY_A:
146                 case KEY_HOME:              cli_cursor_home();      break;
147                 case KEY_END:
148                 case KEY_CTRLED + KEY_E:    cli_cursor_end();       break;
149                 case KEY_CTRLED + KEY_C:    cli_clear();            break;
150                 case KEY_LEFT:              cli_cursor_left();      break;
151                 case KEY_RIGHT:             cli_cursor_right();     break;
152                 case KEY_BACKSP:            cli_cursor_backspace(); break;
153                 case KEY_CTRLED + KEY_D:
154                 case KEY_DELETE:            cli_cursor_del();       break;
155                 case KEY_UP:                cli_history_prev();     break;
156                 case KEY_DOWN:              cli_history_next();     break;
157                 case KEY_TAB:               cli_autocomplete();     break;
158                 case KEY_ENTER:             cli_execute();          break;
159                 case KEY_INSERT:
160                         CLI_insert_mode = !CLI_insert_mode;
161                         break;
162                 default:
163                         if (character == 255)
164                                 break;
165                         cli_add_character(character);
166                         break;
167         }
168         return 0;
169 }
170
171
172 /* Updates the console buffer */
173 static void con_update(void)
174 {
175         int loop;
176         int loop2;
177         int Screenlines;
178         grs_canvas *canv_save;
179
180         /* Due to the Blits, the update is not very fast: So only update if it's worth it */
181         if (!con_is_visible())
182                 return;
183
184         Screenlines = ConsoleSurface->cv_h / (CON_LINE_SPACE + ConsoleSurface->cv_font->ft_h);
185
186         canv_save = grd_curcanv;
187         gr_set_current_canvas(ConsoleSurface);
188
189         /* draw the background image if there is one */
190         if (BackgroundImage)
191                 gr_bitmap(0, 0, BackgroundImage);
192
193         // now draw text from last but second line to top
194         for (loop = 0; loop < Screenlines-1 && loop < LineBuffer - ConsoleScrollBack; loop++) {
195                 if (ConsoleScrollBack != 0 && loop == 0)
196                         for (loop2 = 0; loop2 < (VChars / 5) + 1; loop2++)
197                         {
198                                 gr_string(CON_CHAR_BORDER + (loop2*5*ConsoleSurface->cv_font->ft_w), (Screenlines - loop - 2) * (CON_LINE_SPACE + ConsoleSurface->cv_font->ft_h), CON_SCROLL_INDICATOR);
199                         }
200                 else
201                 {
202                         gr_string(CON_CHAR_BORDER, (Screenlines - loop - 2) * (CON_LINE_SPACE + ConsoleSurface->cv_font->ft_h), ConsoleLines[ConsoleScrollBack + loop]);
203                 }
204         }
205
206         gr_set_current_canvas(canv_save);
207 }
208
209
210 static void con_update_offset(void)
211 {
212         switch (Visible) {
213                 case CON_CLOSING:
214                         RaiseOffset -= CON_OPENCLOSE_SPEED;
215                         if(RaiseOffset <= 0) {
216                                 RaiseOffset = 0;
217                                 Visible = CON_CLOSED;
218                         }
219                         break;
220                 case CON_OPENING:
221                         RaiseOffset += CON_OPENCLOSE_SPEED;
222                         if(RaiseOffset >= ConsoleSurface->cv_h) {
223                                 RaiseOffset = ConsoleSurface->cv_h;
224                                 Visible = CON_OPEN;
225                         }
226                         break;
227                 case CON_OPEN:
228                 case CON_CLOSED:
229                         break;
230         }
231 }
232
233
234 /* Draws the console buffer to the screen if the console is "visible" */
235 void con_draw(void)
236 {
237         grs_canvas *canv_save;
238         grs_bitmap *clip;
239
240         /* only draw if console is visible: here this means, that the console is not CON_CLOSED */
241         if (Visible == CON_CLOSED)
242                 return;
243
244         /* Update the scrolling offset */
245         con_update_offset();
246
247         canv_save = grd_curcanv;
248
249         /* Update the command line since it has a blinking cursor */
250         gr_set_current_canvas(ConsoleSurface);
251
252         // restore InputBackground
253         gr_bitmap(0, ConsoleSurface->cv_h - ConsoleSurface->cv_font->ft_h, InputBackground);
254
255         cli_draw(ConsoleSurface->cv_h);
256
257         gr_set_current_canvas(&grd_curscreen->sc_canvas);
258
259         clip = gr_create_sub_bitmap(&ConsoleSurface->cv_bitmap, 0, ConsoleSurface->cv_h - RaiseOffset, ConsoleSurface->cv_w, RaiseOffset);
260
261         gr_bitmap(0, 0, clip);
262         gr_free_sub_bitmap(clip);
263
264         gr_set_current_canvas(canv_save);
265 }
266
267
268 /* Initializes the console */
269 void con_init()
270 {
271         int loop;
272
273         Visible = CON_CLOSED;
274         RaiseOffset = 0;
275         ConsoleLines = NULL;
276         TotalConsoleLines = 0;
277         ConsoleScrollBack = 0;
278         BackgroundImage = NULL;
279         HideKey = CON_DEFAULT_HIDEKEY;
280
281         /* load the console surface */
282         ConsoleSurface = NULL;
283
284         /* Load the dirty rectangle for user input */
285         InputBackground = NULL;
286
287         VChars = CON_CHARS_PER_LINE - 1;
288         LineBuffer = CON_NUM_LINES;
289
290         ConsoleLines = (char **)d_malloc(sizeof(char *) * LineBuffer);
291         for (loop = 0; loop <= LineBuffer - 1; loop++) {
292                 ConsoleLines[loop] = (char *)d_calloc(CON_CHARS_PER_LINE, sizeof(char));
293         }
294
295         cli_init();
296         cmd_init();
297
298         /* Initialise the cvars */
299         cvar_registervariable (&con_threshold);
300
301         con_initialized = 1;
302
303         atexit(con_free);
304 }
305
306
307 void gr_init_bitmap_alloc( grs_bitmap *bm, int mode, int x, int y, int w, int h, int bytesperline);
308 void con_init_gfx(int w, int h)
309 {
310         int pcx_error;
311         grs_bitmap bmp;
312         ubyte pal[256*3];
313
314         if (ConsoleSurface) {
315                 /* resize console surface */
316                 gr_free_bitmap_data(&ConsoleSurface->cv_bitmap);
317                 gr_init_bitmap_alloc(&ConsoleSurface->cv_bitmap, BM_LINEAR, 0, 0, w, h, w);
318         } else {
319                 /* load the console surface */
320                 ConsoleSurface = gr_create_canvas(w, h);
321         }
322
323         /* Load the consoles font */
324         con_font(SMALL_FONT, gr_find_closest_color(29,29,47), -1);
325
326         /* make sure that the size of the console is valid */
327         if (w > grd_curscreen->sc_w || w < ConsoleSurface->cv_font->ft_w * 32)
328                 w = grd_curscreen->sc_w;
329         if (h > grd_curscreen->sc_h || h < ConsoleSurface->cv_font->ft_h)
330                 h = grd_curscreen->sc_h;
331
332         /* Load the dirty rectangle for user input */
333         if (InputBackground)
334                 gr_free_bitmap(InputBackground);
335         InputBackground = gr_create_bitmap(w, ConsoleSurface->cv_font->ft_h);
336
337         /* calculate the number of visible characters in the command line */
338 #if 0 // doesn't work because proportional font
339         VChars = (w - CON_CHAR_BORDER) / ConsoleSurface->cv_font->ft_w;
340         if (VChars >= CON_CHARS_PER_LINE)
341                 VChars = CON_CHARS_PER_LINE - 1;
342 #endif
343
344         gr_init_bitmap_data(&bmp);
345         pcx_error = pcx_read_bitmap(CON_BG, &bmp, BM_LINEAR, pal);
346         Assert(pcx_error == PCX_ERROR_NONE);
347         gr_remap_bitmap_good(&bmp, pal, -1, -1);
348         con_background(&bmp);
349         gr_free_bitmap_data(&bmp);
350 }
351
352
353 /* Makes the console visible */
354 void con_show(void)
355 {
356         Visible = CON_OPENING;
357         con_update();
358 }
359
360
361 /* Hides the console (make it invisible) */
362 void con_hide(void)
363 {
364         Visible = CON_CLOSING;
365         key_flush();
366 }
367
368
369 /* tells wether the console is visible or not */
370 int con_is_visible(void)
371 {
372         return((Visible == CON_OPEN) || (Visible == CON_OPENING));
373 }
374
375
376 /* Frees all the memory loaded by the console */
377 static void con_free(void)
378 {
379         int i;
380
381         for (i = 0; i <= LineBuffer - 1; i++) {
382                 d_free(ConsoleLines[i]);
383         }
384         d_free(ConsoleLines);
385
386         ConsoleLines = NULL;
387
388         if (ConsoleSurface)
389                 gr_free_canvas(ConsoleSurface);
390         ConsoleSurface = NULL;
391
392         if (BackgroundImage)
393                 gr_free_bitmap(BackgroundImage);
394         BackgroundImage = NULL;
395
396         if (InputBackground)
397                 gr_free_bitmap(InputBackground);
398         InputBackground = NULL;
399
400         con_initialized = 0;
401 }
402
403
404 /* Increments the console lines */
405 static void con_newline(void)
406 {
407         int loop;
408         char *temp;
409
410         temp = ConsoleLines[LineBuffer - 1];
411
412         for (loop = LineBuffer - 1; loop > 0; loop--)
413                 ConsoleLines[loop] = ConsoleLines[loop - 1];
414
415         ConsoleLines[0] = temp;
416
417         memset(ConsoleLines[0], 0, CON_CHARS_PER_LINE);
418         if (TotalConsoleLines < LineBuffer - 1)
419                 TotalConsoleLines++;
420         
421         //Now adjust the ConsoleScrollBack
422         //dont scroll if not at bottom
423         if(ConsoleScrollBack != 0)
424                 ConsoleScrollBack++;
425         //boundaries
426         if(ConsoleScrollBack > LineBuffer-1)
427                 ConsoleScrollBack = LineBuffer-1;
428 }
429
430
431 static inline int con_get_width(void)
432 {
433         if (!ConsoleSurface)
434                 return 0;
435
436         return ConsoleSurface->cv_bitmap.bm_w - CON_CHAR_BORDER;
437 }
438
439
440 static inline int con_get_string_width(char *string)
441 {
442         grs_canvas *canv_save;
443         int w = 0, h, aw;
444
445         if (!ConsoleSurface)
446                 return 0;
447
448         canv_save = grd_curcanv;
449         gr_set_current_canvas(ConsoleSurface);
450         gr_get_string_size(string, &w, &h, &aw);
451         gr_set_current_canvas(canv_save);
452
453         return w;
454 }
455
456
457 #ifdef _MSC_VER
458 # define vsnprintf _vsnprintf
459 #endif
460
461 /* Outputs text to the console (in game), up to CON_CHARS_PER_LINE chars can be entered */
462 static void con_out(const char *str, ...)
463 {
464         va_list marker;
465         //keep some space free for stuff like CON_Out("blablabla %s", Command);
466         char temp[CON_CHARS_PER_LINE + 128];
467         char* ptemp;
468
469         va_start(marker, str);
470         vsnprintf(temp, CON_CHARS_PER_LINE + 127, str, marker);
471         va_end(marker);
472
473         ptemp = temp;
474
475         // temp now contains the complete string we want to output
476         // the only problem is that temp is maybe longer than the console
477         // width so we have to cut it into several pieces
478
479         if (ConsoleLines) {
480                 char *p = ptemp;
481
482                 while (*p) {
483                         if (*p == '\n') {
484                                 *p = '\0';
485                                 con_newline();
486                                 strcat(ConsoleLines[0], ptemp);
487                                 ptemp = p+1;
488                         } else if (p - ptemp > VChars - strlen(ConsoleLines[0]) ||
489                                            con_get_string_width(ptemp) > con_get_width()) {
490                                 con_newline();
491                                 strncat(ConsoleLines[0], ptemp, VChars - strlen(ConsoleLines[0]));
492                                 ConsoleLines[0][VChars] = '\0';
493                                 ptemp = p;
494                         }
495                         p++;
496                 }
497                 if (strlen(ptemp)) {
498                         strncat(ConsoleLines[0], ptemp, VChars - strlen(ConsoleLines[0]));
499                         ConsoleLines[0][VChars] = '\0';
500                 }
501                 con_update();
502         }
503 }
504
505
506 /* Adds background image to the console, scaled to size of console*/
507 static int con_background(grs_bitmap *image)
508 {
509         /* Free the background from the console */
510         if (image == NULL) {
511                 if (BackgroundImage)
512                         gr_free_bitmap(BackgroundImage);
513                 BackgroundImage = NULL;
514                 return 0;
515         }
516
517         /* Load a new background */
518         if (BackgroundImage)
519                 gr_free_bitmap(BackgroundImage);
520         BackgroundImage = gr_create_bitmap(ConsoleSurface->cv_w, ConsoleSurface->cv_h);
521         gr_bitmap_scale_to(image, BackgroundImage);
522
523         gr_bm_bitblt(BackgroundImage->bm_w, InputBackground->bm_h, 0, 0, 0, ConsoleSurface->cv_h - ConsoleSurface->cv_font->ft_h, BackgroundImage, InputBackground);
524
525         return 0;
526 }
527
528
529 /* Sets font info for the console */
530 static void con_font(grs_font *font, int fg, int bg)
531 {
532         grs_canvas *canv_save;
533
534         canv_save = grd_curcanv;
535         gr_set_current_canvas(ConsoleSurface);
536         gr_set_curfont(font);
537         gr_set_fontcolor(fg, bg);
538         gr_set_current_canvas(canv_save);
539 }
540
541
542 static void con_clear(void)
543 {
544         int loop;
545         
546         for (loop = 0; loop <= LineBuffer - 1; loop++)
547                 memset(ConsoleLines[loop], 0, CON_CHARS_PER_LINE);
548 }
549
550
551 /* convert to ansi rgb colors 17-231 */
552 #define PAL2ANSI(x) ((36*gr_palette[(x)*3]/11) + (6*gr_palette[(x)*3+1]/11) + (gr_palette[(x)*3+2]/11) + 16)
553
554 /* Print a message to the console */
555 void con_printf(int priority, char *fmt, ...)
556 {
557         va_list arglist;
558         char buffer[2048];
559
560         if (priority <= (con_threshold.intval))
561         {
562                 va_start (arglist, fmt);
563                 vsprintf (buffer,  fmt, arglist);
564                 va_end (arglist);
565
566                 if (con_initialized)
567                         con_out(buffer);
568
569                 if (!text_console_enabled)
570                         return;
571
572                 if (isatty(fileno(stdout))) {
573                         char *buf, *p;
574                         unsigned char color, spacing, underline;
575
576                         p = buf = buffer;
577                         do
578                                 switch (*p)
579                                 {
580                                 case CC_COLOR:
581                                         *p++ = 0;
582                                         printf("%s", buf);
583                                         color = *p++;
584                                         printf("\x1B[38;5;%dm", PAL2ANSI(color));
585                                         buf = p;
586                                         break;
587                                 case CC_LSPACING:
588                                         *p++ = 0;
589                                         printf("%s", buf);
590                                         spacing = *p++;
591                                         //printf("<SPACING %d>", color);
592                                         buf = p;
593                                         break;
594                                 case CC_UNDERLINE:
595                                         *p++ = 0;
596                                         printf("%s", buf);
597                                         underline = 1;
598                                         //printf("<UNDERLINE>");
599                                         buf = p;
600                                         break;
601                                 default:
602                                         p++;
603                                 }
604                         while (*p);
605
606                         printf("%s", buf);
607
608                 } else {
609                         /* Produce a sanitised version and send it to the standard output */
610                         char *p1, *p2;
611
612                         p1 = p2 = buffer;
613                         do
614                                 switch (*p1)
615                                 {
616                                 case CC_COLOR:
617                                 case CC_LSPACING:
618                                         p1++;
619                                 case CC_UNDERLINE:
620                                         p1++;
621                                         break;
622                                 default:
623                                         *p2++ = *p1++;
624                                 }
625                         while (*p1);
626                         *p2 = 0;
627
628                         printf("%s", buffer);
629                 }
630         }
631 }