pymud 0.20.0__py3-none-any.whl → 0.20.0a1__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/pymud.py CHANGED
@@ -1,6 +1,6 @@
1
- import asyncio, functools, re, os, webbrowser, threading
1
+ import asyncio, functools, re, logging, math, json, os, webbrowser, threading
2
2
  from datetime import datetime
3
- from pathlib import Path
3
+ import importlib.util
4
4
  from prompt_toolkit.shortcuts import set_title, radiolist_dialog
5
5
  from prompt_toolkit.output import ColorDepth
6
6
  from prompt_toolkit.clipboard.pyperclip import PyperclipClipboard
@@ -36,8 +36,7 @@ from prompt_toolkit.layout.processors import (
36
36
  from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
37
37
 
38
38
  from .objects import CodeBlock
39
- from .extras import MudFormatProcessor, SessionBuffer, EasternMenuContainer, VSplitWindow, SessionBufferControl, DotDict
40
- from .modules import Plugin
39
+ from .extras import MudFormatProcessor, SessionBuffer, EasternMenuContainer, VSplitWindow, SessionBufferControl, DotDict, Plugin
41
40
  from .session import Session
42
41
  from .settings import Settings
43
42
  from .dialogs import MessageDialog, WelcomeDialog, QueryDialog, NewSessionDialog, LogSelectionDialog
@@ -319,8 +318,8 @@ class PyMudApp:
319
318
  ),
320
319
 
321
320
  MenuItem(
322
- "", # 增加一个空名称MenuItem,单机后焦点移动至命令行输入处,阻止右侧空白栏点击响应
323
- handler = lambda : self.app.layout.focus(self.commandLine)
321
+ "", # 增加一个空名称MenuItem,阻止右侧空白栏点击响应
322
+ children=[]
324
323
  )
325
324
  ],
326
325
  floats=[
@@ -341,9 +340,34 @@ class PyMudApp:
341
340
  ss = Settings.sessions
342
341
 
343
342
  for key, site in ss.items():
343
+ host = site["host"]
344
+ port = site["port"]
345
+ encoding = site["encoding"]
346
+ autologin = site["autologin"]
347
+ scripts = list()
348
+ default_script = site["default_script"]
349
+
350
+ def_scripts = list()
351
+ if isinstance(default_script, str):
352
+ def_scripts.extend(default_script.split(","))
353
+ elif isinstance(default_script, (list, tuple)):
354
+ def_scripts.extend(default_script)
355
+
344
356
  menu = MenuItem(key)
345
- for name in site["chars"].keys():
346
- sub = MenuItem(name, handler = functools.partial(self._quickHandleSession, key, name))
357
+ for name, info in site["chars"].items():
358
+ after_connect = autologin.format(info[0], info[1])
359
+ sess_scripts = list()
360
+ sess_scripts.extend(def_scripts)
361
+
362
+ if len(info) == 3:
363
+ session_script = info[2]
364
+ if session_script:
365
+ if isinstance(session_script, str):
366
+ sess_scripts.extend(session_script.split(","))
367
+ elif isinstance(session_script, (list, tuple)):
368
+ sess_scripts.extend(session_script)
369
+
370
+ sub = MenuItem(name, handler = functools.partial(self.create_session, name, host, port, encoding, after_connect, sess_scripts, info[0]))
347
371
  menu.children.append(sub)
348
372
  menus.append(menu)
349
373
 
@@ -482,7 +506,7 @@ class PyMudApp:
482
506
  line = self.mudFormatProc.line_correction(b.document.current_line)
483
507
  start = max(0, scol)
484
508
  end = min(ecol, len(line))
485
- line_plain = re.sub(r"\x1b\[[\d;]+[abcdmz]", "", line, flags = re.IGNORECASE).replace("\r", "").replace("\x00", "")
509
+ line_plain = re.sub("\x1b\\[[\d;]+[abcdmz]", "", line, flags = re.IGNORECASE).replace("\r", "").replace("\x00", "")
486
510
  #line_plain = re.sub("\x1b\\[[^mz]+[mz]", "", line).replace("\r", "").replace("\x00", "")
487
511
  selection = line_plain[start:end]
488
512
  self.app.clipboard.set_text(selection)
@@ -494,7 +518,7 @@ class PyMudApp:
494
518
  lines = []
495
519
  for row in range(srow, erow + 1):
496
520
  line = b.document.lines[row]
497
- line_plain = re.sub(r"\x1b\[[\d;]+[abcdmz]", "", line, flags = re.IGNORECASE).replace("\r", "").replace("\x00", "")
521
+ line_plain = re.sub("\x1b\\[[\d;]+[abcdmz]", "", line, flags = re.IGNORECASE).replace("\r", "").replace("\x00", "")
498
522
  lines.append(line_plain)
499
523
 
500
524
  self.app.clipboard.set_text("\n".join(lines))
@@ -568,7 +592,6 @@ class PyMudApp:
568
592
  log_list = list()
569
593
  files = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith('.log')]
570
594
  for file in files:
571
- file = os.path.abspath(file)
572
595
  filename = os.path.basename(file).ljust(20)
573
596
  filesize = f"{os.path.getsize(file):,} Bytes".rjust(20)
574
597
  # ctime = datetime.fromtimestamp(os.path.getctime(file)).strftime('%Y-%m-%d %H:%M:%S').rjust(23)
@@ -576,19 +599,6 @@ class PyMudApp:
576
599
 
577
600
  file_display_line = "{}{}{}".format(filename, filesize, mtime)
578
601
  log_list.append((file, file_display_line))
579
-
580
- logDir = os.path.abspath(os.path.join(os.curdir, 'log'))
581
- if os.path.exists(logDir):
582
- files = [f for f in os.listdir(logDir) if f.endswith('.log')]
583
- for file in files:
584
- file = os.path.join(logDir, file)
585
- filename = ('log/' + os.path.basename(file)).ljust(20)
586
- filesize = f"{os.path.getsize(file):,} Bytes".rjust(20)
587
- # ctime = datetime.fromtimestamp(os.path.getctime(file)).strftime('%Y-%m-%d %H:%M:%S').rjust(23)
588
- mtime = datetime.fromtimestamp(os.path.getmtime(file)).strftime('%Y-%m-%d %H:%M:%S').rjust(23)
589
-
590
- file_display_line = "{}{}{}".format(filename, filesize, mtime)
591
- log_list.append((file, file_display_line))
592
602
 
593
603
  dialog = LogSelectionDialog(
594
604
  text = head_line,
@@ -653,7 +663,6 @@ class PyMudApp:
653
663
  plugin.onSessionDestroy(self.current_session)
654
664
 
655
665
  name = self.current_session.name
656
- self.current_session.closeLoggers()
657
666
  self.current_session.clean()
658
667
  self.current_session = None
659
668
  self.consoleView.buffer = SessionBuffer()
@@ -909,50 +918,6 @@ class PyMudApp:
909
918
  self.status_message = msg
910
919
  self.app.invalidate()
911
920
 
912
- def _quickHandleSession(self, group, name):
913
- '''
914
- 根据指定的组名和会话角色名,从Settings内容,创建一个会话
915
- '''
916
- handled = False
917
- if name in self.sessions.keys():
918
- self.activate_session(name)
919
- handled = True
920
-
921
- else:
922
- site = Settings.sessions[group]
923
- if name in site["chars"].keys():
924
- host = site["host"]
925
- port = site["port"]
926
- encoding = site["encoding"]
927
- autologin = site["autologin"]
928
- default_script = site["default_script"]
929
-
930
- def_scripts = list()
931
- if isinstance(default_script, str):
932
- def_scripts.extend(default_script.split(","))
933
- elif isinstance(default_script, (list, tuple)):
934
- def_scripts.extend(default_script)
935
-
936
- charinfo = site["chars"][name]
937
-
938
- after_connect = autologin.format(charinfo[0], charinfo[1])
939
- sess_scripts = list()
940
- sess_scripts.extend(def_scripts)
941
-
942
- if len(charinfo) == 3:
943
- session_script = charinfo[2]
944
- if session_script:
945
- if isinstance(session_script, str):
946
- sess_scripts.extend(session_script.split(","))
947
- elif isinstance(session_script, (list, tuple)):
948
- sess_scripts.extend(session_script)
949
-
950
- self.create_session(name, host, port, encoding, after_connect, sess_scripts, charinfo[0])
951
- handled = True
952
-
953
- return handled
954
-
955
-
956
921
  def handle_session(self, *args):
957
922
  '''
958
923
  嵌入命令 #session 的执行函数,创建一个远程连接会话。
@@ -963,18 +928,12 @@ class PyMudApp:
963
928
  - 当不指定 Encoding: 时, 默认使用utf-8编码
964
929
  - 可以直接使用 #{名称} 切换会话和操作会话命令
965
930
 
966
- - #session {group}.{name}
967
- - 相当于直接点击菜单{group}下的{name}菜单来创建会话. 当该会话已存在时,切换到该会话
968
-
969
931
  参数:
970
932
  :name: 会话名称
971
933
  :host: 服务器域名或IP地址
972
934
  :port: 端口号
973
935
  :encoding: 编码格式,不指定时默认为 utf8
974
936
 
975
- :group: 组名, 即配置文件中, sessions 字段下的某个关键字
976
- :name: 会话快捷名称, 上述 group 关键字下的 chars 字段中的某个关键字
977
-
978
937
  示例:
979
938
  ``#session {名称} {宿主机} {端口} {编码}``
980
939
  创建一个远程连接会话,使用指定编码格式连接到远程宿主机的指定端口并保存为 {名称} 。其中,编码可以省略,此时使用Settings.server["default_encoding"]的值,默认为utf8
@@ -987,9 +946,6 @@ class PyMudApp:
987
946
  ``#newstart give miui gold``
988
947
  使名称为newstart的会话执行give miui gold指令,但不切换到该会话
989
948
 
990
- ``#session pkuxkx.newstart``
991
- 通过指定快捷配置创建会话,相当于点击 世界->pkuxkx->newstart 菜单创建会话。若该会话存在,则切换到该会话
992
-
993
949
  相关命令:
994
950
  - #close
995
951
  - #exit
@@ -997,17 +953,8 @@ class PyMudApp:
997
953
  '''
998
954
 
999
955
  nothandle = True
1000
- errmsg = "错误的#session命令"
1001
- if len(args) == 1:
1002
- host_session = args[0]
1003
- if '.' in host_session:
1004
- group, name = host_session.split('.')
1005
- nothandle = not self._quickHandleSession(group, name)
1006
956
 
1007
- else:
1008
- errmsg = f'通过单一参数快速创建会话时,要使用 group.name 形式,如 #session pkuxkx.newstart'
1009
-
1010
- elif len(args) >= 3:
957
+ if len(args) >= 3:
1011
958
  session_name = args[0]
1012
959
  session_host = args[1]
1013
960
  session_port = int(args[2])
@@ -1020,7 +967,7 @@ class PyMudApp:
1020
967
  nothandle = False
1021
968
 
1022
969
  if nothandle:
1023
- self.set_status(errmsg)
970
+ self.set_status("错误的#session命令")
1024
971
 
1025
972
  def enter_pressed(self, buffer: Buffer):
1026
973
  "命令行回车按键处理"
@@ -1153,8 +1100,8 @@ class PyMudApp:
1153
1100
  #asyncio.run(self.run_async())
1154
1101
 
1155
1102
  def get_width(self):
1156
- "获取ConsoleView的实际宽度,等于输出宽度,(已经没有左右线条和滚动条了)"
1157
- size = self.app.output.get_size().columns
1103
+ "获取ConsoleView的实际宽度,等于输出宽度-4,(左右线条宽度, 滚动条宽度,右边让出的1列)"
1104
+ size = self.app.output.get_size().columns - 4
1158
1105
  if Settings.client["status_display"] == 2:
1159
1106
  size = size - Settings.client["status_width"] - 1
1160
1107
  return size
@@ -1214,6 +1161,21 @@ class PyMudApp:
1214
1161
  plugin.onSessionCreate(session)
1215
1162
 
1216
1163
 
1217
- def startApp(cfg_data = None):
1164
+ def main(cfg_data = None):
1218
1165
  app = PyMudApp(cfg_data)
1219
1166
  app.run()
1167
+
1168
+ if __name__ == "__main__":
1169
+
1170
+ cfg = "pymud.cfg"
1171
+ import sys
1172
+ args = sys.argv
1173
+ if len(args) > 1:
1174
+ cfg = args[1]
1175
+
1176
+ if os.path.exists(cfg):
1177
+ with open(cfg, "r", encoding="utf8", errors="ignore") as fp:
1178
+ cfg_data = json.load(fp)
1179
+ main(cfg_data)
1180
+ else:
1181
+ main()