YARP
Yet Another Robot Platform
Terminal.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2006-2020 Istituto Italiano di Tecnologia (IIT)
3  * Copyright (C) 2006-2010 RobotCub Consortium
4  * All rights reserved.
5  *
6  * This software may be modified and distributed under the terms of the
7  * BSD-3-Clause license. See the accompanying LICENSE file for details.
8  */
9 
10 #include <yarp/os/impl/Terminal.h>
11 
12 #include <yarp/os/Bottle.h>
13 #include <yarp/os/Port.h>
14 #include <yarp/os/Vocab.h>
17 
18 #include <cstdio>
19 #include <cstring>
20 
21 #ifdef YARP_HAS_Libedit
22 # include <editline/readline.h>
23 char* szLine = (char*)nullptr;
24 bool readlineEOF = false;
25 #endif // YARP_HAS_Libedit
26 
28 {
29 #ifdef YARP_HAS_Libedit
30  if (yarp::os::impl::isatty(yarp::os::impl::fileno(stdin)) != 0) {
31  return readlineEOF;
32  }
33 #endif // YARP_HAS_Libedit
34  return feof(stdin) != 0;
35 }
36 
38 {
39  std::string txt;
40 
41 #ifdef YARP_HAS_Libedit
42  if (yarp::os::impl::isatty(yarp::os::impl::fileno(stdin)) != 0) {
43  if (szLine != nullptr) {
44  free(szLine);
45  szLine = (char*)nullptr;
46  }
47 
48  szLine = readline(">>");
49  if ((szLine != nullptr) && (*szLine != 0)) {
50  txt = szLine;
51  add_history(szLine);
52  } else if (szLine == nullptr) {
53  readlineEOF = true;
54  }
55  return txt;
56  }
57 #endif // YARP_HAS_Libedit
58 
59  bool done = false;
60  char buf[2048];
61  while (!done) {
62  char* result = fgets(buf, sizeof(buf), stdin);
63  if (result != nullptr) {
64  for (unsigned int i = 0; i < strlen(buf); i++) {
65  if (buf[i] == '\n') {
66  buf[i] = '\0';
67  done = true;
68  break;
69  }
70  }
71  txt += buf;
72  } else {
73  done = true;
74  }
75  }
76  return txt;
77 }
78 
80 {
81  bool end = false;
82 
83  std::string txt;
84  if (!EOFreached()) {
85  txt = getStdin();
86  }
87 
88  if (EOFreached() || (!txt.empty() && txt[0] < 32 && txt[0] != '\n' && txt[0] != '\r')) {
89  end = true;
90  }
91 
92  if (end) {
93  txt = "";
94  }
95 
96  if (eof != nullptr) {
97  *eof = end;
98  }
99  return txt;
100 }
Port.h
PlatformStdio.h
yarp::os::impl::Terminal::readString
std::string readString(bool *eof)
Definition: Terminal.cpp:79
yarp::os::impl::Terminal::EOFreached
bool EOFreached()
Definition: Terminal.cpp:27
Terminal.h
PlatformUnistd.h
Vocab.h
yarp::os::impl::Terminal::getStdin
std::string getStdin()
Definition: Terminal.cpp:37
Bottle.h