~nhanb/mcross

ref: bd7d6dec5c9bd8c9f1f08ac64f33c0eff34f8163 mcross/src/mcross/gui/view.py -rw-r--r-- 9.1 KiB
bd7d6decBùi Thành Nhân satisfy black + isort 1 year, 1 month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import logging
import sys
from tkinter import Text, Tk, font, ttk

from .. import conf
from ..document import (
    GeminiNode,
    H1Node,
    H2Node,
    H3Node,
    LinkNode,
    ListItemNode,
    PreformattedNode,
    TextNode,
)
from .model import Model
from .widgets import AltButton, McEntry, ReadOnlyText

# OS-specific values
if sys.platform == "win32":
    TTK_THEME = "vista"
    POINTER_CURSOR = "hand2"
    WAITING_CURSOR = "wait"
elif sys.platform == "darwin":
    TTK_THEME = "aqua"
    POINTER_CURSOR = "pointinghand"
    WAITING_CURSOR = "wait"
else:
    TTK_THEME = "clam"
    POINTER_CURSOR = "hand1"
    WAITING_CURSOR = "watch"


def pick_font(names):
    available = font.families()
    picked = None
    for name in names:
        if name in available:
            picked = name
            break

    if not picked:
        picked = names[-1]

    print("Picked font:", picked)
    return picked


def register_status_bar_log_handler(status_bar: ttk.Label):
    class StatusBarHandler(logging.Handler):
        def emit(self, record):
            status_bar.config(text=self.format(record))

    logger = logging.getLogger("statusbar")
    logger.setLevel(logging.INFO)
    logger.addHandler(StatusBarHandler())


class View:
    model: Model
    address_bar: ttk.Entry
    go_btn: AltButton
    back_btn: AltButton
    forward_btn: AltButton
    text: Text
    status_bar: ttk.Label

    allow_changing_cursor = True

    go_callback = None
    link_click_callback = None
    back_callback = None
    forward_callback = None

    def __init__(self, root: Tk, model: Model):
        self.model = model

        # first row - address bar + buttons
        row1 = ttk.Frame(root)
        row1.pack(fill="x")

        # second row - web viewport
        row2 = ttk.Frame(root)
        row2.pack(fill="both", expand=True)

        # third row - status bar
        status_bar = ttk.Label(root)
        self.status_bar = status_bar
        status_bar.config(justify="right")
        status_bar.pack(fill="x")
        register_status_bar_log_handler(status_bar)

        # Back/Forward buttons
        back_btn = AltButton(
            row1,
            text="◀",
            width=3,
            command=lambda: self.back_callback(),
            root=root,
            alt_char_index=0,
            alt_key="Left",
        )
        forward_btn = AltButton(
            row1,
            text="▶",
            width=3,
            command=lambda: self.forward_callback(),
            root=root,
            alt_char_index=0,
            alt_key="Right",
        )
        back_btn.pack(side="left", padx=2)
        forward_btn.pack(side="left", padx=2)
        self.back_btn = back_btn
        self.forward_btn = forward_btn

        # Address bar prefix
        address_prefix = ttk.Label(row1, text="gemini://")
        address_prefix.pack(side="left")

        # Address bar
        address_bar = McEntry(row1)
        self.address_bar = address_bar
        address_bar.pack(side="left", fill="both", expand=True, pady=3)
        address_bar.bind("<Return>", self._on_go)
        address_bar.bind("<KP_Enter>", self._on_go)
        address_bar.focus_set()

        def on_ctrl_l(ev):
            address_bar.focus()
            address_bar.select_all()

        root.bind("<Control-l>", on_ctrl_l)

        # Go button
        go_btn = AltButton(
            row1, text="Go", root=root, alt_char_index=0, command=self._on_go, width=5
        )
        self.go_btn = go_btn
        go_btn.pack(side="left", padx=2, pady=3)

        # Main viewport implemented as a Text widget.
        text = ReadOnlyText(row2, wrap="word")
        self.text = text
        self.render_page()
        text_font = pick_font(
            [
                conf.get("text-font"),
                "Charis SIL",
                "Source Serif Pro",
                "Cambria",
                "Georgia",
                "DejaVu Serif",
                "Times New Roman",
                "Times",
                "TkTextFont",
            ]
        )

        mono_font = pick_font(
            [conf.get("mono-font"), "Ubuntu Mono", "Consolas", "Courier", "TkFixedFont"]
        )

        text.config(
            font=(text_font, 13),
            bg=conf.get("background-color"),
            fg=conf.get("text-color"),
            padx=5,
            pady=5,
            # hide blinking insertion cursor:
            insertontime=0,
            # prevent text widget from pushing scrollbar/status bar out of the window:
            width=1,
            height=1,
        )
        text.pack(side="left", fill="both", expand=True)
        text.tag_config("link", foreground=conf.get("link-color"))
        text.tag_bind("link", "<Enter>", self._on_link_enter)
        text.tag_bind("link", "<Leave>", self._on_link_leave)
        text.tag_bind("link", "<Button-1>", self._on_link_click)
        text.tag_config("pre", font=(mono_font, 13))
        text.tag_config("plaintext", font=(mono_font, 13))
        text.tag_config("listitem", foreground=conf.get("list-item-color"))

        base_heading_font = font.Font(font=text["font"])
        base_heading_font.config(weight="bold")
        h1_font = font.Font(font=base_heading_font)
        h1_font.config(size=h1_font["size"] + 8)
        text.tag_config("h1", font=h1_font)
        h2_font = font.Font(font=base_heading_font)
        h2_font.config(size=h2_font["size"] + 4)
        text.tag_config("h2", font=h2_font)
        h3_font = font.Font(font=base_heading_font)
        text.tag_config("h3", font=h3_font)

        text_scrollbar = ttk.Scrollbar(row2, command=text.yview)
        text["yscrollcommand"] = text_scrollbar.set
        text_scrollbar.pack(side="left", fill="y")

        style = ttk.Style()
        style.theme_use(TTK_THEME)

    def _on_go(self, ev=None):
        orig_url = self.address_bar.get()
        url = orig_url.strip()

        if url.startswith("gemini://"):
            url = url[9:]

        if not url:
            return

        if url != orig_url:
            self.address_bar.delete(0, "end")
            self.address_bar.insert(0, url)

        if self.go_callback is not None:
            self.go_callback("gemini://" + url)

    def _on_link_enter(self, ev):
        if self.allow_changing_cursor:
            self.text.config(cursor=POINTER_CURSOR)

    def _on_link_leave(self, ev):
        if self.allow_changing_cursor:
            self.text.config(cursor="xterm")

    def _on_link_click(self, ev):
        raw_url = get_content_from_tag_click_event(ev)
        self.link_click_callback(raw_url)

    def render_page(self):
        # Enable/Disable forward/back buttons according to history
        self.back_btn.config(
            state="normal" if self.model.history.can_go_back() else "disabled"
        )
        self.forward_btn.config(
            state="normal" if self.model.history.can_go_forward() else "disabled"
        )

        # Update url in address bar
        current_url = self.model.history.get_current_url()
        if current_url is not None:
            self.address_bar.delete(0, "end")
            self.address_bar.insert(0, current_url.without_protocol())

        self.render_viewport()

    def render_viewport(self):
        self.text.delete("1.0", "end")
        if self.model.mime_type.startswith("text/gemini"):
            for node in self.model.gemini_nodes:
                render_node(node, self.text)
            # delete final trailing newline:
            self.text.delete("insert-1c", "insert")
        elif self.model.mime_type.startswith("text/"):
            self.text.insert("end", self.model.plaintext, ("plaintext",))
        else:
            self.text.insert(
                "end", f"Unsupported MIME type: {self.model.mime_type}", ("plaintext",)
            )


def render_node(node: GeminiNode, widget: Text):
    nodetype = type(node)
    if nodetype is TextNode:
        widget.insert("end", node.text)
    elif nodetype is LinkNode:
        widget.insert("end", "=> ")
        widget.insert("end", node.url, ("link",))
        if node.name:
            widget.insert("end", f" {node.name}")
    elif nodetype is PreformattedNode:
        widget.insert("end", f"```{node.alt}\n{node.text}\n```", ("pre",))
    elif nodetype is ListItemNode:
        widget.insert("end", node.text, ("listitem",))
    elif nodetype is H1Node:
        widget.insert("end", node.text, ("h1",))
    elif nodetype is H2Node:
        widget.insert("end", node.text, ("h2",))
    elif nodetype is H3Node:
        widget.insert("end", node.text, ("h3",))
    else:
        widget.insert("end", node.text)

    widget.insert("end", "\n")


def get_content_from_tag_click_event(event):
    # get the index of the mouse click
    index = event.widget.index("@%s,%s" % (event.x, event.y))

    # get the indices of all "link" tags
    tag_indices = list(event.widget.tag_ranges("link"))

    # iterate them pairwise (start and end index)
    for start, end in zip(tag_indices[0::2], tag_indices[1::2]):
        # check if the tag matches the mouse click index
        if event.widget.compare(start, "<=", index) and event.widget.compare(
            index, "<", end
        ):
            # return string between tag start and end
            return event.widget.get(start, end)