5.13. 간단한 TUI Spoke 정의

다음 예제에서는 Hello World 샘플 애드온에서 간단한 텍스트 사용자 인터페이스(TUI) 스포크의 구현을 보여줍니다.

사전 요구 사항

절차

  • 다음 예에 따라 추가 기능 텍스트 사용자 인터페이스(TUI)에 대한 지원을 추가하는 데 필요한 모든 정의로 모듈을 생성합니다.

예 5.11. 간단한 TUI Spoke 정의

def __init__(self, *args, **kwargs):
    """
    Create the representation of the spoke.

    :see: simpleline.render.screen.UIScreen
    """
    super().__init__(*args, **kwargs)
    self.title = N_("Hello World")
    self._hello_world_module = HELLO_WORLD.get_proxy()
    self._container = None
    self._reverse = False
    self._lines = ""

def initialize(self):
    """
    The initialize method that is called after the instance is created.
    The difference between __init__ and this method is that this may take
    a long time and thus could be called in a separated thread.

    :see: pyanaconda.ui.common.UIObject.initialize
    """
    # nothing to do here
    super().initialize()

def setup(self, args=None):
    """
    The setup method that is called right before the spoke is entered.
    It should update its state according to the contents of DBus modules.

    :see: simpleline.render.screen.UIScreen.setup
    """
    super().setup(args)

    self._reverse = self._hello_world_module.Reverse
    self._lines = self._hello_world_module.Lines

    return True

def refresh(self, args=None):
    """
    The refresh method that is called every time the spoke is displayed.
    It should generate the UI elements according to its state.

    :see: pyanaconda.ui.common.UIObject.refresh
    :see: simpleline.render.screen.UIScreen.refresh
    """
    super().refresh(args)

    self._container = ListColumnContainer(
        columns=1
    )
    self._container.add(
        CheckboxWidget(
            title="Reverse",
            completed=self._reverse
        ),
        callback=self._change_reverse
    )
    self._container.add(
        EntryWidget(
            title="Hello world text",
            value="".join(self._lines)
        ),
        callback=self._change_lines
    )

    self.window.add_with_separator(self._container)

def _change_reverse(self, data):
    """
    Callback when user wants to switch checkbox.
    Flip state of the "reverse" parameter which is boolean.
    """
    self._reverse = not self._reverse

def _change_lines(self, data):
    """
    Callback when user wants to input new lines.
    Show a dialog and save the provided lines.
    """
    dialog = Dialog("Lines")
    result = dialog.run()
    self._lines = result.splitlines(True)

def input(self, args, key):
    """
    The input method that is called by the main loop on user's input.

    * If the input should not be handled here, return it.
    * If the input is invalid, return InputState.DISCARDED.
    * If the input is handled and the current screen should be refreshed,
      return InputState.PROCESSED_AND_REDRAW.
    * If the input is handled and the current screen should be closed,
      return InputState.PROCESSED_AND_CLOSE.

    :see: simpleline.render.screen.UIScreen.input
    """
    if self._container.process_user_input(key):
        return InputState.PROCESSED_AND_REDRAW

    if key.lower() == Prompt.CONTINUE:
        self.apply()
        self.execute()
        return InputState.PROCESSED_AND_CLOSE

    return super().input(args, key)

def apply(self):
    """
    The apply method is not called automatically for TUI. It should be called
    in input() if required. It should update the contents of internal data
    structures with values set in the spoke.
    """
    self._hello_world_module.SetReverse(self._reverse)
    self._hello_world_module.SetLines(self._lines)

def execute(self):
    """
    The execute method is not called automatically for TUI. It should be called
    in input() if required. It is supposed to do all changes to the runtime
    environment according to the values set in the spoke.
    """
    # nothing to do here
    pass
참고

RuntimeClass의 init 만 호출할 경우에만 init 메서드를 재정의할 필요는 없지만 예제에 있는 주석은 스포크 클래스의 생성자에 전달된 인수를 이해할 수 있는 방식으로 설명합니다.

이전 예에서 다음을 수행합니다.

  • 설정 방법은 모든 항목에 대해 스포크의 내부 특성에 대한 기본값을 설정합니다. 그러면 refresh 메서드에서 표시하고 입력 방법으로 업데이트하고 apply 방법으로 내부 데이터 구조를 업데이트하는 데 사용합니다.
  • execute 방법은 GUI의 동등한 방법과 동일한 목적을 가지고 있습니다; 이 경우 방법은 적용되지 않습니다.
  • 입력 방법은 텍스트 인터페이스에 고유합니다. Kickstart 또는 GUI에는 동등하지 않습니다. 입력 방법은 사용자 상호 작용을 담당합니다.
  • 입력 메서드는 입력된 문자열을 처리하고 유형 및 값에 따라 조치를 취합니다. 위의 예에서는 값을 요청한 다음 내부 속성(키)으로 저장합니다. 더 복잡한 추가 기능에서는 일반적으로 구문 분석 문자와 같은 일부 비추적 작업을 수행하고, 숫자를 정수로 변환하고, 추가 화면을 표시하거나, 부울 값을 토글링해야 합니다.
  • 입력 클래스의 반환 값은 InputState Track 또는 입력 문자열 자체여야 하며, 이 입력을 다른 화면에서 처리해야 합니다. 그래픽 모드와 달리 applyexecute 메서드는 대화된 상태로 둘 때 자동으로 호출되지 않습니다. 입력 방법에서 명시적으로 호출해야 합니다. 스포크의 화면을 닫기(hiding)하는 데 동일한 적용: 닫기 방법에서 명시적으로 호출해야 합니다.

다른 화면을 표시하려면 예를 들어 다른 대화 상자에 입력된 추가 정보가 필요한 경우 다른 TUIObject 를 인스턴스화하고 이를 표시하려면 ScreenHandler.push_screen_modal() 을 사용할 수 있습니다.

텍스트 기반 인터페이스의 제한으로 인해 TUI spokes는 확인란 목록 또는 선택 해제로 구성되는 매우 유사한 구조를 갖는 경향이 있습니다.