-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomTerminal.cpp
472 lines (365 loc) · 14.4 KB
/
CustomTerminal.cpp
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//********************************************************************
// Author: Lauro França (oPisiti) #
// Contact: #
// github: oPisiti #
// Email: [email protected] #
// Date: 2023 #
// Description: #
// A custom terminal emulator, using the OLC Pixel Game engine as #
// a framework #
//********************************************************************
#define OLC_PGE_APPLICATION
#include <chrono>
#include <filesystem>
#include "Font.h"
#include <fstream>
#include "KeysMap.h"
#include "olcPixelGameEngine.h"
#include <sstream>
#include <thread>
#include <vector>
#ifdef _WIN32
#define WINDOWS_OS true
const std::string CURR_DIR_COMMAND = "cd";
const std::string CURR_USER_COMMAND = "echo %username%";
#include <cstdint>
#else
#define WINDOWS_OS false
const std::string CURR_DIR_COMMAND = "pwd";
const std::string CURR_USER_COMMAND = "whoami";
#endif
// Returns the index in which the strings differ
// Returns -1 if equal
int CompareStrings(std::string sA, std::string sB){
int iSmallestSize = sA.size() > sB.size() ? sB.size() : sA.size();
for(int i = 0; i < iSmallestSize; i++){
if(sA[i] != sB[i]) return i;
}
return -1;
}
class CustomTerminal : public olc::PixelGameEngine {
private:
// Rendering
const olc::Pixel olcPBackColor = {50, 50, 50, 255};
const olc::Pixel olcPFontColor = olc::MAGENTA;
uint32_t iBaseCharPosX = 10, iBaseCharPosY = 10;
uint32_t iInitCharPosX = iBaseCharPosX, iInitCharPosY = iBaseCharPosY; // Offset to begin drawing the first character
int32_t iBeginRenderPosY = 0; // Rendering begins in this position. Changes when user scrolls
uint8_t iCharWidth = 8, iCharHeight = 8; // The grid in which to draw the pixels
uint8_t charac = 0, iCharScale = 1;
uint8_t iMinScale = 1, iMaxScale = 10; // For zooming
// Keys
std::vector<uint8_t> pressedKeys, heldKeys;
std::vector<std::string> history; // Contains all the typed information. Every command is stored one position of this vector
std::vector<std::string> sCommandsHistory; // Contains only the valid issued commands
std::string sUser = "", addChar; // Constant initial text on screen
std::string sWorkingDir = "";
bool bNewChar = false;
// Time and blinking
float fTimeCount; // Loops from 0 to fMaxTimeBlink
float fMaxTimeBlink = 0.75; // Intervals in which the blinking light turns on and off
uint8_t iBlinkChar = 3; // Which char (based on ascii) to
bool bDrawBlinker = true;
std::vector<uint32_t> blinkerPos = { iInitCharPosX, iInitCharPosY }; // Position to draw the blinker
// Commands to terminal
std::string sTmpOutputFileName = ".output.tmp";
std::string sTerminalOutput = "";
std::string sTmpUsernameFileName = ".username.tmp";
std::string sTmpWorkingDirFileName = ".currdir.tmp";
std::string sOnlyCommand;
bool bUserCommandBeingExecuted = false;
// Accessing history
int16_t iRelativeCommandsHistoryIndex = 0; // Which commands history index to show when up or down arrow is pressed. Relative to the last element
// IO monitoring
std::filesystem::file_time_type fLastModifiedTime, fCurrModifiedTime;
std::thread tMonitorStdout, tExecuteCommand;
public:
CustomTerminal() {
sAppName = "Custom Terminal";
}
~CustomTerminal(){
std::filesystem::remove(sTmpOutputFileName);
std::filesystem::remove(sTmpUsernameFileName);
std::filesystem::remove(sTmpWorkingDirFileName);
return;
}
// Draws a single character
void drawCharacter(int32_t x, int32_t y, uint8_t Char, olc::Pixel color = olc::RED) {
uint8_t curPosX, curPosY; // Positions inside the font matrix
int32_t screenX, screenY; // Positions regarding the screen pixels
for (int hei = 0; hei < iCharHeight; hei++) {
curPosY = hei;
screenY = y + hei * iCharScale;
for (int wid = 0; wid < iCharWidth; wid++) {
curPosX = wid;
screenX = x + wid * iCharScale;
// https://stackoverflow.com/questions/2249731/how-do-i-get-bit-by-bit-data-from-an-integer-value-in-c
if ((font[Char][curPosY] & (1 << curPosX)) >> curPosX) {
for (int i = 0; i < iCharScale; i++) {
for (int j = 0; j < iCharScale; j++) {
Draw(screenX + i, screenY + j, color);
}
}
}
}
}
}
// Draws a full string. If screen width not enough, jumps to next line
void drawString(int32_t initialX, int32_t initialY, std::string str, std::vector<uint32_t>& blinkerPos, uint32_t iBeginRenderPosY, olc::Pixel color = olc::RED) {
int screenWidth = ScreenWidth();
int32_t y = initialY;
int maxSingleLineChars = (screenWidth - initialX) / (iCharWidth * iCharScale);
int mod;
for (int elemNum = 0; elemNum < str.size(); elemNum++) {
// If screen space ends, jump to next line
mod = elemNum % maxSingleLineChars;
if (!mod && elemNum) {
y += iCharHeight * iCharScale;
}
// Too high up or down on screen space
if(y < 0) continue;
if(y > screenWidth) break;
drawCharacter(initialX + iCharWidth * mod * iCharScale, y, str[elemNum], color);
}
// Adjusting the blinker position
mod = str.size() % maxSingleLineChars;
if (!mod) {
y += iCharHeight * iCharScale;
}
blinkerPos = { initialX + uint32_t(iCharWidth * mod * iCharScale), uint32_t(y)};
}
// Executes a command to the appropriate terminal
// A temporary output file is used and then the contents are read and put into
void ExecuteCommand(std::string sCommand,
std::string sOutputFile,
std::string& sOutputString,
bool bMonitorExecution = false){
// Signaling the start of execution for the monitoring thread
if(bMonitorExecution) bUserCommandBeingExecuted = true;
sCommand = "cd \"" + sWorkingDir + "\" && " + sCommand + " > " + sOutputFile + " 2>&1";
sCommand += " && " + CURR_DIR_COMMAND + " > '" + sWorkingDir + "/" + sTmpWorkingDirFileName + "'";
std::system(sCommand.data());
if(bMonitorExecution) bUserCommandBeingExecuted = false;
}
// Copies the contents of a file into a string
void FileToVariable(std::string sFileName, std::string& sVariable){
// As reading a file (with rdbuf()) returns a stream, this intermediary step is required
std::stringstream buffer;
buffer << std::ifstream(sFileName).rdbuf();
sVariable = buffer.str();
}
// Returns the fix part of every new command line
std::string GetFixText(){
std::string ans = sUser + "@" + sWorkingDir + ": ";
return ans;
}
// Handling discrepancies between ASCII norm and what "GetAllKeys()" returns.
void HandleKeyPress(std::string& addChar, const std::vector<uint8_t>& pressedKeys) {
uint8_t iASCIIKey;
for (auto key : pressedKeys) {
// Default value
iASCIIKey = 0;
// Adjusting the key value
auto equivalent = valueInputKeys.find(key);
// Key found
if(equivalent != valueInputKeys.end()){
if(isShiftHeld()) iASCIIKey = equivalent->second.upper;
else iASCIIKey = equivalent->second.lower;
// Printable/supported char
bNewChar = true;
continue;
}
// Key not found -> Not a printable/supported char
bNewChar = false;
// ENTER
if (key == 66) {
// Executing the command and showing output
if(bUserCommandBeingExecuted){
std::cout << history.back() + "\x0D";
}
else{
// If a thread is called a second time without beeing joined , the program crashes
if(tExecuteCommand.joinable()) tExecuteCommand.join();
tExecuteCommand = std::thread(&CustomTerminal::ExecuteCommand,
this,
sOnlyCommand,
std::ref(sTmpOutputFileName),
std::ref(sTerminalOutput),
true);
}
// Dealing with the specific commands history vector
sCommandsHistory.push_back(sOnlyCommand);
sOnlyCommand.clear();
bNewChar = false;
}
// BACKSPACE
else if (key == 63) {
if (sOnlyCommand.size() > 0){
history.back().pop_back();
sOnlyCommand.pop_back();
}
bNewChar = false;
}
// ARROW KEYS
else if((key == 49 || key == 50) && history.size() > 1){
// UP ARROW
if(key == 49 && -iRelativeCommandsHistoryIndex < sCommandsHistory.size())
iRelativeCommandsHistoryIndex -= 1;
// DOWN ARROW
else if(key == 50 && iRelativeCommandsHistoryIndex < 0)
iRelativeCommandsHistoryIndex += 1;
// Action
if(iRelativeCommandsHistoryIndex == 0)
history.back() = GetFixText();
else {
sOnlyCommand = sCommandsHistory[sCommandsHistory.size() + iRelativeCommandsHistoryIndex];
history.back() = GetFixText() + sOnlyCommand;
}
}
}
if (bNewChar) {
// Resetting the count if user typed something - Prevents unnecessary blinking all the time (weird)
fTimeCount = 0.0f;
// The actual appending
history.back() += iASCIIKey;
sOnlyCommand += iASCIIKey;
}
}
// Handles new ouput in "sTmpOutputFileName" file
void HandleNewOuput(){
std::string sOldTerminalOutput, sNewData;
int iIndexStringDiffer;
// --- Comparing stdout' current version to sTerminalOutput ---
sOldTerminalOutput = sTerminalOutput;
FileToVariable(sTmpOutputFileName, sTerminalOutput);
iIndexStringDiffer = CompareStrings(sTerminalOutput, sOldTerminalOutput);
//--- Adding only the difference in strings ---
if(iIndexStringDiffer == -1){ // Strings are equal
sNewData = sTerminalOutput;
}
else{ // Unequal strings
if(sTerminalOutput.size() > sOldTerminalOutput.size()){
sNewData = sTerminalOutput.substr(iIndexStringDiffer);
}
else{
sNewData = sTerminalOutput;
}
}
history.push_back("");
for(auto c: sNewData){
if(c == '\n') history.push_back("");
else history.back() += c;
}
// If something is being executed, the new ouput is from a running system() call.
// Therefore, a new command line should not be appended
if(bUserCommandBeingExecuted) return;
history.push_back(GetFixText());
// Dealing with the specific commands history vector
iRelativeCommandsHistoryIndex = 0;
}
// Monitors stdout file for changes
void MonitorStdout(){
while(true){
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
fCurrModifiedTime = std::filesystem::last_write_time(sTmpOutputFileName);
// Something was written to stdout
if(fCurrModifiedTime > fLastModifiedTime){
HandleNewOuput();
fLastModifiedTime = fCurrModifiedTime;
}
}
}
// Updates the variable sUser
void UpdateUserString(){
ExecuteCommand(CURR_USER_COMMAND, sTmpUsernameFileName, sUser);
FileToVariable(sTmpUsernameFileName, sUser);
sUser = sUser.substr(0, sUser.length() - 1);
}
// Updates the variable sWorkingDir
void UpdateWorkingDirString(){
ExecuteCommand(CURR_DIR_COMMAND, sTmpWorkingDirFileName, sWorkingDir);
FileToVariable(sTmpWorkingDirFileName, sWorkingDir);
sWorkingDir = sWorkingDir.substr(0, sWorkingDir.length() - 1);
}
// Called once at the start, so create things here
bool OnUserCreate() override {
// Creating the tmp file
std::string sUseless;
if(!WINDOWS_OS) ExecuteCommand(">" + sTmpOutputFileName, sTmpOutputFileName, sUseless);
else{
ExecuteCommand("type nul >" + sTmpOutputFileName, sTmpOutputFileName, sUseless);
ExecuteCommand("type nul >" + sTmpUsernameFileName, sTmpOutputFileName, sUseless);
ExecuteCommand("type nul >" + sTmpWorkingDirFileName, sTmpOutputFileName, sUseless);
}
UpdateUserString();
UpdateWorkingDirString();
history.push_back(GetFixText());
// Getting the last modified time
fLastModifiedTime = std::filesystem::last_write_time(sTmpOutputFileName);
fCurrModifiedTime = fLastModifiedTime;
tMonitorStdout = std::thread(&CustomTerminal::MonitorStdout, this);
return true;
}
// Called once per frame
bool OnUserUpdate(float fElapsedTime) override {
Clear(olcPBackColor);
// Getting keys
pressedKeys = GetAllPressedKeys();
heldKeys = GetAllHeldKeys();
// Zooming - Each wheel tick equals 120 in value (??)
if (GetMouseWheel()) {
int wheel = GetMouseWheel() / 120;
// When zooming
if (std::find(heldKeys.begin(), heldKeys.end(), 56) != heldKeys.end()) { // 56: CTRL
iCharScale += wheel;
if (iCharScale < iMinScale) iCharScale = iMinScale;
else if (iCharScale > iMaxScale) iCharScale = iMaxScale;
}
// When scrolling
else{
int num = -wheel * iCharScale * iCharHeight;
if (num < 0) {
if (iBeginRenderPosY > iBaseCharPosX) iBeginRenderPosY += num;
else iBeginRenderPosY = 0;
}
else iBeginRenderPosY += num;
}
}
// Handling discrepancies between ASCII norm and what "GetAllKeys()" returns.
bNewChar = true;
if (pressedKeys.size() > 0) {
// Ctrl + C
if(std::find(heldKeys.begin(), heldKeys.end(), 56) != heldKeys.end() && // Ctrl
std::find(pressedKeys.begin(), pressedKeys.end(), 3) != pressedKeys.end()){ // c
return false;
}
HandleKeyPress(addChar, pressedKeys);
}
// Printing whole history
// Drawing the whole String. If only one character needed, try "drawCharacter"
for (int i = 0; i < history.size(); i++) {
drawString(iInitCharPosX,
i ? blinkerPos[1] + iCharHeight * iCharScale : blinkerPos[1] - iBeginRenderPosY,
history[i],
blinkerPos,
iBeginRenderPosY,
olcPFontColor);
}
// Blinking of last character
fTimeCount += fElapsedTime;
if (fTimeCount > fMaxTimeBlink) {
bDrawBlinker = !bDrawBlinker;
fTimeCount -= fMaxTimeBlink;
}
if (bDrawBlinker) drawCharacter(blinkerPos[0], blinkerPos[1], iBlinkChar, olcPFontColor);
// Resetting stuff
blinkerPos = { iInitCharPosX, iInitCharPosY };
return true;
}
};
int main(){
CustomTerminal CustomTerminal;
if (CustomTerminal.Construct(600, 500, 2, 2))
CustomTerminal.Start();
return 0;
}