/[svn]/linuxsampler/trunk/src/shell/lscp.cpp
ViewVC logotype

Contents of /linuxsampler/trunk/src/shell/lscp.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2525 - (show annotations) (download)
Mon Feb 24 17:52:51 2014 UTC (10 years, 1 month ago) by schoenebeck
File size: 16498 byte(s)
- Just updated comments regarding auto completion implementation and
  other LSCP shell features.

1 /*
2 * LSCP Shell
3 *
4 * Copyright (c) 2014 Christian Schoenebeck
5 *
6 * This program is part of LinuxSampler and released under the same terms.
7 */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <iostream>
12 #include <sstream>
13 #include <string.h>
14
15 #include "LSCPClient.h"
16 #include "KeyboardReader.h"
17 #include "TerminalCtrl.h"
18 #include "CFmt.h"
19 #include "CCursor.h"
20
21 #include "../common/global.h"
22 #include "../common/global_private.h"
23 #include "../common/Condition.h"
24
25 #define LSCP_DEFAULT_HOST "localhost"
26 #define LSCP_DEFAULT_PORT 8888
27
28 using namespace std;
29 using namespace LinuxSampler;
30
31 static LSCPClient* g_client = NULL;
32 static KeyboardReader* g_keyboardReader = NULL;
33 static Condition g_todo;
34 static String g_goodPortion;
35 static String g_badPortion;
36 static String g_suggestedPortion;
37 static const String g_prompt = "lscp=# ";
38 static std::vector<String> g_commandHistory;
39 static int g_commandHistoryIndex = -1;
40
41 static void printUsage() {
42 cout << "lscp - The LinuxSampler Control Protocol (LSCP) Shell." << endl;
43 cout << endl;
44 cout << "Usage: lscp [-h HOSTNAME] [-p PORT]" << endl;
45 cout << endl;
46 cout << " -h Host name of LSCP server (default \"" << LSCP_DEFAULT_HOST << "\")." << endl;
47 cout << endl;
48 cout << " -p TCP port number of LSCP server (default " << LSCP_DEFAULT_PORT << ")." << endl;
49 cout << endl;
50 cout << " --no-auto-correct Don't perform auto correction of obvious syntax errors." << endl;
51 cout << endl;
52 }
53
54 static void printWelcome() {
55 cout << "Welcome to lscp " << VERSION << ", the LinuxSampler Control Protocol (LSCP) shell." << endl;
56 cout << endl;
57 }
58
59 static void printPrompt() {
60 cout << g_prompt << flush;
61 }
62
63 static int promptOffset() {
64 return g_prompt.size();
65 }
66
67 // Called by the network reading thread, whenever new data arrived from the
68 // network connection.
69 static void onLSCPClientNewInputAvailable(LSCPClient* client) {
70 g_todo.Set(true);
71 }
72
73 // Called by the keyboard reading thread, whenever a key stroke was received.
74 static void onNewKeyboardInputAvailable(KeyboardReader* reader) {
75 g_todo.Set(true);
76 }
77
78 static void autoComplete() {
79 if (g_suggestedPortion.empty()) return;
80 String s;
81 // let the server delete mistaken characters first
82 for (int i = 0; i < g_badPortion.size(); ++i) s += '\b';
83 // now add the suggested, correct characters
84 s += g_suggestedPortion;
85 g_suggestedPortion.clear();
86 g_client->send(s);
87 }
88
89 static void commandFromHistory(int offset) {
90 if (g_commandHistoryIndex + offset < 0 ||
91 g_commandHistoryIndex + offset >= g_commandHistory.size()) return;
92 g_commandHistoryIndex += offset;
93 int len = g_goodPortion.size() + g_badPortion.size();
94 // erase current active line
95 for (int i = 0; i < len; ++i) g_client->send('\b');
96 // transmit new/old line to LSCP server
97 String command = g_commandHistory[g_commandHistory.size() - g_commandHistoryIndex - 1];
98 g_client->send(command);
99 }
100
101 static void previousCommand() {
102 commandFromHistory(1);
103 }
104
105 static void nextCommand() {
106 commandFromHistory(-1);
107 }
108
109 static void storeCommandInHistory(const String& sCommand) {
110 g_commandHistoryIndex = -1; // reset history index
111 // don't save the command if the previous one was the same
112 if (g_commandHistory.empty() || g_commandHistory.back() != sCommand)
113 g_commandHistory.push_back(sCommand);
114 }
115
116 /**
117 * This LSCP shell application is designed as thin client. That means the heavy
118 * LSCP grammar evaluation tasks are peformed by the LSCP server and the shell
119 * application's task are simply limited to forward individual characters typed
120 * by the user to the LSCP server and showing the result of the LSCP server's
121 * evaluation to the user on the screen. This has the big advantage that the
122 * shell works perfectly with any machine running (some minimum recent version
123 * of) LinuxSampler, no matter which precise LSCP version the server side
124 * is using. Which reduces the maintenance efforts for the shell application
125 * development tremendously.
126 *
127 * As soon as this application established a TCP connection to a LSCP server, it
128 * sends this command to the LSCP server:
129 * @code
130 * SET SHELL INTERACT 1
131 * @endcode
132 * which will inform the LSCP server that this LSCP client is actually a LSCP
133 * shell application. The shell will then simply forward every single character
134 * typed by the user immediately to the LSCP server, which in turn will evaluate
135 * every single character typed by the user and will return immediately a
136 * specially formatted string to the shell application like (assuming the user's
137 * current command line was "CREATE AUasdf"):
138 * @code
139 * SHU:1:CREATE AU{{GF}}asdf{{CU}}{{SB}}DIO_OUTPUT_DEVICE
140 * @endcode
141 * which informs this shell application about the result of the LSCP grammar
142 * evaluation and allows the shell to easily show that result of the evaluation
143 * to the user on the screen. In the example reply above, the prefix "SHU:" just
144 * indicates to the shell application that this response line is the result
145 * of the latest grammar evaluation, the number followed (here 1) indicates the
146 * semantic status of the current command line:
147 *
148 * - 0: Command line is complete, thus ENTER key may be hit by the user now.
149 * - 1: Current command line contains syntax error(s).
150 * - 2: Command line is incomplete, but contains no syntax errors so far.
151 *
152 * Then the actual current command line follows, with special markers:
153 *
154 * - Left of "{{GF}}" the command line is syntactically correct, right of that
155 * marker the command line is syntactically wrong.
156 *
157 * - Marker "{{CU}}" indicates the current cursor position of the command line.
158 *
159 * - Right of "{{SB}}" follows the current auto completion suggestion, so that
160 * string portion was not typed by the user yet, but is expected to be typed
161 * by him next to retain syntax correctness.
162 */
163 int main(int argc, char *argv[]) {
164 String host = LSCP_DEFAULT_HOST;
165 int port = LSCP_DEFAULT_PORT;
166 bool autoCorrect = true;
167
168 // parse command line arguments
169 for (int i = 0; i < argc; ++i) {
170 String s = argv[i];
171 if (s == "-h" || s == "--host") {
172 if (++i >= argc) {
173 printUsage();
174 return -1;
175 }
176 host = argv[i];
177 } else if (s == "-p" || s == "--port") {
178 if (++i >= argc) {
179 printUsage();
180 return -1;
181 }
182 port = atoi(argv[i]);
183 if (port <= 0) {
184 cerr << "Error: invalid port argument \"" << argv[i] << "\"\n";
185 return -1;
186 }
187 } else if (s == "--no-auto-correct") {
188 autoCorrect = false;
189 } else if (s[0] == '-') { // invalid / unknown command line argument ...
190 printUsage();
191 return -1;
192 }
193 }
194
195 // try to connect to the sampler's LSCP server and start a thread for
196 // receiving incoming network data from the sampler's LSCP server
197 g_client = new LSCPClient;
198 g_client->setCallback(onLSCPClientNewInputAvailable);
199 if (!g_client->connect(host, port)) return -1;
200 String sResponse = g_client->sendCommandSync(
201 (autoCorrect) ? "SET SHELL AUTO_CORRECT 1" : "SET SHELL AUTO_CORRECT 0"
202 );
203 sResponse = g_client->sendCommandSync("SET SHELL INTERACT 1");
204 if (sResponse.substr(0, 2) != "OK") {
205 cerr << "Error: sampler too old, it does not support shell instructions\n";
206 return -1;
207 }
208
209 printWelcome();
210 printPrompt();
211
212 // start a thread for reading from the local text input keyboard
213 // (keyboard echo will be disabled as well to have a clean control on what
214 // is appearing on the screen)
215 g_keyboardReader = new KeyboardReader;
216 g_keyboardReader->setCallback(onNewKeyboardInputAvailable);
217 g_keyboardReader->startReading();
218
219 int iKbdEscapeCharsExpected = 0;
220 char kbdPrevEscapeChar;
221
222 // main thread's loop
223 //
224 // This application runs 3 threads:
225 //
226 // - Keyboard thread: reads constantly on stdin for new characters (which
227 // will block this keyboard thread until new character(s) were typed by
228 // the user) and pushes the typed characters into a FIFO buffer.
229 //
230 // - Network thread: reads constantly on the TCP connection for new bytes
231 // being sent by the LSCP server (which will block this network thread
232 // until new bytes were received) and pushes the received bytes into a
233 // FIFO buffer.
234 //
235 // - Main thread: this thread runs in the loop below. The main thread sleeps
236 // (by using the "g_todo" semaphore) until either new keys on the keyboard
237 // were stroke by the user or until new bytes were received from the LSCP
238 // server. The main thread will then accordingly send the typed characters
239 // to the LSCP server and/or show the result of the LSCP server's latest
240 // evaluation to the user on the screen (by pulling those data from the
241 // other two thread's FIFO buffers).
242 while (true) {
243 // sleep until either new data from the network or from keyboard arrived
244 g_todo.WaitIf(false);
245 // immediately unset the condition variable and unlock it
246 g_todo.Set(false);
247 g_todo.Unlock();
248
249 // did network data arrive?
250 while (g_client->messageComplete()) {
251 String line = *g_client->popLine();
252 //printf("line '%s'\n", line.c_str());
253 if (line.substr(0,4) == "SHU:") {
254 int code = 0, n = 0;
255 int res = sscanf(line.c_str(), "SHU:%d:%n", &code, &n);
256 if (res >= 1) {
257 String s = line.substr(n);
258
259 // extract portion that is already syntactically correct
260 size_t iGood = s.find(LSCP_SHK_GOOD_FRONT);
261 String sGood = s.substr(0, iGood);
262 if (sGood.find(LSCP_SHK_CURSOR) != string::npos)
263 sGood.erase(sGood.find(LSCP_SHK_CURSOR), strlen(LSCP_SHK_CURSOR)); // erase cursor marker
264
265 // extract portion that was written syntactically incorrect
266 String sBad = s.substr(iGood + strlen(LSCP_SHK_GOOD_FRONT));
267 if (sBad.find(LSCP_SHK_CURSOR) != string::npos)
268 sBad.erase(sBad.find(LSCP_SHK_CURSOR), strlen(LSCP_SHK_CURSOR)); // erase cursor marker
269 if (sBad.find(LSCP_SHK_SUGGEST_BACK) != string::npos)
270 sBad.erase(sBad.find(LSCP_SHK_SUGGEST_BACK)); // erase auto suggestion portion
271
272 // extract portion that is suggested for auto completion
273 String sSuggest;
274 if (s.find(LSCP_SHK_SUGGEST_BACK) != string::npos) {
275 sSuggest = s.substr(s.find(LSCP_SHK_SUGGEST_BACK) + strlen(LSCP_SHK_SUGGEST_BACK));
276 if (sSuggest.find(LSCP_SHK_CURSOR) != string::npos)
277 sSuggest.erase(sSuggest.find(LSCP_SHK_CURSOR), strlen(LSCP_SHK_CURSOR)); // erase cursor marker
278 }
279
280 // extract current cursor position
281 int cursorColumn = sGood.size();
282 String sCursor = s;
283 if (sCursor.find(LSCP_SHK_GOOD_FRONT) != string::npos)
284 sCursor.erase(sCursor.find(LSCP_SHK_GOOD_FRONT), strlen(LSCP_SHK_GOOD_FRONT)); // erase good/bad marker
285 if (sCursor.find(LSCP_SHK_SUGGEST_BACK) != string::npos)
286 sCursor.erase(sCursor.find(LSCP_SHK_SUGGEST_BACK), strlen(LSCP_SHK_SUGGEST_BACK)); // erase suggestion marker
287 if (sCursor.find(LSCP_SHK_CURSOR) != string::npos)
288 cursorColumn = sCursor.find(LSCP_SHK_CURSOR);
289
290 // store those informations globally for the auto-completion
291 // feature
292 g_goodPortion = sGood;
293 g_badPortion = sBad;
294 g_suggestedPortion = sSuggest;
295
296 //printf("line '%s' good='%s' bad='%s' suggested='%s' cursor=%d\n", line.c_str(), sGood.c_str(), sBad.c_str(), sSuggest.c_str(), cursorColumn);
297
298 CCursor cursor = CCursor::now().toColumn(0).clearLine();
299 printPrompt();
300
301 CFmt cfmt;
302 if (code == LSCP_SHU_COMPLETE) cfmt.bold().green();
303 else cfmt.bold().white();
304 cout << sGood << flush;
305 cfmt.reset().red();
306 cout << sBad << flush;
307 cfmt.bold().yellow();
308 cout << sSuggest << flush;
309
310 cursor.toColumn(cursorColumn + promptOffset());
311 }
312 } else if (line.substr(0,2) == "OK") { // single-line response expected ...
313 cout << endl << flush;
314 CFmt cfmt;
315 cfmt.green();
316 cout << line.substr(0,2) << flush;
317 cfmt.reset();
318 cout << line.substr(2) << endl << flush;
319 printPrompt();
320 } else if (line.substr(0,3) == "WRN") { // single-line response expected ...
321 cout << endl << flush;
322 CFmt cfmt;
323 cfmt.yellow();
324 cout << line.substr(0,3) << flush;
325 cfmt.reset();
326 cout << line.substr(3) << endl << flush;
327 printPrompt();
328 } else if (line.substr(0,3) == "ERR") { // single-line response expected ...
329 cout << endl << flush;
330 CFmt cfmt;
331 cfmt.bold().red();
332 cout << line.substr(0,3) << flush;
333 cfmt.reset();
334 cout << line.substr(3) << endl << flush;
335 printPrompt();
336 } else if (g_client->multiLine()) { // multi-line response expected ...
337 cout << endl << flush;
338 while (true) {
339 cout << line << endl << flush;
340 if (line.substr(0, 1) == ".") break;
341 if (!g_client->lineAvailable()) break;
342 line = *g_client->popLine();
343 }
344 printPrompt();
345 } else {
346 cout << endl << line << endl << flush;
347 printPrompt();
348 }
349 }
350
351 // did keyboard input arrive?
352 while (g_keyboardReader->charAvailable()) {
353 char c = g_keyboardReader->popChar();
354
355 CFmt cfmt;
356 cfmt.white();
357 //std::cout << c << "(" << int(c) << ")" << std::endl << std::flush;
358 if (iKbdEscapeCharsExpected) { // escape sequence (still) expected now ...
359 iKbdEscapeCharsExpected--;
360 if (iKbdEscapeCharsExpected) kbdPrevEscapeChar = c;
361 else { // escape sequence is complete ...
362 if (kbdPrevEscapeChar == 91 && c == 65) // up key
363 previousCommand();
364 else if (kbdPrevEscapeChar == 91 && c == 66) // down key
365 nextCommand();
366 else if (kbdPrevEscapeChar == 91 && c == 68) { // left key
367 //TODO: move cursor left
368 } else if (kbdPrevEscapeChar == 91 && c == 67) { // right key
369 //TODO: move cursor right
370 }
371 }
372 continue; // don't send this escape sequence character to LSCP server
373 } else if (c == KBD_ESCAPE) { // escape sequence for special keys expected next ...
374 iKbdEscapeCharsExpected = 2;
375 continue; // don't send ESC character to LSCP server
376 } else if (c == KBD_BACKSPACE) {
377 if (promptOffset() < CCursor::now().column())
378 cout << "\b \b" << flush;
379 c = '\b';
380 } else if (c == '\t') { // auto completion ...
381 autoComplete();
382 continue; // don't send tab character to LSCP server
383 } else if (c == '\n') {
384 storeCommandInHistory(g_goodPortion + g_badPortion);
385 } else { // don't apply RETURN stroke yet, since the typed command might still be corrected by the sampler
386 cout << c << flush;
387 }
388
389 g_client->send(c);
390 }
391 }
392
393 return 0;
394 }

  ViewVC Help
Powered by ViewVC