view.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program 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
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. //use log::debug;
  19. use std::collections::HashMap;
  20. use ratatui::{
  21. backend::Backend,
  22. layout::{Constraint, Direction, Layout, Rect},
  23. style::{Color, Modifier, Style},
  24. text::{Line, Span},
  25. widgets::{Block, Borders, List, ListItem, ListState, Paragraph},
  26. Frame,
  27. };
  28. use darkfi::util::time::NanoTimestamp;
  29. use crate::{
  30. error::{DnetViewError, DnetViewResult},
  31. model::{NodeInfo, SelectableObject},
  32. };
  33. type MsgLog = Vec<(NanoTimestamp, String, String)>;
  34. type MsgMap = HashMap<String, MsgLog>;
  35. #[derive(Debug, Clone)]
  36. pub struct View {
  37. pub id_menu: IdMenu,
  38. pub msg_list: MsgList,
  39. pub selectables: HashMap<String, SelectableObject>,
  40. pub ordered_list: Vec<String>,
  41. }
  42. impl Default for View {
  43. fn default() -> Self {
  44. Self::new()
  45. }
  46. }
  47. impl<'a> View {
  48. pub fn new() -> Self {
  49. let msg_map = HashMap::new();
  50. let msg_list = MsgList::new(msg_map, 0);
  51. let selectables = HashMap::new();
  52. let id_menu = IdMenu::new(Vec::new());
  53. let ordered_list = Vec::new();
  54. Self { id_menu, msg_list, selectables, ordered_list }
  55. }
  56. pub fn update(&mut self, msg_map: MsgMap, selectables: HashMap<String, SelectableObject>) {
  57. self.update_selectable(selectables.clone());
  58. self.update_msg_list(msg_map);
  59. self.update_id_menu(selectables);
  60. self.update_msg_index();
  61. self.make_ordered_list();
  62. }
  63. // We copy the values into a string to initialize List as a StatefulObject.
  64. fn update_id_menu(&mut self, selectables: HashMap<String, SelectableObject>) {
  65. for id in selectables.keys() {
  66. if !self.id_menu.ids.iter().any(|i| i == id) {
  67. self.id_menu.ids.push(id.to_string());
  68. }
  69. }
  70. }
  71. // We first add every selectable object into a hashmap to avoid duplicates.
  72. fn update_selectable(&mut self, selectables: HashMap<String, SelectableObject>) {
  73. for (id, obj) in selectables {
  74. self.selectables.insert(id, obj);
  75. }
  76. }
  77. // The order of the ordered_list created here must match the order
  78. // of the Vec<ListItem> created in render_left().
  79. // This is used to render_right() correctly.
  80. fn make_ordered_list(&mut self) {
  81. for obj in self.selectables.values() {
  82. match obj {
  83. SelectableObject::Node(node) => {
  84. if !self.ordered_list.iter().any(|i| i == &node.dnet_id) {
  85. self.ordered_list.push(node.dnet_id.clone());
  86. }
  87. if !node.is_offline && node.dnet_enabled {
  88. for inbound in &node.inbound {
  89. if !inbound.is_empty {
  90. if !self.ordered_list.iter().any(|i| i == &inbound.dnet_id) {
  91. self.ordered_list.push(inbound.dnet_id.clone());
  92. }
  93. if !self.ordered_list.iter().any(|i| i == &inbound.info.dnet_id) {
  94. self.ordered_list.push(inbound.info.dnet_id.clone());
  95. }
  96. }
  97. }
  98. for outbound in &node.outbound {
  99. if !outbound.is_empty {
  100. if !self.ordered_list.iter().any(|i| i == &outbound.dnet_id) {
  101. self.ordered_list.push(outbound.dnet_id.clone());
  102. }
  103. if !self.ordered_list.iter().any(|i| i == &outbound.info.dnet_id) {
  104. self.ordered_list.push(outbound.info.dnet_id.clone());
  105. }
  106. }
  107. }
  108. }
  109. }
  110. SelectableObject::Lilith(lilith) => {
  111. if !self.ordered_list.iter().any(|i| i == &lilith.id) {
  112. self.ordered_list.push(lilith.id.clone());
  113. }
  114. for network in &lilith.networks {
  115. if !self.ordered_list.iter().any(|i| i == &network.id) {
  116. self.ordered_list.push(network.id.clone());
  117. }
  118. }
  119. }
  120. _ => (),
  121. }
  122. }
  123. }
  124. // TODO: this function displays msgs according to what id is
  125. // selected. It's ugly, would prefer something more simple.
  126. fn update_msg_index(&mut self) {
  127. if let Some(sel) = self.id_menu.state.selected() {
  128. if let Some(ord) = self.ordered_list.get(sel) {
  129. if let Some(i) = self.msg_list.msg_map.get(ord) {
  130. self.msg_list.index = i.len();
  131. }
  132. }
  133. }
  134. }
  135. fn update_msg_list(&mut self, msg_map: MsgMap) {
  136. for (id, msg) in msg_map {
  137. self.msg_list.msg_map.insert(id, msg);
  138. }
  139. }
  140. pub fn render<B: Backend>(&mut self, f: &mut Frame<'_, B>) -> DnetViewResult<()> {
  141. let margin = 2;
  142. let direction = Direction::Horizontal;
  143. let cnstrnts = vec![Constraint::Percentage(50), Constraint::Percentage(50)];
  144. let slice = Layout::default()
  145. .direction(direction)
  146. .margin(margin)
  147. .constraints(cnstrnts)
  148. .split(f.size());
  149. self.render_left(f, slice[0])?;
  150. if self.ordered_list.is_empty() {
  151. // we have not received any data
  152. Ok(())
  153. } else {
  154. // get the id at the current index
  155. match self.id_menu.state.selected() {
  156. Some(i) => match self.ordered_list.get(i) {
  157. Some(i) => {
  158. let id = i.clone();
  159. self.render_right(f, slice[1], id)?;
  160. Ok(())
  161. }
  162. None => Err(DnetViewError::NoIdAtIndex),
  163. },
  164. // nothing is selected right now
  165. None => Ok(()),
  166. }
  167. }
  168. }
  169. fn render_left<B: Backend>(&mut self, f: &mut Frame<'_, B>, slice: Rect) -> DnetViewResult<()> {
  170. let style = Style::default();
  171. let mut nodes = Vec::new();
  172. for obj in self.selectables.values() {
  173. match obj {
  174. SelectableObject::Node(node) => {
  175. if node.is_offline {
  176. let style =
  177. Style::default().fg(Color::LightBlue).add_modifier(Modifier::ITALIC);
  178. let mut name = String::new();
  179. name.push_str(&node.name);
  180. name.push_str("(Offline)");
  181. let name_span = Span::styled(name, style);
  182. let lines = vec![Line::from(name_span)];
  183. let names = ListItem::new(lines);
  184. nodes.push(names);
  185. } else {
  186. if !node.dnet_enabled {
  187. let style =
  188. Style::default().fg(Color::LightBlue).add_modifier(Modifier::BOLD);
  189. let mut name = String::new();
  190. name.push_str(&node.name);
  191. name.push_str("(dnetview is not enabled)");
  192. let name_span = Span::styled(name, style);
  193. let lines = vec![Line::from(name_span)];
  194. let names = ListItem::new(lines);
  195. nodes.push(names);
  196. } else {
  197. let name_span = Span::raw(&node.name);
  198. let lines = vec![Line::from(name_span)];
  199. let names = ListItem::new(lines);
  200. nodes.push(names);
  201. if !node.inbound.is_empty() {
  202. let name = Span::styled(format!(" Inbound"), style);
  203. let lines = vec![Line::from(name)];
  204. let names = ListItem::new(lines);
  205. nodes.push(names);
  206. for inbound in &node.inbound {
  207. let mut infos = Vec::new();
  208. match inbound.info.addr.as_str() {
  209. "Null" => {
  210. let style = Style::default()
  211. .fg(Color::Blue)
  212. .add_modifier(Modifier::ITALIC);
  213. let name = Span::styled(
  214. format!(" {} ", inbound.info.addr),
  215. style,
  216. );
  217. infos.push(name);
  218. }
  219. addr => {
  220. let name =
  221. Span::styled(format!(" {}", addr), style);
  222. infos.push(name);
  223. if !inbound.info.remote_id.is_empty() {
  224. let remote_id = Span::styled(
  225. format!("({})", inbound.info.remote_id),
  226. style,
  227. );
  228. infos.push(remote_id)
  229. }
  230. }
  231. }
  232. let lines = vec![Line::from(infos)];
  233. let names = ListItem::new(lines);
  234. nodes.push(names);
  235. }
  236. }
  237. if !&node.outbound.is_empty() {
  238. let name = Span::styled(format!(" Outbound"), style);
  239. let lines = vec![Line::from(name)];
  240. let names = ListItem::new(lines);
  241. nodes.push(names);
  242. for outbound in &node.outbound {
  243. let mut infos = Vec::new();
  244. match outbound.info.addr.as_str() {
  245. "Null" => {
  246. let style = Style::default()
  247. .fg(Color::Blue)
  248. .add_modifier(Modifier::ITALIC);
  249. let name = Span::styled(
  250. format!(" {} ", outbound.info.addr),
  251. style,
  252. );
  253. infos.push(name);
  254. }
  255. addr => {
  256. let name =
  257. Span::styled(format!(" {}", addr), style);
  258. infos.push(name);
  259. if !outbound.info.remote_id.is_empty() {
  260. let remote_id = Span::styled(
  261. format!("({})", outbound.info.remote_id),
  262. style,
  263. );
  264. infos.push(remote_id)
  265. }
  266. }
  267. }
  268. let lines = vec![Line::from(infos)];
  269. let names = ListItem::new(lines);
  270. nodes.push(names);
  271. }
  272. }
  273. }
  274. }
  275. }
  276. SelectableObject::Lilith(lilith) => {
  277. let name_span = Span::raw(&lilith.name);
  278. let lines = vec![Line::from(name_span)];
  279. let names = ListItem::new(lines);
  280. nodes.push(names);
  281. for network in &lilith.networks {
  282. let name = Span::styled(format!(" {}", network.name), style);
  283. let lines = vec![Line::from(name)];
  284. let names = ListItem::new(lines);
  285. nodes.push(names);
  286. }
  287. }
  288. _ => (),
  289. }
  290. }
  291. let nodes =
  292. List::new(nodes).block(Block::default().borders(Borders::ALL)).highlight_symbol(">> ");
  293. f.render_stateful_widget(nodes, slice, &mut self.id_menu.state);
  294. Ok(())
  295. }
  296. fn parse_msg_list(&self, info_id: String) -> DnetViewResult<List<'a>> {
  297. let send_style = Style::default().fg(Color::LightCyan);
  298. let recv_style = Style::default().fg(Color::DarkGray);
  299. let mut texts = Vec::new();
  300. let mut lines = Vec::new();
  301. let log = self.msg_list.msg_map.get(&info_id);
  302. match log {
  303. Some(values) => {
  304. for (i, (t, k, v)) in values.iter().enumerate() {
  305. lines.push(match k.as_str() {
  306. "send" => {
  307. Span::styled(format!("{} {} S: {}", i, t, v), send_style)
  308. }
  309. "recv" => {
  310. Span::styled(format!("{} {} R: {}", i, t, v), recv_style)
  311. }
  312. data => return Err(DnetViewError::UnexpectedData(data.to_string())),
  313. });
  314. }
  315. }
  316. None => return Err(DnetViewError::CannotFindId),
  317. }
  318. for line in lines.clone() {
  319. let text = ListItem::new(line);
  320. texts.push(text);
  321. }
  322. let msg_list = List::new(texts).block(Block::default().borders(Borders::ALL));
  323. Ok(msg_list)
  324. }
  325. fn render_right<B: Backend>(
  326. &mut self,
  327. f: &mut Frame<'_, B>,
  328. slice: Rect,
  329. selected: String,
  330. ) -> DnetViewResult<()> {
  331. //debug!(target: "dnetview", "render_right() selected ID: {}", selected.clone());
  332. let style = Style::default();
  333. let mut lines = Vec::new();
  334. if self.selectables.is_empty() {
  335. // we have not received any selectable data
  336. return Ok(())
  337. } else {
  338. let info = self.selectables.get(&selected);
  339. match info {
  340. Some(SelectableObject::Node(node)) => {
  341. lines.push(Line::from(Span::styled("Type: Normal", style)));
  342. lines.push(Line::from(Span::styled("Hosts:", style)));
  343. for host in &node.hosts {
  344. lines.push(Line::from(Span::styled(format!(" {}", host), style)));
  345. }
  346. }
  347. Some(SelectableObject::Session(session)) => {
  348. let addr = Span::styled(format!("Addr: {}", session.addr), style);
  349. lines.push(Line::from(addr));
  350. if session.state.is_some() {
  351. let addr = Span::styled(
  352. format!("State: {}", session.state.as_ref().unwrap()),
  353. style,
  354. );
  355. lines.push(Line::from(addr));
  356. }
  357. }
  358. Some(SelectableObject::Slot(slot)) => {
  359. let text = self.parse_msg_list(slot.dnet_id.clone())?;
  360. f.render_stateful_widget(text, slice, &mut self.msg_list.state);
  361. }
  362. Some(SelectableObject::Lilith(_lilith)) => {
  363. lines.push(Line::from(Span::styled("Type: Lilith", style)));
  364. }
  365. Some(SelectableObject::Network(network)) => {
  366. lines.push(Line::from(Span::styled("URLs:", style)));
  367. for url in &network.urls {
  368. lines.push(Line::from(Span::styled(format!(" {}", url), style)));
  369. }
  370. lines.push(Line::from(Span::styled("Hosts:", style)));
  371. for node in &network.nodes {
  372. lines.push(Line::from(Span::styled(format!(" {}", node), style)));
  373. }
  374. }
  375. None => return Err(DnetViewError::NotSelectableObject),
  376. }
  377. }
  378. let graph = Paragraph::new(lines)
  379. .block(Block::default().borders(Borders::ALL))
  380. .style(Style::default());
  381. f.render_widget(graph, slice);
  382. Ok(())
  383. }
  384. }
  385. #[derive(Debug, Clone)]
  386. pub struct IdMenu {
  387. pub state: ListState,
  388. pub ids: Vec<String>,
  389. }
  390. impl IdMenu {
  391. pub fn new(ids: Vec<String>) -> IdMenu {
  392. IdMenu { state: ListState::default(), ids }
  393. }
  394. pub fn next(&mut self) {
  395. let i = match self.state.selected() {
  396. Some(i) => {
  397. if i >= self.ids.len() - 1 {
  398. 0
  399. } else {
  400. i + 1
  401. }
  402. }
  403. None => 0,
  404. };
  405. self.state.select(Some(i));
  406. }
  407. pub fn previous(&mut self) {
  408. let i = match self.state.selected() {
  409. Some(i) => {
  410. if i == 0 {
  411. self.ids.len() - 1
  412. } else {
  413. i - 1
  414. }
  415. }
  416. None => 0,
  417. };
  418. self.state.select(Some(i));
  419. }
  420. pub fn unselect(&mut self) {
  421. self.state.select(None);
  422. }
  423. }
  424. #[derive(Debug, Clone)]
  425. pub struct MsgList {
  426. pub state: ListState,
  427. pub msg_map: MsgMap,
  428. pub index: usize,
  429. }
  430. impl MsgList {
  431. pub fn new(msg_map: MsgMap, index: usize) -> MsgList {
  432. MsgList { state: ListState::default(), msg_map, index }
  433. }
  434. // TODO: reimplement
  435. //pub fn next(&mut self) {
  436. // let i = match self.state.selected() {
  437. // Some(i) => {
  438. // if i >= self.msg_len - 1 {
  439. // 0
  440. // } else {
  441. // i + 1
  442. // }
  443. // }
  444. // None => 0,
  445. // };
  446. // self.state.select(Some(i));
  447. //}
  448. //pub fn previous(&mut self) {
  449. // let i = match self.state.selected() {
  450. // Some(i) => {
  451. // if i == 0 {
  452. // self.msg_len - 1
  453. // } else {
  454. // i - 1
  455. // }
  456. // }
  457. // None => 0,
  458. // };
  459. // self.state.select(Some(i));
  460. //}
  461. pub fn scroll(&mut self) -> DnetViewResult<()> {
  462. let i = match self.state.selected() {
  463. Some(i) => i + self.index,
  464. None => 0,
  465. };
  466. self.state.select(Some(i));
  467. Ok(())
  468. }
  469. pub fn unselect(&mut self) {
  470. self.state.select(None);
  471. }
  472. }
  473. #[derive(Debug, Clone)]
  474. pub struct NodeInfoView {
  475. pub index: usize,
  476. pub infos: HashMap<String, NodeInfo>,
  477. }
  478. impl NodeInfoView {
  479. pub fn new(infos: HashMap<String, NodeInfo>) -> NodeInfoView {
  480. let index = 0;
  481. NodeInfoView { index, infos }
  482. }
  483. //pub fn next(&mut self) {
  484. // self.index = (self.index + 1) % self.infos.len();
  485. //}
  486. //pub fn previous(&mut self) {
  487. // if self.index > 0 {
  488. // self.index -= 1;
  489. // } else {
  490. // self.index = self.infos.len() - 1;
  491. // }
  492. //}
  493. }