RichString.c 1.74 KB
Newer Older
Hisham Muhammad's avatar
Hisham Muhammad committed
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

#include "RichString.h"

#include <stdlib.h>
#include <string.h>
#include <curses.h>

#include "debug.h"
#include <assert.h>

#define RICHSTRING_MAXLEN 300

/*{

typedef struct RichString_ {
   int len;
   chtype chstr[RICHSTRING_MAXLEN+1];
} RichString;

}*/

#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif

/* private property */
WINDOW* workArea = NULL;

RichString RichString_new() {
   RichString this;
   this.len = 0;
   return this;
}

void RichString_delete(RichString this) {
}

void RichString_prune(RichString* this) {
   this->len = 0;
}

void RichString_write(RichString* this, int attrs, char* data) {
   this->len = 0;
   RichString_append(this, attrs, data);
}

inline void RichString_append(RichString* this, int attrs, char* data) {
   RichString_appendn(this, attrs, data, strlen(data));
}

inline void RichString_appendn(RichString* this, int attrs, char* data, int len) {
   if (!workArea) {
      workArea = newpad(1, RICHSTRING_MAXLEN);
   }
   assert(workArea);
   wattrset(workArea, attrs);
   int maxToWrite = (RICHSTRING_MAXLEN - 1) - this->len;
   int wrote = MIN(maxToWrite, len);
   mvwaddnstr(workArea, 0, 0, data, maxToWrite);
   int oldstrlen = this->len;
   this->len += wrote;
   mvwinchnstr(workArea, 0, 0, this->chstr + oldstrlen, wrote);
   wattroff(workArea, attrs);
}

void RichString_setAttr(RichString *this, int attrs) {
   for (int i = 0; i < this->len; i++) {
      char c = this->chstr[i];
      this->chstr[i] = c | attrs;
   }
}

void RichString_applyAttr(RichString *this, int attrs) {
   for (int i = 0; i < this->len - 1; i++) {
      this->chstr[i] |= attrs;
   }
}

RichString RichString_quickString(int attrs, char* data) {
   RichString str = RichString_new();
   RichString_write(&str, attrs, data);
   return str;
}