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
|
#define _GNU_SOURCE
#include <iostream>
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <unistd.h>
#include "screenbuffer.h"
using namespace std;
static void initTerminal(){
cout<<"\x1B[?1049h" // start alternate screen
"\x1B[2J" // clear screen
"\x1B[H" // move to top left
<<flush;
}
static void deinitTerminal(){
cout<<"\x1B[?1049l" // end alternate screen
<<flush;
}
ScreenBuffer::ScreenBuffer(int W,int H)
:W(W),H(H){
screen=new char[W*H];
prevscreen=new char[W*H];
memset(screen,' ',W*H);
memset(prevscreen,' ',W*H);
initTerminal();
}
ScreenBuffer::~ScreenBuffer(){
delete[] screen;
delete[] prevscreen;
deinitTerminal();
}
void ScreenBuffer::moveto(int x,int y){
assert(x>=0&&x<W&&y>=0&&y<H);
curx=x;
cury=y;
}
void ScreenBuffer::printstr(const char *buf){
int basex=curx;
for(int i=0;buf[i];i++){
if(buf[i]!='\n'){
if(curx==W){
if(cury==H-1){
curx--;
break;
}
curx=basex;
cury++;
}
screen[W*cury+curx]=buf[i];
curx++;
} else {
if(cury==H-1)break;
curx=basex;
}
}
if(curx==W){
if(cury==H-1){
curx--;
} else {
curx=basex;
cury++;
}
}
}
int ScreenBuffer::printf_varargs(const char *format,va_list ap){
char *buf;
int ret=vasprintf(&buf,format,ap);
assert(buf);
printstr(buf);
free(buf);
return ret;
}
__attribute__((format (printf, 2, 3)))
int ScreenBuffer::printf(const char *format,...){
va_list ap;
va_start(ap,format);
int ret=printf_varargs(format,ap);
va_end(ap);
return ret;
}
__attribute__((format (printf, 4, 5)))
int ScreenBuffer::mvprintf(int x,int y,const char *format,...){
moveto(x,y);
va_list ap;
va_start(ap,format);
int ret=printf_varargs(format,ap);
va_end(ap);
return ret;
}
void ScreenBuffer::draw(){
bool changed[W*H];
for(int i=0;i<W*H;i++){
changed[i]=screen[i]!=prevscreen[i];
}
for(int y=0;y<H;y++){
for(int x=1;x<W-1;x++){
changed[W*y+x]|=changed[W*y+x-1]&changed[W*y+x+1];
}
}
bool prepped=false;
for(int y=0;y<H;y++){
bool needtomove=true;
for(int x=0;x<W;x++){
if(!changed[W*y+x]){
needtomove=true;
continue;
}
if(!prepped){
cout<<"\x1B[?25l"; // invisible cursor
prepped=true;
}
if(needtomove){
cout<<"\x1B["<<y+1<<';'<<x+1<<'H';
needtomove=false;
}
cout.put(screen[W*y+x]);
}
}
if(prepped){
cout<<"\x1B[?12;25h" // visible cursor
<<"\x1B["<<H<<';'<<W<<'H' // move past screen
<<flush;
}
memcpy(prevscreen,screen,W*H);
}
void ScreenBuffer::emergencyDeinit(){
static const char *str="\n\x1B[?1049l\x1B[12;25h^C\n";
write(1,str,strlen(str));
}
|