browser: allow browsing local directories

This commit is contained in:
dece 2021-06-03 17:14:32 +02:00
parent c65c385a20
commit 5b1a544761
2 changed files with 25 additions and 8 deletions

View file

@ -1,7 +1,5 @@
TODO TODO
---------------------------------------- ----------------------------------------
opt. maintain history between sessions
directory view for file scheme
search in page (ugh) search in page (ugh)
@ -59,3 +57,4 @@ home page
different rendering mode different rendering mode
preferences per site preferences per site
basic mouse support basic mouse support
basic local browsing

View file

@ -1,5 +1,8 @@
"""Local files browser.""" """Local files browser."""
import logging
from pathlib import Path
from bebop.browser.browser import Browser from bebop.browser.browser import Browser
from bebop.page import Page from bebop.page import Page
@ -20,13 +23,28 @@ def open_file(browser: Browser, filepath: str, encoding="utf-8"):
Returns: Returns:
The loaded file URI on success, None otherwise (e.g. file not found). The loaded file URI on success, None otherwise (e.g. file not found).
""" """
try: path = Path(filepath)
with open(filepath, "rt", encoding=encoding) as f: if not path.exists():
text = f.read() logging.error(f"File {filepath} does not exist.")
except (OSError, ValueError) as exc:
browser.set_status_error(f"Failed to open file: {exc}")
return None return None
browser.load_page(Page.from_text(text))
if path.is_file():
try:
with open(filepath, "rt", encoding=encoding) as f:
text = f.read()
except (OSError, ValueError) as exc:
browser.set_status_error(f"Failed to open file: {exc}")
return None
browser.load_page(Page.from_text(text))
elif path.is_dir():
gemtext = filepath + "\n\n"
for entry in sorted(path.iterdir()):
name = entry.name
if entry.is_dir():
name += "/"
gemtext += f"=> {entry} {name}\n"
wrap_at = browser.config["text_width"]
browser.load_page(Page.from_gemtext(gemtext, wrap_at))
file_url = "file://" + filepath file_url = "file://" + filepath
browser.current_url = file_url browser.current_url = file_url
return file_url return file_url