Toot-Mastodon-CLI-TUI-clien.../toot/ui/utils.py

60 lines
1.6 KiB
Python
Raw Normal View History

2018-01-21 15:45:07 +01:00
import re
2018-01-20 13:43:21 +01:00
from textwrap import wrap
2018-01-06 17:32:27 +01:00
def draw_horizontal_divider(window, y):
height, width = window.getmaxyx()
2018-01-13 13:03:45 +01:00
# Don't draw out of bounds
if y < height - 1:
line = '' + '' * (width - 2) + ''
window.addstr(y, 0, line)
2018-01-06 17:32:27 +01:00
2018-01-20 13:43:21 +01:00
def enumerate_lines(lines, text_width, default_color):
def parse_line(line):
if isinstance(line, tuple) and len(line) == 2:
return line[0], line[1]
elif isinstance(line, str):
return line, default_color
elif line is None:
return "", default_color
raise ValueError("Wrong yield in generator")
def wrap_lines(lines):
for line in lines:
line, color = parse_line(line)
if line:
for wrapped in wrap(line, text_width):
yield wrapped, color
else:
yield "", color
2018-01-06 17:32:27 +01:00
2018-01-20 13:43:21 +01:00
return enumerate(wrap_lines(lines))
2018-01-21 15:45:07 +01:00
HASHTAG_PATTERN = re.compile(r'(?<!\w)(#\w+)\b')
def highlight_hashtags(window, y, padding, line):
from toot.ui.app import Color
for match in re.finditer(HASHTAG_PATTERN, line):
start, end = match.span()
window.chgat(y, start + padding, end - start, Color.HASHTAG)
2018-01-20 13:43:21 +01:00
def draw_lines(window, lines, start_y, padding, default_color):
height, width = window.getmaxyx()
text_width = width - 2 * padding
2018-01-06 17:32:27 +01:00
2018-01-20 13:43:21 +01:00
for dy, (line, color) in enumerate_lines(lines, text_width, default_color):
y = start_y + dy
if y < height - 1:
window.addstr(y, padding, line.ljust(text_width), color)
2018-01-21 15:45:07 +01:00
highlight_hashtags(window, y, padding, line)
2018-01-06 17:32:27 +01:00
2018-01-20 13:43:21 +01:00
return y + 1