mirror of
https://github.com/markqvist/NomadNet.git
synced 2025-05-17 13:20:25 -04:00
Merge commit 'refs/pull/70/head' of github.com:markqvist/NomadNet into ifconf
This commit is contained in:
commit
0889d4e5e3
6 changed files with 4080 additions and 13 deletions
|
@ -51,6 +51,14 @@ THEMES = {
|
|||
("browser_controls", "light gray", "default", "default", "#bbb", "default"),
|
||||
("progress_full", "black", "light gray", "standout", "#111", "#bbb"),
|
||||
("progress_empty", "light gray", "default", "default", "#ddd", "default"),
|
||||
("interface_title", "", "", "default", "", ""),
|
||||
("interface_title_selected", "bold", "", "bold", "", ""),
|
||||
("connected_status", "dark green", "default", "default", "dark green", "default"),
|
||||
("disconnected_status", "dark red", "default", "default", "dark red", "default"),
|
||||
("placeholder", "dark gray", "default", "default", "dark gray", "default"),
|
||||
("placeholder_text", "dark gray", "default", "default", "dark gray", "default"),
|
||||
("error", "light red,blink", "default", "blink", "#f44,blink", "default"),
|
||||
|
||||
],
|
||||
},
|
||||
THEME_LIGHT: {
|
||||
|
@ -69,6 +77,7 @@ THEMES = {
|
|||
("msg_header_ok", "black", "dark green", "standout", "#111", "#6b2"),
|
||||
("msg_header_caution", "black", "yellow", "standout", "#111", "#fd3"),
|
||||
("msg_header_sent", "black", "dark gray", "standout", "#111", "#ddd"),
|
||||
("msg_header_propagated", "black", "light blue", "standout", "#111", "#28b"),
|
||||
("msg_header_delivered", "black", "light blue", "standout", "#111", "#28b"),
|
||||
("msg_header_failed", "black", "dark gray", "standout", "#000", "#777"),
|
||||
("msg_warning_untrusted", "black", "dark red", "standout", "#111", "dark red"),
|
||||
|
@ -86,6 +95,13 @@ THEMES = {
|
|||
("browser_controls", "dark gray", "default", "default", "#444", "default"),
|
||||
("progress_full", "black", "dark gray", "standout", "#111", "#bbb"),
|
||||
("progress_empty", "dark gray", "default", "default", "#ddd", "default"),
|
||||
("interface_title", "dark gray", "default", "default", "#444", "default"),
|
||||
("interface_title_selected", "dark gray,bold", "default", "bold", "#444,bold", "default"),
|
||||
("connected_status", "dark green", "default", "default", "#4a0", "default"),
|
||||
("disconnected_status", "dark red", "default", "default", "#a22", "default"),
|
||||
("placeholder", "light gray", "default", "default", "#999", "default"),
|
||||
("placeholder_text", "light gray", "default", "default", "#999", "default"),
|
||||
("error", "dark red,blink", "default", "blink", "#a22,blink", "default"),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
@ -128,6 +144,8 @@ GLYPHS = {
|
|||
("sent", "/\\", "\u2191", "\U000f0cd8"),
|
||||
("papermsg", "P", "\u25a4", "\uf719"),
|
||||
("qrcode", "QR", "\u25a4", "\uf029"),
|
||||
("selected", "[*] ", "\u25CF", "\u25CF"),
|
||||
("unselected", "[ ] ", "\u25CB", "\u25CB"),
|
||||
}
|
||||
|
||||
class TextUI:
|
||||
|
@ -163,7 +181,7 @@ class TextUI:
|
|||
|
||||
if self.app.config["textui"]["glyphs"] == "plain":
|
||||
glyphset = "plain"
|
||||
elif self.app.config["textui"]["glyphs"] == "unicoode":
|
||||
elif self.app.config["textui"]["glyphs"] == "unicode":
|
||||
glyphset = "unicode"
|
||||
elif self.app.config["textui"]["glyphs"] == "nerdfont":
|
||||
glyphset = "nerdfont"
|
||||
|
|
|
@ -109,6 +109,7 @@ class TopicList(urwid.WidgetWrap):
|
|||
self.topic_list = [
|
||||
GuideEntry(self.app, self, guide_display, "Introduction"),
|
||||
GuideEntry(self.app, self, guide_display, "Concepts & Terminology"),
|
||||
GuideEntry(self.app, self, guide_display, "Interfaces"),
|
||||
GuideEntry(self.app, self, guide_display, "Hosting a Node"),
|
||||
GuideEntry(self.app, self, guide_display, "Configuration Options"),
|
||||
GuideEntry(self.app, self, guide_display, "Keyboard Shortcuts"),
|
||||
|
@ -386,6 +387,225 @@ Links can be inserted into micron documents. See the `*Markup`* section of this
|
|||
|
||||
'''
|
||||
|
||||
TOPIC_INTERFACES = '''>Interfaces
|
||||
|
||||
Reticulum supports using many kinds of devices as networking interfaces, and allows you to mix and match them in any way you choose.
|
||||
|
||||
The number of distinct network topologies you can create with Reticulum is more or less endless, but common to them all is that you will need to define one or more interfaces for Reticulum to use.
|
||||
|
||||
The `![ Interfaces ]`! section of NomadNet lets you add, monitor, and update interfaces configured for your Reticulum instance.
|
||||
|
||||
If you are starting NomadNet for the first time you will find that an `!AutoInterface`! has been added by default. This interface will try to use your available network device to communicate with other peers discovered on your local network.
|
||||
|
||||
Interfaces come in many different types and can interact with physical mediums like LoRa radios or standard IP networks.
|
||||
|
||||
>>Viewing Interfaces
|
||||
|
||||
To view more info about an interface, navigate using the `!Up`! and `!Down`! arrow keys or by clicking with the mouse. Pressing `! < Enter >`! on a selected interface will bring you to a detailed interface view, which will show configuration parameters and realtime charts. From here you can also disable or edit the interface. To change the orientation of the TX/RX charts, press `!< V >`! for a vertical layout, and `!< H >`! for a horizontal view.
|
||||
|
||||
>>Updating Interfaces
|
||||
|
||||
To edit an interface, select the interface and press `!< Ctrl + E >`!.
|
||||
|
||||
To remove an interface, select the interface and press `!< Ctrl + X >`!. You can also perform both of these actions from the details view.
|
||||
|
||||
>>Adding Interfaces
|
||||
|
||||
To add a new interface, press `!< Ctrl + A >`!. From here you can select which type of interface you want to add. Each unique interface type will have different configuration options.
|
||||
|
||||
`Ffff`! (!) Note:`! After adding or modifying interfaces, you will need to restart NomadNet or your Reticulum instance for changes to take effect.`f`b
|
||||
|
||||
|
||||
>Interface Types
|
||||
|
||||
>>AutoInterface
|
||||
|
||||
The Auto Interface enables communication with other discoverable Reticulum nodes over autoconfigured IPv6 and UDP. It does not need any functional IP infrastructure like routers or DHCP servers, but will require at least some sort of switching medium between peers (a wired switch, a hub, a WiFi access point or similar).
|
||||
|
||||
```
|
||||
Required Parameters:
|
||||
Interface Name
|
||||
|
||||
Optional Parameters:
|
||||
Devices: Specific network devices to use
|
||||
Ignored Devices: Network devices to exclude
|
||||
Group ID: Create isolated networks on the same physical LAN
|
||||
Discovery Scope: Can set to link, admin, site, organisation or global
|
||||
```
|
||||
|
||||
The AutoInterface is ideal for quickly connecting to other Reticulum nodes on your local network without complex configuration.
|
||||
|
||||
>>TCPClientInterface
|
||||
|
||||
The TCP Client interface connects to remote TCP server interfaces, enabling communication over the Internet or private networks.
|
||||
|
||||
```
|
||||
Required Parameters:
|
||||
Target Host: Hostname or IP address of the server
|
||||
Target Port: Port number to connect to
|
||||
|
||||
Optional Parameters:
|
||||
I2P Tunneled: Enable for connecting through I2P
|
||||
KISS Framing: Enable for KISS framing for software modems
|
||||
```
|
||||
|
||||
This interface is commonly used to connect to Reticulum testnets or other persistent nodes on the Internet.
|
||||
|
||||
>>TCPServerInterface
|
||||
|
||||
The TCP Server interface listens for incoming connections, allowing other Reticulum peers to connect to your node using TCPClientInterface.
|
||||
|
||||
```
|
||||
Required Parameters:
|
||||
Listen IP: IP address to bind to (0.0.0.0 for all interfaces)
|
||||
Listen Port: Port number to listen on
|
||||
|
||||
Optional Parameters:
|
||||
Prefer IPv6: Bind to IPv6 address if available
|
||||
I2P Tunneled: Enable for I2P tunnel support
|
||||
Device: Specific network device to use (e,g
|
||||
```
|
||||
|
||||
Useful when you want other nodes to be able to connect to your Transport instance over TCP/IP.
|
||||
|
||||
>>UDPInterface
|
||||
|
||||
The UDP interface allows communication over IP networks using UDP packets.
|
||||
|
||||
```
|
||||
Required Parameters:
|
||||
Listen IP: IP address to bind to
|
||||
Listen Port: Port to listen on
|
||||
Forward IP: IP address to forward to (Can be broadcast address)
|
||||
Forward Port: Port to forward to
|
||||
|
||||
Optional Parameters:
|
||||
Device: Specific network device to use
|
||||
```
|
||||
|
||||
>>I2PInterface
|
||||
|
||||
The I2P interface enables connections over the Invisible Internet Protocol. The I2PInterface requires an I2P daemon to be running on your system, such as `!i2pd`!
|
||||
|
||||
```
|
||||
Optional Parameters:
|
||||
Peers: I2P addresses to connect to (Can be left as none if running as a Transport)
|
||||
```
|
||||
|
||||
|
||||
>>RNodeInterface
|
||||
|
||||
The RNode interface allows using LoRa transceivers running RNode firmware as Reticulum network interfaces.
|
||||
|
||||
```
|
||||
Required Parameters:
|
||||
Port: Serial port or BLE device path
|
||||
Frequency: Operating frequency in MHz
|
||||
Bandwidth: Channel bandwidth
|
||||
TX Power: Transmit power in dBm
|
||||
Spreading Factor: LoRa spreading factor (7-12)
|
||||
Coding Rate: LoRa coding rate (4:5-4:8)
|
||||
|
||||
Optional Parameters:
|
||||
ID Callsign: Station identification
|
||||
ID Interval: Identification interval in seconds
|
||||
Airtime Limits: Control duty cycle
|
||||
```
|
||||
|
||||
The interface includes a parameter calculator to estimate link budget, sensitivity, and data rate on the air based on your settings.
|
||||
|
||||
>>RNodeMultiInterface
|
||||
|
||||
The RNode Multi Interface is designed for use with specific hardware platforms that support multiple subinterfaces or virtual radios. For most LoRa hardware platforms, you will want to use the standard `!RNodeInterface`! instead.
|
||||
|
||||
```
|
||||
Required Parameters:
|
||||
Port: Serial port or BLE device path
|
||||
Subinterfaces: Configuration for each subinterface / virtual radio port
|
||||
|
||||
```
|
||||
|
||||
>>SerialInterface
|
||||
|
||||
The Serial interface enables using direct serial connections as Reticulum interfaces.
|
||||
|
||||
```
|
||||
Required Parameters:
|
||||
Port: Serial port path
|
||||
Speed: Baud rate of serial device
|
||||
Databits: Number of data bits
|
||||
Parity: Parity setting
|
||||
Stopbits: Number of stop bits
|
||||
```
|
||||
|
||||
>>KISSInterface
|
||||
|
||||
The KISS interface supports packet radio modems and TNCs using the KISS protocol.
|
||||
|
||||
```
|
||||
Required Parameters:
|
||||
|
||||
Port: Serial port path
|
||||
Speed: Baud rate of serial device
|
||||
Databits: Number of data bits
|
||||
Parity: Parity setting
|
||||
Stopbits: Number of stop bits
|
||||
Preamble: Modem preamble in milliseconds
|
||||
TX Tail: Transmit tail in milliseconds
|
||||
Slottime: CSMA slottime in milliseconds
|
||||
Persistence: CSMA persistence value
|
||||
|
||||
Optional Parameters:
|
||||
|
||||
ID Callsign: Station identification
|
||||
ID Interval: Identification interval in seconds
|
||||
Flow Control: Enable packet flow control
|
||||
```
|
||||
|
||||
>>PipeInterface
|
||||
|
||||
The Pipe interface allows using external programs as Reticulum interfaces via stdin and stdout.
|
||||
|
||||
```
|
||||
Required Parameters:
|
||||
|
||||
Command: External command to execute
|
||||
|
||||
Optional Parameters:
|
||||
Respawn Delay: Seconds to wait before restarting after failure
|
||||
```
|
||||
|
||||
<
|
||||
>>
|
||||
-∿
|
||||
For more information and to view the full Interface documentation consult the Reticulum manual or visit https://reticulum.network/manual/interfaces.html (Requires external Internet connection)
|
||||
|
||||
|
||||
>Interface Access Code (IFAC) Settings
|
||||
|
||||
Interface Access Codes create private networks and securely segment network traffic. Under `!Show more options`!, you'll find these IFAC settings:
|
||||
|
||||
`!Virtual Network Name`! (network_name):
|
||||
When added, creates a logical network that only communicates with other interfaces using the same name. This allows multiple separate Reticulum networks to exist on the same physical channel or medium.
|
||||
|
||||
`!IFAC Passphrase`! (passphrase):
|
||||
Sets an authentication passphrase for the interface. Only interfaces configured with the same passphrase will be able to communicate. Can be used with or without a network name.
|
||||
|
||||
`!IFAC Size`! (ifac_size):
|
||||
Controls the length of Interface Authentication Codes (8-512 bits). Larger sizes provide stronger security but add overhead to each packet. The default of `!8`! is usually appropriate for most uses.
|
||||
|
||||
>Interface Modes
|
||||
|
||||
When running a Transport node, you can configure interface modes that affect how Reticulum selects paths, propagates announces, and discovers routes:
|
||||
|
||||
`!full`!: Default mode with all discovery, meshing and transport functionality
|
||||
`!gateway`!: Discovers paths on behalf of other nodes
|
||||
`!access_point`!: Operates as a network access point
|
||||
`!roaming`!: For physically mobile interfaces
|
||||
`!boundary`!: For interfaces connecting different network segments
|
||||
|
||||
'''
|
||||
|
||||
TOPIC_CONVERSATIONS = '''>Conversations
|
||||
|
||||
Conversations in Nomad Network
|
||||
|
@ -1247,6 +1467,7 @@ TOPICS = {
|
|||
"Introduction": TOPIC_INTRODUCTION,
|
||||
"Concepts & Terminology": TOPIC_CONCEPTS,
|
||||
"Conversations": TOPIC_CONVERSATIONS,
|
||||
"Interfaces": TOPIC_INTERFACES,
|
||||
"Hosting a Node": TOPIC_HOSTING,
|
||||
"Configuration Options": TOPIC_CONFIG,
|
||||
"Keyboard Shortcuts": TOPIC_SHORTCUTS,
|
||||
|
|
3196
nomadnet/ui/textui/Interfaces.py
Normal file
3196
nomadnet/ui/textui/Interfaces.py
Normal file
File diff suppressed because it is too large
Load diff
|
@ -4,6 +4,7 @@ from .Network import *
|
|||
from .Conversations import *
|
||||
from .Directory import *
|
||||
from .Config import *
|
||||
from .Interfaces import *
|
||||
from .Map import *
|
||||
from .Log import *
|
||||
from .Guide import *
|
||||
|
@ -16,6 +17,7 @@ class SubDisplays():
|
|||
self.conversations_display = ConversationsDisplay(self.app)
|
||||
self.directory_display = DirectoryDisplay(self.app)
|
||||
self.config_display = ConfigDisplay(self.app)
|
||||
self.interface_display = InterfaceDisplay(self.app)
|
||||
self.map_display = MapDisplay(self.app)
|
||||
self.log_display = LogDisplay(self.app)
|
||||
self.guide_display = GuideDisplay(self.app)
|
||||
|
@ -113,6 +115,11 @@ class MainDisplay():
|
|||
self.sub_displays.active_display = self.sub_displays.config_display
|
||||
self.update_active_sub_display()
|
||||
|
||||
def show_interfaces(self, user_data):
|
||||
self.sub_displays.active_display = self.sub_displays.interface_display
|
||||
self.update_active_sub_display()
|
||||
self.sub_displays.interface_display.start()
|
||||
|
||||
def show_log(self, user_data):
|
||||
self.sub_displays.active_display = self.sub_displays.log_display
|
||||
self.sub_displays.log_display.show()
|
||||
|
@ -171,21 +178,22 @@ class MenuDisplay():
|
|||
|
||||
self.menu_indicator = urwid.Text("")
|
||||
|
||||
menu_text = (urwid.PACK, self.menu_indicator)
|
||||
button_network = (11, MenuButton("Network", on_press=handler.show_network))
|
||||
button_conversations = (17, MenuButton("Conversations", on_press=handler.show_conversations))
|
||||
button_directory = (13, MenuButton("Directory", on_press=handler.show_directory))
|
||||
button_map = (7, MenuButton("Map", on_press=handler.show_map))
|
||||
button_log = (7, MenuButton("Log", on_press=handler.show_log))
|
||||
button_config = (10, MenuButton("Config", on_press=handler.show_config))
|
||||
button_guide = (9, MenuButton("Guide", on_press=handler.show_guide))
|
||||
button_quit = (8, MenuButton("Quit", on_press=handler.quit))
|
||||
menu_text = (urwid.PACK, self.menu_indicator)
|
||||
button_network = (11, MenuButton("Network", on_press=handler.show_network))
|
||||
button_conversations = (17, MenuButton("Conversations", on_press=handler.show_conversations))
|
||||
button_directory = (13, MenuButton("Directory", on_press=handler.show_directory))
|
||||
button_map = (7, MenuButton("Map", on_press=handler.show_map))
|
||||
button_log = (7, MenuButton("Log", on_press=handler.show_log))
|
||||
button_config = (10, MenuButton("Config", on_press=handler.show_config))
|
||||
button_interfaces = (14, MenuButton("Interfaces", on_press=handler.show_interfaces))
|
||||
button_guide = (9, MenuButton("Guide", on_press=handler.show_guide))
|
||||
button_quit = (8, MenuButton("Quit", on_press=handler.quit))
|
||||
|
||||
# buttons = [menu_text, button_conversations, button_node, button_directory, button_map]
|
||||
if self.app.config["textui"]["hide_guide"]:
|
||||
buttons = [menu_text, button_conversations, button_network, button_log, button_config, button_quit]
|
||||
buttons = [menu_text, button_conversations, button_network, button_log, button_interfaces, button_config, button_quit]
|
||||
else:
|
||||
buttons = [menu_text, button_conversations, button_network, button_log, button_config, button_guide, button_quit]
|
||||
buttons = [menu_text, button_conversations, button_network, button_log, button_interfaces, button_config, button_guide, button_quit]
|
||||
|
||||
columns = MenuColumns(buttons, dividechars=1)
|
||||
columns.handler = handler
|
||||
|
|
87
nomadnet/vendor/AsciiChart.py
vendored
Normal file
87
nomadnet/vendor/AsciiChart.py
vendored
Normal file
|
@ -0,0 +1,87 @@
|
|||
from __future__ import division
|
||||
from math import ceil, floor, isnan
|
||||
# Derived from asciichartpy | https://github.com/kroitor/asciichart/blob/master/asciichartpy/__init__.py
|
||||
class AsciiChart:
|
||||
def __init__(self, glyphset="unicode"):
|
||||
self.symbols = ['┼', '┤', '╶', '╴', '─', '╰', '╭', '╮', '╯', '│']
|
||||
if glyphset == "plain":
|
||||
self.symbols = ['+', '|', '-', '-', '-', '\'', ',', '.', '`', '|']
|
||||
def plot(self, series, cfg=None):
|
||||
if len(series) == 0:
|
||||
return ''
|
||||
if not isinstance(series[0], list):
|
||||
if all(isnan(n) for n in series):
|
||||
return ''
|
||||
else:
|
||||
series = [series]
|
||||
cfg = cfg or {}
|
||||
minimum = cfg.get('min', min(filter(lambda n: not isnan(n), [j for i in series for j in i])))
|
||||
maximum = cfg.get('max', max(filter(lambda n: not isnan(n), [j for i in series for j in i])))
|
||||
symbols = cfg.get('symbols', self.symbols)
|
||||
if minimum > maximum:
|
||||
raise ValueError('The min value cannot exceed the max value.')
|
||||
interval = maximum - minimum
|
||||
offset = cfg.get('offset', 3)
|
||||
height = cfg.get('height', interval)
|
||||
ratio = height / interval if interval > 0 else 1
|
||||
|
||||
min2 = int(floor(minimum * ratio))
|
||||
max2 = int(ceil(maximum * ratio))
|
||||
|
||||
def clamp(n):
|
||||
return min(max(n, minimum), maximum)
|
||||
|
||||
def scaled(y):
|
||||
return int(round(clamp(y) * ratio) - min2)
|
||||
|
||||
rows = max2 - min2
|
||||
|
||||
width = 0
|
||||
for i in range(0, len(series)):
|
||||
width = max(width, len(series[i]))
|
||||
width += offset
|
||||
|
||||
placeholder = cfg.get('format', '{:8.2f} ')
|
||||
|
||||
result = [[' '] * width for i in range(rows + 1)]
|
||||
|
||||
for y in range(min2, max2 + 1):
|
||||
label = placeholder.format(maximum - ((y - min2) * interval / (rows if rows else 1)))
|
||||
result[y - min2][max(offset - len(label), 0)] = label
|
||||
result[y - min2][offset - 1] = symbols[0] if y == 0 else symbols[1]
|
||||
|
||||
d0 = series[0][0]
|
||||
if not isnan(d0):
|
||||
result[rows - scaled(d0)][offset - 1] = symbols[0]
|
||||
|
||||
for i in range(0, len(series)):
|
||||
for x in range(0, len(series[i]) - 1):
|
||||
d0 = series[i][x + 0]
|
||||
d1 = series[i][x + 1]
|
||||
|
||||
if isnan(d0) and isnan(d1):
|
||||
continue
|
||||
|
||||
if isnan(d0) and not isnan(d1):
|
||||
result[rows - scaled(d1)][x + offset] = symbols[2]
|
||||
continue
|
||||
|
||||
if not isnan(d0) and isnan(d1):
|
||||
result[rows - scaled(d0)][x + offset] = symbols[3]
|
||||
continue
|
||||
|
||||
y0 = scaled(d0)
|
||||
y1 = scaled(d1)
|
||||
if y0 == y1:
|
||||
result[rows - y0][x + offset] = symbols[4]
|
||||
continue
|
||||
|
||||
result[rows - y1][x + offset] = symbols[5] if y0 > y1 else symbols[6]
|
||||
result[rows - y0][x + offset] = symbols[7] if y0 > y1 else symbols[8]
|
||||
|
||||
start = min(y0, y1) + 1
|
||||
end = max(y0, y1)
|
||||
for y in range(start, end):
|
||||
result[rows - y][x + offset] = symbols[9]
|
||||
|
||||
return '\n'.join([''.join(row).rstrip() for row in result])
|
537
nomadnet/vendor/additional_urwid_widgets/FormWidgets.py
vendored
Normal file
537
nomadnet/vendor/additional_urwid_widgets/FormWidgets.py
vendored
Normal file
|
@ -0,0 +1,537 @@
|
|||
import urwid
|
||||
|
||||
class DialogLineBox(urwid.LineBox):
|
||||
def __init__(self, body, parent=None, title="?"):
|
||||
super().__init__(body, title=title)
|
||||
self.parent = parent
|
||||
|
||||
def keypress(self, size, key):
|
||||
if key == "esc":
|
||||
if self.parent and hasattr(self.parent, "dismiss_dialog"):
|
||||
self.parent.dismiss_dialog()
|
||||
return None
|
||||
return super().keypress(size, key)
|
||||
|
||||
class Placeholder(urwid.Edit):
|
||||
def __init__(self, caption="", edit_text="", placeholder="", **kwargs):
|
||||
super().__init__(caption, edit_text, **kwargs)
|
||||
self.placeholder = placeholder
|
||||
|
||||
def render(self, size, focus=False):
|
||||
if not self.edit_text and not focus:
|
||||
placeholder_widget = urwid.Text(("placeholder", self.placeholder))
|
||||
return placeholder_widget.render(size, focus)
|
||||
else:
|
||||
return super().render(size, focus)
|
||||
|
||||
class Dropdown(urwid.WidgetWrap):
|
||||
signals = ['change'] # emit for urwid.connect_signal fn
|
||||
|
||||
def __init__(self, label, options, default=None):
|
||||
self.label = label
|
||||
self.options = options
|
||||
self.selected = default if default is not None else options[0]
|
||||
|
||||
self.main_text = f"{self.selected}"
|
||||
self.main_button = urwid.SelectableIcon(self.main_text, 0)
|
||||
self.main_button = urwid.AttrMap(self.main_button, "button_normal", "button_focus")
|
||||
|
||||
self.option_widgets = []
|
||||
for opt in options:
|
||||
icon = urwid.SelectableIcon(opt, 0)
|
||||
icon = urwid.AttrMap(icon, "list_normal", "list_focus")
|
||||
self.option_widgets.append(icon)
|
||||
|
||||
self.options_walker = urwid.SimpleFocusListWalker(self.option_widgets)
|
||||
self.options_listbox = urwid.ListBox(self.options_walker)
|
||||
self.dropdown_box = None # will be created on open_dropdown
|
||||
|
||||
self.pile = urwid.Pile([self.main_button])
|
||||
self.dropdown_visible = False
|
||||
|
||||
super().__init__(self.pile)
|
||||
|
||||
def open_dropdown(self):
|
||||
if not self.dropdown_visible:
|
||||
height = len(self.options)
|
||||
self.dropdown_box = urwid.BoxAdapter(self.options_listbox, height)
|
||||
self.pile.contents.append((self.dropdown_box, self.pile.options()))
|
||||
self.dropdown_visible = True
|
||||
self.pile.focus_position = 1
|
||||
self.options_walker.set_focus(0)
|
||||
|
||||
def close_dropdown(self):
|
||||
if self.dropdown_visible:
|
||||
self.pile.contents.pop() # remove the dropdown_box
|
||||
self.dropdown_visible = False
|
||||
self.pile.focus_position = 0
|
||||
self.dropdown_box = None
|
||||
|
||||
def keypress(self, size, key):
|
||||
if not self.dropdown_visible:
|
||||
if key == "enter":
|
||||
self.open_dropdown()
|
||||
return None
|
||||
return self.main_button.keypress(size, key)
|
||||
else:
|
||||
if key == "enter":
|
||||
focus_result = self.options_walker.get_focus()
|
||||
if focus_result is not None:
|
||||
focus_widget = focus_result[0]
|
||||
new_val = focus_widget.base_widget.text
|
||||
old_val = self.selected
|
||||
self.selected = new_val
|
||||
self.main_button.base_widget.set_text(f"{self.selected}")
|
||||
|
||||
if old_val != new_val:
|
||||
self._emit('change', new_val)
|
||||
|
||||
self.close_dropdown()
|
||||
return None
|
||||
return self.dropdown_box.keypress(size, key)
|
||||
|
||||
def get_value(self):
|
||||
return self.selected
|
||||
|
||||
class ValidationError(urwid.Text):
|
||||
def __init__(self, message=""):
|
||||
super().__init__(("error", message))
|
||||
|
||||
class FormField:
|
||||
def __init__(self, config_key, transform=None):
|
||||
self.config_key = config_key
|
||||
self.transform = transform or (lambda x: x)
|
||||
|
||||
class FormEdit(Placeholder, FormField):
|
||||
def __init__(self, config_key, caption="", edit_text="", placeholder="", validation_types=None, transform=None, **kwargs):
|
||||
Placeholder.__init__(self, caption, edit_text, placeholder, **kwargs)
|
||||
FormField.__init__(self, config_key, transform)
|
||||
self.validation_types = validation_types or []
|
||||
self.error_widget = urwid.Text("")
|
||||
self.error = None
|
||||
|
||||
def get_value(self):
|
||||
return self.transform(self.edit_text.strip())
|
||||
|
||||
def validate(self):
|
||||
value = self.edit_text.strip()
|
||||
self.error = None
|
||||
|
||||
for validation in self.validation_types:
|
||||
if validation == "required":
|
||||
if not value:
|
||||
self.error = "This field is required"
|
||||
break
|
||||
elif validation == "number":
|
||||
if value and not value.replace('-', '').replace('.', '').isdigit():
|
||||
self.error = "This field must be a number"
|
||||
break
|
||||
elif validation == "float":
|
||||
try:
|
||||
if value:
|
||||
float(value)
|
||||
except ValueError:
|
||||
self.error = "This field must be decimal number"
|
||||
break
|
||||
|
||||
self.error_widget.set_text(("error", self.error or ""))
|
||||
return self.error is None
|
||||
|
||||
class FormCheckbox(urwid.CheckBox, FormField):
|
||||
def __init__(self, config_key, label="", state=False, validation_types=None, transform=None, **kwargs):
|
||||
urwid.CheckBox.__init__(self, label, state, **kwargs)
|
||||
FormField.__init__(self, config_key, transform)
|
||||
self.validation_types = validation_types or []
|
||||
self.error_widget = urwid.Text("")
|
||||
self.error = None
|
||||
|
||||
def get_value(self):
|
||||
return self.transform(self.get_state())
|
||||
|
||||
def validate(self):
|
||||
|
||||
value = self.get_state()
|
||||
self.error = None
|
||||
|
||||
for validation in self.validation_types:
|
||||
if validation == "required":
|
||||
if not value:
|
||||
self.error = "This field is required"
|
||||
break
|
||||
|
||||
self.error_widget.set_text(("error", self.error or ""))
|
||||
return self.error is None
|
||||
|
||||
class FormDropdown(Dropdown, FormField):
|
||||
signals = ['change']
|
||||
|
||||
def __init__(self, config_key, label, options, default=None, validation_types=None, transform=None):
|
||||
self.options = [str(opt) for opt in options]
|
||||
|
||||
if default is not None:
|
||||
default_str = str(default)
|
||||
if default_str in self.options:
|
||||
default = default_str
|
||||
elif transform:
|
||||
try:
|
||||
default_transformed = transform(default_str)
|
||||
for opt in self.options:
|
||||
if transform(opt) == default_transformed:
|
||||
default = opt
|
||||
break
|
||||
except:
|
||||
default = self.options[0]
|
||||
else:
|
||||
default = self.options[0]
|
||||
else:
|
||||
default = self.options[0]
|
||||
|
||||
Dropdown.__init__(self, label, self.options, default)
|
||||
FormField.__init__(self, config_key, transform)
|
||||
|
||||
self.validation_types = validation_types or []
|
||||
self.error_widget = urwid.Text("")
|
||||
self.error = None
|
||||
|
||||
if hasattr(self, 'main_button'):
|
||||
self.main_button.base_widget.set_text(str(default))
|
||||
|
||||
def get_value(self):
|
||||
return self.transform(self.selected)
|
||||
|
||||
def validate(self):
|
||||
value = self.get_value()
|
||||
self.error = None
|
||||
|
||||
for validation in self.validation_types:
|
||||
if validation == "required":
|
||||
if not value:
|
||||
self.error = "This field is required"
|
||||
break
|
||||
|
||||
self.error_widget.set_text(("error", self.error or ""))
|
||||
return self.error is None
|
||||
|
||||
def open_dropdown(self):
|
||||
if not self.dropdown_visible:
|
||||
super().open_dropdown()
|
||||
try:
|
||||
current_index = self.options.index(self.selected)
|
||||
self.options_walker.set_focus(current_index)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
class FormMultiList(urwid.Pile, FormField):
|
||||
def __init__(self, config_key, placeholder="", validation_types=None, transform=None, **kwargs):
|
||||
self.entries = []
|
||||
self.error_widget = urwid.Text("")
|
||||
self.error = None
|
||||
self.placeholder = placeholder
|
||||
self.validation_types = validation_types or []
|
||||
|
||||
first_entry = self.create_entry_row()
|
||||
self.entries.append(first_entry)
|
||||
|
||||
self.add_button = urwid.Button("+ Add Another", on_press=self.add_entry)
|
||||
add_button_padded = urwid.Padding(self.add_button, left=2, right=2)
|
||||
|
||||
pile_widgets = [first_entry, add_button_padded]
|
||||
urwid.Pile.__init__(self, pile_widgets)
|
||||
FormField.__init__(self, config_key, transform)
|
||||
|
||||
def create_entry_row(self):
|
||||
edit = urwid.Edit("", "")
|
||||
entry_row = urwid.Columns([
|
||||
('weight', 1, edit),
|
||||
(3, urwid.Button("×", on_press=lambda button: self.remove_entry(button, entry_row))),
|
||||
])
|
||||
return entry_row
|
||||
|
||||
def remove_entry(self, button, entry_row):
|
||||
if len(self.entries) > 1:
|
||||
self.entries.remove(entry_row)
|
||||
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
|
||||
|
||||
def add_entry(self, button):
|
||||
new_entry = self.create_entry_row()
|
||||
self.entries.append(new_entry)
|
||||
|
||||
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
|
||||
|
||||
def get_pile_widgets(self):
|
||||
return self.entries + [urwid.Padding(self.add_button, left=2, right=2)]
|
||||
|
||||
def get_value(self):
|
||||
values = []
|
||||
for entry in self.entries:
|
||||
edit_widget = entry.contents[0][0]
|
||||
value = edit_widget.edit_text.strip()
|
||||
if value:
|
||||
values.append(value)
|
||||
return self.transform(values)
|
||||
|
||||
def validate(self):
|
||||
values = self.get_value()
|
||||
self.error = None
|
||||
|
||||
for validation in self.validation_types:
|
||||
if validation == "required" and not values:
|
||||
self.error = "At least one entry is required"
|
||||
break
|
||||
|
||||
self.error_widget.set_text(("error", self.error or ""))
|
||||
return self.error is None
|
||||
|
||||
|
||||
class FormMultiTable(urwid.Pile, FormField):
|
||||
def __init__(self, config_key, fields, validation_types=None, transform=None, **kwargs):
|
||||
self.entries = []
|
||||
self.fields = fields
|
||||
self.error_widget = urwid.Text("")
|
||||
self.error = None
|
||||
self.validation_types = validation_types or []
|
||||
|
||||
header_columns = [('weight', 3, urwid.Text(("list_focus", "Name")))]
|
||||
for field_key, field_config in self.fields.items():
|
||||
header_columns.append(('weight', 2, urwid.Text(("list_focus", field_config.get("label", field_key)))))
|
||||
header_columns.append((4, urwid.Text(("list_focus", ""))))
|
||||
|
||||
self.header_row = urwid.Columns(header_columns)
|
||||
|
||||
first_entry = self.create_entry_row()
|
||||
self.entries.append(first_entry)
|
||||
|
||||
self.add_button = urwid.Button("+ Add ", on_press=self.add_entry)
|
||||
add_button_padded = urwid.Padding(self.add_button, left=2, right=2)
|
||||
|
||||
pile_widgets = [
|
||||
self.header_row,
|
||||
urwid.Divider("-"),
|
||||
first_entry,
|
||||
add_button_padded
|
||||
]
|
||||
|
||||
urwid.Pile.__init__(self, pile_widgets)
|
||||
FormField.__init__(self, config_key, transform)
|
||||
|
||||
def create_entry_row(self, name="", values=None):
|
||||
if values is None:
|
||||
values = {}
|
||||
|
||||
name_edit = urwid.Edit("", name)
|
||||
|
||||
columns = [('weight', 3, name_edit)]
|
||||
|
||||
field_widgets = {}
|
||||
for field_key, field_config in self.fields.items():
|
||||
field_value = values.get(field_key, "")
|
||||
|
||||
if field_config.get("type") == "checkbox":
|
||||
widget = urwid.CheckBox("", state=bool(field_value))
|
||||
elif field_config.get("type") == "dropdown":
|
||||
# TODO: dropdown in MultiTable
|
||||
widget = urwid.Edit("", str(field_value))
|
||||
else:
|
||||
widget = urwid.Edit("", str(field_value))
|
||||
|
||||
field_widgets[field_key] = widget
|
||||
columns.append(('weight', 2, widget))
|
||||
|
||||
remove_button = urwid.Button("×", on_press=lambda button: self.remove_entry(button, entry_row))
|
||||
columns.append((4, remove_button))
|
||||
|
||||
entry_row = urwid.Columns(columns)
|
||||
entry_row.name_edit = name_edit
|
||||
entry_row.field_widgets = field_widgets
|
||||
|
||||
return entry_row
|
||||
|
||||
def remove_entry(self, button, entry_row):
|
||||
if len(self.entries) > 1:
|
||||
self.entries.remove(entry_row)
|
||||
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
|
||||
|
||||
def add_entry(self, button):
|
||||
new_entry = self.create_entry_row()
|
||||
self.entries.append(new_entry)
|
||||
|
||||
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
|
||||
|
||||
def get_pile_widgets(self):
|
||||
return [
|
||||
self.header_row,
|
||||
urwid.Divider("-")
|
||||
] + self.entries + [
|
||||
urwid.Padding(self.add_button, left=2, right=2)
|
||||
]
|
||||
|
||||
def get_value(self):
|
||||
values = {}
|
||||
for entry in self.entries:
|
||||
name = entry.name_edit.edit_text.strip()
|
||||
if name:
|
||||
subinterface = {}
|
||||
subinterface["interface_enabled"] = True
|
||||
|
||||
for field_key, widget in entry.field_widgets.items():
|
||||
field_config = self.fields.get(field_key, {})
|
||||
|
||||
if hasattr(widget, "get_state"):
|
||||
value = widget.get_state()
|
||||
elif hasattr(widget, "edit_text"):
|
||||
value = widget.edit_text.strip()
|
||||
|
||||
transform = field_config.get("transform")
|
||||
if transform and value:
|
||||
try:
|
||||
value = transform(value)
|
||||
except (ValueError, TypeError):
|
||||
value = ""
|
||||
|
||||
if value:
|
||||
subinterface[field_key] = value
|
||||
|
||||
values[name] = subinterface
|
||||
|
||||
return self.transform(values) if self.transform else values
|
||||
|
||||
def set_value(self, value):
|
||||
self.entries = []
|
||||
|
||||
if not value:
|
||||
self.entries.append(self.create_entry_row())
|
||||
else:
|
||||
for name, config in value.items():
|
||||
self.entries.append(self.create_entry_row(name=name, values=config))
|
||||
|
||||
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
|
||||
|
||||
def validate(self):
|
||||
values = self.get_value()
|
||||
self.error = None
|
||||
|
||||
for validation in self.validation_types:
|
||||
if validation == "required" and not values:
|
||||
self.error = "At least one subinterface is required"
|
||||
break
|
||||
|
||||
self.error_widget.set_text(("error", self.error or ""))
|
||||
return self.error is None
|
||||
|
||||
|
||||
class FormKeyValuePairs(urwid.Pile, FormField):
|
||||
def __init__(self, config_key, validation_types=None, transform=None, **kwargs):
|
||||
self.entries = []
|
||||
self.error_widget = urwid.Text("")
|
||||
self.error = None
|
||||
self.validation_types = validation_types or []
|
||||
|
||||
header_columns = [
|
||||
('weight', 1, urwid.AttrMap(urwid.Text("Parameter Key"), "multitable_header")),
|
||||
('weight', 1, urwid.AttrMap(urwid.Text("Parameter Value"), "multitable_header")),
|
||||
(4, urwid.AttrMap(urwid.Text("Action"), "multitable_header"))
|
||||
]
|
||||
|
||||
self.header_row = urwid.AttrMap(urwid.Columns(header_columns), "multitable_header")
|
||||
|
||||
first_entry = self.create_entry_row()
|
||||
self.entries.append(first_entry)
|
||||
|
||||
self.add_button = urwid.Button("+ Add Parameter", on_press=self.add_entry)
|
||||
add_button_padded = urwid.Padding(self.add_button, left=2, right=2)
|
||||
|
||||
pile_widgets = [
|
||||
self.header_row,
|
||||
urwid.Divider("-"),
|
||||
first_entry,
|
||||
add_button_padded
|
||||
]
|
||||
|
||||
urwid.Pile.__init__(self, pile_widgets)
|
||||
FormField.__init__(self, config_key, transform)
|
||||
|
||||
def create_entry_row(self, key="", value=""):
|
||||
key_edit = urwid.Edit("", key)
|
||||
value_edit = urwid.Edit("", value)
|
||||
|
||||
remove_button = urwid.Button("×", on_press=lambda button: self.remove_entry(button, entry_row))
|
||||
|
||||
entry_row = urwid.Columns([
|
||||
('weight', 1, key_edit),
|
||||
('weight', 1, value_edit),
|
||||
(4, remove_button)
|
||||
])
|
||||
|
||||
entry_row.key_edit = key_edit
|
||||
entry_row.value_edit = value_edit
|
||||
|
||||
return entry_row
|
||||
|
||||
def remove_entry(self, button, entry_row):
|
||||
if len(self.entries) > 1:
|
||||
self.entries.remove(entry_row)
|
||||
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
|
||||
|
||||
def add_entry(self, button):
|
||||
new_entry = self.create_entry_row()
|
||||
self.entries.append(new_entry)
|
||||
|
||||
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
|
||||
|
||||
def get_pile_widgets(self):
|
||||
return [
|
||||
self.header_row,
|
||||
urwid.Divider("-")
|
||||
] + self.entries + [
|
||||
urwid.Padding(self.add_button, left=2, right=2)
|
||||
]
|
||||
|
||||
def get_value(self):
|
||||
values = {}
|
||||
for entry in self.entries:
|
||||
key = entry.key_edit.edit_text.strip()
|
||||
value = entry.value_edit.edit_text.strip()
|
||||
|
||||
if key:
|
||||
if value.isdigit():
|
||||
values[key] = int(value)
|
||||
elif value.replace('.', '', 1).isdigit() and value.count('.') <= 1:
|
||||
values[key] = float(value)
|
||||
elif value.lower() == 'true':
|
||||
values[key] = True
|
||||
elif value.lower() == 'false':
|
||||
values[key] = False
|
||||
else:
|
||||
values[key] = value
|
||||
|
||||
return self.transform(values) if self.transform else values
|
||||
|
||||
def set_value(self, value):
|
||||
self.entries = []
|
||||
|
||||
if not value or not isinstance(value, dict):
|
||||
self.entries.append(self.create_entry_row())
|
||||
else:
|
||||
for key, val in value.items():
|
||||
self.entries.append(self.create_entry_row(key=key, value=str(val)))
|
||||
|
||||
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
|
||||
|
||||
def validate(self):
|
||||
values = self.get_value()
|
||||
self.error = None
|
||||
|
||||
keys = [entry.key_edit.edit_text.strip() for entry in self.entries
|
||||
if entry.key_edit.edit_text.strip()]
|
||||
if len(keys) != len(set(keys)):
|
||||
self.error = "Duplicate keys are not allowed"
|
||||
self.error_widget.set_text(("error", self.error))
|
||||
return False
|
||||
|
||||
for validation in self.validation_types:
|
||||
if validation == "required" and not values:
|
||||
self.error = "Atleast one parameter is required"
|
||||
break
|
||||
|
||||
self.error_widget.set_text(("error", self.error or ""))
|
||||
return self.error is None
|
Loading…
Add table
Add a link
Reference in a new issue