view.rs 11 KB

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