commit 3a797aee88896c4f71a062c9281801f25821246e
parent 9e455cf38f2450f37387068feb8f9f1e83d76711
Author: Jake Bauer <jbauer@paritybit.ca>
Date: Tue, 14 Feb 2023 19:42:29 -0500
Implement chapter 2
Diffstat:
M | browser.py | | | 65 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------- |
1 file changed, 57 insertions(+), 8 deletions(-)
diff --git a/browser.py b/browser.py
@@ -1,6 +1,57 @@
+import tkinter
import socket
import ssl
+WIDTH, HEIGHT = 800, 600
+HSTEP, VSTEP = 13, 18
+SCROLLSTEP = 100
+
+class Browser:
+ def __init__(self):
+ self.scroll = 0
+ self.window = tkinter.Tk()
+ self.canvas = tkinter.Canvas(
+ self.window,
+ width=WIDTH,
+ height=HEIGHT
+ )
+ self.canvas.pack()
+ self.window.bind("<Down>", self.scrolldown)
+
+
+ def scrolldown(self, e):
+ self.canvas.delete("all")
+ self.scroll += SCROLLSTEP
+ self.draw()
+
+
+ def load(self, url):
+ headers, body = request(url)
+ text = lex(body)
+ self.display_list = layout(text)
+ self.draw()
+
+
+ def draw(self):
+ for x, y, c in self.display_list:
+ if y > self.scroll + HEIGHT: continue
+ if y + VSTEP < self.scroll: continue
+ self.canvas.create_text(x, y - self.scroll, text=c)
+
+
+def layout(text):
+ display_list = []
+ cursor_x, cursor_y = HSTEP, VSTEP
+ for c in text:
+ display_list.append((cursor_x, cursor_y, c))
+ if cursor_x >= WIDTH - HSTEP:
+ cursor_y += VSTEP
+ cursor_x = HSTEP
+ else:
+ cursor_x += HSTEP
+ return display_list;
+
+
def request(url):
scheme,url = url.split("://", 1)
assert scheme in ["http", "https"], \
@@ -51,7 +102,8 @@ def request(url):
return headers, body
-def show(body):
+def lex(body):
+ text = ""
in_angle = False
for c in body:
if c == "<":
@@ -59,14 +111,11 @@ def show(body):
elif c == ">":
in_angle = False
elif not in_angle:
- print(c, end="")
-
-
-def load(url):
- headers, body = request(url)
- show(body)
+ text += c
+ return text
if __name__ == "__main__":
import sys
- load(sys.argv[1])
+ Browser().load(sys.argv[1])
+ tkinter.mainloop()