Debian Codegraph @

sandbox/inputfield.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import sys
4 from argparse import ArgumentParser, Namespace
5 from pathlib import Path
6
7 import pytermgui as ptg
8
9
10 def _process_arguments(argv: list[str] | None = None) -> Namespace:
11 """Processes command line arguments.
12
13 Note that you don't _have to_ use the bultin argparse module for this; it
14 is just what the module uses.
15
16 Args:
17 argv: A list of command line arguments, not including the binary path
18 (sys.argv[0]).
19 """
20
21 parser = ArgumentParser(description="A simple text editor.")
22 parser.add_argument("file", help="The file to read.", type=Path, nargs="?")
23 parser.add_argument(
24 "-s",
25 "--string",
26 help="String to edit, when file is not given.",
27 metavar="STR",
28 )
29
30 parser.add_argument(
31 "--highlight", action="store_true", help="Enable Python syntax highlighting."
32 )
33
34 return parser.parse_args(argv)
35
36
37 def _create_aliases() -> None:
38 """Creates all the TIM aliases used by the application."""
39
40 ptg.tim.alias("editor.header", "@157 240")
41 ptg.tim.alias("editor.footer", "inverse editor.header")
42
43
44 def _configure_widgets() -> None:
45 """Defines all the global widget configurations."""
46
47 ptg.boxes.EMPTY.set_chars_of(ptg.Window)
48 ptg.Splitter.set_char("separator", "")
49
50
51 def _define_layout() -> ptg.Layout:
52 """Defines the application layout."""
53
54 layout = ptg.Layout()
55
56 layout.add_slot("Header", height=1)
57 layout.add_break()
58
59 layout.add_slot("Body")
60 layout.add_break()
61
62 layout.add_slot("Footer", height=1)
63
64 return layout
65
66
67 def get_watcher(obj: object, *attrs: str | tuple[str, str]) -> Callable[[str], str]:
68 """Creates a macro callable for retrieving attributes of an object.
69
70 Args:
71 obj: The object to get attributes of.
72 *attrs: The name of the attributes to look at. Each attribute is looked
73 up with using getattr, and the given name will be formatted into the
74 template when the macro is called.
75
76 Example of usage:
77
78 field = InputField()
79 tim.define("!cursor", get_watcher(field.cursor, "row", "col"))
80 tim.print("[!cursor]Cursor: {row}:{col}")
81
82 """
83
84 valid_attrs = []
85 for attr in attrs:
86 if isinstance(attr, str):
87 valid_attrs.append((attr, attr))
88 continue
89
90 alias, real = attr
91 valid_attrs.append((alias, real))
92
93 def _macro(fmt: str) -> None:
94 try:
95 return fmt.format(
96 **{alias: getattr(obj, real) for alias, real in valid_attrs}
97 )
98 except Exception as err:
99 return str(err)
100
101 return _macro
102
103
104 def _read_content(path: Path) -> str:
105 with open(path, "r") as file:
106 return file.read()
107
108
109 def main(argv: list[str] | None = None, tim: ptg.MarkupLanguage = ptg.tim) -> None:
110 """Runs the application."""
111
112 _create_aliases()
113 _configure_widgets()
114
115 args = _process_arguments(argv)
116
117 if args.file is not None:
118 content = _read_content(args.file).replace("[", r"\[")
119
120 elif args.string is not None:
121 content = args.string.replace("[", r"\[")
122
123 else:
124 print("Please provide either a file or a string to edit.")
125 return
126
127 field = ptg.InputField(content, multiline=True)
128 if args.highlight:
129 field.styles.value = lambda _, text: ptg.tim.parse(ptg.highlight_python(text))
130
131 tim.define("!cursor", get_watcher(field.cursor, "row", "col"))
132 tim.define("!select_len", get_watcher(field, ("select_len", "_selection_length")))
133 tim.define("!select_text", get_watcher(field, ("select_text", "selection")))
134
135 with ptg.WindowManager() as manager:
136 manager.layout = _define_layout()
137
138 header = ptg.Window("[editor.header bold]Code Editor", box="EMPTY")
139 header.styles.fill = "editor.header"
140
141 footer = ptg.Window(
142 ptg.Splitter(
143 ptg.Label(
144 "[editor.footer !cursor] Cursor: {row}:{col}"
145 + " // [/!cursor !select_len]{select_len}",
146 parent_align=0,
147 ),
148 ptg.Label(
149 "[editor.footer !select_text]{select_text}",
150 parent_align=2,
151 ),
152 ).styles(fill="editor.footer"),
153 box="EMPTY",
154 )
155 footer.styles.fill = "editor.footer"
156
157 body = ptg.Window(field, overflow=ptg.Overflow.SCROLL)
158
159 manager.add(header, assign="header")
160 manager.add(body, assign="body")
161 manager.add(footer, assign="footer")
162
163
164 if __name__ == "__main__":
165 main(sys.argv[1:])