pymud 0.20.0__py3-none-any.whl → 0.20.0a2__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,
@@ -909,50 +919,6 @@ class PyMudApp:
909
919
  self.status_message = msg
910
920
  self.app.invalidate()
911
921
 
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
922
  def handle_session(self, *args):
957
923
  '''
958
924
  嵌入命令 #session 的执行函数,创建一个远程连接会话。
@@ -963,18 +929,12 @@ class PyMudApp:
963
929
  - 当不指定 Encoding: 时, 默认使用utf-8编码
964
930
  - 可以直接使用 #{名称} 切换会话和操作会话命令
965
931
 
966
- - #session {group}.{name}
967
- - 相当于直接点击菜单{group}下的{name}菜单来创建会话. 当该会话已存在时,切换到该会话
968
-
969
932
  参数:
970
933
  :name: 会话名称
971
934
  :host: 服务器域名或IP地址
972
935
  :port: 端口号
973
936
  :encoding: 编码格式,不指定时默认为 utf8
974
937
 
975
- :group: 组名, 即配置文件中, sessions 字段下的某个关键字
976
- :name: 会话快捷名称, 上述 group 关键字下的 chars 字段中的某个关键字
977
-
978
938
  示例:
979
939
  ``#session {名称} {宿主机} {端口} {编码}``
980
940
  创建一个远程连接会话,使用指定编码格式连接到远程宿主机的指定端口并保存为 {名称} 。其中,编码可以省略,此时使用Settings.server["default_encoding"]的值,默认为utf8
@@ -987,9 +947,6 @@ class PyMudApp:
987
947
  ``#newstart give miui gold``
988
948
  使名称为newstart的会话执行give miui gold指令,但不切换到该会话
989
949
 
990
- ``#session pkuxkx.newstart``
991
- 通过指定快捷配置创建会话,相当于点击 世界->pkuxkx->newstart 菜单创建会话。若该会话存在,则切换到该会话
992
-
993
950
  相关命令:
994
951
  - #close
995
952
  - #exit
@@ -997,17 +954,8 @@ class PyMudApp:
997
954
  '''
998
955
 
999
956
  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
957
 
1007
- else:
1008
- errmsg = f'通过单一参数快速创建会话时,要使用 group.name 形式,如 #session pkuxkx.newstart'
1009
-
1010
- elif len(args) >= 3:
958
+ if len(args) >= 3:
1011
959
  session_name = args[0]
1012
960
  session_host = args[1]
1013
961
  session_port = int(args[2])
@@ -1020,7 +968,7 @@ class PyMudApp:
1020
968
  nothandle = False
1021
969
 
1022
970
  if nothandle:
1023
- self.set_status(errmsg)
971
+ self.set_status("错误的#session命令")
1024
972
 
1025
973
  def enter_pressed(self, buffer: Buffer):
1026
974
  "命令行回车按键处理"
@@ -1153,8 +1101,8 @@ class PyMudApp:
1153
1101
  #asyncio.run(self.run_async())
1154
1102
 
1155
1103
  def get_width(self):
1156
- "获取ConsoleView的实际宽度,等于输出宽度,(已经没有左右线条和滚动条了)"
1157
- size = self.app.output.get_size().columns
1104
+ "获取ConsoleView的实际宽度,等于输出宽度-4,(左右线条宽度, 滚动条宽度,右边让出的1列)"
1105
+ size = self.app.output.get_size().columns - 4
1158
1106
  if Settings.client["status_display"] == 2:
1159
1107
  size = size - Settings.client["status_width"] - 1
1160
1108
  return size
@@ -1214,6 +1162,21 @@ class PyMudApp:
1214
1162
  plugin.onSessionCreate(session)
1215
1163
 
1216
1164
 
1217
- def startApp(cfg_data = None):
1165
+ def main(cfg_data = None):
1218
1166
  app = PyMudApp(cfg_data)
1219
1167
  app.run()
1168
+
1169
+ if __name__ == "__main__":
1170
+
1171
+ cfg = "pymud.cfg"
1172
+ import sys
1173
+ args = sys.argv
1174
+ if len(args) > 1:
1175
+ cfg = args[1]
1176
+
1177
+ if os.path.exists(cfg):
1178
+ with open(cfg, "r", encoding="utf8", errors="ignore") as fp:
1179
+ cfg_data = json.load(fp)
1180
+ main(cfg_data)
1181
+ else:
1182
+ main()