Utils/Termlib: Implement LineEditor auxiliary display support
[senf.git] / Utils / Termlib / Editor.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 Editor non-inline non-template implementation */
25
26 #include "Editor.hh"
27 //#include "Editor.ih"
28
29 // Custom includes
30 #include <senf/Utils/membind.hh>
31 #include <senf/Scheduler/Scheduler.hh>
32
33 //#include "Editor.mpp"
34 #define prefix_
35 ///////////////////////////////cc.p////////////////////////////////////////
36
37 prefix_ senf::term::BaseEditor::BaseEditor(AbstractTerminal & terminal)
38     : terminal_ (&terminal),
39       keyTimeout_ (senf::ClockService::milliseconds(DEFAULT_KEY_TIMEOUT_MS)),
40       timer_ ("senf::term::BaseEditor::keySequenceTimeout", 
41               senf::membind(&BaseEditor::keySequenceTimeout, this)),
42       column_ (0u), displayHeight_ (1u), line_ (0u)
43 {
44     terminal_->setCallbacks(*this);
45 }
46
47 prefix_ void senf::term::BaseEditor::newline()
48 {
49     reset();
50     write("\n");
51     write(tifo_.getString(Terminfo::properties::ClrEol));
52     column_ = 0;
53 }
54
55 prefix_ void senf::term::BaseEditor::toColumn(unsigned c)
56 {
57     if (c >= width())
58         c = width();
59     if (c > column_) {
60         if (tifo_.hasProperty(Terminfo::properties::ParmRightCursor)) {
61             write(tifo_.formatString(Terminfo::properties::ParmRightCursor, c - column_));
62             column_ = c;
63         }
64         else {
65             char const * cuf1 (tifo_.getString(Terminfo::properties::CursorRight));
66             while (c > column_) {
67                 write(cuf1);
68                 ++column_;
69             }
70         }
71     }
72     else if (c < column_) {
73         if (tifo_.hasProperty(Terminfo::properties::ParmLeftCursor)) {
74             write(tifo_.formatString(Terminfo::properties::ParmLeftCursor, column_ - c));
75             column_ = c;
76         }
77         else {
78             char const * cub1 (tifo_.getString(Terminfo::properties::CursorLeft));
79             while (c < column_) {
80                 write(cub1);
81                 --column_;
82             }
83         }
84     }
85 }
86
87 prefix_ void senf::term::BaseEditor::put(char ch)
88 {
89     if (column_ >= width()-1)
90         return;
91     write(ch);
92     ++ column_;
93 }
94
95 prefix_ void senf::term::BaseEditor::put(std::string const & text)
96 {
97     if (text.size() > width()-column_-1) {
98         write(text.substr(0,width()-column_-1));
99         column_ = width() - 1;
100     }
101     else {
102         write(text);
103         column_ += text.size();
104     }
105 }
106
107 prefix_ void senf::term::BaseEditor::clearLine()
108 {
109     write("\r");
110     write(tifo_.getString(Terminfo::properties::ClrEol));
111     column_ = 0;
112 }
113
114 prefix_ void senf::term::BaseEditor::setBold()
115 {
116     if (tifo_.hasProperty(Terminfo::properties::EnterBoldMode) &&
117         tifo_.hasProperty(Terminfo::properties::ExitAttributeMode))
118         write(tifo_.getString(Terminfo::properties::EnterBoldMode));
119 }
120
121 prefix_ void senf::term::BaseEditor::setNormal()
122 {
123     if (tifo_.hasProperty(Terminfo::properties::EnterBoldMode) &&
124         tifo_.hasProperty(Terminfo::properties::ExitAttributeMode))
125         write(tifo_.getString(Terminfo::properties::ExitAttributeMode));
126 }
127
128 prefix_ void senf::term::BaseEditor::maybeClrScr()
129 {
130     if (tifo_.hasProperty(Terminfo::properties::ClearScreen))
131         write(tifo_.getString(Terminfo::properties::ClearScreen));
132 }
133
134 prefix_ void senf::term::BaseEditor::toLine(unsigned l)
135 {
136     if (l >= height())
137         l = height() - 1;
138     unsigned ll (l);
139     if (ll >= displayHeight_)
140         ll = displayHeight_-1;
141     if (ll > line_) {
142         if (tifo_.hasProperty(Terminfo::properties::ParmDownCursor)) {
143             write(tifo_.formatString(Terminfo::properties::ParmDownCursor, ll - line_));
144             line_ = ll;
145         }
146         else {
147             char const * cud1 (tifo_.getString(Terminfo::properties::CursorDown));
148             while (ll > line_) {
149                 write(cud1);
150                 ++line_;
151             }
152         }
153     }
154     else if (ll < line_) {
155         if (tifo_.hasProperty(Terminfo::properties::ParmUpCursor)) {
156             write(tifo_.formatString(Terminfo::properties::ParmUpCursor, line_ - ll));
157             line_ = ll;
158         }
159         else {
160             char const * cuu1 (tifo_.getString(Terminfo::properties::CursorUp));
161             while (ll < line_) {
162                 write(cuu1);
163                 --line_;
164             }
165         }
166     }
167     while (line_ < l) {
168         write("\n");
169         write(tifo_.getString(Terminfo::properties::ClrEol));
170         ++displayHeight_;
171         ++line_;
172     }
173     write('\r');
174     column_ = 0;
175 }
176
177 prefix_ void senf::term::BaseEditor::reset()
178 {
179     for (unsigned i (1); i < displayHeight_; ++i) {
180         toLine(i);
181         clearLine();
182     }
183     toLine(0);
184     displayHeight_ = 1;
185 }
186
187 prefix_ unsigned senf::term::BaseEditor::currentColumn()
188    const
189 {
190     return column_;
191 }
192
193 prefix_ unsigned senf::term::BaseEditor::currentLine()
194     const
195 {
196     return line_;
197 }
198
199 prefix_ bool senf::term::BaseEditor::cb_init()
200 {
201     try {
202         tifo_.load(terminal_->terminalType());
203         keyParser_.load(tifo_);
204     }
205     catch (Terminfo::InvalidTerminfoException & ex) {
206         return false;
207     }
208
209     typedef Terminfo::properties p;
210     if (! (tifo_.hasProperty(p::ClrEol) &&
211            (tifo_.hasProperty(p::ParmRightCursor) || tifo_.hasProperty(p::CursorRight)) &&
212            (tifo_.hasProperty(p::ParmLeftCursor) || tifo_.hasProperty(p::CursorLeft))))
213         return false;
214
215     if (tifo_.hasProperty(Terminfo::properties::KeypadXmit))
216         write(tifo_.getString(Terminfo::properties::KeypadXmit));
217     return true;
218 }
219
220 prefix_ void senf::term::BaseEditor::cb_charReceived(char c)
221 {
222     inputBuffer_ += c;
223     timer_.timeout(senf::scheduler::eventTime() + keyTimeout_);
224     processKeys();
225 }
226
227 prefix_ void senf::term::BaseEditor::cb_windowSizeChanged()
228 {
229     if (column_ >= width())
230         column_ = width()-1;
231 }
232
233 prefix_ void senf::term::BaseEditor::keySequenceTimeout()
234 {
235     while (!inputBuffer_.empty()) {
236         processKeys();
237         v_keyReceived(keycode_t(inputBuffer_[0]));
238         inputBuffer_.erase(0, 1);
239     }
240 }
241
242 prefix_ void senf::term::BaseEditor::processKeys()
243 {
244     do {
245         std::pair<senf::term::KeyParser::keycode_t, std::string::size_type> result
246             (keyParser_.lookup(inputBuffer_));
247         if (result.first == senf::term::KeyParser::Incomplete)
248             return;
249         v_keyReceived(result.first);
250         inputBuffer_.erase(0, result.second);
251     } while (! inputBuffer_.empty());
252     timer_.disable();
253 }
254
255 prefix_ unsigned senf::term::BaseEditor::width()
256 {
257     return terminal_->width();
258 }
259
260 prefix_ unsigned senf::term::BaseEditor::height()
261 {
262     return terminal_->height();
263 }
264
265 prefix_ void senf::term::BaseEditor::write(char ch)
266 {
267     terminal_->write(ch);
268 }
269
270 prefix_ void senf::term::BaseEditor::write(std::string const & s)
271 {
272     for (std::string::const_iterator i (s.begin()); i != s.end(); ++i)
273         write(*i);
274 }
275
276 ///////////////////////////////////////////////////////////////////////////
277
278 prefix_ senf::term::LineEditor::LineEditor(AbstractTerminal & terminal, AcceptCallback cb)
279     : BaseEditor(terminal), enabled_ (true), prompt_ ("$"), promptWidth_ (1u), editWidth_ (0u), 
280       text_ (""), point_ (0u), displayPos_ (0u), lastKey_ (0u), callback_ (cb), historyPoint_ (0u)
281 {
282     defineKey(KeyParser::Return,    &bindings::accept);
283     defineKey(KeyParser::Right,     &bindings::forwardChar);
284     defineKey(KeyParser::Left,      &bindings::backwardChar);
285     defineKey(KeyParser::Up,        &bindings::prevHistory);
286     defineKey(KeyParser::Down,      &bindings::nextHistory);
287     defineKey(KeyParser::Backspace, &bindings::backwardDeleteChar);
288     defineKey(KeyParser::Delete,    &bindings::deleteChar);
289     defineKey(KeyParser::Home,      &bindings::beginningOfLine);
290     defineKey(KeyParser::End,       &bindings::endOfLine);
291     defineKey(KeyParser::Ctrl('K'), &bindings::deleteToEndOfLine);
292     defineKey(KeyParser::Ctrl('A'), &bindings::beginningOfLine);
293     defineKey(KeyParser::Ctrl('E'), &bindings::endOfLine);
294     defineKey(KeyParser::Ctrl('D'), &bindings::deleteChar);
295     defineKey(KeyParser::Ctrl('C'), &bindings::restartEdit);
296     defineKey(KeyParser::Ctrl('L'), &bindings::clearScreen);
297 }
298
299 prefix_ void senf::term::LineEditor::prompt(std::string const & text)
300 {
301     prompt_ = text;
302     promptWidth_ = prompt_.size();
303     if (promptWidth_ > width() - 4 && width() > 4)
304         promptWidth_ = width() - 4;
305     editWidth_ = width() - promptWidth_ - 3;
306     if (enabled_)
307         redisplay();
308 }
309
310 prefix_ void senf::term::LineEditor::set(std::string const & text, unsigned pos)
311 {
312     text_ = text;
313     point_ = pos;
314     if (point_ > text.size())
315         point_ = text.size();
316     displayPos_ = 0u;
317     if (point_ > editWidth_)
318         displayPos_ = point_ - editWidth_;
319     redisplay();
320 }
321
322 prefix_ void senf::term::LineEditor::show()
323 {
324     if (enabled_)
325         return;
326     enabled_ = true;
327     forceRedisplay();
328 }
329
330 prefix_ void senf::term::LineEditor::hide()
331 {
332     if (! enabled_)
333         return;
334     clearLine();
335     enabled_ = false;
336 }
337
338 prefix_ void senf::term::LineEditor::accept()
339 {
340     if (enabled_)
341         newline();
342     hide();
343     pushHistory(text_);
344     callback_(text_);
345     clear();
346 }
347
348 prefix_ void senf::term::LineEditor::clear()
349 {
350     set("");
351     historyPoint_ = history_.size();
352 }
353
354 prefix_ void senf::term::LineEditor::redisplay()
355 {
356     redisplayNeeded_ = true;
357 }
358
359 prefix_ void senf::term::LineEditor::forceRedisplay()
360 {
361     if (! enabled_)
362         return;
363     clearLine();
364     setBold();
365     if (prompt_.size() > promptWidth_)
366         put(prompt_.substr(prompt_.size()-promptWidth_));
367     else
368         put(prompt_);
369     put( displayPos_ > 0 ? '<' : ' ' );
370     if (text_.size() > displayPos_ + editWidth_) {
371         toColumn(editWidth_ + promptWidth_ + 1);
372         put('>');
373         toColumn(promptWidth_ + 1);
374     }
375     setNormal();
376     put(text_.substr(displayPos_, editWidth_));
377     toColumn(point_ - displayPos_ + promptWidth_ + 1);
378     redisplayNeeded_ = false;
379 }
380
381 prefix_ void senf::term::LineEditor::gotoChar(unsigned n)
382 {
383     point_ = n;
384     if (point_ > text_.size())
385         point_ = text_.size();
386     if (point_ < displayPos_)
387         displayPos_ = point_;
388     if (point_ > displayPos_+editWidth_)
389         displayPos_ = point_-editWidth_;
390     redisplay();
391 }
392
393 prefix_ void senf::term::LineEditor::scrollTo(unsigned n)
394 {
395     displayPos_ = n;
396     if (displayPos_ > text_.size())
397         displayPos_ = text_.size();
398     if (point_ < displayPos_)
399         point_ = displayPos_;
400     if (point_ > displayPos_+editWidth_)
401         point_ = displayPos_+editWidth_;
402     redisplay();
403 }
404
405 prefix_ void senf::term::LineEditor::deleteChar(unsigned n)
406 {
407     if (point_ >= text_.size())
408         return;
409     text_.erase(point_, n);
410     redisplay();
411 }
412
413 prefix_ void senf::term::LineEditor::insert(char ch)
414 {
415     text_.insert(point_, std::string(1, ch));
416     gotoChar(point_+1);
417     redisplay();
418 }
419
420 prefix_ void senf::term::LineEditor::insert(std::string const & text)
421 {
422     text_.insert(point_, text);
423     gotoChar(point_+text.size());
424     redisplay();
425 }
426
427 prefix_ void senf::term::LineEditor::pushHistory(std::string const & text)
428 {
429     if (! text.empty()
430         && (historyPoint_ == history_.size() || history_[historyPoint_] != text)
431         && (history_.empty() || history_.back() != text)) {
432         history_.push_back(text);
433         while (history_.size() > MAX_HISTORY_SIZE)
434             history_.erase(history_.begin());
435         historyPoint_ = history_.size() - 1;
436     }
437 }
438
439 prefix_ void senf::term::LineEditor::prevHistory()
440 {
441     if (historyPoint_ <= 0)
442         return;
443     pushHistory(text_);
444     std::string entry (history_[--historyPoint_]);
445     set(entry, entry.size());
446 }
447
448 prefix_ void senf::term::LineEditor::nextHistory()
449 {
450     if (historyPoint_ >= history_.size())
451         return;
452     pushHistory(text_);
453     ++ historyPoint_;
454     if (historyPoint_ >= history_.size())
455         set("");
456     else {
457         std::string entry (history_[historyPoint_]);
458         set(entry, entry.size());
459     }
460 }
461
462 prefix_ void senf::term::LineEditor::auxDisplay(int line, std::string const & text)
463 {
464     toLine(line+1);
465     clearLine();
466     put(text);
467 }
468
469 prefix_ unsigned senf::term::LineEditor::maxAuxDisplayHeight()
470 {
471     return height()-1;
472 }
473
474 prefix_ void senf::term::LineEditor::clearAuxDisplay()
475 {
476     reset();
477 }
478
479 prefix_ std::string const & senf::term::LineEditor::text()
480 {
481     return text_;
482 }
483
484 prefix_ unsigned senf::term::LineEditor::point()
485 {
486     return point_;
487 }
488
489 prefix_ unsigned senf::term::LineEditor::displayPos()
490 {
491     return displayPos_;
492 }
493
494 prefix_ senf::term::LineEditor::keycode_t senf::term::LineEditor::lastKey()
495 {
496     return lastKey_;
497 }
498
499 prefix_ void senf::term::LineEditor::defineKey(keycode_t key, KeyBinding binding)
500 {
501     bindings_[key] = binding;
502 }
503
504 prefix_ void senf::term::LineEditor::unsetKey(keycode_t key)
505 {
506     bindings_.erase(key);
507 }
508
509 prefix_ bool senf::term::LineEditor::cb_init()
510 {
511     if (!BaseEditor::cb_init())
512         return false;
513     prompt(prompt_);
514     forceRedisplay();
515     return true;
516 }
517
518 prefix_ void senf::term::LineEditor::cb_windowSizeChanged()
519 {
520     BaseEditor::cb_windowSizeChanged();
521     clearAuxDisplay();
522     prompt(prompt_);
523     gotoChar(point_);
524     forceRedisplay();
525 }
526
527 prefix_ void senf::term::LineEditor::v_keyReceived(keycode_t key)
528 {
529     if (! enabled_)
530         return;
531     clearAuxDisplay();
532     lastKey_ = key;
533     KeyMap::iterator i (bindings_.find(key));
534     if (i != bindings_.end())
535         i->second(*this);
536     else if (key >= ' ' && key < 256)
537         insert(char(key));
538     if (currentLine() != 0)
539         toLine(0);
540     if (redisplayNeeded_)
541         forceRedisplay();
542     else
543         toColumn(point_ - displayPos_ + promptWidth_ + 1);
544 }
545
546 ///////////////////////////////////////////////////////////////////////////
547
548 prefix_ void senf::term::bindings::selfInsertCommand(LineEditor & editor)
549 {
550     LineEditor::keycode_t key (editor.lastKey());
551     if (key >= ' ' && key < 256)
552         editor.insert(key);
553 }
554
555 prefix_ void senf::term::bindings::forwardChar(LineEditor & editor)
556 {
557     editor.gotoChar(editor.point()+1);
558 }
559
560 prefix_ void senf::term::bindings::backwardChar(LineEditor & editor)
561 {
562     unsigned p (editor.point());
563     if (p>0)
564         editor.gotoChar(p-1);
565 }
566
567 prefix_ void senf::term::bindings::accept(LineEditor & editor)
568 {
569     editor.accept();
570 }
571
572 prefix_ void senf::term::bindings::backwardDeleteChar(LineEditor & editor)
573 {
574     unsigned p (editor.point());
575     if (p>0) {
576         editor.gotoChar(p-1);
577         editor.deleteChar();
578     }
579 }
580
581 prefix_ void senf::term::bindings::deleteChar(LineEditor & editor)
582 {
583     editor.deleteChar();
584 }
585
586 prefix_ void senf::term::bindings::beginningOfLine(LineEditor & editor)
587 {
588     editor.gotoChar(0u);
589 }
590
591 prefix_ void senf::term::bindings::endOfLine(LineEditor & editor)
592 {
593     editor.gotoChar(editor.text().size());
594 }
595
596 prefix_ void senf::term::bindings::deleteToEndOfLine(LineEditor & editor)
597 {
598     editor.deleteChar(editor.text().size()-editor.point());
599 }
600
601 prefix_ void senf::term::bindings::restartEdit(LineEditor & editor)
602 {
603     editor.newline();
604     editor.clear();
605     editor.redisplay();
606 }
607
608 prefix_ void senf::term::bindings::prevHistory(LineEditor & editor)
609 {
610     editor.prevHistory();
611 }
612
613 prefix_ void senf::term::bindings::nextHistory(LineEditor & editor)
614 {
615     editor.nextHistory();
616 }
617
618 prefix_ void senf::term::bindings::clearScreen(LineEditor & editor)
619 {
620     editor.maybeClrScr();
621     editor.clearLine();
622     editor.forceRedisplay();
623 }
624
625 prefix_ void senf::term::bindings::complete(LineEditor & editor, Completer completer)
626 {
627     typedef std::vector<std::string> Completions;
628
629     Completions completions;
630     completer(editor, 0, editor.point(), completions);
631     if (completions.empty())
632         return;
633     
634     // Find common start string of all completions
635     unsigned commonStart (completions[0].size());
636     unsigned maxLen (commonStart);
637     for (Completions::const_iterator i (boost::next(completions.begin()));
638          i != completions.end(); ++i) {
639         if (i->size() > maxLen)
640             maxLen = i->size();
641         unsigned n (0u);
642         for (; n < commonStart && n < i->size() && completions[0][n] == (*i)[n]; ++n) ;
643         commonStart = n;
644     }
645
646     // Replace to-be-completed string with the common start string shared by all completions
647     std::string text (editor.text());
648     std::string completion (completions[0].substr(0, commonStart));
649     bool didComplete (false);
650     if (text.substr(0, editor.point()) != completion) {
651         text.erase(0, editor.point());
652         text.insert(0, completion);
653         didComplete = true;
654     }
655
656     // If completion is already unique, make sure completion is followed by a space and place cursor
657     // after that space
658     if (completions.size() == 1u) {
659         if (text.size() <= commonStart || text[commonStart] != ' ')
660             text.insert(commonStart, " ");
661         editor.set(text, commonStart + 1);
662         return;
663     }
664
665     // Otherwise place cursor directly after the partial completion
666     editor.set(text, commonStart);
667     if (didComplete)
668         return;
669
670     // Text was not changed, show list of possible completions
671     unsigned colWidth (maxLen+2);
672     unsigned nColumns ((editor.width()-1) / colWidth);
673     if (nColumns < 1) nColumns = 1;
674     unsigned nRows ((completions.size()+nColumns-1) / nColumns);
675     if (nRows > editor.maxAuxDisplayHeight()) {
676         editor.auxDisplay(0, "(too many completions)");
677         return;
678     }
679     Completions::iterator i (completions.begin());
680     for (unsigned row (0); row < nRows; ++row) {
681         std::string line;
682         for (unsigned column (0); column < nColumns && i != completions.end(); ++column) {
683             std::string entry (colWidth, ' ');
684             if (i->size() > colWidth-2)
685                 std::copy(i->begin(), i->begin()+colWidth-2, entry.begin());
686             else
687                 std::copy(i->begin(), i->end(), entry.begin());
688             line += entry;
689             ++i;
690         }
691         editor.auxDisplay(row, line);
692     }
693 }
694
695 ///////////////////////////////cc.e////////////////////////////////////////
696 #undef prefix_
697 //#include "Editor.mpp"
698
699 \f
700 // Local Variables:
701 // mode: c++
702 // fill-column: 100
703 // comment-column: 40
704 // c-file-style: "senf"
705 // indent-tabs-mode: nil
706 // ispell-local-dictionary: "american"
707 // compile-command: "scons -u test"
708 // End: