-
Notifications
You must be signed in to change notification settings - Fork 869
/
TTYConsoleReader.java
executable file
·574 lines (506 loc) · 18.8 KB
/
TTYConsoleReader.java
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.common.console;
import com.orientechnologies.common.exception.OSystemException;
import com.orientechnologies.common.log.OLogManager;
import sun.misc.Signal;
import sun.misc.SignalHandler;
import java.io.*;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Custom implementation of TTY reader. Supports arrow keys + history.
*/
public class TTYConsoleReader implements OConsoleReader {
public final static int HORIZONTAL_TAB_CHAR = 9;
public final static int NEW_LINE_CHAR = 10;
public final static int VERTICAL_TAB_CHAR = 11;
public final static int ESC = 27;
public final static int UNIT_SEPARATOR_CHAR = 31;
public final static int CTRL = 53;
public final static int SEMICOLON = 59;
public final static int UP_CHAR = 65;
public final static int DOWN_CHAR = 66;
public final static int RIGHT_CHAR = 67;
public final static int LEFT_CHAR = 68;
public final static int END_CHAR = 70;
public final static int BEGIN_CHAR = 72;
public final static int BACKSLASH = 92;
public final static int DEL_CHAR = 126;
public final static int BACKSPACE_CHAR = 127;
private final static int MAX_HISTORY_ENTRIES = 50;
private static final Object signalLock = new Object();
private static String HISTORY_FILE_NAME = ".orientdb_history";
private static String ORIENTDB_HOME_DIR = ".orientdb";
private static int cachedConsoleWidth = -1; // -1 for no cached value, -2 to indicate the error
static {
final Signal signal = new Signal("WINCH");
Signal.handle(signal, new SignalHandler() {
@Override
public void handle(Signal signal) {
synchronized (signalLock) {
cachedConsoleWidth = -1;
}
}
});
}
protected final List<String> history = new ArrayList<String>();
protected int cursorPosition = 0;
protected int oldPromptLength = 0;
protected int oldTextLength = 0;
protected int oldCursorPosition = 0;
protected int maxTotalLength = 0;
protected String historyBuffer;
protected Reader inStream;
protected PrintStream outStream;
protected OConsoleApplication console;
public TTYConsoleReader() {
File file = getHistoryFile(true);
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
String historyEntry = reader.readLine();
while (historyEntry != null) {
history.add(historyEntry);
historyEntry = reader.readLine();
}
if (System.getProperty("file.encoding") != null) {
inStream = new InputStreamReader(System.in, System.getProperty("file.encoding"));
outStream = new PrintStream(System.out, false, System.getProperty("file.encoding"));
} else {
inStream = new InputStreamReader(System.in);
outStream = System.out;
}
} catch (FileNotFoundException fnfe) {
OLogManager.instance().error(this, "History file not found", fnfe);
} catch (IOException ioe) {
OLogManager.instance().error(this, "Error reading history file", ioe);
}
if (inStream == null)
throw new OSystemException("Cannot access to the input stream. Check permissions of running process");
}
public String readPassword() throws IOException {
return readLine();
}
public String readLine() throws IOException {
String consoleInput = "";
StringBuffer buffer = new StringBuffer();
cursorPosition = 0;
historyBuffer = null;
int historyNum = history.size();
boolean hintedHistory = false;
while (true) {
boolean escape = false;
boolean ctrl = false;
int next = inStream.read();
if (next == ESC) {
escape = true;
inStream.read();
next = inStream.read();
}
if (escape) {
if (next == 49) {
inStream.read();
next = inStream.read();
}
if (next == CTRL) {
ctrl = true;
next = inStream.read();
}
if (ctrl) {
if (next == RIGHT_CHAR) {
cursorPosition = buffer.indexOf(" ", cursorPosition) + 1;
if (cursorPosition == 0)
cursorPosition = buffer.length();
updatePrompt(buffer);
} else if (next == LEFT_CHAR) {
if (cursorPosition > 1 && cursorPosition < buffer.length() && buffer.charAt(cursorPosition - 1) == ' ') {
cursorPosition = buffer.lastIndexOf(" ", (cursorPosition - 2)) + 1;
} else {
cursorPosition = buffer.lastIndexOf(" ", cursorPosition) + 1;
}
if (cursorPosition < 0)
cursorPosition = 0;
updatePrompt(buffer);
}
} else {
if (next == UP_CHAR && !history.isEmpty()) {
if (history.size() > 0) { // UP
if (!hintedHistory && (historyNum == history.size() || !buffer.toString().equals(history.get(historyNum)))) {
if (buffer.length() > 0) {
hintedHistory = true;
historyBuffer = buffer.toString();
} else {
historyBuffer = null;
}
}
historyNum = getHintedHistoryIndexUp(historyNum);
if (historyNum > -1) {
buffer = new StringBuffer(history.get(historyNum));
} else {
buffer = new StringBuffer(historyBuffer);
}
cursorPosition = buffer.length();
updatePrompt(buffer);
}
} else if (next == DOWN_CHAR && !history.isEmpty()) { // DOWN
if (history.size() > 0) {
historyNum = getHintedHistoryIndexDown(historyNum);
if (historyNum == history.size()) {
if (historyBuffer != null) {
buffer = new StringBuffer(historyBuffer);
} else {
buffer = new StringBuffer("");
}
} else {
buffer = new StringBuffer(history.get(historyNum));
}
cursorPosition = buffer.length();
updatePrompt(buffer);
}
} else if (next == RIGHT_CHAR) {
if (cursorPosition < buffer.length()) {
cursorPosition++;
updatePrompt(buffer);
}
} else if (next == LEFT_CHAR) {
if (cursorPosition > 0) {
cursorPosition--;
updatePrompt(buffer);
}
} else if (next == END_CHAR) {
cursorPosition = buffer.length();
updatePrompt(buffer);
} else if (next == BEGIN_CHAR) {
cursorPosition = 0;
updatePrompt(buffer);
}
}
} else {
if (next == NEW_LINE_CHAR) {
outStream.println();
oldPromptLength = 0;
oldTextLength = 0;
oldCursorPosition = 0;
maxTotalLength = 0;
break;
} else if (next == BACKSPACE_CHAR) {
if (buffer.length() > 0 && cursorPosition > 0) {
buffer.deleteCharAt(cursorPosition - 1);
cursorPosition--;
updatePrompt(buffer);
}
} else if (next == DEL_CHAR) {
if (buffer.length() > 0 && cursorPosition >= 0 && cursorPosition < buffer.length()) {
buffer.deleteCharAt(cursorPosition);
updatePrompt(buffer);
}
} else if (next == HORIZONTAL_TAB_CHAR) {
buffer = writeHint(buffer);
cursorPosition = buffer.length();
updatePrompt(buffer);
} else {
if ((next > UNIT_SEPARATOR_CHAR && next < BACKSPACE_CHAR) || next > BACKSPACE_CHAR) {
if (cursorPosition == buffer.length()) {
buffer.append((char) next);
} else {
buffer.insert(cursorPosition, (char) next);
}
cursorPosition++;
updatePrompt(buffer);
} else {
outStream.println();
outStream.print(buffer);
}
}
historyNum = history.size();
hintedHistory = false;
}
}
consoleInput = buffer.toString();
history.remove(consoleInput);
history.add(consoleInput);
historyNum = history.size();
writeHistory(historyNum);
if (consoleInput.equals("clear")) {
outStream.flush();
for (int i = 0; i < 150; i++) {
outStream.println();
}
outStream.print("\r");
outStream.print(console.getPrompt());
return readLine();
} else {
return consoleInput;
}
}
public void setConsole(OConsoleApplication iConsole) {
console = iConsole;
}
@Override
public int getConsoleWidth() {
synchronized (signalLock) {
if (cachedConsoleWidth > 0) // we have cached value
return cachedConsoleWidth;
if (cachedConsoleWidth == -1) { // no cached value
try {
final Process process = Runtime.getRuntime().exec(new String[] { "sh", "-c", "tput cols 2> /dev/tty" });
final String line = new BufferedReader(new InputStreamReader(process.getInputStream())).readLine();
process.waitFor();
if (process.exitValue() == 0 && line != null) {
cachedConsoleWidth = Integer.parseInt(line);
} else
cachedConsoleWidth = -2;
} catch (IOException | NumberFormatException | InterruptedException ignore) {
cachedConsoleWidth = -2;
}
}
return cachedConsoleWidth == -2 || cachedConsoleWidth == 0 ? OConsoleReader.FALLBACK_CONSOLE_WIDTH : cachedConsoleWidth;
}
}
private void writeHistory(int historyNum) throws IOException {
if (historyNum <= MAX_HISTORY_ENTRIES) {
File historyFile = getHistoryFile(false);
BufferedWriter writer = new BufferedWriter(new FileWriter(historyFile));
try {
for (String historyEntry : history) {
writer.write(historyEntry);
writer.newLine();
}
} finally {
writer.flush();
writer.close();
}
} else {
File historyFile = getHistoryFile(false);
BufferedWriter writer = new BufferedWriter(new FileWriter(historyFile));
try {
for (String historyEntry : history.subList(historyNum - MAX_HISTORY_ENTRIES - 1, historyNum - 1)) {
writer.write(historyEntry);
writer.newLine();
}
} finally {
writer.flush();
writer.close();
}
}
}
private StringBuffer writeHint(StringBuffer buffer) {
List<String> suggestions = new ArrayList<String>();
for (Method method : console.getConsoleMethods().keySet()) {
String command = OConsoleApplication.getClearName(method.getName());
if (command.startsWith(buffer.toString())) {
suggestions.add(command);
}
}
if (suggestions.size() > 1) {
StringBuffer hintBuffer = new StringBuffer();
String[] bufferComponents = buffer.toString().split(" ");
String[] suggestionComponents;
Set<String> bufferPart = new HashSet<String>();
String suggestionPart = null;
boolean appendSpace = true;
for (String suggestion : suggestions) {
suggestionComponents = suggestion.split(" ");
hintBuffer.append("* " + suggestion + " ");
hintBuffer.append("\n");
suggestionPart = "";
if (bufferComponents.length == 0 || buffer.length() == 0) {
suggestionPart = null;
} else if (bufferComponents.length == 1) {
bufferPart.add(suggestionComponents[0]);
if (bufferPart.size() > 1) {
suggestionPart = bufferComponents[0];
appendSpace = false;
} else {
suggestionPart = suggestionComponents[0];
}
} else {
bufferPart.add(suggestionComponents[bufferComponents.length - 1]);
if (bufferPart.size() > 1) {
for (int i = 0; i < bufferComponents.length; i++) {
suggestionPart += bufferComponents[i];
if (i < (bufferComponents.length - 1)) {
suggestionPart += " ";
}
appendSpace = false;
}
} else {
for (int i = 0; i < suggestionComponents.length; i++) {
suggestionPart += suggestionComponents[i] + " ";
}
}
}
}
if (suggestionPart != null) {
buffer = new StringBuffer();
buffer.append(suggestionPart);
if (appendSpace) {
buffer.append(" ");
}
}
hintBuffer.append("-----------------------------\n");
updateHints(hintBuffer);
} else if (suggestions.size() > 0) {
buffer = new StringBuffer();
buffer.append(suggestions.get(0));
buffer.append(" ");
}
return buffer;
}
private void updatePrompt(StringBuffer newText) {
final int consoleWidth = getConsoleWidth();
final String newPrompt = console.getPrompt();
final int newTotalLength = newPrompt.length() + newText.length();
final int oldTotalLength = oldPromptLength + oldTextLength;
// 1. Hide the cursor to reduce flickering.
hideCursor();
// 2. Position to the old prompt beginning.
outStream.print("\r");
moveCursorVertically(-getWraps(oldPromptLength, oldCursorPosition, consoleWidth));
// 3. Write the new prompt over the old one.
outStream.print(newPrompt);
outStream.print(newText);
// 4. Clear the remaining ending part of the old prompt, if any.
final StringBuilder spaces = new StringBuilder();
final int promptLengthDelta = oldTotalLength - newTotalLength;
for (int i = 0; i < promptLengthDelta; i++)
spaces.append(' ');
outStream.print(spaces);
// 5. Reset the cursor to the prompt beginning. We may do navigation relative to the updated console cursor position,
// but the math becomes too tricky in this case. Feel free to fix this ;)
outStream.print("\r");
if (newTotalLength > oldTotalLength) {
if (newTotalLength > maxTotalLength && newTotalLength % consoleWidth == 0) {
outStream.print('\n'); // make room for the cursor
moveCursorVertically(-1);
}
moveCursorVertically(-getWraps(newPrompt.length(), newText.length() - 1, consoleWidth));
} else
moveCursorVertically(-getWraps(oldPromptLength, oldTextLength - 1, consoleWidth));
// 6. Place the cursor at the right place.
moveCursorVertically((newPrompt.length() + cursorPosition) / consoleWidth);
moveCursorHorizontally((newPrompt.length() + cursorPosition) % consoleWidth);
// 7. Update the stored things.
oldPromptLength = newPrompt.length();
oldTextLength = newText.length();
oldCursorPosition = cursorPosition;
maxTotalLength = Math.max(newTotalLength, maxTotalLength);
// 8. Show the cursor.
showCursor();
}
private void erasePrompt() {
final int consoleWidth = getConsoleWidth();
final int oldTotalLength = oldPromptLength + oldTextLength;
// 1. Hide the cursor to reduce flickering.
hideCursor();
// 2. Position to the prompt beginning.
outStream.print("\r");
moveCursorVertically(-getWraps(oldPromptLength, oldCursorPosition, consoleWidth));
// 3. Clear the prompt.
final StringBuilder spaces = new StringBuilder();
for (int i = 0; i < oldTotalLength; i++)
spaces.append(' ');
outStream.print(spaces);
// 4. Reset the cursor to the prompt beginning.
outStream.print("\r");
moveCursorVertically(-getWraps(oldPromptLength, oldCursorPosition, consoleWidth));
// 5. Update the stored things.
oldPromptLength = 0;
oldTextLength = 0;
oldCursorPosition = 0;
maxTotalLength = 0;
// 6. Show the cursor.
showCursor();
}
private void updateHints(StringBuffer hints) {
erasePrompt();
outStream.print("\r");
outStream.print(hints);
}
private int getWraps(int promptLength, int cursorPosition, int consoleWidth) {
return (promptLength + Math.max(0, cursorPosition)) / consoleWidth;
}
private void hideCursor() {
outStream.print("\033[?25l");
}
private void showCursor() {
outStream.print("\033[?25h");
}
private void moveCursorHorizontally(int delta) {
if (delta > 0)
outStream.print("\033[" + delta + "C");
else if (delta < 0)
outStream.print("\033[" + Math.abs(delta) + "D");
}
private void moveCursorVertically(int delta) {
if (delta > 0)
outStream.print("\033[" + delta + "B");
else if (delta < 0)
outStream.print("\033[" + Math.abs(delta) + "A");
}
private int getHintedHistoryIndexUp(int historyNum) {
if (historyBuffer != null && !historyBuffer.equals("")) {
for (int i = (historyNum - 1); i >= 0; i--) {
if (history.get(i).startsWith(historyBuffer)) {
return i;
}
}
return -1;
}
return historyNum > 0 ? (historyNum - 1) : 0;
}
private int getHintedHistoryIndexDown(int historyNum) throws IOException {
if (historyBuffer != null && !historyBuffer.equals("")) {
for (int i = historyNum + 1; i < history.size(); i++) {
if (history.get(i).startsWith(historyBuffer)) {
return i;
}
}
return history.size();
}
return historyNum < history.size() ? (historyNum + 1) : history.size();
}
private File getHistoryFile(boolean read) {
final Path orientDBDir = Paths.get(System.getProperty("user.home"), ORIENTDB_HOME_DIR);
try {
Files.createDirectories(orientDBDir);
} catch (IOException e) {
OLogManager.instance().error(this, "Error creating OrientDB directory", e);
}
Path history = orientDBDir.resolve(HISTORY_FILE_NAME);
try {
if (!read)
Files.deleteIfExists(history);
if (Files.exists(history))
return history.toFile();
return Files.createFile(history).toFile();
} catch (IOException e) {
OLogManager.instance().error(this, "Error creating history file", e);
}
return history.toFile();
}
}