Move sourcecode into 'senf/' directory
[senf.git] / senf / Utils / Console / LineEditor.cc
1 // $Id$
2 //
3 // Copyright (C) 2009 
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 LineEditor non-inline non-template implementation */
25
26 #include "LineEditor.hh"
27 //#include "LineEditor.ih"
28
29 // Custom includes
30 #include "../Logger/SenfLog.hh"
31 #include "../../Utils/range.hh"
32
33 //#include "LineEditor.mpp"
34 #define prefix_
35 ///////////////////////////////cc.p////////////////////////////////////////
36
37 ///////////////////////////////////////////////////////////////////////////
38 // senf::console::detail::LineEditorSwitcher
39
40 prefix_ senf::console::detail::LineEditorSwitcher::LineEditorSwitcher(Client & client)
41     : ClientReader(client),
42       reader_ (new LineEditorClientReader(client, *this))
43 {}
44
45 prefix_ void senf::console::detail::LineEditorSwitcher::editorSetupFailed()
46 {
47     // We need to delete the old reader *before* creating the new one such that all old scheduler
48     // events are removed before installing the new ones.
49     reader_.reset(0);
50     reader_.reset(new DumbClientReader(client()));
51 }
52
53 prefix_ void senf::console::detail::LineEditorSwitcher::v_disablePrompt()
54 {
55     reader_->disablePrompt();
56 }
57
58 prefix_ void senf::console::detail::LineEditorSwitcher::v_enablePrompt()
59 {
60     reader_->enablePrompt();
61 }
62
63 prefix_ void senf::console::detail::LineEditorSwitcher::v_write(std::string const & data)
64 {
65     reader_->write(data);
66 }
67
68 prefix_ unsigned senf::console::detail::LineEditorSwitcher::v_width()
69     const
70 {
71     return reader_->width();
72 }
73
74 ///////////////////////////////////////////////////////////////////////////
75 // senf::console::detail::LineEditorClientReader
76
77 prefix_ senf::console::detail::LineEditorClientReader::
78 LineEditorClientReader(Client & client, LineEditorSwitcher & switcher)
79     : term::BaseTelnetProtocol(client.handle()), ClientReader(client),
80       editor_ (*this, senf::membind(&LineEditorClientReader::executeLine, this)),
81       switcher_ (&switcher)
82 {
83     editor_.prompt(promptString());
84     editor_.defineKey(senf::term::KeyParser::Ctrl('D'),
85                       senf::membind(&LineEditorClientReader::deleteCharOrExit, this));
86     editor_.defineKey(senf::term::KeyParser::Tab,
87                       boost::bind(&term::bindings::complete,
88                                   _1, 
89                                   senf::membind(&LineEditorClientReader::completePath, this)));
90     editor_.defineKey(senf::term::KeyParser::Return, &senf::term::bindings::acceptWithRepeat);
91 }
92
93 prefix_ void senf::console::detail::LineEditorClientReader::v_setupFailed()
94 {
95     // Commits suicide
96     switcher_->editorSetupFailed();
97 }
98
99 prefix_ void senf::console::detail::LineEditorClientReader::v_eof()
100 {
101     stopClient();
102 }
103
104 prefix_ void senf::console::detail::LineEditorClientReader::v_disablePrompt()
105 {
106     editor_.hide();
107 }
108
109 prefix_ void senf::console::detail::LineEditorClientReader::v_enablePrompt()
110 {
111     editor_.show();
112 }
113
114 prefix_ void senf::console::detail::LineEditorClientReader::v_write(std::string const & data)
115 {
116     BaseTelnetProtocol::write(data);
117 }
118
119 prefix_ unsigned senf::console::detail::LineEditorClientReader::v_width()
120     const
121 {
122     return editor_.width();
123 }
124
125 prefix_ void
126 senf::console::detail::LineEditorClientReader::executeLine(std::string const & text)
127 {
128     handleInput(text);
129     stream() << std::flush;
130     editor_.prompt(promptString());
131     editor_.show();
132 }
133
134 prefix_ void
135 senf::console::detail::LineEditorClientReader::deleteCharOrExit(term::LineEditor & editor)
136 {
137     if (editor.text().empty())
138         ClientReader::handle().facet<TCPSocketProtocol>().shutdown(TCPSocketProtocol::ShutRD);
139     else
140         term::bindings::deleteChar(editor);
141 }
142
143 prefix_ void senf::console::detail::LineEditorClientReader::
144 completePath(term::LineEditor & editor, unsigned & b, unsigned & e, std::string & prefix,
145              std::vector<std::string> & completions)
146 {
147     std::string const & t (editor.text());
148     // Search backward from e finding the longest valid path. This does *not* accept all valid
149     // path's, only those without embedded white-space. However, this is only for completion so
150     // it's ok. 
151     if (b<e) {
152         unsigned bb (e-1);
153         for (;;) {
154             if (! CommandParser::isWordChar(t[bb]) && t[bb] != '/') {
155                 ++bb;
156                 break;
157             }
158             if (bb == b)
159                 break;
160             --bb;
161         }
162         b = bb;
163     }
164     std::string base (t.substr(b,e));
165     CommandParser parser;
166     ParseCommandInfo cmd;
167     try {
168         parser.parsePath(base, cmd);
169     }
170     catch (CommandParser::ParserErrorException & ex) {
171         return;
172     }
173  
174     ParseCommandInfo::TokensRange path (cmd.commandPath());
175     if (path.empty()) {
176         DirectoryNode::ChildrenRange cs (client().cwd().children());
177         for (DirectoryNode::ChildrenRange::iterator i (cs.begin()); i != cs.end(); ++i)
178             completions.push_back(i->first + (i->second->followLink().isDirectory() ? "/" : " "));
179         return;
180     }
181     
182     ParseCommandInfo::TokensRange::const_iterator i (path.begin());
183     ParseCommandInfo::TokensRange::const_iterator const i_end (boost::prior(path.end()));
184     DirectoryNode * dir (& client().cwd());
185     for (; i != i_end; ++i)
186         if (*i == NoneToken()) {
187             if (i == path.begin()) {
188                 dir = & client().root();
189                 prefix = "/";
190             }
191         }
192         else if (*i == WordToken("..")) {
193             DirectoryNode * parent (dir->parent().get());
194             if (parent) dir = parent;
195             prefix += "../";
196         }
197         else if (*i == WordToken(".")) 
198             prefix += "./";
199         else {
200             if (dir->hasChild(i->value())) {
201                 try {
202                     dir = & dir->getDirectory(i->value());
203                 }
204                 catch (std::bad_cast &) {
205                     return;
206                 }
207                 prefix += i->value() + "/";
208             } 
209             else {
210                 DirectoryNode::ChildrenRange cs (dir->completions(i->value()));
211                 if (has_one_elt(cs)) {
212                     GenericNode & node (cs.begin()->second->followLink());
213                     if (!node.isDirectory())
214                         return;
215                     dir = static_cast<DirectoryNode*>(&node);
216                     prefix += cs.begin()->first + "/";
217                 }
218                 else
219                     return;
220             }
221         }
222
223     DirectoryNode::ChildrenRange cs (dir->completions(i->value()));
224     for (DirectoryNode::ChildrenRange::iterator j (cs.begin()); j != cs.end(); ++j)
225         completions.push_back(j->first + (j->second->followLink().isDirectory() ? "/" : " "));
226 }
227
228 ///////////////////////////////cc.e////////////////////////////////////////
229 #undef prefix_
230 //#include "LineEditor.mpp"
231
232 \f
233 // Local Variables:
234 // mode: c++
235 // fill-column: 100
236 // comment-column: 40
237 // c-file-style: "senf"
238 // indent-tabs-mode: nil
239 // ispell-local-dictionary: "american"
240 // compile-command: "scons -u test"
241 // End: