pymud 0.21.1__py3-none-any.whl → 0.21.2__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/extras.py CHANGED
@@ -1,919 +1,975 @@
1
- # External Libraries
2
- from unicodedata import east_asian_width
3
- from wcwidth import wcwidth
4
- import time, re, logging
5
-
6
- from typing import Iterable, Optional, Union, Tuple
7
- from prompt_toolkit import ANSI
8
- from prompt_toolkit.application import get_app
9
- from prompt_toolkit.buffer import Buffer
10
- from prompt_toolkit.formatted_text import to_formatted_text, fragment_list_to_text
11
- from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple
12
- from prompt_toolkit.layout.processors import Processor, Transformation
13
- from prompt_toolkit.application.current import get_app
14
- from prompt_toolkit.buffer import Buffer
15
- from prompt_toolkit.document import Document
16
- from prompt_toolkit.data_structures import Point
17
- from prompt_toolkit.layout.controls import UIContent
18
- from prompt_toolkit.lexers import Lexer
19
- from prompt_toolkit.mouse_events import MouseButton, MouseEvent, MouseEventType
20
- from prompt_toolkit.selection import SelectionType
21
- from prompt_toolkit.buffer import Buffer, ValidationState
22
-
23
- from prompt_toolkit.filters import (
24
- FilterOrBool,
25
- )
26
- from prompt_toolkit.formatted_text import (
27
- StyleAndTextTuples,
28
- to_formatted_text,
29
- )
30
- from prompt_toolkit.formatted_text.utils import fragment_list_to_text
31
- from prompt_toolkit.history import InMemoryHistory
32
- from prompt_toolkit.key_binding.key_bindings import KeyBindingsBase
33
- from prompt_toolkit.layout.containers import (
34
- Window,
35
- WindowAlign,
36
- )
37
- from prompt_toolkit.layout.controls import (
38
- BufferControl,
39
- FormattedTextControl,
40
- )
41
- from prompt_toolkit.layout.processors import (
42
- Processor,
43
- TransformationInput,
44
- Transformation
45
- )
46
- from prompt_toolkit.lexers import Lexer
47
- from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
48
- from prompt_toolkit.utils import get_cwidth
49
- from prompt_toolkit.widgets import Button, MenuContainer, MenuItem
50
- from prompt_toolkit.widgets.base import Border
51
-
52
- from prompt_toolkit.layout.screen import _CHAR_CACHE, Screen, WritePosition
53
- from prompt_toolkit.layout.utils import explode_text_fragments
54
- from prompt_toolkit.formatted_text.utils import (
55
- fragment_list_to_text,
56
- fragment_list_width,
57
- )
58
-
59
- from .settings import Settings
60
-
61
- class MudFormatProcessor(Processor):
62
- "在BufferControl中显示ANSI格式的处理器"
63
-
64
- def __init__(self) -> None:
65
- super().__init__()
66
- self.FULL_BLOCKS = set("▂▃▅▆▇▄█")
67
- self.SINGLE_LINES = set("┌└├┬┼┴╭╰─")
68
- self.DOUBLE_LINES = set("╔╚╠╦╪╩═")
69
- self.ALL_COLOR_REGX = re.compile(r"(?:\[[\d;]+m)+")
70
- self.AVAI_COLOR_REGX = re.compile(r"(?:\[[\d;]+m)+(?!$)")
71
- self._color_start = ""
72
- self._color_correction = False
73
- self._color_line_index = 0
74
-
75
- def width_correction(self, line: str) -> str:
76
- new_str = []
77
- for ch in line:
78
- new_str.append(ch)
79
- if (east_asian_width(ch) in "FWA") and (wcwidth(ch) == 1):
80
- if ch in self.FULL_BLOCKS:
81
- new_str.append(ch)
82
- elif ch in self.SINGLE_LINES:
83
- new_str.append("─")
84
- elif ch in self.DOUBLE_LINES:
85
- new_str.append("═")
86
- else:
87
- new_str.append(' ')
88
-
89
- return "".join(new_str)
90
-
91
- def return_correction(self, line: str):
92
- return line.replace("\r", "").replace("\x00", "")
93
-
94
- def tab_correction(self, line: str):
95
- return line.replace("\t", " " * Settings.client["tabstop"])
96
-
97
- def line_correction(self, line: str):
98
- # 处理\r符号(^M)
99
- line = self.return_correction(line)
100
- # 处理Tab(\r)符号(^I)
101
- line = self.tab_correction(line)
102
-
103
- # 美化(解决中文英文在Console中不对齐的问题)
104
- if Settings.client["beautify"]:
105
- line = self.width_correction(line)
106
-
107
- return line
108
-
109
- def apply_transformation(self, transformation_input: TransformationInput):
110
- # 准备(先还原为str)
111
- line = fragment_list_to_text(transformation_input.fragments)
112
-
113
- # 颜色校正
114
- thislinecolors = len(self.AVAI_COLOR_REGX.findall(line))
115
- if thislinecolors == 0:
116
- lineno = transformation_input.lineno - 1
117
- while lineno > 0:
118
- lastline = transformation_input.document.lines[lineno]
119
- allcolors = self.ALL_COLOR_REGX.findall(lastline)
120
-
121
- if len(allcolors) == 0:
122
- lineno = lineno - 1
123
-
124
- elif len(allcolors) == 1:
125
- colors = self.AVAI_COLOR_REGX.findall(lastline)
126
-
127
- if len(colors) == 1:
128
- line = f"{colors[0]}{line}"
129
- break
130
-
131
- else:
132
- break
133
-
134
- else:
135
- break
136
-
137
- # 其他校正
138
- line = self.line_correction(line)
139
-
140
- # 处理ANSI标记(生成FormmatedText)
141
- fragments = to_formatted_text(ANSI(line))
142
-
143
- return Transformation(fragments)
144
-
145
- class SessionBuffer(Buffer):
146
- "继承自Buffer,为Session内容所修改,主要修改为只能在最后新增内容,并且支持分屏显示适配"
147
-
148
- def __init__(
149
- self,
150
- ):
151
- super().__init__()
152
-
153
- # 修改内容
154
- self.__text = ""
155
- self.__split = False
156
-
157
- def _set_text(self, value: str) -> bool:
158
- """set text at current working_index. Return whether it changed."""
159
- original_value = self.__text
160
- self.__text = value
161
-
162
- # Return True when this text has been changed.
163
- if len(value) != len(original_value):
164
- return True
165
- elif value != original_value:
166
- return True
167
- return False
168
-
169
- @property
170
- def text(self) -> str:
171
- return self.__text
172
-
173
- @text.setter
174
- def text(self, value: str) -> None:
175
- # SessionBuffer is only appendable
176
-
177
- if self.cursor_position > len(value):
178
- self.cursor_position = len(value)
179
-
180
- changed = self._set_text(value)
181
-
182
- if changed:
183
- self._text_changed()
184
- self.history_search_text = None
185
-
186
- @property
187
- def working_index(self) -> int:
188
- return 0
189
-
190
- @working_index.setter
191
- def working_index(self, value: int) -> None:
192
- pass
193
-
194
- def _text_changed(self) -> None:
195
- # Remove any validation errors and complete state.
196
- self.validation_error = None
197
- self.validation_state = ValidationState.UNKNOWN
198
- self.complete_state = None
199
- self.yank_nth_arg_state = None
200
- self.document_before_paste = None
201
-
202
- # 添加内容时,不取消选择
203
- #self.selection_state = None
204
-
205
- self.suggestion = None
206
- self.preferred_column = None
207
-
208
- # fire 'on_text_changed' event.
209
- self.on_text_changed.fire()
210
-
211
- def set_document(self, value: Document, bypass_readonly: bool = False) -> None:
212
- pass
213
-
214
- @property
215
- def split(self) -> bool:
216
- return self.__split
217
-
218
- @split.setter
219
- def split(self, value: bool) -> None:
220
- self.__split = value
221
-
222
- @property
223
- def is_returnable(self) -> bool:
224
- return False
225
-
226
- # End of <getters/setters>
227
-
228
- # def save_to_undo_stack(self, clear_redo_stack: bool = True) -> None:
229
- # pass
230
-
231
- # def delete(self, count: int = 1) -> str:
232
- # pass
233
-
234
- def insert_text(
235
- self,
236
- data: str,
237
- overwrite: bool = False,
238
- move_cursor: bool = True,
239
- fire_event: bool = True,
240
- ) -> None:
241
- # 始终在最后增加内容
242
- self.text += data
243
-
244
- # 分隔情况下,光标保持原位置不变,否则光标始终位于最后
245
- if not self.__split:
246
- # 若存在选择状态,则视情保留选择
247
- if self.selection_state:
248
- start = self.selection_state.original_cursor_position
249
- end = self.cursor_position
250
- row, col = self.document.translate_index_to_position(start)
251
- lastrow, col = self.document.translate_index_to_position(len(self.text))
252
- self.exit_selection()
253
- # 还没翻过半页的话,就重新选择上
254
- if lastrow - row < get_app().output.get_size().rows // 2 - 1:
255
- self.cursor_position = len(self.text)
256
- self.cursor_position = start
257
- self.start_selection
258
- self.cursor_position = end
259
- else:
260
- self.cursor_position = len(self.text)
261
- else:
262
- self.cursor_position = len(self.text)
263
- else:
264
- pass
265
-
266
-
267
- def clear_half(self):
268
- "将Buffer前半段内容清除,并清除缓存"
269
- remain_lines = len(self.document.lines) // 2
270
- start = self.document.translate_row_col_to_index(remain_lines, 0)
271
- new_text = self.text[start:]
272
-
273
- del self.history
274
- self.history = InMemoryHistory()
275
-
276
- self.text = ""
277
- self._set_text(new_text)
278
-
279
- self._document_cache.clear()
280
- new_doc = Document(text = new_text, cursor_position = len(new_text))
281
- self.reset(new_doc, False)
282
- self.__split = False
283
-
284
- return new_doc.line_count
285
-
286
- def undo(self) -> None:
287
- pass
288
-
289
- def redo(self) -> None:
290
- pass
291
-
292
-
293
- class SessionBufferControl(BufferControl):
294
- def __init__(self, buffer: Optional[SessionBuffer] = None, input_processors = None, include_default_input_processors: bool = True, lexer: Optional[Lexer] = None, preview_search: FilterOrBool = False, focusable: FilterOrBool = True, search_buffer_control = None, menu_position = None, focus_on_click: FilterOrBool = False, key_bindings: Optional[KeyBindingsBase] = None):
295
- # 将所属Buffer类型更改为SessionBuffer
296
- buffer = buffer or SessionBuffer()
297
- super().__init__(buffer, input_processors, include_default_input_processors, lexer, preview_search, focusable, search_buffer_control, menu_position, focus_on_click, key_bindings)
298
- self.buffer = buffer
299
-
300
-
301
- def mouse_handler(self, mouse_event: MouseEvent):
302
- """
303
- 鼠标处理,修改内容包括:
304
- 1. 在CommandLine获得焦点的时候,鼠标对本Control也可以操作
305
- 2. 鼠标双击为选中行
306
- """
307
- buffer = self.buffer
308
- position = mouse_event.position
309
-
310
- # Focus buffer when clicked.
311
- cur_control = get_app().layout.current_control
312
- cur_buffer = get_app().layout.current_buffer
313
- # 这里是修改的内容
314
- if (cur_control == self) or (cur_buffer and cur_buffer.name == "input"):
315
- if self._last_get_processed_line:
316
- processed_line = self._last_get_processed_line(position.y)
317
-
318
- # Translate coordinates back to the cursor position of the
319
- # original input.
320
- xpos = processed_line.display_to_source(position.x)
321
- index = buffer.document.translate_row_col_to_index(position.y, xpos)
322
-
323
- # Set the cursor position.
324
- if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
325
- buffer.exit_selection()
326
- buffer.cursor_position = index
327
-
328
- elif (
329
- mouse_event.event_type == MouseEventType.MOUSE_MOVE
330
- and mouse_event.button != MouseButton.NONE
331
- ):
332
- # Click and drag to highlight a selection
333
- if (
334
- buffer.selection_state is None
335
- and abs(buffer.cursor_position - index) > 0
336
- ):
337
- buffer.start_selection(selection_type=SelectionType.CHARACTERS)
338
- buffer.cursor_position = index
339
-
340
- elif mouse_event.event_type == MouseEventType.MOUSE_UP:
341
- # When the cursor was moved to another place, select the text.
342
- # (The >1 is actually a small but acceptable workaround for
343
- # selecting text in Vi navigation mode. In navigation mode,
344
- # the cursor can never be after the text, so the cursor
345
- # will be repositioned automatically.)
346
-
347
- if abs(buffer.cursor_position - index) > 1:
348
- if buffer.selection_state is None:
349
- buffer.start_selection(
350
- selection_type=SelectionType.CHARACTERS
351
- )
352
- buffer.cursor_position = index
353
-
354
- # Select word around cursor on double click.
355
- # Two MOUSE_UP events in a short timespan are considered a double click.
356
- double_click = (
357
- self._last_click_timestamp
358
- and time.time() - self._last_click_timestamp < 0.3
359
- )
360
- self._last_click_timestamp = time.time()
361
-
362
- if double_click:
363
- start = buffer.document.translate_row_col_to_index(position.y, 0)
364
- end = buffer.document.translate_row_col_to_index(position.y + 1, 0) - 1
365
- buffer.cursor_position = start
366
- buffer.start_selection(selection_type=SelectionType.LINES)
367
- buffer.cursor_position = end
368
-
369
- else:
370
- # Don't handle scroll events here.
371
- return NotImplemented
372
-
373
- # Not focused, but focusing on click events.
374
- else:
375
- if (
376
- self.focus_on_click()
377
- and mouse_event.event_type == MouseEventType.MOUSE_UP
378
- ):
379
- # Focus happens on mouseup. (If we did this on mousedown, the
380
- # up event will be received at the point where this widget is
381
- # focused and be handled anyway.)
382
- get_app().layout.current_control = self
383
- else:
384
- return NotImplemented
385
-
386
- return None
387
-
388
- def move_cursor_down(self) -> None:
389
- b = self.buffer
390
- b.cursor_position += b.document.get_cursor_down_position()
391
-
392
- def move_cursor_up(self) -> None:
393
- b = self.buffer
394
- b.cursor_position += b.document.get_cursor_up_position()
395
-
396
- def move_cursor_right(self, count = 1) -> None:
397
- b = self.buffer
398
- b.cursor_position += count
399
-
400
- def move_cursor_left(self, count = 1) -> None:
401
- b = self.buffer
402
- b.cursor_position -= count
403
-
404
-
405
- class VSplitWindow(Window):
406
- "修改的分块窗口,向上翻页时,下半部保持最后数据不变"
407
-
408
- def _copy_body(
409
- self,
410
- ui_content: UIContent,
411
- new_screen: Screen,
412
- write_position: WritePosition,
413
- move_x: int,
414
- width: int,
415
- vertical_scroll: int = 0,
416
- horizontal_scroll: int = 0,
417
- wrap_lines: bool = False,
418
- highlight_lines: bool = False,
419
- vertical_scroll_2: int = 0,
420
- always_hide_cursor: bool = False,
421
- has_focus: bool = False,
422
- align: WindowAlign = WindowAlign.LEFT,
423
- get_line_prefix = None,
424
- isNotMargin = True,
425
- ):
426
- """
427
- Copy the UIContent into the output screen.
428
- Return (visible_line_to_row_col, rowcol_to_yx) tuple.
429
-
430
- :param get_line_prefix: None or a callable that takes a line number
431
- (int) and a wrap_count (int) and returns formatted text.
432
- """
433
- xpos = write_position.xpos + move_x
434
- ypos = write_position.ypos
435
- line_count = ui_content.line_count
436
- new_buffer = new_screen.data_buffer
437
- empty_char = _CHAR_CACHE["", ""]
438
-
439
- # Map visible line number to (row, col) of input.
440
- # 'col' will always be zero if line wrapping is off.
441
- visible_line_to_row_col: dict[int, tuple[int, int]] = {}
442
-
443
- # Maps (row, col) from the input to (y, x) screen coordinates.
444
- rowcol_to_yx: dict[tuple[int, int], tuple[int, int]] = {}
445
-
446
- def copy_line(
447
- line: StyleAndTextTuples,
448
- lineno: int,
449
- x: int,
450
- y: int,
451
- is_input: bool = False,
452
- ):
453
- """
454
- Copy over a single line to the output screen. This can wrap over
455
- multiple lines in the output. It will call the prefix (prompt)
456
- function before every line.
457
- """
458
- if is_input:
459
- current_rowcol_to_yx = rowcol_to_yx
460
- else:
461
- current_rowcol_to_yx = {} # Throwaway dictionary.
462
-
463
- # Draw line prefix.
464
- if is_input and get_line_prefix:
465
- prompt = to_formatted_text(get_line_prefix(lineno, 0))
466
- x, y = copy_line(prompt, lineno, x, y, is_input=False)
467
-
468
- # Scroll horizontally.
469
- skipped = 0 # Characters skipped because of horizontal scrolling.
470
- if horizontal_scroll and is_input:
471
- h_scroll = horizontal_scroll
472
- line = explode_text_fragments(line)
473
- while h_scroll > 0 and line:
474
- h_scroll -= get_cwidth(line[0][1])
475
- skipped += 1
476
- del line[:1] # Remove first character.
477
-
478
- x -= h_scroll # When scrolling over double width character,
479
- # this can end up being negative.
480
-
481
- # Align this line. (Note that this doesn't work well when we use
482
- # get_line_prefix and that function returns variable width prefixes.)
483
- if align == WindowAlign.CENTER:
484
- line_width = fragment_list_width(line)
485
- if line_width < width:
486
- x += (width - line_width) // 2
487
- elif align == WindowAlign.RIGHT:
488
- line_width = fragment_list_width(line)
489
- if line_width < width:
490
- x += width - line_width
491
-
492
- col = 0
493
- wrap_count = 0
494
- for style, text, *_ in line:
495
- new_buffer_row = new_buffer[y + ypos]
496
-
497
- # Remember raw VT escape sequences. (E.g. FinalTerm's
498
- # escape sequences.)
499
- if "[ZeroWidthEscape]" in style:
500
- new_screen.zero_width_escapes[y + ypos][x + xpos] += text
501
- continue
502
-
503
- for c in text:
504
- char = _CHAR_CACHE[c, style]
505
- char_width = char.width
506
-
507
- # Wrap when the line width is exceeded.
508
- if wrap_lines and x + char_width > width:
509
- visible_line_to_row_col[y + 1] = (
510
- lineno,
511
- visible_line_to_row_col[y][1] + x,
512
- )
513
- y += 1
514
- wrap_count += 1
515
- x = 0
516
-
517
- # Insert line prefix (continuation prompt).
518
- if is_input and get_line_prefix:
519
- prompt = to_formatted_text(
520
- get_line_prefix(lineno, wrap_count)
521
- )
522
- x, y = copy_line(prompt, lineno, x, y, is_input=False)
523
-
524
- new_buffer_row = new_buffer[y + ypos]
525
-
526
- if y >= write_position.height:
527
- return x, y # Break out of all for loops.
528
-
529
- # Set character in screen and shift 'x'.
530
- if x >= 0 and y >= 0 and x < width:
531
- new_buffer_row[x + xpos] = char
532
-
533
- # When we print a multi width character, make sure
534
- # to erase the neighbours positions in the screen.
535
- # (The empty string if different from everything,
536
- # so next redraw this cell will repaint anyway.)
537
- if char_width > 1:
538
- for i in range(1, char_width):
539
- new_buffer_row[x + xpos + i] = empty_char
540
-
541
- # If this is a zero width characters, then it's
542
- # probably part of a decomposed unicode character.
543
- # See: https://en.wikipedia.org/wiki/Unicode_equivalence
544
- # Merge it in the previous cell.
545
- elif char_width == 0:
546
- # Handle all character widths. If the previous
547
- # character is a multiwidth character, then
548
- # merge it two positions back.
549
- for pw in [2, 1]: # Previous character width.
550
- if (
551
- x - pw >= 0
552
- and new_buffer_row[x + xpos - pw].width == pw
553
- ):
554
- prev_char = new_buffer_row[x + xpos - pw]
555
- char2 = _CHAR_CACHE[
556
- prev_char.char + c, prev_char.style
557
- ]
558
- new_buffer_row[x + xpos - pw] = char2
559
-
560
- # Keep track of write position for each character.
561
- current_rowcol_to_yx[lineno, col + skipped] = (
562
- y + ypos,
563
- x + xpos,
564
- )
565
-
566
- col += 1
567
- x += char_width
568
- return x, y
569
-
570
- # Copy content.
571
- def copy() -> int:
572
- y = -vertical_scroll_2
573
- lineno = vertical_scroll
574
-
575
- total = write_position.height
576
- upper = (total - 1) // 2
577
- below = total - upper - 1
578
-
579
- if lineno + total < line_count:
580
- if isinstance(self.content, SessionBufferControl):
581
- b = self.content.buffer
582
- b.split = True
583
-
584
- while y < upper and lineno < line_count:
585
- line = ui_content.get_line(lineno)
586
- visible_line_to_row_col[y] = (lineno, horizontal_scroll)
587
- x = 0
588
- x, y = copy_line(line, lineno, x, y, is_input=True)
589
- lineno += 1
590
- y += 1
591
-
592
- x = 0
593
- x, y = copy_line([("","-"*width)], lineno, x, y, is_input=False)
594
- y += 1
595
-
596
- lineno = line_count - below
597
- while y < total and lineno < line_count:
598
- line = ui_content.get_line(lineno)
599
- visible_line_to_row_col[y] = (lineno, horizontal_scroll)
600
- x = 0
601
- x, y = copy_line(line, lineno, x, y, is_input=True)
602
- lineno += 1
603
- y += 1
604
-
605
- return y
606
-
607
- else:
608
- if isNotMargin and isinstance(self.content, SessionBufferControl):
609
- b = self.content.buffer
610
- b.split = False
611
-
612
- while y < write_position.height and lineno < line_count:
613
- # Take the next line and copy it in the real screen.
614
- line = ui_content.get_line(lineno)
615
-
616
- visible_line_to_row_col[y] = (lineno, horizontal_scroll)
617
-
618
- # Copy margin and actual line.
619
- x = 0
620
- x, y = copy_line(line, lineno, x, y, is_input=True)
621
-
622
- lineno += 1
623
- y += 1
624
- return y
625
-
626
-
627
-
628
- copy()
629
-
630
- def cursor_pos_to_screen_pos(row: int, col: int) -> Point:
631
- "Translate row/col from UIContent to real Screen coordinates."
632
- try:
633
- y, x = rowcol_to_yx[row, col]
634
- except KeyError:
635
- # Normally this should never happen. (It is a bug, if it happens.)
636
- # But to be sure, return (0, 0)
637
- return Point(x=0, y=0)
638
-
639
- # raise ValueError(
640
- # 'Invalid position. row=%r col=%r, vertical_scroll=%r, '
641
- # 'horizontal_scroll=%r, height=%r' %
642
- # (row, col, vertical_scroll, horizontal_scroll, write_position.height))
643
- else:
644
- return Point(x=x, y=y)
645
-
646
- # Set cursor and menu positions.
647
- if ui_content.cursor_position:
648
- screen_cursor_position = cursor_pos_to_screen_pos(
649
- ui_content.cursor_position.y, ui_content.cursor_position.x
650
- )
651
-
652
- if has_focus:
653
- new_screen.set_cursor_position(self, screen_cursor_position)
654
-
655
- if always_hide_cursor:
656
- new_screen.show_cursor = False
657
- else:
658
- new_screen.show_cursor = ui_content.show_cursor
659
-
660
- self._highlight_digraph(new_screen)
661
-
662
- if highlight_lines:
663
- self._highlight_cursorlines(
664
- new_screen,
665
- screen_cursor_position,
666
- xpos,
667
- ypos,
668
- width,
669
- write_position.height,
670
- )
671
-
672
- # Draw input characters from the input processor queue.
673
- if has_focus and ui_content.cursor_position:
674
- self._show_key_processor_key_buffer(new_screen)
675
-
676
- # Set menu position.
677
- if ui_content.menu_position:
678
- new_screen.set_menu_position(
679
- self,
680
- cursor_pos_to_screen_pos(
681
- ui_content.menu_position.y, ui_content.menu_position.x
682
- ),
683
- )
684
-
685
- # Update output screen height.
686
- new_screen.height = max(new_screen.height, ypos + write_position.height)
687
-
688
- return visible_line_to_row_col, rowcol_to_yx
689
-
690
- def _copy_margin(
691
- self,
692
- margin_content: UIContent,
693
- new_screen: Screen,
694
- write_position: WritePosition,
695
- move_x: int,
696
- width: int,
697
- ) -> None:
698
- """
699
- Copy characters from the margin screen to the real screen.
700
- """
701
- xpos = write_position.xpos + move_x
702
- ypos = write_position.ypos
703
-
704
- margin_write_position = WritePosition(xpos, ypos, width, write_position.height)
705
- self._copy_body(margin_content, new_screen, margin_write_position, 0, width, isNotMargin=False)
706
-
707
- def _scroll_down(self) -> None:
708
- "向下滚屏,处理屏幕分隔"
709
- info = self.render_info
710
-
711
- if info is None:
712
- return
713
-
714
- if isinstance(self.content, SessionBufferControl):
715
- b = self.content.buffer
716
- d = b.document
717
-
718
- b.exit_selection()
719
- cur_line = d.cursor_position_row
720
-
721
- # # 向下滚动时,如果存在自动折行情况,要判断本行被折成了几行,在行内时要逐行移动(此处未调试好)
722
- # cur_col = d.cursor_position_col
723
- # line = d.current_line
724
- # line_width = len(line)
725
- # line_start = d.translate_row_col_to_index(cur_line, 0)
726
- # screen_width = info.window_width
727
-
728
- # offset_y = cur_col // screen_width
729
- # wraplines = math.ceil(1.0 * line_width / screen_width)
730
-
731
- if cur_line < info.content_height:
732
-
733
- # if offset_y < wraplines: # add
734
- # self.content.move_cursor_right(screen_width) # add
735
- # else: # add
736
-
737
- self.content.move_cursor_down()
738
- self.vertical_scroll = cur_line + 1
739
-
740
- firstline = d.line_count - len(info.displayed_lines)
741
- if cur_line >= firstline:
742
- b.cursor_position = len(b.text)
743
-
744
- def _scroll_up(self) -> None:
745
- "向上滚屏,处理屏幕分隔"
746
- info = self.render_info
747
-
748
- if info is None:
749
- return
750
-
751
- #if info.cursor_position.y >= 1:
752
- if isinstance(self.content, SessionBufferControl):
753
- b = self.content.buffer
754
- d = b.document
755
-
756
- b.exit_selection()
757
- cur_line = d.cursor_position_row
758
- if cur_line > d.line_count - len(info.displayed_lines):
759
- firstline = d.line_count - len(info.displayed_lines)
760
- newpos = d.translate_row_col_to_index(firstline, 0)
761
- b.cursor_position = newpos
762
- cur_line = d.cursor_position_row
763
- self.vertical_scroll = cur_line
764
-
765
- elif cur_line > 0:
766
- self.content.move_cursor_up()
767
- self.vertical_scroll = cur_line - 1
768
-
769
-
770
- class EasternButton(Button):
771
- "解决增加中文等东亚全宽字符后不对齐问题"
772
-
773
- def _get_text_fragments(self) -> StyleAndTextTuples:
774
- # 主要改动在这里
775
- width = self.width - (
776
- get_cwidth(self.left_symbol) + get_cwidth(self.right_symbol)
777
- ) - (get_cwidth(self.text) - len(self.text))
778
-
779
-
780
- text = (f"{{:^{width}}}").format(self.text)
781
-
782
- def handler(mouse_event: MouseEvent) -> None:
783
- if (
784
- self.handler is not None
785
- and mouse_event.event_type == MouseEventType.MOUSE_UP
786
- ):
787
- self.handler()
788
-
789
- return [
790
- ("class:button.arrow", self.left_symbol, handler),
791
- #("[SetCursorPosition]", ""),
792
- ("class:button.text", text, handler),
793
- ("class:button.arrow", self.right_symbol, handler),
794
- ]
795
-
796
- class EasternMenuContainer(MenuContainer):
797
- "解决增加中文等东亚全宽字符后不对齐问题"
798
-
799
- def _submenu(self, level: int = 0) -> Window:
800
- def get_text_fragments() -> StyleAndTextTuples:
801
- result: StyleAndTextTuples = []
802
- if level < len(self.selected_menu):
803
- menu = self._get_menu(level)
804
- if menu.children:
805
- result.append(("class:menu", Border.TOP_LEFT))
806
- result.append(("class:menu", Border.HORIZONTAL * (menu.width + 4)))
807
- result.append(("class:menu", Border.TOP_RIGHT))
808
- result.append(("", "\n"))
809
- try:
810
- selected_item = self.selected_menu[level + 1]
811
- except IndexError:
812
- selected_item = -1
813
-
814
- def one_item(
815
- i: int, item: MenuItem
816
- ) -> Iterable[OneStyleAndTextTuple]:
817
- def mouse_handler(mouse_event: MouseEvent) -> None:
818
- if item.disabled:
819
- # The arrow keys can't interact with menu items that are disabled.
820
- # The mouse shouldn't be able to either.
821
- return
822
- hover = mouse_event.event_type == MouseEventType.MOUSE_MOVE
823
- if (
824
- mouse_event.event_type == MouseEventType.MOUSE_UP
825
- or hover
826
- ):
827
- app = get_app()
828
- if not hover and item.handler:
829
- app.layout.focus_last()
830
- item.handler()
831
- else:
832
- self.selected_menu = self.selected_menu[
833
- : level + 1
834
- ] + [i]
835
-
836
- if i == selected_item:
837
- yield ("[SetCursorPosition]", "")
838
- style = "class:menu-bar.selected-item"
839
- else:
840
- style = ""
841
-
842
- yield ("class:menu", Border.VERTICAL)
843
- if item.text == "-":
844
- yield (
845
- style + "class:menu-border",
846
- f"{Border.HORIZONTAL * (menu.width + 3)}",
847
- mouse_handler,
848
- )
849
- else:
850
- # 主要改动在这里,其他地方都未更改.
851
- adj_width = menu.width + 3 - (get_cwidth(item.text) - len(item.text))
852
- yield (
853
- style,
854
- f" {item.text}".ljust(adj_width),
855
- mouse_handler,
856
- )
857
-
858
- if item.children:
859
- yield (style, ">", mouse_handler)
860
- else:
861
- yield (style, " ", mouse_handler)
862
-
863
- if i == selected_item:
864
- yield ("[SetMenuPosition]", "")
865
- yield ("class:menu", Border.VERTICAL)
866
-
867
- yield ("", "\n")
868
-
869
- for i, item in enumerate(menu.children):
870
- result.extend(one_item(i, item))
871
-
872
- result.append(("class:menu", Border.BOTTOM_LEFT))
873
- result.append(("class:menu", Border.HORIZONTAL * (menu.width + 4)))
874
- result.append(("class:menu", Border.BOTTOM_RIGHT))
875
- return result
876
-
877
- return Window(FormattedTextControl(get_text_fragments), style="class:menu")
878
-
879
-
880
-
881
- class DotDict(dict):
882
- """
883
- 可以通过点.访问内部key-value对的字典。此类型继承自dict。
884
-
885
- - 由于继承关系,此类型可以使用所有dict可以使用的方法
886
- - 额外增加的点.访问方法使用示例如下
887
-
888
- 示例:
889
- .. code:: Python
890
-
891
- mydict = DotDict()
892
-
893
- # 以下写内容访问等价
894
- mydict["key1"] = "value1"
895
- mydict.key1 = "value1"
896
-
897
- # 以下读访问等价
898
- val = mydict["key1"]
899
- val = mydict.key1
900
- """
901
-
902
- def __getattr__(self, __key):
903
- if (not __key in self.__dict__) and (not __key.startswith("__")):
904
- return self.__getitem__(__key)
905
-
906
- def __setattr__(self, __name: str, __value):
907
- if __name in self.__dict__:
908
- object.__setattr__(self, __name, __value)
909
- else:
910
- self.__setitem__(__name, __value)
911
-
912
- def __getstate__(self):
913
- return self
914
-
915
- def __setstate__(self, state):
916
- self.update(state)
917
-
918
-
1
+ # External Libraries
2
+ from functools import lru_cache
3
+ from unicodedata import east_asian_width
4
+ from wcwidth import wcwidth
5
+ from dataclasses import dataclass
6
+ import time, re, logging, linecache, os
7
+ from typing import Optional, List, Dict
8
+ from typing import Iterable, NamedTuple, Optional, Union, Tuple
9
+ from prompt_toolkit import ANSI
10
+ from prompt_toolkit.application import get_app
11
+ from prompt_toolkit.buffer import Buffer
12
+ from prompt_toolkit.formatted_text import to_formatted_text, fragment_list_to_text
13
+ from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple
14
+ from prompt_toolkit.layout.controls import UIContent, UIControl
15
+ from prompt_toolkit.layout.processors import Processor, Transformation
16
+ from prompt_toolkit.application.current import get_app
17
+ from prompt_toolkit.buffer import Buffer
18
+ from prompt_toolkit.document import Document
19
+ from prompt_toolkit.data_structures import Point
20
+ from prompt_toolkit.layout.controls import UIContent, FormattedTextControl
21
+ from prompt_toolkit.lexers import Lexer
22
+ from prompt_toolkit.mouse_events import MouseButton, MouseEvent, MouseEventType
23
+ from prompt_toolkit.selection import SelectionType
24
+ from prompt_toolkit.buffer import Buffer, ValidationState
25
+ from prompt_toolkit.utils import Event
26
+
27
+ from prompt_toolkit.filters import (
28
+ FilterOrBool,
29
+ )
30
+ from prompt_toolkit.formatted_text import (
31
+ StyleAndTextTuples,
32
+ to_formatted_text,
33
+ )
34
+ from prompt_toolkit.formatted_text.utils import fragment_list_to_text
35
+ from prompt_toolkit.history import InMemoryHistory
36
+ from prompt_toolkit.key_binding.key_bindings import KeyBindingsBase
37
+ from prompt_toolkit.layout.containers import (
38
+ Window,
39
+ WindowAlign,
40
+ )
41
+ from prompt_toolkit.layout.controls import (
42
+
43
+ FormattedTextControl,
44
+ )
45
+ from prompt_toolkit.layout.processors import (
46
+ Processor,
47
+ TransformationInput,
48
+ Transformation
49
+ )
50
+ from prompt_toolkit.lexers import Lexer
51
+ from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
52
+ from prompt_toolkit.utils import get_cwidth
53
+ from prompt_toolkit.widgets import Button, MenuContainer, MenuItem
54
+ from prompt_toolkit.widgets.base import Border
55
+
56
+ from prompt_toolkit.layout.screen import _CHAR_CACHE, Screen, WritePosition
57
+ from prompt_toolkit.layout.utils import explode_text_fragments
58
+ from prompt_toolkit.formatted_text.utils import (
59
+ fragment_list_to_text,
60
+ fragment_list_width,
61
+ )
62
+
63
+ from .settings import Settings
64
+
65
+ class VSplitWindow(Window):
66
+ "修改的分块窗口,向上翻页时,下半部保持最后数据不变"
67
+
68
+ def _copy_body(
69
+ self,
70
+ ui_content: UIContent,
71
+ new_screen: Screen,
72
+ write_position: WritePosition,
73
+ move_x: int,
74
+ width: int,
75
+ vertical_scroll: int = 0,
76
+ horizontal_scroll: int = 0,
77
+ wrap_lines: bool = False,
78
+ highlight_lines: bool = False,
79
+ vertical_scroll_2: int = 0,
80
+ always_hide_cursor: bool = False,
81
+ has_focus: bool = False,
82
+ align: WindowAlign = WindowAlign.LEFT,
83
+ get_line_prefix = None,
84
+ isNotMargin = True,
85
+ ):
86
+ """
87
+ Copy the UIContent into the output screen.
88
+ Return (visible_line_to_row_col, rowcol_to_yx) tuple.
89
+
90
+ :param get_line_prefix: None or a callable that takes a line number
91
+ (int) and a wrap_count (int) and returns formatted text.
92
+ """
93
+ xpos = write_position.xpos + move_x
94
+ ypos = write_position.ypos
95
+ line_count = ui_content.line_count
96
+ new_buffer = new_screen.data_buffer
97
+ empty_char = _CHAR_CACHE["", ""]
98
+
99
+ # Map visible line number to (row, col) of input.
100
+ # 'col' will always be zero if line wrapping is off.
101
+ visible_line_to_row_col: dict[int, tuple[int, int]] = {}
102
+
103
+ # Maps (row, col) from the input to (y, x) screen coordinates.
104
+ rowcol_to_yx: dict[tuple[int, int], tuple[int, int]] = {}
105
+
106
+ def copy_line(
107
+ line: StyleAndTextTuples,
108
+ lineno: int,
109
+ x: int,
110
+ y: int,
111
+ is_input: bool = False,
112
+ ):
113
+ """
114
+ Copy over a single line to the output screen. This can wrap over
115
+ multiple lines in the output. It will call the prefix (prompt)
116
+ function before every line.
117
+ """
118
+ if is_input:
119
+ current_rowcol_to_yx = rowcol_to_yx
120
+ else:
121
+ current_rowcol_to_yx = {} # Throwaway dictionary.
122
+
123
+ # Draw line prefix.
124
+ if is_input and get_line_prefix:
125
+ prompt = to_formatted_text(get_line_prefix(lineno, 0))
126
+ x, y = copy_line(prompt, lineno, x, y, is_input=False)
127
+
128
+ # Scroll horizontally.
129
+ skipped = 0 # Characters skipped because of horizontal scrolling.
130
+ if horizontal_scroll and is_input:
131
+ h_scroll = horizontal_scroll
132
+ line = explode_text_fragments(line)
133
+ while h_scroll > 0 and line:
134
+ h_scroll -= get_cwidth(line[0][1])
135
+ skipped += 1
136
+ del line[:1] # Remove first character.
137
+
138
+ x -= h_scroll # When scrolling over double width character,
139
+ # this can end up being negative.
140
+
141
+ # Align this line. (Note that this doesn't work well when we use
142
+ # get_line_prefix and that function returns variable width prefixes.)
143
+ if align == WindowAlign.CENTER:
144
+ line_width = fragment_list_width(line)
145
+ if line_width < width:
146
+ x += (width - line_width) // 2
147
+ elif align == WindowAlign.RIGHT:
148
+ line_width = fragment_list_width(line)
149
+ if line_width < width:
150
+ x += width - line_width
151
+
152
+ col = 0
153
+ wrap_count = 0
154
+ for style, text, *_ in line:
155
+ new_buffer_row = new_buffer[y + ypos]
156
+
157
+ # Remember raw VT escape sequences. (E.g. FinalTerm's
158
+ # escape sequences.)
159
+ if "[ZeroWidthEscape]" in style:
160
+ new_screen.zero_width_escapes[y + ypos][x + xpos] += text
161
+ continue
162
+
163
+ for c in text:
164
+ char = _CHAR_CACHE[c, style]
165
+ char_width = char.width
166
+
167
+ # Wrap when the line width is exceeded.
168
+ if wrap_lines and x + char_width > width:
169
+ visible_line_to_row_col[y + 1] = (
170
+ lineno,
171
+ visible_line_to_row_col[y][1] + x,
172
+ )
173
+ y += 1
174
+ wrap_count += 1
175
+ x = 0
176
+
177
+ # Insert line prefix (continuation prompt).
178
+ if is_input and get_line_prefix:
179
+ prompt = to_formatted_text(
180
+ get_line_prefix(lineno, wrap_count)
181
+ )
182
+ x, y = copy_line(prompt, lineno, x, y, is_input=False)
183
+
184
+ new_buffer_row = new_buffer[y + ypos]
185
+
186
+ if y >= write_position.height:
187
+ return x, y # Break out of all for loops.
188
+
189
+ # Set character in screen and shift 'x'.
190
+ if x >= 0 and y >= 0 and x < width:
191
+ new_buffer_row[x + xpos] = char
192
+
193
+ # When we print a multi width character, make sure
194
+ # to erase the neighbours positions in the screen.
195
+ # (The empty string if different from everything,
196
+ # so next redraw this cell will repaint anyway.)
197
+ if char_width > 1:
198
+ for i in range(1, char_width):
199
+ new_buffer_row[x + xpos + i] = empty_char
200
+
201
+ # If this is a zero width characters, then it's
202
+ # probably part of a decomposed unicode character.
203
+ # See: https://en.wikipedia.org/wiki/Unicode_equivalence
204
+ # Merge it in the previous cell.
205
+ elif char_width == 0:
206
+ # Handle all character widths. If the previous
207
+ # character is a multiwidth character, then
208
+ # merge it two positions back.
209
+ for pw in [2, 1]: # Previous character width.
210
+ if (
211
+ x - pw >= 0
212
+ and new_buffer_row[x + xpos - pw].width == pw
213
+ ):
214
+ prev_char = new_buffer_row[x + xpos - pw]
215
+ char2 = _CHAR_CACHE[
216
+ prev_char.char + c, prev_char.style
217
+ ]
218
+ new_buffer_row[x + xpos - pw] = char2
219
+
220
+ # Keep track of write position for each character.
221
+ current_rowcol_to_yx[lineno, col + skipped] = (
222
+ y + ypos,
223
+ x + xpos,
224
+ )
225
+
226
+ col += 1
227
+ x += char_width
228
+ return x, y
229
+
230
+ # Copy content.
231
+ def copy() -> int:
232
+ y = -vertical_scroll_2
233
+ lineno = vertical_scroll
234
+
235
+ total = write_position.height
236
+ upper = (total - 1) // 2
237
+ below = total - upper - 1
238
+
239
+ #if isNotMargin:
240
+ if isinstance(self.content, PyMudBufferControl):
241
+ b = self.content.buffer
242
+ if not b:
243
+ return y
244
+
245
+ line_count = b.lineCount
246
+ start_lineno = b.start_lineno
247
+ if start_lineno < 0:
248
+ # no split window
249
+ if line_count < total:
250
+ # 内容行数小于屏幕行数
251
+ lineno = 0
252
+
253
+ while y < total and lineno < line_count:
254
+ # Take the next line and copy it in the real screen.
255
+ line = ui_content.get_line(lineno)
256
+ visible_line_to_row_col[y] = (lineno, horizontal_scroll)
257
+ x = 0
258
+ x, y = copy_line(line, lineno, x, y, is_input=True)
259
+ lineno += 1
260
+ y += 1
261
+
262
+ else:
263
+ # 若内容行数大于屏幕行数,则倒序复制,确保即使有自动折行时,最后一行也保持在屏幕最底部
264
+
265
+ y = total
266
+ lineno = line_count
267
+
268
+ while y >= 0 and lineno >= 0:
269
+ lineno -= 1
270
+ # Take the next line and copy it in the real screen.
271
+ display_lines = ui_content.get_height_for_line(lineno, width, None)
272
+ y -= display_lines
273
+ line = ui_content.get_line(lineno)
274
+ visible_line_to_row_col[y] = (lineno, horizontal_scroll)
275
+ copy_line(line, lineno, 0, y, is_input=True)
276
+
277
+
278
+ else:
279
+ # 有split window
280
+
281
+
282
+
283
+ # 先复制下半部分,倒序复制,确保即使有自动折行时,最后一行也保持在屏幕最底部
284
+ y = total
285
+ lineno = line_count
286
+
287
+ while y > below and lineno >= 0:
288
+ lineno -= 1
289
+ # Take the next line and copy it in the real screen.
290
+ display_lines = ui_content.get_height_for_line(lineno, width, None)
291
+ y -= display_lines
292
+ if y <= below:
293
+ break
294
+ line = ui_content.get_line(lineno)
295
+ visible_line_to_row_col[y] = (lineno, horizontal_scroll)
296
+ copy_line(line, lineno, 0, y, is_input=True)
297
+
298
+ # 复制上半部分,正序复制,确保即使有自动折行时,第一行也保持在屏幕最顶部
299
+ y = -vertical_scroll_2
300
+ lineno = start_lineno
301
+ while y <= below and lineno < line_count:
302
+ line = ui_content.get_line(lineno)
303
+ visible_line_to_row_col[y] = (lineno, horizontal_scroll)
304
+ x = 0
305
+ x, y = copy_line(line, lineno, x, y, is_input=True)
306
+ lineno += 1
307
+ y += 1
308
+
309
+ # 最后复制分割线,若上下有由于折行额外占用的内容,都用分割线给覆盖掉
310
+ copy_line([("","-"*width)], -1, 0, upper + 1, is_input=False)
311
+
312
+ return y
313
+
314
+ copy()
315
+
316
+ def cursor_pos_to_screen_pos(row: int, col: int) -> Point:
317
+ "Translate row/col from UIContent to real Screen coordinates."
318
+ try:
319
+ y, x = rowcol_to_yx[row, col]
320
+ except KeyError:
321
+ # Normally this should never happen. (It is a bug, if it happens.)
322
+ # But to be sure, return (0, 0)
323
+ return Point(x=0, y=0)
324
+
325
+ # raise ValueError(
326
+ # 'Invalid position. row=%r col=%r, vertical_scroll=%r, '
327
+ # 'horizontal_scroll=%r, height=%r' %
328
+ # (row, col, vertical_scroll, horizontal_scroll, write_position.height))
329
+ else:
330
+ return Point(x=x, y=y)
331
+
332
+ # Set cursor and menu positions.
333
+ if ui_content.cursor_position:
334
+ screen_cursor_position = cursor_pos_to_screen_pos(
335
+ ui_content.cursor_position.y, ui_content.cursor_position.x
336
+ )
337
+
338
+ if has_focus:
339
+ new_screen.set_cursor_position(self, screen_cursor_position)
340
+
341
+ if always_hide_cursor:
342
+ new_screen.show_cursor = False
343
+ else:
344
+ new_screen.show_cursor = ui_content.show_cursor
345
+
346
+ self._highlight_digraph(new_screen)
347
+
348
+ if highlight_lines:
349
+ self._highlight_cursorlines(
350
+ new_screen,
351
+ screen_cursor_position,
352
+ xpos,
353
+ ypos,
354
+ width,
355
+ write_position.height,
356
+ )
357
+
358
+ # Draw input characters from the input processor queue.
359
+ if has_focus and ui_content.cursor_position:
360
+ self._show_key_processor_key_buffer(new_screen)
361
+
362
+ # Set menu position.
363
+ if ui_content.menu_position:
364
+ new_screen.set_menu_position(
365
+ self,
366
+ cursor_pos_to_screen_pos(
367
+ ui_content.menu_position.y, ui_content.menu_position.x
368
+ ),
369
+ )
370
+
371
+ # Update output screen height.
372
+ new_screen.height = max(new_screen.height, ypos + write_position.height)
373
+
374
+ return visible_line_to_row_col, rowcol_to_yx
375
+
376
+ def _scroll_down(self) -> None:
377
+ "向下滚屏,处理屏幕分隔"
378
+ info = self.render_info
379
+
380
+ if info is None:
381
+ return
382
+
383
+ if isinstance(self.content, PyMudBufferControl):
384
+ b = self.content.buffer
385
+ if not b:
386
+ return
387
+ start_lineno = b.start_lineno
388
+ if (start_lineno >= 0) and (start_lineno < b.lineCount - len(info.displayed_lines)):
389
+ b.start_lineno = b.start_lineno + 1
390
+ else:
391
+ b.start_lineno = -1
392
+
393
+ def _scroll_up(self) -> None:
394
+ "向上滚屏,处理屏幕分隔"
395
+ info = self.render_info
396
+
397
+ if info is None:
398
+ return
399
+
400
+ if isinstance(self.content, PyMudBufferControl):
401
+ b = self.content.buffer
402
+ if not b:
403
+ return
404
+ start_lineno = b.start_lineno
405
+ if start_lineno > 0:
406
+ b.start_lineno = b.start_lineno - 1
407
+
408
+ elif start_lineno == 0:
409
+ b.start_lineno = 0
410
+
411
+ else:
412
+ b.start_lineno = b.lineCount - len(info.displayed_lines) - 1
413
+
414
+
415
+ class EasternButton(Button):
416
+ "解决增加中文等东亚全宽字符后不对齐问题"
417
+
418
+ def _get_text_fragments(self) -> StyleAndTextTuples:
419
+ # 主要改动在这里
420
+ width = self.width - (
421
+ get_cwidth(self.left_symbol) + get_cwidth(self.right_symbol)
422
+ ) - (get_cwidth(self.text) - len(self.text))
423
+
424
+
425
+ text = (f"{{:^{width}}}").format(self.text)
426
+
427
+ def handler(mouse_event: MouseEvent) -> None:
428
+ if (
429
+ self.handler is not None
430
+ and mouse_event.event_type == MouseEventType.MOUSE_UP
431
+ ):
432
+ self.handler()
433
+
434
+ return [
435
+ ("class:button.arrow", self.left_symbol, handler),
436
+ #("[SetCursorPosition]", ""),
437
+ ("class:button.text", text, handler),
438
+ ("class:button.arrow", self.right_symbol, handler),
439
+ ]
440
+
441
+ class EasternMenuContainer(MenuContainer):
442
+ "解决增加中文等东亚全宽字符后不对齐问题"
443
+
444
+ def _submenu(self, level: int = 0) -> Window:
445
+ def get_text_fragments() -> StyleAndTextTuples:
446
+ result: StyleAndTextTuples = []
447
+ if level < len(self.selected_menu):
448
+ menu = self._get_menu(level)
449
+ if menu.children:
450
+ result.append(("class:menu", Border.TOP_LEFT))
451
+ result.append(("class:menu", Border.HORIZONTAL * (menu.width + 4)))
452
+ result.append(("class:menu", Border.TOP_RIGHT))
453
+ result.append(("", "\n"))
454
+ try:
455
+ selected_item = self.selected_menu[level + 1]
456
+ except IndexError:
457
+ selected_item = -1
458
+
459
+ def one_item(
460
+ i: int, item: MenuItem
461
+ ) -> Iterable[OneStyleAndTextTuple]:
462
+ def mouse_handler(mouse_event: MouseEvent) -> None:
463
+ if item.disabled:
464
+ # The arrow keys can't interact with menu items that are disabled.
465
+ # The mouse shouldn't be able to either.
466
+ return
467
+ hover = mouse_event.event_type == MouseEventType.MOUSE_MOVE
468
+ if (
469
+ mouse_event.event_type == MouseEventType.MOUSE_UP
470
+ or hover
471
+ ):
472
+ app = get_app()
473
+ if not hover and item.handler:
474
+ app.layout.focus_last()
475
+ item.handler()
476
+ else:
477
+ self.selected_menu = self.selected_menu[
478
+ : level + 1
479
+ ] + [i]
480
+
481
+ if i == selected_item:
482
+ yield ("[SetCursorPosition]", "")
483
+ style = "class:menu-bar.selected-item"
484
+ else:
485
+ style = ""
486
+
487
+ yield ("class:menu", Border.VERTICAL)
488
+ if item.text == "-":
489
+ yield (
490
+ style + "class:menu-border",
491
+ f"{Border.HORIZONTAL * (menu.width + 3)}",
492
+ mouse_handler,
493
+ )
494
+ else:
495
+ # 主要改动在这里,其他地方都未更改.
496
+ adj_width = menu.width + 3 - (get_cwidth(item.text) - len(item.text))
497
+ yield (
498
+ style,
499
+ f" {item.text}".ljust(adj_width),
500
+ mouse_handler,
501
+ )
502
+
503
+ if item.children:
504
+ yield (style, ">", mouse_handler)
505
+ else:
506
+ yield (style, " ", mouse_handler)
507
+
508
+ if i == selected_item:
509
+ yield ("[SetMenuPosition]", "")
510
+ yield ("class:menu", Border.VERTICAL)
511
+
512
+ yield ("", "\n")
513
+
514
+ for i, item in enumerate(menu.children):
515
+ result.extend(one_item(i, item))
516
+
517
+ result.append(("class:menu", Border.BOTTOM_LEFT))
518
+ result.append(("class:menu", Border.HORIZONTAL * (menu.width + 4)))
519
+ result.append(("class:menu", Border.BOTTOM_RIGHT))
520
+ return result
521
+
522
+ return Window(FormattedTextControl(get_text_fragments), style="class:menu")
523
+
524
+
525
+ @dataclass
526
+ class SessionSelectionState:
527
+ start_row: int = -1
528
+ end_row: int = -1
529
+ start_col: int = -1
530
+ end_col: int = -1
531
+ def is_valid(self):
532
+ if self.start_row >= 0 and self.end_row >= 0 and self.start_col >= 0 and self.end_col >= 0:
533
+ if (self.start_row == self.end_row) and (self.start_col == self.end_col):
534
+ return False
535
+ elif self.start_row > self.end_row:
536
+ srow, scol = self.end_row, self.end_col
537
+ erow, ecol = self.start_row, self.start_col
538
+ self.start_row, self.end_row = srow, erow
539
+ self.start_col, self.end_col = scol, ecol
540
+ elif self.start_row == self.end_row and self.start_col > self.end_col:
541
+ scol, ecol = self.end_col, self.start_col
542
+ self.start_col, self.end_col = scol, ecol
543
+
544
+ return True
545
+
546
+ return False
547
+
548
+ @property
549
+ def rows(self):
550
+ if self.is_valid():
551
+ return self.end_row - self.start_row + 1
552
+ else:
553
+ return 0
554
+
555
+
556
+ class BufferBase:
557
+ def __init__(self, name, newline = "\n", max_buffered_lines = 10000) -> None:
558
+ self.name = name
559
+ self.newline = newline
560
+ self.max_buffered_lines = max_buffered_lines
561
+ self.start_lineno = -1
562
+ self.selection = SessionSelectionState(-1, -1, -1, -1)
563
+
564
+ def clear(self):
565
+ pass
566
+
567
+ @property
568
+ def lineCount(self) -> int:
569
+ return 0
570
+
571
+ def getLine(self, lineno: int) -> str:
572
+ return ""
573
+
574
+ # 获取指定某行到某行的内容。当start未设置时,从首行开始。当end未设置时,到最后一行结束。
575
+ # 注意判断首位顺序逻辑,以及给定参数是否越界
576
+ def selection_range_at_line(self, lineno: int) -> Optional[Tuple[int, int]]:
577
+ if self.selection.is_valid():
578
+ if self.selection.rows > 1:
579
+ if lineno == self.selection.start_row:
580
+ return (self.selection.start_col, len(self.getLine(lineno)) - 1)
581
+ elif lineno == self.selection.end_row:
582
+ return (0, self.selection.end_col)
583
+ elif lineno > self.selection.start_row and lineno < self.selection.end_row:
584
+ return (0, len(self.getLine(lineno)) - 1)
585
+
586
+ elif self.selection.rows == 1:
587
+ if lineno == self.selection.start_row:
588
+ return (self.selection.start_col, self.selection.end_col)
589
+
590
+ return None
591
+
592
+ def exit_selection(self):
593
+ self.selection = SessionSelectionState(-1, -1, -1, -1)
594
+
595
+ def nosplit(self):
596
+ self.start_lineno = -1
597
+ get_app().invalidate()
598
+
599
+
600
+ class SessionBuffer(BufferBase):
601
+ def __init__(
602
+ self,
603
+ name,
604
+ newline = "\n",
605
+ max_buffered_lines = 10000,
606
+ ) -> None:
607
+
608
+ super().__init__(name, newline, max_buffered_lines)
609
+
610
+ self._lines : List[str] = []
611
+ self._isnewline = True
612
+
613
+ def append(self, line: str):
614
+ """
615
+ 追加文本到缓冲区。
616
+ 当文本以换行符结尾时,会自动添加到缓冲区。
617
+ 当文本不以换行符结尾时,会自动添加到上一行。
618
+ """
619
+ newline_after_append = False
620
+ if line.endswith(self.newline):
621
+ line = line.rstrip(self.newline)
622
+ newline_after_append = True
623
+ if not self.newline in line:
624
+ if self._isnewline:
625
+ self._lines.append(line)
626
+ else:
627
+ self._lines[-1] += line
628
+
629
+ else:
630
+ lines = line.split(self.newline)
631
+ if self._isnewline:
632
+ self._lines.extend(lines)
633
+ else:
634
+ self._lines[-1] += lines[0]
635
+ self._lines.extend(lines[1:])
636
+
637
+ self._isnewline = newline_after_append
638
+
639
+ ## limit buffered lines
640
+ if len(self._lines) > self.max_buffered_lines:
641
+ diff = self.max_buffered_lines - len(self._lines)
642
+ del self._lines[:diff]
643
+ ## adjust selection
644
+ if self.selection.start_row >= 0:
645
+ self.selection.start_row -= diff
646
+ self.selection.end_row -= diff
647
+
648
+ get_app().invalidate()
649
+
650
+ def clear(self):
651
+ self._lines.clear()
652
+ self.selection = SessionSelectionState(-1, -1, -1, -1)
653
+
654
+ get_app().invalidate()
655
+
656
+ @property
657
+ def lineCount(self):
658
+ return len(self._lines)
659
+
660
+ def getLine(self, lineno: int):
661
+ if lineno < 0 or lineno >= len(self._lines):
662
+ return ""
663
+ return self._lines[lineno]
664
+
665
+
666
+ class LogFileBuffer(BufferBase):
667
+ def __init__(
668
+ self,
669
+ name,
670
+ filepath: Optional[str] = None,
671
+ ) -> None:
672
+
673
+ super().__init__(name)
674
+ self._lines : Dict[int, str] = {}
675
+ self.loadfile(filepath)
676
+
677
+ def loadfile(self, filepath: Optional[str] = None):
678
+ if filepath and os.path.exists(filepath):
679
+ self.filepath = filepath
680
+ else:
681
+ self.filepath = None
682
+
683
+ def clear(self):
684
+ self.filepath = None
685
+
686
+ @property
687
+ def lineCount(self):
688
+ if not self.filepath or not os.path.exists(self.filepath):
689
+ return 0
690
+
691
+ with open(self.filepath, 'r', encoding = 'utf-8', errors = 'ignore') as fp:
692
+ return sum(1 for _ in fp)
693
+
694
+ def getLine(self, lineno: int):
695
+ if not self.filepath or not os.path.exists(self.filepath):
696
+ return ""
697
+
698
+ return linecache.getline(self.filepath, lineno).rstrip(self.newline)
699
+
700
+ def __del__(self):
701
+ self._lines.clear()
702
+
703
+ class PyMudBufferControl(UIControl):
704
+ def __init__(self, buffer: Optional[BufferBase]) -> None:
705
+ self.buffer = buffer
706
+
707
+ # 为MUD显示进行校正的处理,包括对齐校正,换行颜色校正等
708
+ self.FULL_BLOCKS = set("▂▃▅▆▇▄█")
709
+ self.SINGLE_LINES = set("┌└├┬┼┴╭╰─")
710
+ self.DOUBLE_LINES = set("╔╚╠╦╪╩═")
711
+ self.ALL_COLOR_REGX = re.compile(r"(?:\[[\d;]+m)+")
712
+ self.AVAI_COLOR_REGX = re.compile(r"(?:\[[\d;]+m)+(?!$)")
713
+ self._color_start = ""
714
+ self._color_correction = False
715
+ self._color_line_index = 0
716
+
717
+ self._last_click_timestamp = 0
718
+
719
+ def reset(self) -> None:
720
+ # Default reset. (Doesn't have to be implemented.)
721
+ pass
722
+
723
+ def preferred_width(self, max_available_width: int) -> int | None:
724
+ return None
725
+
726
+ def is_focusable(self) -> bool:
727
+ """
728
+ Tell whether this user control is focusable.
729
+ """
730
+ return False
731
+
732
+
733
+ def width_correction(self, line: str) -> str:
734
+ new_str = []
735
+ for ch in line:
736
+ new_str.append(ch)
737
+ if (east_asian_width(ch) in "FWA") and (wcwidth(ch) == 1):
738
+ if ch in self.FULL_BLOCKS:
739
+ new_str.append(ch)
740
+ elif ch in self.SINGLE_LINES:
741
+ new_str.append("─")
742
+ elif ch in self.DOUBLE_LINES:
743
+ new_str.append("═")
744
+ else:
745
+ new_str.append(' ')
746
+
747
+ return "".join(new_str)
748
+
749
+ def return_correction(self, line: str):
750
+ return line.replace("\r", "").replace("\x00", "")
751
+
752
+ def tab_correction(self, line: str):
753
+ return line.replace("\t", " " * Settings.client["tabstop"])
754
+
755
+ def line_correction(self, line: str):
756
+ # 处理\r符号(^M)
757
+ line = self.return_correction(line)
758
+ # 处理Tab(\r)符号(^I)
759
+ line = self.tab_correction(line)
760
+
761
+ # 美化(解决中文英文在Console中不对齐的问题)
762
+ if Settings.client["beautify"]:
763
+ line = self.width_correction(line)
764
+
765
+ return line
766
+
767
+ def create_content(self, width: int, height: int) -> UIContent:
768
+ """
769
+ Generate the content for this user control.
770
+
771
+ Returns a :class:`.UIContent` instance.
772
+ """
773
+ buffer = self.buffer
774
+ if not buffer:
775
+ return UIContent(
776
+ get_line = lambda i: [],
777
+ line_count = 0,
778
+ cursor_position = None
779
+ )
780
+
781
+ def get_line(i: int) -> StyleAndTextTuples:
782
+ line = buffer.getLine(i)
783
+ # 颜色校正
784
+ SEARCH_LINES = 10
785
+ thislinecolors = len(self.AVAI_COLOR_REGX.findall(line))
786
+ if thislinecolors == 0:
787
+ lineno = i - 1
788
+ search = 0
789
+ while lineno >= 0 and search < SEARCH_LINES:
790
+ search += 1
791
+
792
+ lastline = buffer.getLine(lineno)
793
+ allcolors = self.ALL_COLOR_REGX.findall(lastline)
794
+
795
+ if len(allcolors) == 0:
796
+ lineno = lineno - 1
797
+
798
+ elif len(allcolors) == 1:
799
+ colors = self.AVAI_COLOR_REGX.findall(lastline)
800
+
801
+ if len(colors) == 1:
802
+ line = f"{colors[0]}{line}"
803
+ break
804
+
805
+ else:
806
+ break
807
+
808
+ else:
809
+ break
810
+
811
+
812
+ # 其他校正
813
+ line = self.line_correction(line)
814
+
815
+ # 处理ANSI标记(生成FormmatedText)
816
+ fragments = to_formatted_text(ANSI(line))
817
+
818
+ # 选择内容标识
819
+ selected_fragment = " class:selected "
820
+
821
+ # In case of selection, highlight all matches.
822
+ selection_at_line = buffer.selection_range_at_line(i)
823
+
824
+ if selection_at_line:
825
+ from_, to = selection_at_line
826
+ # from_ = source_to_display(from_)
827
+ # to = source_to_display(to)
828
+
829
+ fragments = explode_text_fragments(fragments)
830
+
831
+ if from_ == 0 and to == 0 and len(fragments) == 0:
832
+ # When this is an empty line, insert a space in order to
833
+ # visualize the selection.
834
+ return [(selected_fragment, " ")]
835
+ else:
836
+ for i in range(from_, to):
837
+ if i < len(fragments):
838
+ old_fragment, old_text, *_ = fragments[i]
839
+ fragments[i] = (old_fragment + selected_fragment, old_text)
840
+ elif i == len(fragments):
841
+ fragments.append((selected_fragment, " "))
842
+
843
+ return fragments
844
+
845
+ content = UIContent(
846
+ get_line = get_line,
847
+ line_count = buffer.lineCount,
848
+ cursor_position = None
849
+ )
850
+
851
+ return content
852
+
853
+ def mouse_handler(self, mouse_event: MouseEvent):
854
+ """
855
+ Handle mouse events.
856
+
857
+ When `NotImplemented` is returned, it means that the given event is not
858
+ handled by the `UIControl` itself. The `Window` or key bindings can
859
+ decide to handle this event as scrolling or changing focus.
860
+
861
+ :param mouse_event: `MouseEvent` instance.
862
+ """
863
+ """
864
+ 鼠标处理,修改内容包括:
865
+ 1. 在CommandLine获得焦点的时候,鼠标对本Control也可以操作
866
+ 2. 鼠标双击为选中行
867
+ """
868
+ buffer = self.buffer
869
+ position = mouse_event.position
870
+
871
+ # Focus buffer when clicked.
872
+ cur_control = get_app().layout.current_control
873
+ cur_buffer = get_app().layout.current_buffer
874
+ # 这里是修改的内容
875
+ if (cur_control == self) or (cur_buffer and cur_buffer.name == "input"):
876
+
877
+ if buffer:
878
+ # Set the selection position.
879
+ if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
880
+ buffer.exit_selection()
881
+ buffer.selection.start_row = position.y
882
+ buffer.selection.start_col = position.x
883
+
884
+ elif (
885
+ mouse_event.event_type == MouseEventType.MOUSE_MOVE
886
+ and mouse_event.button == MouseButton.LEFT
887
+ ):
888
+ # Click and drag to highlight a selection
889
+ if buffer.selection.start_row >= 0:
890
+ buffer.selection.end_row = position.y
891
+ buffer.selection.end_col = position.x
892
+
893
+ elif mouse_event.event_type == MouseEventType.MOUSE_UP:
894
+ # When the cursor was moved to another place, select the text.
895
+ # (The >1 is actually a small but acceptable workaround for
896
+ # selecting text in Vi navigation mode. In navigation mode,
897
+ # the cursor can never be after the text, so the cursor
898
+ # will be repositioned automatically.)
899
+
900
+ if buffer.selection.start_row >= 0:
901
+ buffer.selection.end_row = position.y
902
+ buffer.selection.end_col = position.x
903
+
904
+ if buffer.selection.start_row == buffer.selection.end_row and buffer.selection.start_col == buffer.selection.end_col:
905
+ buffer.selection = SessionSelectionState(-1, -1, -1, -1)
906
+
907
+
908
+ # Select word around cursor on double click.
909
+ # Two MOUSE_UP events in a short timespan are considered a double click.
910
+ double_click = (
911
+ self._last_click_timestamp
912
+ and time.time() - self._last_click_timestamp < 0.3
913
+ )
914
+ self._last_click_timestamp = time.time()
915
+
916
+ if double_click:
917
+ buffer.selection.start_row = position.y
918
+ buffer.selection.start_col = 0
919
+ buffer.selection.end_row = position.y
920
+ buffer.selection.end_col = len(buffer.getLine(position.y))
921
+
922
+ get_app().layout.focus("input")
923
+
924
+ else:
925
+ # Don't handle scroll events here.
926
+ return NotImplemented
927
+ else:
928
+ # Don't handle scroll events here.
929
+ return NotImplemented
930
+
931
+ # Not focused, but focusing on click events.
932
+ else:
933
+ return NotImplemented
934
+
935
+ return None
936
+
937
+ class DotDict(dict):
938
+ """
939
+ 可以通过点.访问内部key-value对的字典。此类型继承自dict。
940
+
941
+ - 由于继承关系,此类型可以使用所有dict可以使用的方法
942
+ - 额外增加的点.访问方法使用示例如下
943
+
944
+ 示例:
945
+ .. code:: Python
946
+
947
+ mydict = DotDict()
948
+
949
+ # 以下写内容访问等价
950
+ mydict["key1"] = "value1"
951
+ mydict.key1 = "value1"
952
+
953
+ # 以下读访问等价
954
+ val = mydict["key1"]
955
+ val = mydict.key1
956
+ """
957
+
958
+ def __getattr__(self, __key):
959
+ if (not __key in self.__dict__) and (not __key.startswith("__")):
960
+ return self.__getitem__(__key)
961
+
962
+ def __setattr__(self, __name: str, __value):
963
+ if __name in self.__dict__:
964
+ object.__setattr__(self, __name, __value)
965
+ else:
966
+ self.__setitem__(__name, __value)
967
+
968
+ def __getstate__(self):
969
+ return self
970
+
971
+ def __setstate__(self, state):
972
+ self.update(state)
973
+
974
+
919
975