SEvMgr Logo  0.2.0
C++ Simulation-Oriented Discrete Event Management Library
 All Classes Namespaces Files Functions Variables Typedefs Friends Macros Pages
SReadline.hpp
Go to the documentation of this file.
1 
11 //
12 // Date: 17 December 2005
13 // 03 April 2006
14 // 20 April 2006
15 // 07 May 2006
16 //
17 // Copyright (c) Sergey Satskiy 2005 - 2006
18 // <sergesatsky@yahoo.com>
19 //
20 // Permission to copy, use, modify, sell and distribute this software
21 // is granted provided this copyright notice appears in all copies.
22 // This software is provided "as is" without express or implied
23 // warranty, and with no claim as to its suitability for any purpose.
24 //
25 
26 #ifndef SREADLINE_H
27 #define SREADLINE_H
28 
29 #include <cstdio>
30 
31 #include <readline/readline.h>
32 #include <readline/history.h>
33 #include <readline/keymaps.h>
34 
35 #include <string>
36 #include <fstream>
37 #include <vector>
38 #include <stdexcept>
39 #include <map>
40 
41 #include <boost/algorithm/string/trim.hpp>
42 #include <boost/tokenizer.hpp>
43 #include <boost/function.hpp>
44 
45 
50 namespace {
54  typedef std::vector<std::string> TokensStorage;
55 
59  typedef std::vector<TokensStorage> CompletionsStorage;
60 
64  typedef boost::function<int (int, int)> KeyCallback;
65 
69  typedef std::map<int, KeyCallback> KeysBind;
70 
74  const size_t DefaultHistoryLimit (64);
75 
79  CompletionsStorage Completions;
80 
84  TokensStorage Tokens;
85 
89  std::map<Keymap, KeysBind> Keymaps;
90 
94  bool KeymapWasSetup (false);
95 
99  Keymap Earlykeymap (0);
100 
101 
108  char* Generator (const char* text, int State);
109 
110 
118  char** UserCompletion (const char* text, int start, int end);
119 
120 
128  int KeyDispatcher (int Count, int Key);
129 
130 
135  int StartupHook (void);
136 
137 
145  template <typename Container>
146  bool AreTokensEqual (const Container& Pattern, const Container& Input) {
147  if (Input.size() > Pattern.size()) {
148  return false;
149  }
150 
151  typename Container::const_iterator k (Pattern.begin());
152  typename Container::const_iterator j (Input.begin());
153  for ( ; j != Input.end(); ++k, ++j) {
154  const std::string lPattern = *k;
155  if (lPattern == "%file") {
156  continue;
157  }
158 
159  const std::string lInput = *j;
160  if (lPattern != lInput) {
161  return false;
162  }
163  }
164  return true;
165  }
166 
167  // See description near the prototype
168  template <typename ContainerType>
169  void SplitTokens (const std::string& Source, ContainerType& Container) {
170  typedef boost::tokenizer<boost::char_separator<char> > TokenizerType;
171 
172  // Set of token separators
173  boost::char_separator<char> Separators (" \t\n");
174  // Tokens provider
175  TokenizerType Tokenizer (Source, Separators);
176 
177  Container.clear();
178  for (TokenizerType::const_iterator k (Tokenizer.begin());
179  k != Tokenizer.end(); ++k) {
180  // Temporary storage for the token, in order to trim that latter
181  std::string SingleToken (*k);
182 
183  boost::algorithm::trim (SingleToken);
184  Container.push_back (SingleToken);
185  }
186  }
187 
188  // See description near the prototype
189  char** UserCompletion (const char* text, int start, int end) {
190  // No default completion at all
191  rl_attempted_completion_over = 1;
192 
193  if (Completions.empty() == true) {
194  return NULL;
195  }
196 
197  // Memorise all the previous tokens
198  std::string PreInput (rl_line_buffer, start);
199  SplitTokens (PreInput, Tokens);
200 
201  // Detect whether we should call the standard file name completer
202  // or a custom one
203  bool FoundPretender (false);
204 
205  for (CompletionsStorage::const_iterator k (Completions.begin());
206  k != Completions.end(); ++k) {
207  const TokensStorage& lTokenStorage = *k;
208  if (AreTokensEqual (lTokenStorage, Tokens) == false) {
209  continue;
210  }
211 
212  if (lTokenStorage.size() > Tokens.size()) {
213  FoundPretender = true;
214  if (lTokenStorage [Tokens.size()] == "%file") {
215  // Standard file name completer - called for the "%file" keyword
216  return rl_completion_matches (text, rl_filename_completion_function);
217  }
218  }
219  }
220 
221  if (FoundPretender) {
222  return rl_completion_matches (text, Generator);
223  }
224  return NULL;
225  }
226 
227  // See description near the prototype
228  char* Generator (const char* text, int State) {
229  static int Length;
230  static CompletionsStorage::const_iterator Iterator;
231 
232  if ( State == 0 ) {
233  Iterator = Completions.begin();
234  Length = strlen (text);
235  }
236 
237  for ( ; Iterator != Completions.end(); ++Iterator) {
238  const TokensStorage& lCompletion = *Iterator;
239  if (AreTokensEqual (lCompletion, Tokens) == false) {
240  continue;
241  }
242 
243  if (lCompletion.size() > Tokens.size()) {
244  if (lCompletion [Tokens.size()] == "%file") {
245  continue;
246  }
247 
248  const char* lCompletionCharStr (lCompletion [Tokens.size()].c_str());
249  if (strncmp (text, lCompletionCharStr, Length) == 0) {
250  // Readline will free the allocated memory
251  const size_t lCompletionSize = strlen (lCompletionCharStr) + 1;
252  char* NewString (static_cast<char*> (malloc (lCompletionSize)));
253  strcpy (NewString, lCompletionCharStr);
254 
255  ++Iterator;
256 
257  return NewString;
258  }
259  }
260  }
261 
262  return NULL;
263  }
264 
265 
266  // See the description near the prototype
267  int KeyDispatcher (int Count, int Key ) {
268  std::map< Keymap, KeysBind >::iterator Set (Keymaps.find (rl_get_keymap()));
269  if (Set == Keymaps.end()) {
270  // Most probably it happens bacause the header was
271  // included into many compilation units and the
272  // keymap setting calls were made in different files.
273  // This is the problem of "global" data.
274  // The storage of all the registered keymaps is in anonymous
275  // namespace.
276  throw std::runtime_error ("Error selecting a keymap.");
277  }
278 
279  (Set->second)[Key] (Count, Key);
280  return 0;
281  }
282 
283  // See the description near the prototype
284  int StartupHook (void) {
285  if (KeymapWasSetup) {
286  rl_set_keymap (Earlykeymap);
287  }
288  return 0;
289  }
290 
291 } // Anonymous namespace
292 
293 
299 namespace swift {
300 
307  class SKeymap {
308  private:
309  // Readline keymap
310  Keymap keymap;
311 
312  public:
319  explicit SKeymap (bool PrintableBound = false) : keymap (NULL) {
320  if (PrintableBound == true) {
321  // Printable characters are bound
322  keymap = rl_make_keymap();
323 
324  } else {
325  // Empty keymap
326  keymap = rl_make_bare_keymap();
327  }
328 
329  if (keymap == NULL) {
330  throw std::runtime_error ("Cannot allocate keymap.");
331  }
332 
333  // Register a new keymap in the global list
334  Keymaps [keymap] = KeysBind();
335  }
336 
342  explicit SKeymap (Keymap Pattern) : keymap (rl_copy_keymap (Pattern)) {
343  if ( keymap == NULL ) {
344  throw std::runtime_error( "Cannot allocate keymap." );
345  }
346 
347  // Register a new keymap in the global list
348  Keymaps [keymap] = KeysBind();
349  }
350 
355  // Deregister the keymap
356  Keymaps.erase (keymap);
357  rl_discard_keymap (keymap);
358  }
359 
366  void Bind (int Key, KeyCallback Callback) {
367  Keymaps [keymap][Key] = Callback;
368 
369  if (rl_bind_key_in_map (Key, KeyDispatcher, keymap) != 0) {
370  // Remove from the map just bound key
371  Keymaps [keymap].erase (Key);
372  throw std::runtime_error ("Invalid key.");
373  }
374  }
375 
381  void Unbind (int Key) {
382  rl_unbind_key_in_map (Key, keymap);
383  Keymaps [keymap].erase (Key);
384  }
385 
386  // void Bind (const std::string& Sequence, boost::function<int (int, int)>);
387  // void Unbind (std::string& Sequence);
388 
389  public:
395  SKeymap (const SKeymap& rhs) {
396  if (this == &rhs) {
397  return;
398  }
399  keymap = rl_copy_keymap (rhs.keymap);
400  }
401 
407  SKeymap& operator= (const SKeymap& rhs) {
408  if (this == &rhs) {
409  return *this;
410  }
411  keymap = rl_copy_keymap (rhs.keymap);
412  return *this;
413  }
414 
415  friend class SReadline;
416  };
417 
424  class SReadline {
425  public:
431  SReadline (const size_t Limit = DefaultHistoryLimit)
432  : HistoryLimit (Limit), HistoryFileName (""),
433  OriginalCompletion (rl_attempted_completion_function) {
434  rl_startup_hook = StartupHook;
435  rl_attempted_completion_function = UserCompletion;
436  using_history();
437  }
438 
446  SReadline (const std::string& historyFileName,
447  const size_t Limit = DefaultHistoryLimit)
448  : HistoryLimit (Limit), HistoryFileName (historyFileName),
449  OriginalCompletion (rl_attempted_completion_function) {
450  rl_startup_hook = StartupHook;
451  rl_attempted_completion_function = UserCompletion;
452  using_history();
453  LoadHistory (HistoryFileName);
454  }
455 
461  rl_attempted_completion_function = OriginalCompletion;
462  SaveHistory (HistoryFileName);
463  }
464 
471  std::string GetLine (const std::string& Prompt) {
472  bool Unused;
473  return GetLine (Prompt, Unused);
474  }
475 
484  template <typename Container>
485  std::string GetLine (const std::string& Prompt, Container& ReadTokens) {
486  bool Unused;
487  return GetLine (Prompt, ReadTokens, Unused);
488  }
489 
499  template <typename Container>
500  std::string GetLine (const std::string& Prompt, Container& ReadTokens,
501  bool& BreakOut) {
502  std::string Input (GetLine (Prompt, BreakOut));
503  SplitTokens (Input, ReadTokens);
504  return Input;
505  }
506 
507 
515  std::string GetLine (const std::string& Prompt, bool& BreakOut) {
516  BreakOut = true;
517 
518  char* ReadLine (readline (Prompt.c_str()));
519  if (ReadLine == NULL) {
520  return std::string();
521  }
522 
523  // It's OK
524  BreakOut = false;
525  std::string Input (ReadLine);
526  free (ReadLine); ReadLine = NULL;
527 
528  boost::algorithm::trim (Input);
529  if (Input.empty() == false) {
530  if (history_length == 0
531  || Input != history_list()[ history_length - 1 ]->line) {
532  add_history (Input.c_str());
533 
534  if (history_length >= static_cast<int> (HistoryLimit)) {
535  stifle_history (HistoryLimit);
536  }
537  }
538  }
539 
540  return Input;
541  }
542 
543 
549  template <typename ContainerType>
550  void GetHistory (ContainerType& Container) {
551  for (int k (0); k < history_length; ++k ) {
552  Container.push_back (history_list()[k]->line);
553  }
554  }
555 
562  bool SaveHistory (std::ostream& OS) {
563  if (!OS) {
564  return false;
565  }
566 
567  for (int k (0); k < history_length; ++k) {
568  OS << history_list()[ k ]->line << std::endl;
569  }
570  return true;
571  }
572 
579  bool SaveHistory (const std::string& FileName) {
580  if (FileName.empty() == true) {
581  return false;
582  }
583 
584  std::ofstream OS (FileName.c_str());
585  return SaveHistory (OS);
586  }
587 
592  void ClearHistory() {
593  clear_history();
594  }
595 
602  bool LoadHistory (std::istream& IS) {
603  if (!IS) {
604  return false;
605  }
606 
607  ClearHistory();
608  std::string OneLine;
609 
610  while (!getline (IS, OneLine).eof()) {
611  boost::algorithm::trim( OneLine );
612  if ((history_length == 0)
613  || OneLine != history_list()[history_length - 1]->line) {
614  add_history (OneLine.c_str());
615  }
616  }
617  stifle_history (HistoryLimit);
618  return true;
619  }
620 
627  bool LoadHistory (const std::string& FileName) {
628  if (FileName.empty() == true) {
629  return false;
630  }
631 
632  std::ifstream IS (FileName.c_str());
633  return LoadHistory (IS);
634  }
635 
655  template <typename ContainerType>
656  void RegisterCompletions (const ContainerType& Container) {
657  Completions.clear();
658  for (typename ContainerType::const_iterator k (Container.begin());
659  k != Container.end(); ++k) {
660  std::vector<std::string> OneLine;
661  const std::string& kStr = static_cast<std::string> (*k);
662 
663  SplitTokens (kStr, OneLine);
664  Completions.push_back (OneLine);
665  }
666  }
667 
673  void SetKeymap (SKeymap& NewKeymap) {
674  rl_set_keymap (NewKeymap.keymap);
675  KeymapWasSetup = true;
676  Earlykeymap = NewKeymap.keymap;
677  }
678 
679 
680  private:
681  // /////////////////////////// Attributes /////////////////////////
685  const size_t HistoryLimit;
686 
690  const std::string HistoryFileName;
691 
695  rl_completion_func_t* OriginalCompletion;
696  };
697 
698 }; // namespace swift
699 
700 #endif
701