Sunday, March 25, 2018

text based user interface: termbox tutorial - 2. draw box

From the previous post, "text based user interface: termbox tutorial - 1. hello-world.c". I had shown how to add pretty text and how to capsule the text with color.

Now I am showing how to draw box surround the text, same method can be applied to draw a frame.

Let me show the whole code first.

 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
#include <stdio.h>
#include <string.h>
#include "../termbox.h"

static const char chars[] = "hello world";

int main(int argv, char **argc) {
 (void)argc; (void)argv;
 int code = tb_init();
 if (code < 0) {
  fprintf(stderr, "termbox init failed, code: %d\n", code);
  return -1;
 }

 tb_select_input_mode(TB_INPUT_ESC);
 tb_select_output_mode(TB_OUTPUT_NORMAL);
 tb_clear();
 
 int i, j=0;
 
 while(chars[j] != 0) {
   tb_change_cell(j+1, 1, chars[j], TB_BLUE, TB_DEFAULT);
   j++;
 }

 tb_change_cell(0, 0, 0x250C, TB_BLUE, TB_DEFAULT);
 tb_change_cell(12, 0, 0x2510, TB_BLUE, TB_DEFAULT);
 tb_change_cell(0, 2, 0x2514, TB_BLUE, TB_DEFAULT);
 tb_change_cell(12, 2, 0x2518, TB_BLUE, TB_DEFAULT);
 
 for (i = 1; i < 12; ++i) {
  tb_change_cell(i, 0, 0x2500, TB_BLUE, TB_DEFAULT);
  tb_change_cell(i, 2, 0x2500, TB_BLUE, TB_DEFAULT);
 }

 for (i = 1; i < 2; ++i) {
  tb_change_cell(0, i, 0x2502, TB_BLUE, TB_DEFAULT);
  tb_change_cell(12, i, 0x2502, TB_BLUE, TB_DEFAULT);
 }

 tb_present();
 
 while(1) {
  struct tb_event ev;
  tb_poll_event(&ev);

  if (ev.key == TB_KEY_ESC) {
   tb_shutdown();
   return 0;
  }
 }
}

The result:

Simple, but how many lines of codes are needed.
First, I had to print the hello world
while(chars[j] != 0) {
tb_change_cell(j+1, 1, chars[j], TB_BLUE, TB_DEFAULT);
j++;
}

secondly,  draw the four corner using extend ascii
tb_change_cell(0, 0, 0x250C, TB_BLUE, TB_DEFAULT);
tb_change_cell(12, 0, 0x2510, TB_BLUE, TB_DEFAULT);
tb_change_cell(0, 2, 0x2514, TB_BLUE, TB_DEFAULT);
tb_change_cell(12, 2, 0x2518, TB_BLUE, TB_DEFAULT);
0x250C =┌
0x2510 = ┐
0x2514 = └
0x2518 = 
Reference ASCII code for box drawing

thirdly, draw the vertical line on both side.
for (i = 1; i < 2; ++i) {
tb_change_cell(0, i, 0x2502, TB_BLUE, TB_DEFAULT);
tb_change_cell(12, i, 0x2502, TB_BLUE, TB_DEFAULT);
}
0x2502 = │

fourthly, draw the horizontal line for top and bottom.
for (i = 1; i < 12; ++i) {
tb_change_cell(i, 0, 0x2500, TB_BLUE, TB_DEFAULT);
tb_change_cell(i, 2, 0x2500, TB_BLUE, TB_DEFAULT);
}
0x2500 = ─
 
For text UI, you need to do everything in code, compile, then run.
This is the only way you can see the output.
No add and drop features.

No comments:

Post a Comment