Commit bbcf9bf246ab575aeac5eebc2d10ff25cba63b26

antirez 2014-03-12T23:38:40

Scan codes debugging functionality. ./linenoise_example --scancodes

diff --git a/example.c b/example.c
index 5fdc9d1..90030ad 100644
--- a/example.c
+++ b/example.c
@@ -22,8 +22,11 @@ int main(int argc, char **argv) {
         if (!strcmp(*argv,"--multiline")) {
             linenoiseSetMultiLine(1);
             printf("Multi-line mode enabled.\n");
+        } else if (!strcmp(*argv,"--scancodes")) {
+            linenoisePrintScanCodes();
+            exit(0);
         } else {
-            fprintf(stderr, "Usage: %s [--multiline]\n", prgname);
+            fprintf(stderr, "Usage: %s [--multiline] [--scancodes]\n", prgname);
             exit(1);
         }
     }
diff --git a/linenoise.c b/linenoise.c
index f0b1c63..8e6234d 100644
--- a/linenoise.c
+++ b/linenoise.c
@@ -795,6 +795,33 @@ static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen, 
     return l.len;
 }
 
+/* This special mode is used by linenoise in order to print scan codes
+ * on screen for debugging / development purposes. It is implemented
+ * by the linenoise_example program using the --scancodes option. */
+void linenoisePrintScanCodes(void) {
+    char quit[4];
+
+    printf("Linenoise scan codes debugging mode.\n"
+            "Press keys to see scan codes. Type 'quit' at any time to exit.\n");
+    if (enableRawMode(STDIN_FILENO) == -1) return;
+    memset(quit,' ',4);
+    while(1) {
+        char c;
+        int nread;
+
+        nread = read(STDIN_FILENO,&c,1);
+        if (nread <= 0) continue;
+        memmove(quit,quit+1,sizeof(quit)-1); /* shift string to left. */
+        quit[sizeof(quit)-1] = c; /* Insert current char on the right. */
+        if (memcmp(quit,"quit",sizeof(quit)) == 0) break;
+
+        printf("%02x (%d) (type quit to exit)\n", (int)c, (int)c);
+        printf("\x1b[0G"); /* Go left edge manually, we are in raw mode. */
+        fflush(stdout);
+    }
+    disableRawMode(STDIN_FILENO);
+}
+
 /* This function calls the line editing function linenoiseEdit() using
  * the STDIN file descriptor set in raw mode. */
 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
diff --git a/linenoise.h b/linenoise.h
index 9549c91..b767774 100644
--- a/linenoise.h
+++ b/linenoise.h
@@ -57,6 +57,7 @@ int linenoiseHistorySave(const char *filename);
 int linenoiseHistoryLoad(const char *filename);
 void linenoiseClearScreen(void);
 void linenoiseSetMultiLine(int ml);
+void linenoisePrintScanCodes(void);
 
 #ifdef __cplusplus
 }