view.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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::{Color, Modifier, Style},
  8. text::{Span, Spans},
  9. widgets::{Block, Borders, List, ListItem, Paragraph},
  10. Frame,
  11. };
  12. use darkfi::util::NanoTimestamp;
  13. use crate::{
  14. error::{DnetViewError, DnetViewResult},
  15. model::{NodeInfo, SelectableObject},
  16. };
  17. #[derive(Debug)]
  18. pub struct View {
  19. pub nodes: NodeInfoView,
  20. pub msg_log: FxHashMap<String, Vec<(NanoTimestamp, 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<(NanoTimestamp, 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<(NanoTimestamp, 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. self.active_ids.ids.clear();
  56. for info in self.nodes.infos.values() {
  57. self.active_ids.ids.insert(info.id.to_string());
  58. for session in &info.children {
  59. if !session.is_empty == true {
  60. self.active_ids.ids.insert(session.id.to_string());
  61. for connect in &session.children {
  62. self.active_ids.ids.insert(connect.id.to_string());
  63. }
  64. }
  65. }
  66. }
  67. }
  68. fn update_msg_log(&mut self, msg_log: FxHashMap<String, Vec<(NanoTimestamp, String, String)>>) {
  69. for (id, msg) in msg_log {
  70. self.msg_log.insert(id, msg);
  71. }
  72. }
  73. pub fn render<B: Backend>(&mut self, f: &mut Frame<'_, B>) -> DnetViewResult<()> {
  74. let margin = 2;
  75. let direction = Direction::Horizontal;
  76. let cnstrnts = vec![Constraint::Percentage(50), Constraint::Percentage(50)];
  77. let slice = Layout::default()
  78. .direction(direction)
  79. .margin(margin)
  80. .constraints(cnstrnts)
  81. .split(f.size());
  82. let mut id_list = self.render_id_list(f, slice.clone())?;
  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 node_ids: Vec<String> = Vec::new();
  110. let mut session_ids: Vec<String> = Vec::new();
  111. let mut connect_ids: Vec<String> = Vec::new();
  112. let mut ids: Vec<String> = Vec::new();
  113. for info in self.nodes.infos.values() {
  114. match info.is_offline {
  115. true => {
  116. let style = Style::default().fg(Color::Blue).add_modifier(Modifier::ITALIC);
  117. let mut name = String::new();
  118. name.push_str(&info.name);
  119. name.push_str("(Offline)");
  120. let name_span = Span::styled(name, style);
  121. let lines = vec![Spans::from(name_span)];
  122. let names = ListItem::new(lines);
  123. nodes.push(names);
  124. ids.push(info.id.clone());
  125. node_ids.push(info.id.clone());
  126. }
  127. false => {
  128. let name_span = Span::raw(&info.name);
  129. let lines = vec![Spans::from(name_span)];
  130. let names = ListItem::new(lines);
  131. nodes.push(names);
  132. ids.push(info.id.clone());
  133. node_ids.push(info.id.clone());
  134. for session in &info.children {
  135. if !session.is_empty == true {
  136. let name = Span::styled(format!(" {}", session.name), style);
  137. let lines = vec![Spans::from(name)];
  138. let names = ListItem::new(lines);
  139. nodes.push(names);
  140. session_ids.push(session.id.clone());
  141. ids.push(session.id.clone());
  142. for connection in &session.children {
  143. let mut info = Vec::new();
  144. let name =
  145. Span::styled(format!(" {}", connection.addr), style);
  146. info.push(name);
  147. match connection.last_status.as_str() {
  148. "recv" => {
  149. let msg = Span::styled(
  150. format!(
  151. " [R: {}]",
  152. connection.last_msg
  153. ),
  154. style,
  155. );
  156. info.push(msg);
  157. }
  158. "sent" => {
  159. let msg = Span::styled(
  160. format!(
  161. " [S: {}]",
  162. connection.last_msg
  163. ),
  164. style,
  165. );
  166. info.push(msg);
  167. }
  168. "Null" => {
  169. // Empty msg log. Do nothing
  170. }
  171. data => {
  172. return Err(DnetViewError::UnexpectedData(data.to_string()))
  173. }
  174. }
  175. let lines = vec![Spans::from(info)];
  176. let names = ListItem::new(lines);
  177. nodes.push(names);
  178. connect_ids.push(connection.id.clone());
  179. ids.push(connection.id.clone());
  180. }
  181. }
  182. }
  183. }
  184. }
  185. }
  186. let nodes =
  187. List::new(nodes).block(Block::default().borders(Borders::ALL)).highlight_symbol(">> ");
  188. f.render_stateful_widget(nodes, slice[0], &mut self.active_ids.state);
  189. Ok(ids)
  190. }
  191. fn render_info<B: Backend>(
  192. &mut self,
  193. f: &mut Frame<'_, B>,
  194. slice: Vec<Rect>,
  195. selected: String,
  196. ) -> DnetViewResult<()> {
  197. let style = Style::default();
  198. let mut lines = Vec::new();
  199. if self.selectables.is_empty() {
  200. // we have not received any selectable data
  201. return Ok(())
  202. } else {
  203. let info = self.selectables.get(&selected);
  204. match info {
  205. Some(SelectableObject::Node(node)) => {
  206. if node.external_addr.is_some() {
  207. let node_info = Span::styled(
  208. format!("External addr: {}", node.external_addr.as_ref().unwrap()),
  209. style,
  210. );
  211. lines.push(Spans::from(node_info));
  212. }
  213. }
  214. Some(SelectableObject::Session(session)) => {
  215. if session.accept_addr.is_some() {
  216. let session_info = Span::styled(
  217. format!("Accept addr: {}", session.accept_addr.as_ref().unwrap()),
  218. style,
  219. );
  220. lines.push(Spans::from(session_info));
  221. }
  222. }
  223. Some(SelectableObject::Connect(connect)) => {
  224. let log = self.msg_log.get(&connect.id);
  225. match log {
  226. Some(values) => {
  227. for (t, k, v) in values {
  228. lines.push(Spans::from(match k.as_str() {
  229. "send" => {
  230. Span::styled(format!("{} S: {}", t, v), style)
  231. }
  232. "recv" => {
  233. Span::styled(format!("{} R: {}", t, v), style)
  234. }
  235. data => {
  236. return Err(DnetViewError::UnexpectedData(data.to_string()))
  237. }
  238. }));
  239. }
  240. }
  241. None => return Err(DnetViewError::CannotFindId),
  242. }
  243. }
  244. None => return Err(DnetViewError::NotSelectableObject),
  245. }
  246. }
  247. let graph = Paragraph::new(lines)
  248. .block(Block::default().borders(Borders::ALL))
  249. .style(Style::default());
  250. f.render_widget(graph, slice[1]);
  251. Ok(())
  252. }
  253. }
  254. #[derive(Debug, Clone)]
  255. pub struct IdListView {
  256. pub state: ListState,
  257. pub ids: FxHashSet<String>,
  258. }
  259. impl IdListView {
  260. pub fn new(ids: FxHashSet<String>) -> IdListView {
  261. IdListView { state: ListState::default(), ids }
  262. }
  263. pub fn next(&mut self) {
  264. let i = match self.state.selected() {
  265. Some(i) => {
  266. if i >= self.ids.len() - 1 {
  267. 0
  268. } else {
  269. i + 1
  270. }
  271. }
  272. None => 0,
  273. };
  274. self.state.select(Some(i));
  275. }
  276. pub fn previous(&mut self) {
  277. let i = match self.state.selected() {
  278. Some(i) => {
  279. if i == 0 {
  280. self.ids.len() - 1
  281. } else {
  282. i - 1
  283. }
  284. }
  285. None => 0,
  286. };
  287. self.state.select(Some(i));
  288. }
  289. pub fn unselect(&mut self) {
  290. self.state.select(None);
  291. }
  292. }
  293. #[derive(Debug, Clone)]
  294. pub struct NodeInfoView {
  295. pub index: usize,
  296. pub infos: FxHashMap<String, NodeInfo>,
  297. }
  298. impl NodeInfoView {
  299. pub fn new(infos: FxHashMap<String, NodeInfo>) -> NodeInfoView {
  300. let index = 0;
  301. NodeInfoView { index, infos }
  302. }
  303. pub fn next(&mut self) {
  304. self.index = (self.index + 1) % self.infos.len();
  305. }
  306. pub fn previous(&mut self) {
  307. if self.index > 0 {
  308. self.index -= 1;
  309. } else {
  310. self.index = self.infos.len() - 1;
  311. }
  312. }
  313. }