interactive.rs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. //
  2. // imag - the personal information management suite for the commandline
  3. // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
  4. //
  5. // This library is free software; you can redistribute it and/or
  6. // modify it under the terms of the GNU Lesser General Public
  7. // License as published by the Free Software Foundation; version
  8. // 2.1 of the License.
  9. //
  10. // This library is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. // Lesser General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Lesser General Public
  16. // License along with this library; if not, write to the Free Software
  17. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  18. //
  19. use std::collections::BTreeMap;
  20. use std::fmt::{Display, Formatter, Error};
  21. use std::io::Write;
  22. use std::io::stderr;
  23. use std::io::stdin;
  24. use std::process::exit;
  25. use std::result::Result as RResult;
  26. use libimagcounter::counter::Counter;
  27. use libimagcounter::error::CounterError;
  28. use libimagrt::runtime::Runtime;
  29. use libimagutil::key_value_split::IntoKeyValue;
  30. use libimagutil::warn_exit::warn_exit;
  31. use libimagerror::trace::{trace_error, trace_error_exit};
  32. type Result<T> = RResult<T, CounterError>;
  33. pub fn interactive(rt: &Runtime) {
  34. let scmd = rt.cli().subcommand_matches("interactive");
  35. if scmd.is_none() {
  36. warn_exit("No subcommand", 1);
  37. }
  38. let scmd = scmd.unwrap();
  39. debug!("Found 'interactive' command");
  40. let mut pairs : BTreeMap<char, Binding> = BTreeMap::new();
  41. for spec in scmd.values_of("spec").unwrap() {
  42. match compute_pair(rt, &spec) {
  43. Ok((k, v)) => { pairs.insert(k, v); },
  44. Err(e) => { trace_error(&e); },
  45. }
  46. }
  47. if !has_quit_binding(&pairs) {
  48. pairs.insert('q', Binding::Function(String::from("quit"), Box::new(quit)));
  49. }
  50. stderr().flush().ok();
  51. loop {
  52. println!("---");
  53. for (k, v) in &pairs {
  54. println!("\t[{}] => {}", k, v);
  55. }
  56. println!("---");
  57. print!("counter > ");
  58. let mut input = String::new();
  59. if let Err(e) = stdin().read_line(&mut input) {
  60. trace_error_exit(&e, 1);
  61. }
  62. let cont = if !input.is_empty() {
  63. let increment = match input.chars().next() { Some('-') => false, _ => true };
  64. input.chars().all(|chr| {
  65. match pairs.get_mut(&chr) {
  66. Some(&mut Binding::Counter(ref mut ctr)) => {
  67. if increment {
  68. debug!("Incrementing");
  69. if let Err(e) = ctr.inc() {
  70. trace_error(&e);
  71. }
  72. } else {
  73. debug!("Decrementing");
  74. if let Err(e) = ctr.dec() {
  75. trace_error(&e);
  76. }
  77. }
  78. true
  79. },
  80. Some(&mut Binding::Function(ref name, ref f)) => {
  81. debug!("Calling {}", name);
  82. f()
  83. },
  84. None => true,
  85. }
  86. })
  87. } else {
  88. println!("No input...");
  89. println!("\tUse a single character to increment the counter which is bound to it");
  90. println!("\tUse 'q' (or the character bound to quit()) to exit");
  91. println!("\tPrefix the line with '-' to decrement instead of increment the counters");
  92. println!("");
  93. true
  94. };
  95. if !cont {
  96. break;
  97. }
  98. }
  99. }
  100. fn has_quit_binding(pairs: &BTreeMap<char, Binding>) -> bool {
  101. pairs.iter()
  102. .any(|(_, bind)| {
  103. match *bind {
  104. Binding::Function(ref name, _) => name == "quit",
  105. _ => false,
  106. }
  107. })
  108. }
  109. enum Binding<'a> {
  110. Counter(Counter<'a>),
  111. Function(String, Box<Fn() -> bool>),
  112. }
  113. impl<'a> Display for Binding<'a> {
  114. fn fmt(&self, fmt: &mut Formatter) -> RResult<(), Error> {
  115. match *self {
  116. Binding::Counter(ref c) => {
  117. match c.name() {
  118. Ok(name) => {
  119. try!(write!(fmt, "{}", name));
  120. Ok(())
  121. },
  122. Err(e) => {
  123. trace_error(&e);
  124. Ok(()) // TODO: Find a better way to escalate here.
  125. },
  126. }
  127. },
  128. Binding::Function(ref name, _) => write!(fmt, "{}()", name),
  129. }
  130. }
  131. }
  132. fn compute_pair<'a>(rt: &'a Runtime, spec: &str) -> Result<(char, Binding<'a>)> {
  133. let kv = String::from(spec).into_kv();
  134. if kv.is_none() {
  135. warn_exit("Key-Value parsing failed!", 1);
  136. }
  137. let kv = kv.unwrap();
  138. let (k, v) = kv.into();
  139. if !k.len() == 1 {
  140. // We have a key which is not only a single character!
  141. exit(1);
  142. }
  143. if v == "quit" {
  144. // TODO uncaught unwrap()
  145. Ok((k.chars().next().unwrap(), Binding::Function(String::from("quit"), Box::new(quit))))
  146. } else {
  147. // TODO uncaught unwrap()
  148. Counter::load(v, rt.store()).and_then(|ctr| Ok((k.chars().next().unwrap(), Binding::Counter(ctr))))
  149. }
  150. }
  151. fn quit() -> bool {
  152. false
  153. }