view.rs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. //use darkfi::error::{Error, Result};
  2. use fxhash::{FxHashMap, FxHashSet};
  3. use tui::widgets::ListState;
  4. use tui::{
  5. backend::Backend,
  6. layout::{Constraint, Direction, Layout, Rect},
  7. style::Style,
  8. text::{Span, Spans},
  9. widgets::{Block, Borders, List, ListItem, Paragraph},
  10. Frame,
  11. };
  12. use crate::{
  13. error::{DnetViewError, DnetViewResult},
  14. model::{NodeInfo, SelectableObject},
  15. };
  16. use log::debug;
  17. #[derive(Debug)]
  18. pub struct View {
  19. pub nodes: NodeInfoView,
  20. pub msg_log: FxHashMap<String, Vec<(String, String)>>,
  21. pub active_ids: IdListView,
  22. pub selectables: FxHashMap<String, SelectableObject>,
  23. }
  24. impl View {
  25. pub fn new(
  26. nodes: NodeInfoView,
  27. msg_log: FxHashMap<String, Vec<(String, String)>>,
  28. active_ids: IdListView,
  29. selectables: FxHashMap<String, SelectableObject>,
  30. ) -> View {
  31. View { nodes, msg_log, active_ids, selectables }
  32. }
  33. pub fn update(
  34. &mut self,
  35. nodes: FxHashMap<String, NodeInfo>,
  36. msg_log: FxHashMap<String, Vec<(String, String)>>,
  37. selectables: FxHashMap<String, SelectableObject>,
  38. ) {
  39. self.update_nodes(nodes);
  40. self.update_selectable(selectables);
  41. self.update_active_ids();
  42. self.update_msg_log(msg_log);
  43. }
  44. fn update_nodes(&mut self, nodes: FxHashMap<String, NodeInfo>) {
  45. for (id, node) in nodes {
  46. self.nodes.infos.insert(id, node);
  47. }
  48. }
  49. fn update_selectable(&mut self, selectables: FxHashMap<String, SelectableObject>) {
  50. for (id, obj) in selectables {
  51. self.selectables.insert(id, obj);
  52. }
  53. }
  54. fn update_active_ids(&mut self) {
  55. for info in self.nodes.infos.values() {
  56. self.active_ids.ids.insert(info.id.to_string());
  57. for child in &info.children {
  58. if !child.is_empty == true {
  59. self.active_ids.ids.insert(child.id.to_string());
  60. for child in &child.children {
  61. self.active_ids.ids.insert(child.id.to_string());
  62. }
  63. }
  64. }
  65. }
  66. }
  67. fn update_msg_log(&mut self, msg_log: FxHashMap<String, Vec<(String, String)>>) {
  68. for (id, msg) in msg_log {
  69. self.msg_log.insert(id, msg);
  70. }
  71. }
  72. pub fn render<B: Backend>(&mut self, f: &mut Frame<'_, B>) -> DnetViewResult<()> {
  73. let margin = 2;
  74. let direction = Direction::Horizontal;
  75. let cnstrnts = vec![Constraint::Percentage(50), Constraint::Percentage(50)];
  76. let slice = Layout::default()
  77. .direction(direction)
  78. .margin(margin)
  79. .constraints(cnstrnts)
  80. .split(f.size());
  81. let mut id_list = self.render_id_list(f, slice.clone())?;
  82. // remove any duplicates
  83. id_list.dedup();
  84. if id_list.is_empty() {
  85. // we have not received any data
  86. Ok(())
  87. } else {
  88. // get the id at the current index
  89. match self.active_ids.state.selected() {
  90. Some(i) => match id_list.get(i) {
  91. Some(i) => {
  92. self.render_info(f, slice.clone(), i.to_string())?;
  93. Ok(())
  94. }
  95. None => return Err(DnetViewError::NoIdAtIndex),
  96. },
  97. // nothing is selected right now
  98. None => Ok(()),
  99. }
  100. }
  101. }
  102. fn render_id_list<B: Backend>(
  103. &mut self,
  104. f: &mut Frame<'_, B>,
  105. slice: Vec<Rect>,
  106. ) -> DnetViewResult<Vec<String>> {
  107. let style = Style::default();
  108. let mut nodes = Vec::new();
  109. let mut ids: Vec<String> = Vec::new();
  110. for info in self.nodes.infos.values() {
  111. let name_span = Span::raw(&info.name);
  112. let lines = vec![Spans::from(name_span)];
  113. let names = ListItem::new(lines);
  114. nodes.push(names);
  115. ids.push(info.id.clone());
  116. for session in &info.children {
  117. if !session.is_empty == true {
  118. let name = Span::styled(format!(" {}", session.name), style);
  119. let lines = vec![Spans::from(name)];
  120. let names = ListItem::new(lines);
  121. nodes.push(names);
  122. ids.push(session.id.clone());
  123. for connection in &session.children {
  124. let mut info = Vec::new();
  125. let name = Span::styled(format!(" {}", connection.addr), style);
  126. info.push(name);
  127. match connection.last_status.as_str() {
  128. "recv" => {
  129. let msg = Span::styled(
  130. format!(" [R: {}]", connection.last_msg),
  131. style,
  132. );
  133. info.push(msg);
  134. }
  135. "sent" => {
  136. let msg = Span::styled(
  137. format!(" [S: {}]", connection.last_msg),
  138. style,
  139. );
  140. info.push(msg);
  141. }
  142. "Null" => {
  143. // Empty msg log. Do nothing
  144. }
  145. data => return Err(DnetViewError::UnexpectedData(data.to_string())),
  146. }
  147. let lines = vec![Spans::from(info)];
  148. let names = ListItem::new(lines);
  149. nodes.push(names);
  150. ids.push(connection.id.clone());
  151. }
  152. }
  153. }
  154. }
  155. let nodes =
  156. List::new(nodes).block(Block::default().borders(Borders::ALL)).highlight_symbol(">> ");
  157. f.render_stateful_widget(nodes, slice[0], &mut self.active_ids.state);
  158. Ok(ids)
  159. }
  160. fn render_info<B: Backend>(
  161. &mut self,
  162. f: &mut Frame<'_, B>,
  163. slice: Vec<Rect>,
  164. selected: String,
  165. ) -> DnetViewResult<()> {
  166. let style = Style::default();
  167. let mut lines = Vec::new();
  168. if self.selectables.is_empty() {
  169. // we have not received any selectable data
  170. return Ok(())
  171. } else {
  172. let info = self.selectables.get(&selected);
  173. match info {
  174. Some(SelectableObject::Node(node)) => {
  175. let node_info =
  176. Span::styled(format!("External addr: {}", node.external_addr), style);
  177. lines.push(Spans::from(node_info));
  178. }
  179. Some(SelectableObject::Session(_session)) => {
  180. //let name_span = Spans::from("Session Info");
  181. //spans.push(name_span);
  182. }
  183. Some(SelectableObject::Connect(connect)) => {
  184. let log = self.msg_log.get(&connect.id);
  185. match log {
  186. Some(values) => {
  187. for (k, v) in values {
  188. lines.push(Spans::from(match k.as_str() {
  189. "send" => Span::styled(format!("S: {}", v), style),
  190. "recv" => Span::styled(format!("R: {}", v), style),
  191. data => {
  192. return Err(DnetViewError::UnexpectedData(data.to_string()))
  193. }
  194. }));
  195. }
  196. }
  197. None => return Err(DnetViewError::CannotFindId),
  198. }
  199. }
  200. None => return Err(DnetViewError::NotSelectableObject),
  201. }
  202. }
  203. let graph = Paragraph::new(lines)
  204. .block(Block::default().borders(Borders::ALL))
  205. .style(Style::default());
  206. f.render_widget(graph, slice[1]);
  207. Ok(())
  208. }
  209. }
  210. #[derive(Debug, Clone)]
  211. pub struct IdListView {
  212. pub state: ListState,
  213. pub ids: FxHashSet<String>,
  214. }
  215. impl IdListView {
  216. pub fn new(ids: FxHashSet<String>) -> IdListView {
  217. IdListView { state: ListState::default(), ids }
  218. }
  219. pub fn next(&mut self) {
  220. let i = match self.state.selected() {
  221. Some(i) => {
  222. if i >= self.ids.len() - 1 {
  223. 0
  224. } else {
  225. i + 1
  226. }
  227. }
  228. None => 0,
  229. };
  230. self.state.select(Some(i));
  231. }
  232. pub fn previous(&mut self) {
  233. let i = match self.state.selected() {
  234. Some(i) => {
  235. if i == 0 {
  236. self.ids.len() - 1
  237. } else {
  238. i - 1
  239. }
  240. }
  241. None => 0,
  242. };
  243. self.state.select(Some(i));
  244. }
  245. pub fn unselect(&mut self) {
  246. self.state.select(None);
  247. }
  248. }
  249. #[derive(Debug, Clone)]
  250. pub struct NodeInfoView {
  251. pub index: usize,
  252. pub infos: FxHashMap<String, NodeInfo>,
  253. }
  254. impl NodeInfoView {
  255. pub fn new(infos: FxHashMap<String, NodeInfo>) -> NodeInfoView {
  256. let index = 0;
  257. NodeInfoView { index, infos }
  258. }
  259. pub fn next(&mut self) {
  260. self.index = (self.index + 1) % self.infos.len();
  261. }
  262. pub fn previous(&mut self) {
  263. if self.index > 0 {
  264. self.index -= 1;
  265. } else {
  266. self.index = self.infos.len() - 1;
  267. }
  268. }
  269. }