1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.cmdl;
21
22 import java.io.EOFException;
23 import java.io.File;
24 import java.io.IOException;
25
26 import org.gnu.readline.Readline;
27 import org.gnu.readline.ReadlineCompleter;
28 import org.gnu.readline.ReadlineLibrary;
29 import org.xnap.util.FileHelper;
30
31 /***
32 * A wrapper class for JavaReadline and the GNU Readline library.
33 */
34 public class ReadlineConsole implements Console {
35
36
37
38 private File history = new File(FileHelper.getHomeDir() + "history");
39
40
41
42 public ReadlineConsole()
43 {
44 try {
45 Readline.load(ReadlineLibrary.GnuReadline);
46 }
47 catch (UnsatisfiedLinkError e1) {
48 try {
49 Readline.load(ReadlineLibrary.Editline);
50 }
51 catch (UnsatisfiedLinkError e2) {
52 }
53 }
54
55 try {
56 Readline.initReadline("XNap");
57 }
58 catch (UnsatisfiedLinkError e) {
59 System.err.println
60 ("Ooops, your Java-Readline Library seems broken. "
61 + "Using peer-to-peer and.");
62 Readline.load(ReadlineLibrary.PureJava);
63 Readline.initReadline("XNap");
64 }
65
66 Readline.initReadline("XNap");
67 Readline.setCompleter(new MyCompleter());
68
69 try {
70 if (history.exists()) {
71 Readline.readHistoryFile(history.getAbsolutePath());
72 }
73 }
74 catch (Exception e) {
75 }
76 }
77
78
79
80 public Command getCommand(String command)
81 {
82 return Executer.getCommand(command);
83 }
84
85 public Command[] getCommands()
86 {
87 return Executer.getCommands();
88 }
89
90 public boolean isEchoing()
91 {
92 return true;
93 }
94
95 /***
96 * Display a prompt on standard output and read a string from
97 * standard input.
98 *
99 * @param prompt Prompt to display
100 * @return The string the user entered
101 */
102 public String readln(String prompt)
103 {
104 try {
105 String s = Readline.readline(prompt);
106 return (s == null ? "" : s);
107 }
108 catch (EOFException e) {
109 }
110 catch (IOException e) {
111 }
112
113 return null;
114 }
115
116
117 /***
118 * Prints to stdout.
119 *
120 * @param output Text to show
121 */
122 public void println(String output)
123 {
124 System.out.println(output);
125 }
126
127 /***
128 * This should be called when the application is closed.
129 *
130 */
131 public void saveSettings()
132 {
133 try {
134 Readline.writeHistoryFile(history.getAbsolutePath());
135 }
136 catch (Exception e) {
137 }
138 }
139
140
141
142 public class MyCompleter implements ReadlineCompleter {
143
144
145
146
147
148
149
150 public String completer(String text, int state)
151 {
152 return Executer.getCompleter().completer(text, state);
153 }
154
155 }
156
157 }