Skip to content

Commit

Permalink
Show unsupported entities in menu, terminal size handling
Browse files Browse the repository at this point in the history
  • Loading branch information
infeeeee committed Dec 28, 2023
1 parent 9b12a96 commit 21276dd
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 25 deletions.
88 changes: 68 additions & 20 deletions IoTuring/Configurator/Configurator.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
import subprocess

import shutil

from IoTuring.Logger.LogObject import LogObject
from IoTuring.Exceptions.Exceptions import UserCancelledException
Expand Down Expand Up @@ -35,7 +35,7 @@ class Configurator(LogObject):

def __init__(self) -> None:

self.pinned_message = False
self.pinned_lines = 1

self.configuratorIO = ConfiguratorIO.ConfiguratorIO()
self.config = self.LoadConfigurations()
Expand Down Expand Up @@ -90,12 +90,9 @@ def OpenConfigInEditor(self):

self.Log(self.LOG_WARNING, "No editor found")

def Menu(self, clear_screen: bool = True) -> None:
def Menu(self) -> None:
""" UI for Entities and Warehouses settings """

if not clear_screen:
self.pinned_message = True

mainMenuChoices = [
{"name": "Manage entities", "value": self.ManageEntities},
{"name": "Manage warehouses", "value": self.ManageWarehouses},
Expand Down Expand Up @@ -128,6 +125,7 @@ def ManageEntities(self) -> None:
manageEntitiesChoices = [
CHOICE_GO_BACK,
{"name": "+ Add a new entity", "value": "AddNewEntity"},
{"name": "? Unsupported entities", "value": "UnsupportedEntities"},
Separator()
] + manageEntitiesChoices

Expand All @@ -138,6 +136,8 @@ def ManageEntities(self) -> None:

if choice == "AddNewEntity":
self.SelectNewEntity(ecm)
elif choice == "UnsupportedEntities":
self.ShowUnsupportedEntities(ecm)
elif choice == CHOICE_GO_BACK:
self.Menu()
else:
Expand Down Expand Up @@ -173,6 +173,8 @@ def ManageWarehouses(self) -> None:

def DisplayHelp(self) -> None:
self.DisplayMessage(messages.HELP_MESSAGE)
# Help message is too long:
self.pinned_lines = 1
self.Menu()

def Quit(self) -> None:
Expand Down Expand Up @@ -283,6 +285,26 @@ def SelectNewEntity(self, ecm: EntityClassManager):
else:
self.AddActiveEntity(choice, ecm)

def ShowUnsupportedEntities(self, ecm: EntityClassManager):
""" UI to show unsupported entities """

# entity classnames without unsupported entities:
unsupportedEntityList = []
for eClass in ecm.ListAvailableClasses():
try:
eClass.CheckSystemSupport()
except Exception as e:
unsupportedEntityList.append(f"\t{eClass.NAME}: {str(e)}")

if not unsupportedEntityList:
self.DisplayMessage("No unsupported entities :)")

else:
msg = "\n".join(sorted(unsupportedEntityList))
self.DisplayMessage("Unsupported entities:\n" + msg)

self.ManageEntities()

def AddActiveEntity(self, entityName, ecm: EntityClassManager):
""" From entity name, get its class and retrieve the configuration preset, then add to configuration dict """
entityClass = ecm.GetClassFromName(entityName)
Expand All @@ -300,6 +322,7 @@ def AddActiveEntity(self, entityName, ecm: EntityClassManager):
self.DisplayMessage(messages.PRESET_RULES)
self.DisplayMessage(f"Configure {entityName} Entity")
preset.AskQuestions()
self.ClearScreen(force_clear=True)

else:
self.DisplayMessage(
Expand Down Expand Up @@ -354,6 +377,7 @@ def AddActiveWarehouse(self, warehouseName, wcm: WarehouseClassManager) -> None:
if preset.HasQuestions():
self.DisplayMessage(messages.PRESET_RULES)
preset.AskQuestions()
self.ClearScreen(force_clear=True)

else:
self.DisplayMessage(
Expand Down Expand Up @@ -405,29 +429,25 @@ def WarehouseMenuPresetToConfiguration(self, whName, preset) -> None:
_dict = preset.GetDict()
_dict[KEY_WAREHOUSE_TYPE] = whName.replace("Warehouse", "")
self.config[KEY_ACTIVE_WAREHOUSES].append(_dict)
print("Configuration added for \""+whName+"\" :)")
self.DisplayMessage("Configuration added for \""+whName+"\" :)")

def EntityMenuPresetToConfiguration(self, entityName, preset) -> None:
""" Get a MenuPreset with responses and add the entries to the configurations dict in entity part """
_dict = preset.GetDict()
_dict[KEY_ENTITY_TYPE] = entityName
self.config[KEY_ACTIVE_ENTITIES].append(_dict)
print("Configuration added for \""+entityName+"\" :)")
self.DisplayMessage("Configuration added for \""+entityName+"\" :)")

def ClearScreen(self, pin_next_message=False):
""" Clear the screen on any platform. If self.pinned_message is True, it won't be cleared.
def ClearScreen(self, force_clear=False):
""" Clear the screen on any platform. If self.pinned_lines greater than zero, it won't be cleared.
Args:
pin_next_message (bool, optional): Set self.pinned_message after clear. Defaults to False.
force_clear (bool, optional): Clear even pinned messages. Defaults to False.
"""

if not self.pinned_message:
if self.pinned_lines == 0 or force_clear:
self.ClearTerminal()

if pin_next_message:
self.pinned_message = True
else:
self.pinned_message = False
self.pinned_lines = 0

def DisplayMenu(self, choices: list, message: str = "", add_back_choice=True, **kwargs):
""" Wrapper for inquirer.select
Expand All @@ -447,9 +467,37 @@ def DisplayMenu(self, choices: list, message: str = "", add_back_choice=True, **
] + choices

if "max_height" not in kwargs:

# Default max_height:
kwargs["max_height"] = "100%"

# Actual lines in the terminal. fallback to 0 on error:
terminal_lines = shutil.get_terminal_size(fallback=(0, 0)).lines

# Check for pinned messages:
if terminal_lines > 0 and self.pinned_lines > 0:

# Lines of message and instruction if too long:
if "instruction" in kwargs:
message_lines = ((len(kwargs["instruction"]) + len(message) + 3)
/ shutil.get_terminal_size().columns) // 1
# Add only the line of the message:
else:
message_lines = 1

# Calculate nr of lines required to display:
required_lines = len(choices) + \
self.pinned_lines + message_lines

# Set the calculated height:
if required_lines > terminal_lines:
kwargs["max_height"] = terminal_lines \
- self.pinned_lines - message_lines

self.ClearScreen()
# Reset pinned lines:
self.pinned_lines = 0

prompt = inquirer.select(
message=message, choices=choices, **kwargs)

Expand All @@ -469,9 +517,9 @@ def DisplayMessage(self, message: str, force_clear=False):
message (str): The message to display
force_clear (bool): clear screen regardless previous
"""
if force_clear:
self.pinned_message = False
self.ClearScreen(pin_next_message=True)

self.ClearScreen(force_clear)
self.pinned_lines += message.count('\n') + 2
print(message)
print()

Expand Down
6 changes: 2 additions & 4 deletions IoTuring/Configurator/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,5 @@
\tUse ctrl+C to exit without saving
"""

PRESET_RULES = """
Options with this sign are compulsory: {!}
Use Escape to cancel
"""
PRESET_RULES = """Options with this sign are compulsory: {!}
Use Escape to cancel"""
2 changes: 1 addition & 1 deletion IoTuring/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def loop():
# Check old location:
configurator.CheckFile()

configurator.Menu(clear_screen=False)
configurator.Menu()
except KeyboardInterrupt:
logger.Log(Logger.LOG_WARNING, "Configurator",
"Configuration NOT saved")
Expand Down

0 comments on commit 21276dd

Please sign in to comment.