view.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. import urwid
  18. import logging
  19. import asyncio
  20. import datetime as dt
  21. from scroll import ScrollBar, Scrollable
  22. from model import Model
  23. class DnetWidget(urwid.WidgetWrap):
  24. def __init__(self, node_name, session):
  25. self.node_name = node_name
  26. self.session = session
  27. def selectable(self):
  28. return True
  29. def keypress(self, size, key):
  30. return key
  31. def update(self, txt):
  32. super().__init__(txt)
  33. self._w = urwid.AttrWrap(self._w, None)
  34. self._w.focus_attr = 'line'
  35. class Node(DnetWidget):
  36. def set_txt(self, is_empty: bool):
  37. if is_empty:
  38. txt = urwid.Text(f"{self.node_name} (offline)")
  39. super().update(txt)
  40. else:
  41. txt = urwid.Text(f"{self.node_name}")
  42. super().update(txt)
  43. class Session(DnetWidget):
  44. def set_txt(self):
  45. txt = urwid.Text(f" {self.session}")
  46. super().update(txt)
  47. class Slot(DnetWidget):
  48. def set_txt(self, i, addr):
  49. self.i = i
  50. self.addr = addr
  51. if len(self.i) == 1:
  52. txt = urwid.Text(f" {self.i}: {self.addr}")
  53. else:
  54. txt = urwid.Text(f" {self.addr}")
  55. super().update(txt)
  56. class View():
  57. palette = [
  58. ('body','light gray','default', 'standout'),
  59. ('line','dark cyan','default','standout'),
  60. ]
  61. def __init__(self, model):
  62. self.model = model
  63. info_text = urwid.Text("")
  64. self.pile = urwid.Pile([info_text])
  65. scroll = ScrollBar(Scrollable(self.pile))
  66. rightbox = urwid.LineBox(scroll)
  67. self.listbox_content = []
  68. self.listwalker = urwid.SimpleListWalker(self.listbox_content)
  69. self.list = urwid.ListBox(self.listwalker)
  70. leftbox = urwid.LineBox(self.list)
  71. columns = urwid.Columns([leftbox, rightbox], focus_column=0)
  72. self.ui = urwid.Frame(urwid.AttrWrap( columns, 'body' ))
  73. #-----------------------------------------------------------------
  74. # Render get_info()
  75. #-----------------------------------------------------------------
  76. def draw_info(self, node_name, info):
  77. node = Node(node_name, "node")
  78. node.set_txt(False)
  79. self.listwalker.contents.append(node)
  80. if 'outbound' in info and info['outbound']:
  81. session = Session(node_name, "outbound")
  82. session.set_txt()
  83. self.listwalker.contents.append(session)
  84. for i, addr in info['outbound'].items():
  85. slot = Slot(node_name, "outbound-slot")
  86. slot.set_txt(i, addr)
  87. self.listwalker.contents.append(slot)
  88. if 'inbound' in info and info['inbound']:
  89. if any(info['inbound'].values()):
  90. session = Session(node_name, "inbound")
  91. session.set_txt()
  92. self.listwalker.contents.append(session)
  93. for i, addr in info['inbound'].items():
  94. if bool(addr):
  95. slot = Slot(node_name, "inbound-slot")
  96. slot.set_txt(i, addr)
  97. self.listwalker.contents.append(slot)
  98. if 'manual' in info and info['manual']:
  99. session = Session(node_name, "manual")
  100. session.set_txt()
  101. self.listwalker.contents.append(session)
  102. for i, addr in info['manual'].items():
  103. slot = Slot(node_name, "manual-slot")
  104. slot.set_txt(i, addr)
  105. self.listwalker.contents.append(slot)
  106. if 'seed' in info and info['seed']:
  107. session = Session(node_name, "seed")
  108. session.set_txt()
  109. self.listwalker.contents.append(session)
  110. for i, info in info['seed'].items():
  111. slot = Slot(node_name, "seed-slot")
  112. slot.set_txt(i, addr)
  113. self.listwalker.contents.append(slot)
  114. def draw_empty(self, node_name, info):
  115. node = Node(node_name, "node")
  116. node.set_txt(True)
  117. self.listwalker.contents.append(node)
  118. #-----------------------------------------------------------------
  119. # Render subscribe_events() (left menu)
  120. #-----------------------------------------------------------------
  121. def fill_left_box(self):
  122. live_inbound = []
  123. new_inbound= {}
  124. for index, item in enumerate(self.listwalker.contents):
  125. # Update outbound slot info
  126. if item.session == "outbound-slot":
  127. key = (f"{item.node_name}", f"{item.i}")
  128. if key in self.model.nodes[item.node_name]['event']:
  129. info = self.model.nodes[item.node_name]['event'].get(key)
  130. slot = Slot(item.node_name, item.session)
  131. slot.set_txt(item.i, info)
  132. self.listwalker.contents[index] = slot
  133. #-----------------------------------------------------------------
  134. # Render subscribe_events() (right menu)
  135. #-----------------------------------------------------------------
  136. def fill_right_box(self):
  137. self.pile.contents.clear()
  138. focus_w = self.list.get_focus()
  139. if focus_w[0] is None:
  140. return
  141. session = focus_w[0].session
  142. if session == "outbound":
  143. key = (focus_w[0].node_name, "outbound")
  144. info = self.model.nodes.get(focus_w[0].node_name)
  145. if key in info['event']:
  146. ev = info['event'].get(key)
  147. self.pile.contents.append((
  148. urwid.Text(f" {ev}"),
  149. self.pile.options()))
  150. if (session == "outbound-slot" or session == "inbound-slot"
  151. or session == "manual-slot" or session == "seed-slot"):
  152. addr = focus_w[0].addr
  153. node_name = focus_w[0].node_name
  154. info = self.model.nodes.get(node_name)
  155. if addr in info['msgs']:
  156. msg = info['msgs'].get(addr)
  157. for m in msg:
  158. time = m[0]
  159. event = m[1]
  160. msg = m[2]
  161. self.pile.contents.append((urwid.Text(
  162. f"{time}: {event}: {msg}"),
  163. self.pile.options()))
  164. async def update_view(self, evloop: asyncio.AbstractEventLoop,
  165. loop: urwid.MainLoop):
  166. live_nodes = []
  167. dead_nodes = []
  168. reborn_nodes = []
  169. redead_nodes = []
  170. known_nodes = []
  171. live_inbound = []
  172. dead_inbound = []
  173. while True:
  174. await asyncio.sleep(0.1)
  175. nodes = self.model.nodes.items()
  176. listw = self.listwalker.contents
  177. evloop.call_soon(loop.draw_screen)
  178. # TODO: reimplement events handling.
  179. for index, item in enumerate(listw):
  180. # Keep track of known nodes.
  181. if item.node_name not in known_nodes:
  182. logging.debug("Appending to known nodes...")
  183. known_nodes.append(item.node_name)
  184. for name, info in nodes:
  185. # 1. Sort nodes into lists.
  186. if bool(info) and name not in live_nodes:
  187. logging.debug("Online node we do not know.")
  188. live_nodes.append(name)
  189. if not bool(info) and name not in dead_nodes:
  190. logging.debug("Offline node we do not know.")
  191. dead_nodes.append(name)
  192. if bool(info) and name in dead_nodes:
  193. logging.debug("Dead node came online.")
  194. if name not in reborn_nodes:
  195. reborn_nodes.append(name)
  196. if not bool(info) and name in live_nodes:
  197. logging.debug("Online node went offline.")
  198. if name not in redead_nodes:
  199. redead_nodes.append(name)
  200. # 1. Display nodes according to list.
  201. if name in live_nodes and name not in known_nodes:
  202. logging.debug("Drawing unknown live node.")
  203. self.draw_info(name, info)
  204. if name in dead_nodes and name not in known_nodes:
  205. logging.debug("Drawing unknown dead node.")
  206. self.draw_empty(name, info)
  207. if name in reborn_nodes and name in known_nodes:
  208. logging.debug("Removing reborn node from known nodes.")
  209. dead_nodes.clear()
  210. reborn_nodes.clear()
  211. known_nodes.clear()
  212. listw.clear()
  213. if name in redead_nodes and name in known_nodes:
  214. logging.debug("Removing redead node from known nodes.")
  215. live_nodes.clear()
  216. redead_nodes.clear()
  217. known_nodes.clear()
  218. listw.clear()
  219. # 3. Handle events on nodes we know.
  220. if bool(info) and name in known_nodes:
  221. self.fill_left_box()
  222. self.fill_right_box()