Console: Documentation fixes
[senf.git] / Console / Readline.cc
1 // $Id$
2 //
3 // Copyright (C) 2008 
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.de>
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 /** \file
24     \brief Readline non-inline non-template implementation */
25
26 #include "Readline.hh"
27 //#include "Readline.ih"
28
29 // Custom includes
30 #include <stdio.h>
31 #include <readline/readline.h>
32 #include <readline/history.h>
33 #include <boost/algorithm/string/trim.hpp>
34 #include <boost/algorithm/string/replace.hpp>
35 #include "../Utils/membind.hh"
36
37 //#include "Readline.mpp"
38 #define prefix_
39 ///////////////////////////////cc.p////////////////////////////////////////
40
41 //
42 // Readline integration is a bit awkward. There are several things to it:
43 //
44 //  - Readline uses global variables for all state. Therefore, we can use readline only for one
45 //    console.
46 //  - We need to make readline to read from the socket handle instead of some input stream. We can
47 //    do this by setting a custom rl_getc_function.
48 //  - We need to make readline to write to the NonblockingSocketOStream. This is possible in glibc
49 //    by using a 'cookie stream'.
50 //  - We need to correctly handle the terminal mode settings. Currently we unconditionally
51 //    initialize the remote telnet by sending a fixed telnet option string and ignoring any otpions
52 //    sent back to us.
53 //  - We need to make sure, readline never uses stderr -> we must disable beeping
54 //  - There are places, where readline calls read_key unconditionally even when NOT prompted by the
55 //    callback that another key is available. One such place is completion. (The 'show all
56 //    completions (y/n)?' question). For now, we disable completion support.
57 //
58
59 ///////////////////////////////////////////////////////////////////////////
60 // senf::console::detail::ReadlineClientReader
61
62 extern int readline_echoing_p;
63 extern int _rl_bell_preference;
64
65 namespace {
66
67     int readline_getc_function(FILE *)
68     {
69         if (senf::console::detail::ReadlineClientReader::active())
70             return senf::console::detail::ReadlineClientReader::instance().getc();
71         else
72             return -1;
73     }
74
75     void readline_callback(char * input)
76     {
77         if (senf::console::detail::ReadlineClientReader::active() && input)
78             return senf::console::detail::ReadlineClientReader::instance().callback(
79                 std::string(input) );
80     }
81
82     ssize_t readline_cookie_write_function(void * cookie, char const * buffer, size_t size)
83     {
84         if (senf::console::detail::ReadlineClientReader::active() && buffer)
85             senf::console::detail::ReadlineClientReader::instance().write(
86                 std::string(buffer, size));
87         return size;
88     }
89
90     void readline_prep_term(int meta)
91     {
92         readline_echoing_p = 1;
93     }
94
95     void readline_deprep_term()
96     {}
97
98 }
99
100 prefix_ senf::console::detail::ReadlineClientReader::ReadlineClientReader(Client & client)
101     : ClientReader(client), ch_ (-1), skipChars_ (0), 
102       schedBinding_ ( client.handle(), 
103                       senf::membind(&ReadlineClientReader::charEvent, this),
104                       Scheduler::EV_READ, 
105                       false ),
106       terminate_ (false)
107 {
108     if (instance_ != 0)
109         throw DuplicateReaderException();
110     instance_ = this;
111
112     cookie_io_functions_t cookie_io = { 0, &readline_cookie_write_function, 0, 0 };
113     rl_outstream = fopencookie(0, "a", cookie_io);
114     if (rl_outstream == 0)
115         SENF_THROW_SYSTEM_EXCEPTION("");
116     if (setvbuf(rl_outstream, 0, _IONBF, BUFSIZ) < 0)
117         SENF_THROW_SYSTEM_EXCEPTION("");
118     rl_instream = rl_outstream;
119     rl_terminal_name = "vt100";
120     strncpy(nameBuffer_, client.name().c_str(), 128);
121     nameBuffer_[127] = 0;
122     rl_readline_name = nameBuffer_;
123     rl_prep_term_function = &readline_prep_term;
124     rl_deprep_term_function = &readline_deprep_term;
125     rl_getc_function = &readline_getc_function;
126     rl_bind_key('\t', &rl_insert);
127     using_history();
128     
129     // Don't ask me, where I found this ...
130     static char options[] = { 0xFF, 0xFB, 0x01, // IAC WILL ECHO
131                               0xFF, 0xFE, 0x22, // IAC DONT LINEMODE
132                               0xFF, 0xFB, 0x03, // IAC WILL SGA
133                               0x00 };
134     handle().write(options, options+sizeof(options));
135
136     strncpy(promptBuffer_, promptString().c_str(), 1024);
137     promptBuffer_[1023] = 0;
138     rl_callback_handler_install(promptBuffer_, &readline_callback);
139
140     _rl_bell_preference = 0; // Set this *after* the config file has been read
141
142     schedBinding_.enable();
143 }
144
145 prefix_ senf::console::detail::ReadlineClientReader::~ReadlineClientReader()
146 {
147     rl_callback_handler_remove();
148     fclose(rl_outstream);
149     rl_outstream = 0;
150     rl_instream = 0;
151     instance_ = 0;
152 }
153
154 prefix_ void senf::console::detail::ReadlineClientReader::callback(std::string line)
155 {
156     boost::trim(line);
157     if (!line.empty())
158         add_history(line.c_str());
159     handleInput(line);
160     stream() << std::flush;
161     strncpy(promptBuffer_, promptString().c_str(), 1024);
162     promptBuffer_[1023] = 0;
163     rl_set_prompt(promptBuffer_);
164 }
165
166 prefix_ void senf::console::detail::ReadlineClientReader::v_disablePrompt()
167 {}
168
169 prefix_ void senf::console::detail::ReadlineClientReader::v_enablePrompt()
170 {}
171
172 prefix_ void senf::console::detail::ReadlineClientReader::v_translate(std::string & data)
173 {
174     boost::replace_all(data, "\n", "\n\r");
175     boost::replace_all(data, "\xff", "\xff\xff");
176 }
177
178 prefix_ void senf::console::detail::ReadlineClientReader::charEvent(Scheduler::EventId event)
179 {
180     char ch;
181     if (event != Scheduler::EV_READ || handle().read(&ch, &ch+1) <= &ch) {
182         stopClient();
183         return;
184     }
185     ch_ = ch;
186
187     if (skipChars_ > 0)
188         --skipChars_;
189     else if (ch_ == static_cast<char>(0xff))
190         skipChars_ = 2;
191     else if (ch_ != 0)
192         rl_callback_read_char();
193
194     if (terminate_)
195         stopClient();
196 }
197
198 senf::console::detail::ReadlineClientReader * 
199     senf::console::detail::ReadlineClientReader::instance_ (0);
200
201 ///////////////////////////////////////////////////////////////////////////
202 // senf::console::detail::SafeReadlineClientReader
203
204 prefix_ void senf::console::detail::SafeReadlineClientReader::v_disablePrompt()
205 {
206     reader_->disablePrompt();
207 }
208
209 prefix_ void senf::console::detail::SafeReadlineClientReader::v_enablePrompt()
210 {
211     reader_->enablePrompt();
212 }
213
214 prefix_ void senf::console::detail::SafeReadlineClientReader::v_translate(std::string & data)
215 {
216     reader_->translate(data);
217 }
218
219 ///////////////////////////////cc.e////////////////////////////////////////
220 #undef prefix_
221 //#include "Readline.mpp"
222
223 \f
224 // Local Variables:
225 // mode: c++
226 // fill-column: 100
227 // comment-column: 40
228 // c-file-style: "senf"
229 // indent-tabs-mode: nil
230 // ispell-local-dictionary: "american"
231 // compile-command: "scons -u test"
232 // End: