view.rs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 spans = 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 name_span = Spans::from("Node Info");
  176. spans.push(name_span);
  177. }
  178. Some(SelectableObject::Session(_session)) => {
  179. let name_span = Spans::from("Session Info");
  180. spans.push(name_span);
  181. }
  182. Some(SelectableObject::Connect(connect)) => {
  183. let log = self.msg_log.get(&connect.id);
  184. match log {
  185. Some(values) => {
  186. for (k, v) in values {
  187. match k.as_str() {
  188. "send" => {
  189. let msg_log =
  190. Spans::from(Span::styled(format!("S: {}", v), style));
  191. spans.push(msg_log);
  192. }
  193. "recv" => {
  194. let msg_log =
  195. Spans::from(Span::styled(format!("R: {}", v), style));
  196. spans.push(msg_log);
  197. }
  198. data => {
  199. return Err(DnetViewError::UnexpectedData(data.to_string()))
  200. }
  201. }
  202. }
  203. }
  204. None => return Err(DnetViewError::CannotFindId),
  205. }
  206. }
  207. None => return Err(DnetViewError::NotSelectableObject),
  208. }
  209. }
  210. let graph = Paragraph::new(spans)
  211. .block(Block::default().borders(Borders::ALL))
  212. .style(Style::default());
  213. f.render_widget(graph, slice[1]);
  214. Ok(())
  215. }
  216. }
  217. #[derive(Debug, Clone)]
  218. pub struct IdListView {
  219. pub state: ListState,
  220. pub ids: FxHashSet<String>,
  221. }
  222. impl IdListView {
  223. pub fn new(ids: FxHashSet<String>) -> IdListView {
  224. IdListView { state: ListState::default(), ids }
  225. }
  226. pub fn next(&mut self) {
  227. let i = match self.state.selected() {
  228. Some(i) => {
  229. if i >= self.ids.len() - 1 {
  230. 0
  231. } else {
  232. i + 1
  233. }
  234. }
  235. None => 0,
  236. };
  237. self.state.select(Some(i));
  238. }
  239. pub fn previous(&mut self) {
  240. let i = match self.state.selected() {
  241. Some(i) => {
  242. if i == 0 {
  243. self.ids.len() - 1
  244. } else {
  245. i - 1
  246. }
  247. }
  248. None => 0,
  249. };
  250. self.state.select(Some(i));
  251. }
  252. pub fn unselect(&mut self) {
  253. self.state.select(None);
  254. }
  255. }
  256. #[derive(Debug, Clone)]
  257. pub struct NodeInfoView {
  258. pub index: usize,
  259. pub infos: FxHashMap<String, NodeInfo>,
  260. }
  261. impl NodeInfoView {
  262. pub fn new(infos: FxHashMap<String, NodeInfo>) -> NodeInfoView {
  263. let index = 0;
  264. NodeInfoView { index, infos }
  265. }
  266. pub fn next(&mut self) {
  267. self.index = (self.index + 1) % self.infos.len();
  268. }
  269. pub fn previous(&mut self) {
  270. if self.index > 0 {
  271. self.index -= 1;
  272. } else {
  273. self.index = self.infos.len() - 1;
  274. }
  275. }
  276. }