pymud 0.21.0a4__py3-none-any.whl → 0.21.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pymud/__init__.py CHANGED
@@ -1,17 +1,17 @@
1
- from .settings import Settings
2
- from .pymud import PyMudApp
3
- from .modules import IConfig, PymudDecorator, PymudMeta, alias, trigger, timer, gmcp
4
- from .objects import CodeBlock, Alias, SimpleAlias, Trigger, SimpleTrigger, Command, SimpleCommand, Timer, SimpleTimer, GMCPTrigger
5
- from .extras import DotDict
6
- from .session import Session, exception, async_exception
7
- from .logger import Logger
8
- from .main import main
9
-
10
- __all__ = [
11
- "PymudDecorator", "PymudMeta", "alias", "trigger", "timer", "gmcp",
12
- "IConfig", "PyMudApp", "Settings", "CodeBlock",
13
- "Alias", "SimpleAlias", "Trigger", "SimpleTrigger",
14
- "Command", "SimpleCommand", "Timer", "SimpleTimer",
15
- "GMCPTrigger", "Session", "DotDict", "Logger", "main",
16
- "exception", "async_exception"
1
+ from .settings import Settings
2
+ from .pymud import PyMudApp
3
+ from .modules import IConfigBase, IConfig, PymudMeta
4
+ from .objects import CodeBlock, Alias, SimpleAlias, Trigger, SimpleTrigger, Command, SimpleCommand, Timer, SimpleTimer, GMCPTrigger
5
+ from .extras import DotDict
6
+ from .session import Session
7
+ from .logger import Logger
8
+ from .main import main
9
+ from .decorators import exception, async_exception, PymudDecorator, alias, trigger, timer, gmcp
10
+
11
+ __all__ = [
12
+ "PymudMeta", "IConfigBase", "IConfig", "PyMudApp", "Settings", "CodeBlock",
13
+ "Alias", "SimpleAlias", "Trigger", "SimpleTrigger",
14
+ "Command", "SimpleCommand", "Timer", "SimpleTimer",
15
+ "GMCPTrigger", "Session", "DotDict", "Logger", "main",
16
+ "exception", "async_exception", "PymudDecorator", "alias", "trigger", "timer", "gmcp",
17
17
  ]
pymud/__main__.py CHANGED
@@ -1,4 +1,4 @@
1
- from .main import main
2
-
3
- if __name__ == "__main__":
1
+ from .main import main
2
+
3
+ if __name__ == "__main__":
4
4
  main()
pymud/decorators.py ADDED
@@ -0,0 +1,234 @@
1
+ import sys, functools, traceback
2
+ from typing import Union, Optional, List
3
+
4
+ def print_exception(session, e: Exception):
5
+ """打印异常信息"""
6
+ from .settings import Settings
7
+ from .session import Session
8
+ if isinstance(session, Session):
9
+ # tb = sys.exc_info()[2]
10
+ # frames = traceback.extract_tb(tb)
11
+ # frame = frames[-1]
12
+ # session.error(Settings.gettext("exception_traceback", frame.filename, frame.lineno, frame.name), Settings.gettext("script_error"))
13
+ # if frame.line:
14
+ # session.error(f" {frame.line}", Settings.gettext("script_error"))
15
+
16
+ # session.error(Settings.gettext("exception_message", type(e).__name__, e), Settings.gettext("script_error"))
17
+ # session.error("===========================", Settings.gettext("script_error"))
18
+ session.error(traceback.format_exc(), Settings.gettext("script_error"))
19
+
20
+ def exception(func):
21
+ """方法异常处理装饰器,捕获异常后通过会话的session.error打印相关信息"""
22
+ @functools.wraps(func)
23
+ def wrapper(self, *args, **kwargs):
24
+ from .objects import BaseObject
25
+ from .modules import ModuleInfo, IConfig
26
+ from .session import Session
27
+ from .settings import Settings
28
+ try:
29
+ return func(self, *args, **kwargs)
30
+ except Exception as e:
31
+ # 调用类的错误处理方法
32
+ if isinstance(self, Session):
33
+ session = self
34
+ elif isinstance(self, (BaseObject, IConfig, ModuleInfo)):
35
+ session = self.session
36
+ else:
37
+ session = None
38
+
39
+ if isinstance(session, Session):
40
+ print_exception(session, e)
41
+ #session.error(Settings.gettext("exception_message", e, type(e)))
42
+ #session.error(Settings.gettext("exception_traceback", traceback.format_exc()))
43
+ else:
44
+ raise # 当没有会话时,选择重新抛出异常
45
+ return wrapper
46
+
47
+ def async_exception(func):
48
+ """异步方法异常处理装饰器,捕获异常后通过会话的session.error打印相关信息"""
49
+ @functools.wraps(func)
50
+ async def wrapper(self, *args, **kwargs):
51
+ from .objects import BaseObject
52
+ from .modules import ModuleInfo, IConfig
53
+ from .session import Session
54
+ from .settings import Settings
55
+ try:
56
+ return await func(self, *args, **kwargs)
57
+ except Exception as e:
58
+ if isinstance(self, Session):
59
+ session = self
60
+ elif isinstance(self, (BaseObject, IConfig, ModuleInfo)):
61
+ session = self.session
62
+ else:
63
+ session = None
64
+
65
+ if isinstance(session, Session):
66
+ print_exception(session, e)
67
+
68
+ else:
69
+ raise # 当没有会话时,选择重新抛出异常
70
+ return wrapper
71
+
72
+
73
+ class PymudDecorator:
74
+ """
75
+ 装饰器基类。使用装饰器可以快捷创建各类Pymud基础对象。
76
+
77
+ :param type: 装饰器的类型,用于区分不同的装饰器,为字符串类型。
78
+ :param args: 可变位置参数,用于传递额外的参数。
79
+ :param kwargs: 可变关键字参数,用于传递额外的键值对参数。
80
+ """
81
+ def __init__(self, type: str, *args, **kwargs):
82
+ self.type = type
83
+ self.args = args
84
+ self.kwargs = kwargs
85
+
86
+ def __call__(self, func):
87
+ decos = getattr(func, "__pymud_decorators__", [])
88
+ decos.append(self)
89
+ func.__pymud_decorators__ = decos
90
+
91
+ return func
92
+
93
+ def __repr__(self):
94
+ return f"<{self.__class__.__name__} type = {self.type} args = {self.args} kwargs = {self.kwargs}>"
95
+
96
+
97
+ def alias(
98
+ patterns: Union[List[str], str],
99
+ id: Optional[str] = None,
100
+ group: str = "",
101
+ enabled: bool = True,
102
+ ignoreCase: bool = False,
103
+ isRegExp: bool = True,
104
+ keepEval: bool = False,
105
+ expandVar: bool = True,
106
+ priority: int = 100,
107
+ oneShot: bool = False,
108
+ *args, **kwargs):
109
+ """
110
+ 使用装饰器创建一个别名(Alias)对象。被装饰的函数将在别名成功匹配时调用。
111
+ 被装饰的函数,除第一个参数为类实例本身self之外,另外包括id, line, wildcards三个参数。
112
+ 其中id为别名对象的唯一标识符,line为匹配的文本行,wildcards为匹配的通配符列表。
113
+
114
+ :param patterns: 别名匹配的模式。
115
+ :param id: 别名对象的唯一标识符,不指定时将自动生成唯一标识符。
116
+ :param group: 别名所属的组名,默认为空字符串。
117
+ :param enabled: 别名是否启用,默认为 True。
118
+ :param ignoreCase: 匹配时是否忽略大小写,默认为 False。
119
+ :param isRegExp: 模式是否为正则表达式,默认为 True。
120
+ :param keepEval: 若存在多个可匹配的别名时,是否持续匹配,默认为 False。
121
+ :param expandVar: 是否展开变量,默认为 True。
122
+ :param priority: 别名的优先级,值越小优先级越高,默认为 100。
123
+ :param oneShot: 别名是否只触发一次后自动失效,默认为 False。
124
+ :param args: 可变位置参数,用于传递额外的参数。
125
+ :param kwargs: 可变关键字参数,用于传递额外的键值对参数。
126
+ :return: PymudDecorator 实例,类型为 "alias"。
127
+ """
128
+ # 将传入的参数更新到 kwargs 字典中
129
+ kwargs.update({
130
+ "patterns": patterns,
131
+ "id": id,
132
+ "group": group,
133
+ "enabled": enabled,
134
+ "ignoreCase": ignoreCase,
135
+ "isRegExp": isRegExp,
136
+ "keepEval": keepEval,
137
+ "expandVar": expandVar,
138
+ "priority": priority,
139
+ "oneShot": oneShot})
140
+
141
+ # 如果 id 为 None,则从 kwargs 中移除 "id" 键
142
+ if not id:
143
+ kwargs.pop("id")
144
+
145
+ return PymudDecorator("alias", *args, **kwargs)
146
+
147
+ def trigger(
148
+ patterns: Union[List[str], str],
149
+ id: Optional[str] = None,
150
+ group: str = "",
151
+ enabled: bool = True,
152
+ ignoreCase: bool = False,
153
+ isRegExp: bool = True,
154
+ keepEval: bool = False,
155
+ expandVar: bool = True,
156
+ raw: bool = False,
157
+ priority: int = 100,
158
+ oneShot: bool = False,
159
+ *args, **kwargs):
160
+ """
161
+ 使用装饰器创建一个触发器(Trigger)对象。
162
+
163
+ :param patterns: 触发器匹配的模式。单行模式可以是字符串或正则表达式,多行模式必须是元组或列表,其中每个元素都是字符串或正则表达式。
164
+ :param id: 触发器对象的唯一标识符,不指定时将自动生成唯一标识符。
165
+ :param group: 触发器所属的组名,默认为空字符串。
166
+ :param enabled: 触发器是否启用,默认为 True。
167
+ :param ignoreCase: 匹配时是否忽略大小写,默认为 False。
168
+ :param isRegExp: 模式是否为正则表达式,默认为 True。
169
+ :param keepEval: 若存在多个可匹配的触发器时,是否持续匹配,默认为 False。
170
+ :param expandVar: 是否展开变量,默认为 True。
171
+ :param raw: 是否使用原始匹配方式,默认为 False。原始匹配方式下,不对 VT100 下的 ANSI 颜色进行解码,因此可以匹配颜色;正常匹配仅匹配文本。
172
+ :param priority: 触发器的优先级,值越小优先级越高,默认为 100。
173
+ :param oneShot: 触发器是否只触发一次后自动失效,默认为 False。
174
+ :param args: 可变位置参数,用于传递额外的参数。
175
+ :param kwargs: 可变关键字参数,用于传递额外的键值对参数。
176
+ :return: PymudDecorator 实例,类型为 "trigger"。
177
+ """
178
+ # 将传入的参数更新到 kwargs 字典中
179
+ kwargs.update({
180
+ "patterns": patterns,
181
+ "id": id,
182
+ "group": group,
183
+ "enabled": enabled,
184
+ "ignoreCase": ignoreCase,
185
+ "isRegExp": isRegExp,
186
+ "keepEval": keepEval,
187
+ "expandVar": expandVar,
188
+ "raw": raw,
189
+ "priority": priority,
190
+ "oneShot": oneShot})
191
+ if not id:
192
+ kwargs.pop("id")
193
+ return PymudDecorator("trigger", *args, **kwargs)
194
+
195
+ def timer(timeout: float, id: Optional[str] = None, group: str = "", enabled: bool = True, *args, **kwargs):
196
+ """
197
+ 使用装饰器创建一个定时器(Timer)对象。
198
+
199
+ :param timeout: 定时器超时时间,单位为秒。
200
+ :param id: 定时器对象的唯一标识符,不指定时将自动生成唯一标识符。
201
+ :param group: 定时器所属的组名,默认为空字符串。
202
+ :param enabled: 定时器是否启用,默认为 True。
203
+ :param args: 可变位置参数,用于传递额外的参数。
204
+ :param kwargs: 可变关键字参数,用于传递额外的键值对参数。
205
+ :return: PymudDecorator 实例,类型为 "timer"。
206
+ """
207
+ kwargs.update({
208
+ "timeout": timeout,
209
+ "id": id,
210
+ "group": group,
211
+ "enabled": enabled
212
+ })
213
+ if not id:
214
+ kwargs.pop("id")
215
+ return PymudDecorator("timer", *args, **kwargs)
216
+
217
+ def gmcp(name: str, group: str = "", enabled: bool = True, *args, **kwargs):
218
+ """
219
+ 使用装饰器创建一个GMCP触发器(GMCPTrigger)对象。
220
+
221
+ :param name: GMCP触发器的名称。
222
+ :param group: GMCP触发器所属的组名,默认为空字符串。
223
+ :param enabled: GMCP触发器是否启用,默认为 True。
224
+ :param args: 可变位置参数,用于传递额外的参数。
225
+ :param kwargs: 可变关键字参数,用于传递额外的键值对参数。
226
+ :return: PymudDecorator 实例,类型为 "gmcp"。
227
+ """
228
+ kwargs.update({
229
+ "id": name,
230
+ "group": group,
231
+ "enabled": enabled
232
+ })
233
+
234
+ return PymudDecorator("gmcp", *args, **kwargs)
pymud/dialogs.py CHANGED
@@ -1,167 +1,167 @@
1
- import asyncio, webbrowser
2
- from typing import Any, Callable, Iterable, List, Tuple, Union
3
- from prompt_toolkit.layout import AnyContainer, ConditionalContainer, Float, VSplit, HSplit, Window, WindowAlign, ScrollablePane, ScrollOffsets
4
- from prompt_toolkit.widgets import Button, Dialog, Label, MenuContainer, MenuItem, TextArea, SystemToolbar, Frame, RadioList
5
- from prompt_toolkit.layout.dimension import Dimension, D
6
- from prompt_toolkit import ANSI, HTML
7
- from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
8
- from prompt_toolkit.formatted_text import FormattedText, AnyFormattedText
9
- from prompt_toolkit.application.current import get_app
10
- from .extras import EasternButton
11
-
12
- from .settings import Settings
13
-
14
- class BasicDialog:
15
- def __init__(self, title: AnyFormattedText = "", modal = True):
16
- self.future = asyncio.Future()
17
- self.dialog = Dialog(
18
- body = self.create_body(),
19
- title = title,
20
- buttons = self.create_buttons(),
21
- modal = modal,
22
- width = D(preferred=80),
23
- )
24
-
25
- def set_done(self, result: Any = True):
26
- self.future.set_result(result)
27
-
28
- def create_body(self) -> AnyContainer:
29
- return HSplit([Label(text=Settings.gettext("basic_dialog"))])
30
-
31
- def create_buttons(self):
32
- ok_button = EasternButton(text=Settings.gettext("ok"), handler=(lambda: self.set_done()))
33
- return [ok_button]
34
-
35
- def set_exception(self, exc):
36
- self.future.set_exception(exc)
37
-
38
- def __pt_container__(self):
39
- return self.dialog
40
-
41
- class MessageDialog(BasicDialog):
42
- def __init__(self, title="", message = "", modal=True):
43
- self.message = message
44
- super().__init__(title, modal)
45
-
46
- def create_body(self) -> AnyContainer:
47
- return HSplit([Label(text=self.message)])
48
-
49
- class QueryDialog(BasicDialog):
50
- def __init__(self, title: AnyFormattedText = "", message: AnyFormattedText = "", modal = True):
51
- self.message = message
52
- super().__init__(title, modal)
53
-
54
- def create_body(self) -> AnyContainer:
55
- return HSplit([Label(text=self.message)])
56
-
57
- def create_buttons(self):
58
- ok_button = EasternButton(text=Settings.gettext("ok"), handler=(lambda: self.set_done(True)))
59
- cancel_button = EasternButton(text=Settings.gettext("cancel"), handler=(lambda: self.set_done(False)))
60
- return [ok_button, cancel_button]
61
-
62
- class WelcomeDialog(BasicDialog):
63
- def __init__(self, modal=True):
64
- self.website = FormattedText(
65
- [('', f'{Settings.gettext("visit")} '),
66
- #('class:b', 'GitHub:'),
67
- ('', Settings.__website__, self.open_url),
68
- ('', f' {Settings.gettext("displayhelp")}')]
69
- )
70
- super().__init__("PYMUD", modal)
71
-
72
- def open_url(self, event: MouseEvent):
73
- if event.event_type == MouseEventType.MOUSE_UP:
74
- webbrowser.open(Settings.__website__)
75
-
76
- def create_body(self) -> AnyContainer:
77
- import platform, sys
78
- body = HSplit([
79
- Window(height=1),
80
- Label(HTML(Settings.gettext("appinfo", Settings.__version__, Settings.__release__)), align=WindowAlign.CENTER),
81
- Label(HTML(Settings.gettext("author", Settings.__author__, Settings.__email__)), align=WindowAlign.CENTER),
82
- Label(self.website, align=WindowAlign.CENTER),
83
- Label(Settings.gettext("sysversion", platform.system(), platform.version(), platform.python_version()), align = WindowAlign.CENTER),
84
-
85
- Window(height=1),
86
- ])
87
-
88
- return body
89
-
90
- class NewSessionDialog(BasicDialog):
91
- def __init__(self):
92
- super().__init__(Settings.gettext("new_session"), True)
93
-
94
- def create_body(self) -> AnyContainer:
95
- body = HSplit([
96
- VSplit([
97
- HSplit([
98
- Label(f" {Settings.gettext('sessionname')}:"),
99
- Frame(body=TextArea(name = "session", text="session", multiline=False, wrap_lines=False, height = 1, dont_extend_height=True, width = D(preferred=10), focus_on_click=True, read_only=False),)
100
- ]),
101
- HSplit([
102
- Label(f" {Settings.gettext('host')}:"),
103
- Frame(body=TextArea(name = "host", text="mud.pkuxkx.net", multiline=False, wrap_lines=False, height = 1, dont_extend_height=True, width = D(preferred=20), focus_on_click=True, read_only=False),)
104
- ]),
105
- HSplit([
106
- Label(f" {Settings.gettext('port')}:"),
107
- Frame(body=TextArea(name = "port", text="8081", multiline=False, wrap_lines=False, height = 1, dont_extend_height=True, width = D(max=8), focus_on_click=True, read_only=False),)
108
- ]),
109
- HSplit([
110
- Label(f" {Settings.gettext('encoding')}:"),
111
- Frame(body=TextArea(name = "encoding", text="utf8", multiline=False, wrap_lines=False, height = 1, dont_extend_height=True, width = D(max=8), focus_on_click=True, read_only=False),)
112
- ]),
113
- ])
114
- ])
115
-
116
- return body
117
-
118
- def create_buttons(self):
119
- ok_button = EasternButton(text=Settings.gettext("ok"), handler=self.btn_ok_clicked)
120
- cancel_button = EasternButton(text=Settings.gettext("cancel"), handler=(lambda: self.set_done(False)))
121
- return [ok_button, cancel_button]
122
-
123
- def btn_ok_clicked(self):
124
- def get_text_safely(buffer_name):
125
- buffer = get_app().layout.get_buffer_by_name(buffer_name)
126
- return buffer.text if buffer else ""
127
- name = get_text_safely("session")
128
- host = get_text_safely("host")
129
- port = get_text_safely("port")
130
- encoding = get_text_safely("encoding")
131
- result = (name, host, port, encoding)
132
- self.set_done(result)
133
-
134
-
135
- class LogSelectionDialog(BasicDialog):
136
- def __init__(self, text, values, modal=True):
137
- self._header_text = text
138
- self._selection_values = values
139
- self._itemsCount = len(values)
140
- if len(values) > 0:
141
- self._radio_list = RadioList(values = self._selection_values)
142
- else:
143
- self._radio_list = Label(Settings.gettext("nolog").center(13))
144
- super().__init__(Settings.gettext("chooselog"), modal)
145
-
146
- def create_body(self) -> AnyContainer:
147
- body=HSplit([
148
- Label(text = self._header_text, dont_extend_height=True),
149
- self._radio_list
150
- ])
151
- return body
152
-
153
- def create_buttons(self):
154
- ok_button = EasternButton(text=Settings.gettext("ok"), handler=self.btn_ok_clicked)
155
- cancel_button = EasternButton(text=Settings.gettext("cancel"), handler=(lambda: self.set_done(False)))
156
- return [ok_button, cancel_button]
157
-
158
- def btn_ok_clicked(self):
159
- if self._itemsCount:
160
- if isinstance(self._radio_list, RadioList):
161
- result = self._radio_list.current_value
162
- else:
163
- result = None
164
- self.set_done(result)
165
- else:
166
- self.set_done(False)
1
+ import asyncio, webbrowser
2
+ from typing import Any, Callable, Iterable, List, Tuple, Union
3
+ from prompt_toolkit.layout import AnyContainer, ConditionalContainer, Float, VSplit, HSplit, Window, WindowAlign, ScrollablePane, ScrollOffsets
4
+ from prompt_toolkit.widgets import Button, Dialog, Label, MenuContainer, MenuItem, TextArea, SystemToolbar, Frame, RadioList
5
+ from prompt_toolkit.layout.dimension import Dimension, D
6
+ from prompt_toolkit import ANSI, HTML
7
+ from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
8
+ from prompt_toolkit.formatted_text import FormattedText, AnyFormattedText
9
+ from prompt_toolkit.application.current import get_app
10
+ from .extras import EasternButton
11
+
12
+ from .settings import Settings
13
+
14
+ class BasicDialog:
15
+ def __init__(self, title: AnyFormattedText = "", modal = True):
16
+ self.future = asyncio.Future()
17
+ self.dialog = Dialog(
18
+ body = self.create_body(),
19
+ title = title,
20
+ buttons = self.create_buttons(),
21
+ modal = modal,
22
+ width = D(preferred=80),
23
+ )
24
+
25
+ def set_done(self, result: Any = True):
26
+ self.future.set_result(result)
27
+
28
+ def create_body(self) -> AnyContainer:
29
+ return HSplit([Label(text=Settings.gettext("basic_dialog"))])
30
+
31
+ def create_buttons(self):
32
+ ok_button = EasternButton(text=Settings.gettext("ok"), handler=(lambda: self.set_done()))
33
+ return [ok_button]
34
+
35
+ def set_exception(self, exc):
36
+ self.future.set_exception(exc)
37
+
38
+ def __pt_container__(self):
39
+ return self.dialog
40
+
41
+ class MessageDialog(BasicDialog):
42
+ def __init__(self, title="", message = "", modal=True):
43
+ self.message = message
44
+ super().__init__(title, modal)
45
+
46
+ def create_body(self) -> AnyContainer:
47
+ return HSplit([Label(text=self.message)])
48
+
49
+ class QueryDialog(BasicDialog):
50
+ def __init__(self, title: AnyFormattedText = "", message: AnyFormattedText = "", modal = True):
51
+ self.message = message
52
+ super().__init__(title, modal)
53
+
54
+ def create_body(self) -> AnyContainer:
55
+ return HSplit([Label(text=self.message)])
56
+
57
+ def create_buttons(self):
58
+ ok_button = EasternButton(text=Settings.gettext("ok"), handler=(lambda: self.set_done(True)))
59
+ cancel_button = EasternButton(text=Settings.gettext("cancel"), handler=(lambda: self.set_done(False)))
60
+ return [ok_button, cancel_button]
61
+
62
+ class WelcomeDialog(BasicDialog):
63
+ def __init__(self, modal=True):
64
+ self.website = FormattedText(
65
+ [('', f'{Settings.gettext("visit")} '),
66
+ #('class:b', 'GitHub:'),
67
+ ('', Settings.__website__, self.open_url),
68
+ ('', f' {Settings.gettext("displayhelp")}')]
69
+ )
70
+ super().__init__("PYMUD", modal)
71
+
72
+ def open_url(self, event: MouseEvent):
73
+ if event.event_type == MouseEventType.MOUSE_UP:
74
+ webbrowser.open(Settings.__website__)
75
+
76
+ def create_body(self) -> AnyContainer:
77
+ import platform, sys
78
+ body = HSplit([
79
+ Window(height=1),
80
+ Label(HTML(Settings.gettext("appinfo", Settings.__version__, Settings.__release__)), align=WindowAlign.CENTER),
81
+ Label(HTML(Settings.gettext("author", Settings.__author__, Settings.__email__)), align=WindowAlign.CENTER),
82
+ Label(self.website, align=WindowAlign.CENTER),
83
+ Label(Settings.gettext("sysversion", platform.system(), platform.version(), platform.python_version()), align = WindowAlign.CENTER),
84
+
85
+ Window(height=1),
86
+ ])
87
+
88
+ return body
89
+
90
+ class NewSessionDialog(BasicDialog):
91
+ def __init__(self):
92
+ super().__init__(Settings.gettext("new_session"), True)
93
+
94
+ def create_body(self) -> AnyContainer:
95
+ body = HSplit([
96
+ VSplit([
97
+ HSplit([
98
+ Label(f" {Settings.gettext('sessionname')}:"),
99
+ Frame(body=TextArea(name = "session", text="session", multiline=False, wrap_lines=False, height = 1, dont_extend_height=True, width = D(preferred=10), focus_on_click=True, read_only=False),)
100
+ ]),
101
+ HSplit([
102
+ Label(f" {Settings.gettext('host')}:"),
103
+ Frame(body=TextArea(name = "host", text="mud.pkuxkx.net", multiline=False, wrap_lines=False, height = 1, dont_extend_height=True, width = D(preferred=20), focus_on_click=True, read_only=False),)
104
+ ]),
105
+ HSplit([
106
+ Label(f" {Settings.gettext('port')}:"),
107
+ Frame(body=TextArea(name = "port", text="8081", multiline=False, wrap_lines=False, height = 1, dont_extend_height=True, width = D(max=8), focus_on_click=True, read_only=False),)
108
+ ]),
109
+ HSplit([
110
+ Label(f" {Settings.gettext('encoding')}:"),
111
+ Frame(body=TextArea(name = "encoding", text="utf8", multiline=False, wrap_lines=False, height = 1, dont_extend_height=True, width = D(max=8), focus_on_click=True, read_only=False),)
112
+ ]),
113
+ ])
114
+ ])
115
+
116
+ return body
117
+
118
+ def create_buttons(self):
119
+ ok_button = EasternButton(text=Settings.gettext("ok"), handler=self.btn_ok_clicked)
120
+ cancel_button = EasternButton(text=Settings.gettext("cancel"), handler=(lambda: self.set_done(False)))
121
+ return [ok_button, cancel_button]
122
+
123
+ def btn_ok_clicked(self):
124
+ def get_text_safely(buffer_name):
125
+ buffer = get_app().layout.get_buffer_by_name(buffer_name)
126
+ return buffer.text if buffer else ""
127
+ name = get_text_safely("session")
128
+ host = get_text_safely("host")
129
+ port = get_text_safely("port")
130
+ encoding = get_text_safely("encoding")
131
+ result = (name, host, port, encoding)
132
+ self.set_done(result)
133
+
134
+
135
+ class LogSelectionDialog(BasicDialog):
136
+ def __init__(self, text, values, modal=True):
137
+ self._header_text = text
138
+ self._selection_values = values
139
+ self._itemsCount = len(values)
140
+ if len(values) > 0:
141
+ self._radio_list = RadioList(values = self._selection_values)
142
+ else:
143
+ self._radio_list = Label(Settings.gettext("nolog").center(13))
144
+ super().__init__(Settings.gettext("chooselog"), modal)
145
+
146
+ def create_body(self) -> AnyContainer:
147
+ body=HSplit([
148
+ Label(text = self._header_text, dont_extend_height=True),
149
+ self._radio_list
150
+ ])
151
+ return body
152
+
153
+ def create_buttons(self):
154
+ ok_button = EasternButton(text=Settings.gettext("ok"), handler=self.btn_ok_clicked)
155
+ cancel_button = EasternButton(text=Settings.gettext("cancel"), handler=(lambda: self.set_done(False)))
156
+ return [ok_button, cancel_button]
157
+
158
+ def btn_ok_clicked(self):
159
+ if self._itemsCount:
160
+ if isinstance(self._radio_list, RadioList):
161
+ result = self._radio_list.current_value
162
+ else:
163
+ result = None
164
+ self.set_done(result)
165
+ else:
166
+ self.set_done(False)
167
167