Browse Source

possibility to update the write line before longer pauses

Kajetan Johannes Hammerle 5 months ago
parent
commit
5d832b3dab
2 changed files with 20 additions and 9 deletions
  1. 5 3
      Main.cpp
  2. 15 6
      RawReader.h

+ 5 - 3
Main.cpp

@@ -4,14 +4,16 @@
 #include "RawReader.h"
 
 int main() {
-    RawReader<10, 5> reader(1);
+    RawReader<10, 5> reader(0, "> ");
 
     while(reader.canRead()) {
         // simulate work between reads
+        std::cout << "Work 1\n";
+        reader.updateLine();
         usleep(50000);
-        //std::cout << "Work\n";
+        std::cout << "Work 2\n";
 
-        const char* s = reader.readLine("> ");
+        const char* s = reader.readLine();
         if(s != nullptr) {
             std::cout << s << "\n";
             if(strcmp(s, "q") == 0) {

+ 15 - 6
RawReader.h

@@ -10,21 +10,25 @@
 template<int N, int H>
 class RawReader final {
     struct termios original;
+    
     int index;
     char buffer[2][N];
     bool bufferIndex;
     bool noError;
     int move;
+    
     char history[H][N];
     int historyOffset;
     int historyIndex;
     int historyLength;
+    
+    const char* prefix;
 
 public:
     typedef int DeciSeconds;
 
-    RawReader(DeciSeconds timeout) : index(0), bufferIndex(false), noError(true), move(0),
-    historyOffset(0), historyIndex(0), historyLength(0) {
+    RawReader(DeciSeconds timeout, const char* prefix) : index(0), bufferIndex(false), noError(true), move(0),
+    historyOffset(0), historyIndex(0), historyLength(0), prefix(prefix) {
         // https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html
         if(tcgetattr(STDIN_FILENO, &original) == -1) {
             markError();
@@ -63,8 +67,8 @@ public:
         return noError;
     }
 
-    const char* readLine(const char* prefix) {
-        refreshLine(prefix);
+    const char* readLine() {
+        refreshLine();
         while(true) {
             char c = 0;
             int bytes = read(STDIN_FILENO, &c, 1);
@@ -85,12 +89,17 @@ public:
             } else {
                 addChar(c);
             }
-            refreshLine(prefix);
+            refreshLine();
         }
         clearLine();
         return nullptr;
     }
 
+    void updateLine() {
+        refreshLine();
+        clearLine();
+    }
+
 private:
 
     void print(const char* s) {
@@ -112,7 +121,7 @@ private:
         return buffer[!bufferIndex];
     }
 
-    void refreshLine(const char* prefix) {
+    void refreshLine() {
         clearLine();
         print(prefix);
         print(buffer[bufferIndex]);