sheetmap 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sheetmap/__init__.py +9 -0
- sheetmap/__main__.py +5 -0
- sheetmap/addressing.py +57 -0
- sheetmap/cli.py +88 -0
- sheetmap/draw.py +417 -0
- sheetmap/errors.py +2 -0
- sheetmap/layout.py +247 -0
- sheetmap/model.py +246 -0
- sheetmap/page.py +268 -0
- sheetmap/py.typed +0 -0
- sheetmap/render.py +193 -0
- sheetmap-0.1.0.dist-info/METADATA +255 -0
- sheetmap-0.1.0.dist-info/RECORD +15 -0
- sheetmap-0.1.0.dist-info/WHEEL +4 -0
- sheetmap-0.1.0.dist-info/entry_points.txt +2 -0
sheetmap/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Draw labelled cell ranges over Excel worksheets as PNGs and a standalone review page."""
|
|
2
|
+
|
|
3
|
+
from sheetmap.errors import SheetmapError
|
|
4
|
+
from sheetmap.layout import Layout
|
|
5
|
+
from sheetmap.model import MapFile, Preview, Region, SheetMap, load_map_file
|
|
6
|
+
from sheetmap.render import check, render
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
__all__ = ["Layout", "MapFile", "Preview", "Region", "SheetMap", "SheetmapError", "check", "load_map_file", "render"]
|
sheetmap/__main__.py
ADDED
sheetmap/addressing.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Parse A1-style cell and range references."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from openpyxl.utils import column_index_from_string, get_column_letter
|
|
7
|
+
|
|
8
|
+
from sheetmap.errors import SheetmapError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
_CELL = re.compile(r"^\$?([A-Za-z]{1,3})\$?([1-9]\d*)$")
|
|
12
|
+
_COLUMN = re.compile(r"^\$?([A-Za-z]{1,3})$")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Reference:
|
|
17
|
+
"""A cell or rectangular range. ``last_row`` is ``None`` for an open-ended range such as ``B4:F``."""
|
|
18
|
+
|
|
19
|
+
sheet: str | None
|
|
20
|
+
first_col: int
|
|
21
|
+
first_row: int
|
|
22
|
+
last_col: int
|
|
23
|
+
last_row: int | None
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def is_cell(self) -> bool:
|
|
27
|
+
return (self.first_col, self.first_row) == (self.last_col, self.last_row)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_reference(ref: str) -> Reference:
|
|
31
|
+
"""Parse ``A1``, ``B2:D9``, ``B4:F`` or any of them prefixed with ``Sheet!`` or ``'Sheet name'!``."""
|
|
32
|
+
sheet, _, part = ref.strip().rpartition("!")
|
|
33
|
+
if sheet.startswith("'") and sheet.endswith("'") and len(sheet) > 1:
|
|
34
|
+
sheet = sheet[1:-1].replace("''", "'")
|
|
35
|
+
start, separator, end = part.partition(":")
|
|
36
|
+
first = _CELL.match(start)
|
|
37
|
+
if not first:
|
|
38
|
+
raise SheetmapError(f"Invalid cell reference in {ref!r}")
|
|
39
|
+
first_col, first_row = column_index_from_string(first[1].upper()), int(first[2])
|
|
40
|
+
if not separator:
|
|
41
|
+
return Reference(sheet or None, first_col, first_row, first_col, first_row)
|
|
42
|
+
if last := _CELL.match(end):
|
|
43
|
+
last_col, last_row = column_index_from_string(last[1].upper()), int(last[2])
|
|
44
|
+
elif last := _COLUMN.match(end):
|
|
45
|
+
last_col, last_row = column_index_from_string(last[1].upper()), None
|
|
46
|
+
else:
|
|
47
|
+
raise SheetmapError(f"Invalid range end in {ref!r}")
|
|
48
|
+
if last_col < first_col or (last_row is not None and last_row < first_row):
|
|
49
|
+
raise SheetmapError(f"Range {ref!r} must run from its top-left cell to its bottom-right cell")
|
|
50
|
+
return Reference(sheet or None, first_col, first_row, last_col, last_row)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def area_text(first_col: int, first_row: int, last_col: int, last_row: int) -> str:
|
|
54
|
+
start = f"{get_column_letter(first_col)}{first_row}"
|
|
55
|
+
if (first_col, first_row) == (last_col, last_row):
|
|
56
|
+
return start
|
|
57
|
+
return f"{start}:{get_column_letter(last_col)}{last_row}"
|
sheetmap/cli.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Draw labelled cell ranges over Excel worksheets as PNGs and a standalone HTML page."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
from dataclasses import replace
|
|
5
|
+
from importlib.metadata import version
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from sheetmap.errors import SheetmapError
|
|
10
|
+
from sheetmap.layout import DIMENSIONS, SECTION_CHOICES, Layout
|
|
11
|
+
from sheetmap.model import MapFile, load_map_file
|
|
12
|
+
from sheetmap.render import check, render
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _load(paths: list[Path]) -> MapFile:
|
|
16
|
+
"""Combine map files; page settings come from the first file that sets each one."""
|
|
17
|
+
files = [load_map_file(path) for path in paths]
|
|
18
|
+
return MapFile(
|
|
19
|
+
title=next((file.title for file in files if file.title), None),
|
|
20
|
+
maps=[sheet_map for file in files for sheet_map in file.maps],
|
|
21
|
+
layout=next((file.layout for file in files if file.layout), None),
|
|
22
|
+
review=next((file.review for file in files if file.review is not None), None),
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def check_main(arguments: list[str]) -> None:
|
|
27
|
+
parser = argparse.ArgumentParser(
|
|
28
|
+
prog="sheetmap check", description="Check map files against their workbooks without writing anything."
|
|
29
|
+
)
|
|
30
|
+
parser.add_argument("maps", nargs="+", type=Path, metavar="MAP")
|
|
31
|
+
args = parser.parse_args(arguments)
|
|
32
|
+
try:
|
|
33
|
+
summary = check(_load(args.maps).maps)
|
|
34
|
+
except (SheetmapError, OSError) as error:
|
|
35
|
+
parser.exit(1, f"Check failed: {error}\n")
|
|
36
|
+
print(f"OK: {summary['maps']} maps, {summary['sheets']} sheets, {summary['regions']} regions")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def main(arguments: list[str] | None = None) -> None:
|
|
40
|
+
arguments = sys.argv[1:] if arguments is None else arguments
|
|
41
|
+
if arguments[:1] == ["check"]:
|
|
42
|
+
check_main(arguments[1:])
|
|
43
|
+
return
|
|
44
|
+
parser = argparse.ArgumentParser(
|
|
45
|
+
prog="sheetmap",
|
|
46
|
+
description=__doc__,
|
|
47
|
+
epilog="Also: `sheetmap check MAP...` checks map files without writing anything.",
|
|
48
|
+
)
|
|
49
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {version('sheetmap')}")
|
|
50
|
+
parser.add_argument("maps", nargs="+", type=Path, metavar="MAP", help="YAML map file; repeat to combine")
|
|
51
|
+
parser.add_argument(
|
|
52
|
+
"-o", "--output", type=Path, help="HTML output file; defaults to the map's name with .html (one map file only)"
|
|
53
|
+
)
|
|
54
|
+
parser.add_argument("--title", help="page title; defaults to the map file's title")
|
|
55
|
+
layout = parser.add_argument_group("layout", "override the map file's layout; see the README")
|
|
56
|
+
layout.add_argument("--sections", choices=SECTION_CHOICES, help="what each section of the page holds")
|
|
57
|
+
layout.add_argument("--rows", choices=DIMENSIONS, help="what each row of a section holds")
|
|
58
|
+
layout.add_argument("--columns", choices=DIMENSIONS, help="what each column holds, lined up down the page")
|
|
59
|
+
layout.add_argument("--wrap", type=int, metavar="N", help="flow images into N columns")
|
|
60
|
+
layout.add_argument(
|
|
61
|
+
"--fit", action=argparse.BooleanOptionalAction, help="scale images in grids to their column (default: off)"
|
|
62
|
+
)
|
|
63
|
+
parser.add_argument(
|
|
64
|
+
"--review",
|
|
65
|
+
action=argparse.BooleanOptionalAction,
|
|
66
|
+
help="add clickable labels for requesting changes, and a copyable summary (default: off)",
|
|
67
|
+
)
|
|
68
|
+
args = parser.parse_args(arguments)
|
|
69
|
+
if args.output is None and len(args.maps) > 1:
|
|
70
|
+
parser.error("give --output when combining map files")
|
|
71
|
+
output = args.output or args.maps[0].with_suffix(".html")
|
|
72
|
+
try:
|
|
73
|
+
loaded = _load(args.maps)
|
|
74
|
+
review = args.review if args.review is not None else bool(loaded.review)
|
|
75
|
+
overrides = {
|
|
76
|
+
name: getattr(args, name)
|
|
77
|
+
for name in ("sections", "rows", "columns", "wrap", "fit")
|
|
78
|
+
if getattr(args, name) is not None
|
|
79
|
+
}
|
|
80
|
+
if {"rows", "columns", "wrap"} & set(overrides):
|
|
81
|
+
# Naming an arrangement on the command line replaces the file's arrangement, not just one axis.
|
|
82
|
+
base = replace(loaded.layout or Layout(), rows=None, columns=None, wrap=None, cells=None)
|
|
83
|
+
else:
|
|
84
|
+
base = loaded.layout or Layout()
|
|
85
|
+
page_layout = replace(base, **overrides)
|
|
86
|
+
print(render(loaded.maps, output, title=args.title or loaded.title, layout=page_layout, review=review))
|
|
87
|
+
except (SheetmapError, OSError) as error:
|
|
88
|
+
parser.exit(1, f"Map failed: {error}\n")
|
sheetmap/draw.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
"""Place regions on a workbook, lay out a worksheet image and draw it."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import date, datetime
|
|
5
|
+
|
|
6
|
+
from openpyxl.cell.cell import MergedCell
|
|
7
|
+
from openpyxl.utils import get_column_letter
|
|
8
|
+
from openpyxl.workbook import Workbook
|
|
9
|
+
from openpyxl.worksheet.worksheet import Worksheet
|
|
10
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
11
|
+
|
|
12
|
+
from sheetmap.addressing import parse_reference
|
|
13
|
+
from sheetmap.errors import SheetmapError
|
|
14
|
+
from sheetmap.model import Preview, Region, SheetMap
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
COLOURS = {"cell": "#b45309", "range": "#7c3aed", "list": "#0f766e", "table": "#2563eb"}
|
|
18
|
+
ROW_HEADER_WIDTH = 46.0
|
|
19
|
+
COLUMN_BAR = 24.0
|
|
20
|
+
TAG_HEIGHT = 21
|
|
21
|
+
LINE_HEIGHT = 14
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class AxisLabel:
|
|
26
|
+
"""A label above a table column (or column group), or beside a row of a table that reads across."""
|
|
27
|
+
|
|
28
|
+
row: int
|
|
29
|
+
first_col: int
|
|
30
|
+
last_col: int
|
|
31
|
+
text: str
|
|
32
|
+
lines: list[str] = field(default_factory=list)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Placed:
|
|
37
|
+
region: Region
|
|
38
|
+
kind: str
|
|
39
|
+
colour: str
|
|
40
|
+
sheet: str
|
|
41
|
+
area: tuple[int, int, int, int]
|
|
42
|
+
axis_labels: list[AxisLabel]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Tag:
|
|
47
|
+
left: float
|
|
48
|
+
top: float
|
|
49
|
+
right: float
|
|
50
|
+
placed: Placed
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class SheetImage:
|
|
55
|
+
image: Image.Image
|
|
56
|
+
tags: list[Tag]
|
|
57
|
+
values_drawn: int
|
|
58
|
+
truncated: bool
|
|
59
|
+
rows: int
|
|
60
|
+
cols: int
|
|
61
|
+
rows_cut: bool
|
|
62
|
+
cols_cut: bool
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class Fonts:
|
|
67
|
+
regular: ImageFont.ImageFont
|
|
68
|
+
bold: ImageFont.ImageFont
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def load_fonts() -> Fonts:
|
|
72
|
+
return Fonts(_font(11), _font(11, bold=True))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _font(size: int, bold: bool = False):
|
|
76
|
+
if bold:
|
|
77
|
+
names = ("DejaVuSans-Bold.ttf", "arialbd.ttf", "Arial Bold.ttf")
|
|
78
|
+
else:
|
|
79
|
+
names = ("DejaVuSans.ttf", "arial.ttf", "Arial.ttf")
|
|
80
|
+
for name in names:
|
|
81
|
+
try:
|
|
82
|
+
return ImageFont.truetype(name, size)
|
|
83
|
+
except OSError:
|
|
84
|
+
continue
|
|
85
|
+
return ImageFont.load_default(size=size)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def populated_cells(sheet: Worksheet):
|
|
89
|
+
# Styled-only dimensions can extend to XFD, so context comes from cells with values.
|
|
90
|
+
return [cell for cell in sheet._cells.values() if cell.value is not None]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def place(book: Workbook, sheet_map: SheetMap) -> dict[str, list[Placed]]:
|
|
94
|
+
"""Resolve each region to an area of its sheet, grouped by sheet in workbook order."""
|
|
95
|
+
groups: dict[str, list[Placed]] = {sheet.title: [] for sheet in book.worksheets}
|
|
96
|
+
for region in sheet_map.regions:
|
|
97
|
+
reference = parse_reference(region.ref)
|
|
98
|
+
sheet_name = reference.sheet or book.worksheets[0].title
|
|
99
|
+
if sheet_name not in groups:
|
|
100
|
+
raise SheetmapError(f"Sheet {sheet_name!r} for {region.label!r} is not in {sheet_map.workbook}")
|
|
101
|
+
sheet = book[sheet_name]
|
|
102
|
+
kind = region.resolved_kind
|
|
103
|
+
if kind == "cell":
|
|
104
|
+
area = (reference.first_col, reference.first_row, reference.first_col, reference.first_row)
|
|
105
|
+
# A label for one cell of a merged block covers the whole block.
|
|
106
|
+
for merge in sheet.merged_cells.ranges:
|
|
107
|
+
if merge.min_col <= area[0] <= merge.max_col and merge.min_row <= area[1] <= merge.max_row:
|
|
108
|
+
area = (merge.min_col, merge.min_row, merge.max_col, merge.max_row)
|
|
109
|
+
break
|
|
110
|
+
else:
|
|
111
|
+
last_row = reference.last_row
|
|
112
|
+
if last_row is None:
|
|
113
|
+
last_row = max(
|
|
114
|
+
(
|
|
115
|
+
cell.row
|
|
116
|
+
for cell in populated_cells(sheet)
|
|
117
|
+
if reference.first_col <= cell.column <= reference.last_col
|
|
118
|
+
),
|
|
119
|
+
default=reference.first_row,
|
|
120
|
+
)
|
|
121
|
+
last_row = max(last_row, reference.first_row)
|
|
122
|
+
area = (reference.first_col, reference.first_row, reference.last_col, last_row)
|
|
123
|
+
placed = Placed(region, kind, region.colour or COLOURS[kind], sheet_name, area, [])
|
|
124
|
+
placed.axis_labels = _axis_labels(sheet, placed)
|
|
125
|
+
groups[sheet_name].append(placed)
|
|
126
|
+
return {name: regions for name, regions in groups.items() if regions}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _axis_labels(sheet: Worksheet, placed: Placed) -> list[AxisLabel]:
|
|
130
|
+
first_col, first_row, last_col, last_row = placed.area
|
|
131
|
+
name = placed.region.label
|
|
132
|
+
if placed.region.rows:
|
|
133
|
+
labels = {str(key): value for key, value in placed.region.rows.items()}
|
|
134
|
+
outside = set(labels) - {str(row) for row in range(first_row, last_row + 1)}
|
|
135
|
+
if outside:
|
|
136
|
+
raise SheetmapError(f"Rows {', '.join(sorted(outside))} are outside {name} ({placed.region.ref})")
|
|
137
|
+
result = []
|
|
138
|
+
for row in range(first_row, last_row + 1):
|
|
139
|
+
if str(row) in labels:
|
|
140
|
+
result.append(AxisLabel(row, first_col, first_col, f"{row}: {labels[str(row)]}"))
|
|
141
|
+
elif any(sheet.cell(row, col).value is not None for col in range(first_col + 1, last_col + 1)):
|
|
142
|
+
raise SheetmapError(f"Row {row} of {name} has values but no label")
|
|
143
|
+
return result
|
|
144
|
+
if not placed.region.columns:
|
|
145
|
+
return []
|
|
146
|
+
labels = {key.upper(): value for key, value in placed.region.columns.items()}
|
|
147
|
+
outside = set(labels) - {get_column_letter(col) for col in range(first_col, last_col + 1)}
|
|
148
|
+
if outside:
|
|
149
|
+
raise SheetmapError(f"Columns {', '.join(sorted(outside))} are outside {name} ({placed.region.ref})")
|
|
150
|
+
groups: list[list] = []
|
|
151
|
+
for col in range(first_col, last_col + 1):
|
|
152
|
+
letter = get_column_letter(col)
|
|
153
|
+
if letter in labels:
|
|
154
|
+
groups.append([col, col, labels[letter]])
|
|
155
|
+
elif any(sheet.cell(row, col).value is not None for row in range(first_row, last_row + 1)):
|
|
156
|
+
raise SheetmapError(f"Column {letter} of {name} has values but no label")
|
|
157
|
+
elif groups:
|
|
158
|
+
groups[-1][1] = col
|
|
159
|
+
result = []
|
|
160
|
+
for start, end, label in groups:
|
|
161
|
+
axis = get_column_letter(start) + (":" + get_column_letter(end) if end != start else "")
|
|
162
|
+
result.append(AxisLabel(first_row, start, end, f"{axis}: {label}"))
|
|
163
|
+
return result
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@dataclass
|
|
167
|
+
class _Layout:
|
|
168
|
+
rows: int
|
|
169
|
+
cols: int
|
|
170
|
+
x: list[float]
|
|
171
|
+
tops: dict[int, float]
|
|
172
|
+
bottoms: dict[int, float]
|
|
173
|
+
tag_tops: dict[int, float]
|
|
174
|
+
axis_tops: dict[int, float]
|
|
175
|
+
axis_heights: dict[int, float]
|
|
176
|
+
lanes: dict[int, list[list[tuple[float, float, Placed]]]]
|
|
177
|
+
width: int
|
|
178
|
+
height: int
|
|
179
|
+
rows_cut: bool
|
|
180
|
+
cols_cut: bool
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _layout(sheet: Worksheet, regions: list[Placed], preview: Preview | None, fonts: Fonts) -> _Layout:
|
|
184
|
+
populated = populated_cells(sheet)
|
|
185
|
+
source_rows = max((cell.row for cell in populated), default=1)
|
|
186
|
+
source_cols = max((cell.column for cell in populated), default=1)
|
|
187
|
+
if preview:
|
|
188
|
+
# Show the start of every region; regions running past the preview are cut off at its edge.
|
|
189
|
+
rows = max(max(p.area[1] for p in regions) + 2, min(source_rows, preview.rows))
|
|
190
|
+
else:
|
|
191
|
+
rows = max(max(p.area[3] for p in regions) + 2, source_rows)
|
|
192
|
+
cols = max(max(p.area[2] for p in regions) + 1, min(source_cols, preview.columns) if preview else source_cols)
|
|
193
|
+
rows_cut, cols_cut = bool(preview) and source_rows > rows, bool(preview) and source_cols > cols
|
|
194
|
+
|
|
195
|
+
x = [ROW_HEADER_WIDTH]
|
|
196
|
+
for col in range(1, cols + 1):
|
|
197
|
+
dimension = sheet.column_dimensions.get(get_column_letter(col))
|
|
198
|
+
source_width = dimension.width if dimension and dimension.width else 12
|
|
199
|
+
x.append(x[-1] + max(44, min(210, source_width * 7)))
|
|
200
|
+
|
|
201
|
+
measure = ImageDraw.Draw(Image.new("RGB", (1, 1)))
|
|
202
|
+
# Tags for regions starting on the same row stack into lanes so they never overlap.
|
|
203
|
+
lanes: dict[int, list[list[tuple[float, float, Placed]]]] = {}
|
|
204
|
+
for placed in regions:
|
|
205
|
+
first_col, first_row = placed.area[:2]
|
|
206
|
+
left = x[first_col - 1]
|
|
207
|
+
right = left + measure.textlength(placed.region.label, font=fonts.bold) + 12
|
|
208
|
+
row_lanes = lanes.setdefault(first_row, [])
|
|
209
|
+
for lane in row_lanes:
|
|
210
|
+
if all(right + 6 < start or left > end + 6 for start, end, _ in lane):
|
|
211
|
+
lane.append((left, right, placed))
|
|
212
|
+
break
|
|
213
|
+
else:
|
|
214
|
+
row_lanes.append([(left, right, placed)])
|
|
215
|
+
|
|
216
|
+
axis_heights: dict[int, float] = {}
|
|
217
|
+
for placed in regions:
|
|
218
|
+
for label in placed.axis_labels:
|
|
219
|
+
if label.row > rows:
|
|
220
|
+
continue
|
|
221
|
+
label.lines = _wrap(label.text, x[label.last_col] - x[label.first_col - 1] - 8, measure, fonts.regular)
|
|
222
|
+
axis_heights[label.row] = max(axis_heights.get(label.row, 0), len(label.lines) * LINE_HEIGHT + 10)
|
|
223
|
+
|
|
224
|
+
tops, bottoms, tag_tops, axis_tops = {}, {}, {}, {}
|
|
225
|
+
cursor = COLUMN_BAR
|
|
226
|
+
for row in range(1, rows + 1):
|
|
227
|
+
tag_tops[row] = cursor
|
|
228
|
+
cursor += len(lanes.get(row, [])) * TAG_HEIGHT + (5 if row in lanes else 0)
|
|
229
|
+
axis_tops[row] = cursor
|
|
230
|
+
cursor += axis_heights.get(row, 0)
|
|
231
|
+
tops[row] = cursor
|
|
232
|
+
cursor += max(24, min(72, (sheet.row_dimensions[row].height or 18) * 1.3))
|
|
233
|
+
bottoms[row] = cursor
|
|
234
|
+
widest_tag = max(end for row_lanes in lanes.values() for lane in row_lanes for _, end, _ in lane)
|
|
235
|
+
width = int(max(x[-1] + 1, widest_tag + 4))
|
|
236
|
+
return _Layout(
|
|
237
|
+
rows,
|
|
238
|
+
cols,
|
|
239
|
+
x,
|
|
240
|
+
tops,
|
|
241
|
+
bottoms,
|
|
242
|
+
tag_tops,
|
|
243
|
+
axis_tops,
|
|
244
|
+
axis_heights,
|
|
245
|
+
lanes,
|
|
246
|
+
width,
|
|
247
|
+
int(cursor + 1),
|
|
248
|
+
rows_cut,
|
|
249
|
+
cols_cut,
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _wrap(text: str, available: float, measure: ImageDraw.ImageDraw, font) -> list[str]:
|
|
254
|
+
"""Break at the last underscore or space that fits, or mid-word when a word is too long."""
|
|
255
|
+
lines, line = [], ""
|
|
256
|
+
for character in text:
|
|
257
|
+
if line and measure.textlength(line + character, font=font) > available:
|
|
258
|
+
split = max(line.rfind("_"), line.rfind(" ")) + 1
|
|
259
|
+
lines.append(line[:split] if split else line)
|
|
260
|
+
line = line[split:] if split else ""
|
|
261
|
+
line += character
|
|
262
|
+
if line:
|
|
263
|
+
lines.append(line)
|
|
264
|
+
return lines
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def render_sheet(sheet: Worksheet, regions: list[Placed], sheet_map: SheetMap, fonts: Fonts) -> SheetImage:
|
|
268
|
+
layout = _layout(sheet, regions, sheet_map.preview.get(sheet.title), fonts)
|
|
269
|
+
x, tops, bottoms = layout.x, layout.tops, layout.bottoms
|
|
270
|
+
image = Image.new("RGB", (layout.width, layout.height), "white")
|
|
271
|
+
draw = ImageDraw.Draw(image, "RGBA")
|
|
272
|
+
|
|
273
|
+
# Titles and captions belong to the page, so the image holds only the sheet.
|
|
274
|
+
draw.rectangle((0, 0, x[-1], COLUMN_BAR - 1), fill="#f1f5f9")
|
|
275
|
+
for col in range(1, layout.cols + 1):
|
|
276
|
+
draw.text((x[col - 1] + 5, 5), get_column_letter(col), font=fonts.regular, fill="#64748b")
|
|
277
|
+
for row in range(1, layout.rows + 1):
|
|
278
|
+
draw.rectangle((0, tops[row], ROW_HEADER_WIDTH - 1, bottoms[row]), fill="#f8fafc")
|
|
279
|
+
draw.text((5, tops[row] + 5), str(row), font=fonts.regular, fill="#64748b")
|
|
280
|
+
for col in range(1, layout.cols + 1):
|
|
281
|
+
cell = sheet.cell(row, col)
|
|
282
|
+
box = (x[col - 1], tops[row], x[col], bottoms[row])
|
|
283
|
+
draw.rectangle(box, fill=fill_colour(cell), outline="#e2e8f0")
|
|
284
|
+
for side, coords in (
|
|
285
|
+
(cell.border.top, (box[0], box[1], box[2], box[1])),
|
|
286
|
+
(cell.border.bottom, (box[0], box[3], box[2], box[3])),
|
|
287
|
+
(cell.border.left, (box[0], box[1], box[0], box[3])),
|
|
288
|
+
(cell.border.right, (box[2], box[1], box[2], box[3])),
|
|
289
|
+
):
|
|
290
|
+
if side and side.style:
|
|
291
|
+
draw.line(coords, fill="#94a3b8", width=1)
|
|
292
|
+
|
|
293
|
+
merges = {}
|
|
294
|
+
for merge in sheet.merged_cells.ranges:
|
|
295
|
+
if merge.min_col <= layout.cols and merge.min_row <= layout.rows:
|
|
296
|
+
last_col, last_row = min(layout.cols, merge.max_col), min(layout.rows, merge.max_row)
|
|
297
|
+
box = (x[merge.min_col - 1], tops[merge.min_row], x[last_col], bottoms[last_row])
|
|
298
|
+
merges[(merge.min_row, merge.min_col)] = box
|
|
299
|
+
draw.rectangle(box, fill=fill_colour(sheet.cell(merge.min_row, merge.min_col)), outline="#cbd5e1")
|
|
300
|
+
|
|
301
|
+
for placed in regions:
|
|
302
|
+
first_col, first_row, last_col, last_row = placed.area
|
|
303
|
+
rgb = tuple(int(placed.colour[i : i + 2], 16) for i in (1, 3, 5))
|
|
304
|
+
draw.rectangle(
|
|
305
|
+
(x[first_col - 1], tops[first_row], x[last_col], bottoms[min(last_row, layout.rows)]),
|
|
306
|
+
fill=(*rgb, 16),
|
|
307
|
+
outline=placed.colour,
|
|
308
|
+
width=2,
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
values_drawn = 0
|
|
312
|
+
for row in range(1, layout.rows + 1):
|
|
313
|
+
for col in range(1, layout.cols + 1):
|
|
314
|
+
cell = sheet.cell(row, col)
|
|
315
|
+
if isinstance(cell, MergedCell):
|
|
316
|
+
continue
|
|
317
|
+
box = merges.get((row, col), (x[col - 1], tops[row], x[col], bottoms[row]))
|
|
318
|
+
values_drawn += draw_cell_text(image, box, cell, fonts)
|
|
319
|
+
|
|
320
|
+
for placed in regions:
|
|
321
|
+
for label in placed.axis_labels:
|
|
322
|
+
if label.row > layout.rows:
|
|
323
|
+
continue
|
|
324
|
+
top = layout.axis_tops[label.row]
|
|
325
|
+
left, right = x[label.first_col - 1], x[label.last_col]
|
|
326
|
+
draw.rectangle((left, top, right, top + layout.axis_heights[label.row]), fill="#eff6ff", outline="#93c5fd")
|
|
327
|
+
for index, line in enumerate(label.lines):
|
|
328
|
+
draw.text((left + 4, top + 5 + index * LINE_HEIGHT), line, font=fonts.regular, fill="#1d4ed8")
|
|
329
|
+
|
|
330
|
+
tags = []
|
|
331
|
+
for row, row_lanes in layout.lanes.items():
|
|
332
|
+
for lane_index, lane in enumerate(row_lanes):
|
|
333
|
+
top = layout.tag_tops[row] + lane_index * TAG_HEIGHT
|
|
334
|
+
for left, right, placed in lane:
|
|
335
|
+
# Tables with axis labels point at the labels; everything else points at its first cell.
|
|
336
|
+
target = layout.axis_tops[row] if placed.axis_labels and row in layout.axis_heights else tops[row]
|
|
337
|
+
draw.line((left + 4, top + 18, left + 4, target), fill=placed.colour, width=1)
|
|
338
|
+
draw.rectangle((left, top, right, top + 18), fill="white", outline=placed.colour, width=1)
|
|
339
|
+
draw.text((left + 6, top + 2), placed.region.label, font=fonts.bold, fill=placed.colour)
|
|
340
|
+
tags.append(Tag(left, top, right, placed))
|
|
341
|
+
return SheetImage(
|
|
342
|
+
image,
|
|
343
|
+
tags,
|
|
344
|
+
values_drawn,
|
|
345
|
+
layout.rows_cut or layout.cols_cut,
|
|
346
|
+
layout.rows,
|
|
347
|
+
layout.cols,
|
|
348
|
+
layout.rows_cut,
|
|
349
|
+
layout.cols_cut,
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def cell_text(cell) -> str:
|
|
354
|
+
value = cell.value
|
|
355
|
+
if value is None:
|
|
356
|
+
return ""
|
|
357
|
+
if isinstance(value, bool):
|
|
358
|
+
return "TRUE" if value else "FALSE"
|
|
359
|
+
if isinstance(value, datetime):
|
|
360
|
+
return value.strftime("%d/%m/%Y %H:%M" if value.time().isoformat() != "00:00:00" else "%d/%m/%Y")
|
|
361
|
+
if isinstance(value, date):
|
|
362
|
+
return value.strftime("%d/%m/%Y")
|
|
363
|
+
if isinstance(value, float):
|
|
364
|
+
return format(value, ".12g")
|
|
365
|
+
return str(value)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def fill_colour(cell) -> str:
|
|
369
|
+
if cell.fill.patternType == "solid" and cell.fill.fgColor.type == "rgb":
|
|
370
|
+
rgb = cell.fill.fgColor.rgb[-6:]
|
|
371
|
+
if rgb != "000000":
|
|
372
|
+
return "#" + rgb
|
|
373
|
+
return "#ffffff"
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def draw_cell_text(image: Image.Image, box, cell, fonts: Fonts) -> bool:
|
|
377
|
+
value = cell_text(cell)
|
|
378
|
+
if not value:
|
|
379
|
+
return False
|
|
380
|
+
left, top, right, bottom = map(int, box)
|
|
381
|
+
width, height = max(1, right - left - 8), max(1, bottom - top - 4)
|
|
382
|
+
layer = Image.new("RGBA", (width, height))
|
|
383
|
+
draw = ImageDraw.Draw(layer)
|
|
384
|
+
font = fonts.bold if cell.font.bold else fonts.regular
|
|
385
|
+
if cell.alignment.wrap_text:
|
|
386
|
+
lines = []
|
|
387
|
+
for paragraph in value.splitlines():
|
|
388
|
+
line = ""
|
|
389
|
+
for word in paragraph.split(" "):
|
|
390
|
+
candidate = (line + " " + word).strip()
|
|
391
|
+
if line and draw.textlength(candidate, font=font) > width:
|
|
392
|
+
lines.append(line)
|
|
393
|
+
line = word
|
|
394
|
+
else:
|
|
395
|
+
line = candidate
|
|
396
|
+
lines.append(line)
|
|
397
|
+
else:
|
|
398
|
+
lines = [value.replace("\n", " ")]
|
|
399
|
+
colour = "#172033"
|
|
400
|
+
if cell.font.color is not None and cell.font.color.type == "rgb":
|
|
401
|
+
colour = "#" + cell.font.color.rgb[-6:]
|
|
402
|
+
for index, line in enumerate(lines):
|
|
403
|
+
y = index * LINE_HEIGHT
|
|
404
|
+
if y >= height:
|
|
405
|
+
break
|
|
406
|
+
text_width = draw.textlength(line, font=font)
|
|
407
|
+
alignment = cell.alignment.horizontal
|
|
408
|
+
offset = (
|
|
409
|
+
max(0, (width - text_width) / 2)
|
|
410
|
+
if alignment == "center"
|
|
411
|
+
else max(0, width - text_width)
|
|
412
|
+
if alignment == "right"
|
|
413
|
+
else 0
|
|
414
|
+
)
|
|
415
|
+
draw.text((offset, y), line, font=font, fill=colour)
|
|
416
|
+
image.paste(layer, (left + 4, top + 3), layer)
|
|
417
|
+
return True
|
sheetmap/errors.py
ADDED