fix: preserve exports on close and support themed PDF without export quotas

This commit is contained in:
2026-09-07 14:04:03 +08:00
parent 47c53b6f38
commit 9f097ea629
20 changed files with 485 additions and 123 deletions
+12 -12
View File
@@ -143,7 +143,7 @@ def _preprocess(expr: str) -> str:
return _insert_implicit_multiplication(expr.replace("^", "**"))
def _check_node(node: ast.AST, depth: int = 0, counter: list[int] | None = None) -> None:
def _check_node(node: ast.AST, depth: int = 0, counter: list[int] | None = None, unlimited: bool = False) -> None:
"""白名单校验:任何越界节点都抛 FUNCTION_PLOT_EXPRESSION_UNSAFE。
同时限制 AST 深度与节点总数,避免超长/超深表达式在递归校验或求值时触发
@@ -151,10 +151,10 @@ def _check_node(node: ast.AST, depth: int = 0, counter: list[int] | None = None)
"""
if counter is None:
counter = [0]
if depth > _MAX_AST_DEPTH:
if not unlimited and depth > _MAX_AST_DEPTH:
_unsafe(f"表达式嵌套过深(超过 {_MAX_AST_DEPTH} 层)")
counter[0] += 1
if counter[0] > _MAX_AST_NODES:
if not unlimited and counter[0] > _MAX_AST_NODES:
_unsafe(f"表达式过于复杂(节点数超过 {_MAX_AST_NODES}")
if isinstance(node, ast.Constant):
if isinstance(node.value, bool) or not isinstance(node.value, (int, float)):
@@ -167,13 +167,13 @@ def _check_node(node: ast.AST, depth: int = 0, counter: list[int] | None = None)
if isinstance(node, ast.BinOp):
if not isinstance(node.op, _ALLOWED_BINOPS):
_unsafe(f"不支持的运算符 {type(node.op).__name__}")
_check_node(node.left, depth + 1, counter)
_check_node(node.right, depth + 1, counter)
_check_node(node.left, depth + 1, counter, unlimited)
_check_node(node.right, depth + 1, counter, unlimited)
return
if isinstance(node, ast.UnaryOp):
if not isinstance(node.op, _ALLOWED_UNARY):
_unsafe(f"不支持的运算符 {type(node.op).__name__}")
_check_node(node.operand, depth + 1, counter)
_check_node(node.operand, depth + 1, counter, unlimited)
return
if isinstance(node, ast.Call):
if not isinstance(node.func, ast.Name) or node.func.id not in _FUNCTIONS:
@@ -184,12 +184,12 @@ def _check_node(node: ast.AST, depth: int = 0, counter: list[int] | None = None)
if len(node.args) != 1:
_unsafe(f"{node.func.id} 需要 1 个参数,实际 {len(node.args)}")
for arg in node.args:
_check_node(arg, depth + 1, counter)
_check_node(arg, depth + 1, counter, unlimited)
return
_unsafe(f"不支持的语法 {type(node).__name__}")
def parse_expression(expr: str) -> ast.Expression:
def parse_expression(expr: str, unlimited: bool = False) -> ast.Expression:
"""把数学表达式解析为已通过白名单校验的 AST(可直接交给 evaluate)。"""
preprocessed = _preprocess(expr)
try:
@@ -211,7 +211,7 @@ def parse_expression(expr: str) -> ast.Expression:
message="表达式嵌套过深,无法解析",
)
) from exc
_check_node(tree.body)
_check_node(tree.body, unlimited=unlimited)
return tree
@@ -279,7 +279,7 @@ def _parse_directive(line: str) -> tuple[str, str] | None:
return key, value.strip()
def parse_source(source: str) -> FunctionPlotParseResult:
def parse_source(source: str, unlimited: bool = False) -> FunctionPlotParseResult:
"""把 function-plot fenced block 源码解析为 FunctionPlot + 诊断。"""
diagnostics: list[PlotDiagnostic] = []
expressions: list[FunctionPlotExpression] = []
@@ -371,7 +371,7 @@ def parse_source(source: str) -> FunctionPlotParseResult:
continue
try:
tree = parse_expression(expr_text)
tree = parse_expression(expr_text, unlimited=unlimited)
except PlotParseError as exc:
exc.diagnostic.line = lineno
diagnostics.append(exc.diagnostic)
@@ -380,7 +380,7 @@ def parse_source(source: str) -> FunctionPlotParseResult:
total_nodes += _count_nodes(tree.body)
expressions.append(FunctionPlotExpression(expression=expr_text))
# 表达式数量超限:整块回退并提前终止,避免对海量表达式做采样求值
if len(expressions) > _MAX_EXPRESSIONS:
if not unlimited and len(expressions) > _MAX_EXPRESSIONS:
diagnostics.append(
PlotDiagnostic(
severity="error",
+2 -2
View File
@@ -339,7 +339,7 @@ def _sample_segments(
return clipped
def compute_geometry(plot: FunctionPlot) -> PlotGeometry:
def compute_geometry(plot: FunctionPlot, unlimited: bool = False) -> PlotGeometry:
"""解析并计算几何,供 SVG 与 reportlab 后端复用。"""
warnings: list[str] = []
xmin, xmax = plot.domain
@@ -351,7 +351,7 @@ def compute_geometry(plot: FunctionPlot) -> PlotGeometry:
fns: list[tuple[object, object]] = []
for expr in plot.expressions:
try:
tree = parse_expression(expr.expression)
tree = parse_expression(expr.expression, unlimited=unlimited)
except PlotParseError as exc:
warnings.append(f"表达式无法渲染,已跳过:{expr.expression}{exc.diagnostic.message}")
continue
+22 -13
View File
@@ -26,9 +26,12 @@ _TICK_FONT_SIZE = 10
_LABEL_FONT_SIZE = 12
def _build_drawing(geo: PlotGeometry) -> Drawing:
def _build_drawing(geo: PlotGeometry, palette=None) -> Drawing:
"""由共享几何构建矢量 Drawing(坐标翻转后仍沿用 SVG 的像素布局)。"""
drawing = Drawing(geo.width, geo.height)
grid_color = HexColor(palette['border']) if palette else _GRID_COLOR
axis_color = HexColor(palette['muted']) if palette else _AXIS_COLOR
label_color = HexColor(palette['text']) if palette else _LABEL_COLOR
# SVG y-down → reportlab y-up:翻转像素 y
def sx(x: float) -> float:
@@ -41,19 +44,19 @@ def _build_drawing(geo: PlotGeometry) -> Drawing:
if geo.grid:
for x in geo.xticks:
drawing.add(
Line(sx(x), sy(geo.ymin), sx(x), sy(geo.ymax), strokeColor=_GRID_COLOR, strokeWidth=0.5)
Line(sx(x), sy(geo.ymin), sx(x), sy(geo.ymax), strokeColor=grid_color, strokeWidth=0.5)
)
for y in geo.yticks:
drawing.add(
Line(sx(geo.xmin), sy(y), sx(geo.xmax), sy(y), strokeColor=_GRID_COLOR, strokeWidth=0.5)
Line(sx(geo.xmin), sy(y), sx(geo.xmax), sy(y), strokeColor=grid_color, strokeWidth=0.5)
)
# 坐标轴(过原点画在原点,否则贴边,与 SVG 一致)
drawing.add(
Line(sx(geo.xmin), sy(geo.x_axis_y), sx(geo.xmax), sy(geo.x_axis_y), strokeColor=_AXIS_COLOR, strokeWidth=0.7)
Line(sx(geo.xmin), sy(geo.x_axis_y), sx(geo.xmax), sy(geo.x_axis_y), strokeColor=axis_color, strokeWidth=0.7)
)
drawing.add(
Line(sx(geo.y_axis_x), sy(geo.ymin), sx(geo.y_axis_x), sy(geo.ymax), strokeColor=_AXIS_COLOR, strokeWidth=0.7)
Line(sx(geo.y_axis_x), sy(geo.ymin), sx(geo.y_axis_x), sy(geo.ymax), strokeColor=axis_color, strokeWidth=0.7)
)
# 刻度数字(x 轴下方、y 轴左侧)
@@ -61,14 +64,14 @@ def _build_drawing(geo: PlotGeometry) -> Drawing:
drawing.add(
String(
sx(x), sy(geo.x_axis_y) - 14, _fmt_num(x),
fontName=_FONT, fontSize=_TICK_FONT_SIZE, fillColor=_AXIS_COLOR, textAnchor="middle",
fontName=_FONT, fontSize=_TICK_FONT_SIZE, fillColor=axis_color, textAnchor="middle",
)
)
for y in geo.yticks:
drawing.add(
String(
sx(geo.y_axis_x) - 6, sy(y) - 3, _fmt_num(y),
fontName=_FONT, fontSize=_TICK_FONT_SIZE, fillColor=_AXIS_COLOR, textAnchor="end",
fontName=_FONT, fontSize=_TICK_FONT_SIZE, fillColor=axis_color, textAnchor="end",
)
)
@@ -83,7 +86,7 @@ def _build_drawing(geo: PlotGeometry) -> Drawing:
drawing.add(
String(
geo.width / 2, 10, geo.xlabel,
fontName=_FONT, fontSize=_LABEL_FONT_SIZE, fillColor=_LABEL_COLOR, textAnchor="middle",
fontName=_FONT, fontSize=_LABEL_FONT_SIZE, fillColor=label_color, textAnchor="middle",
)
)
if geo.ylabel:
@@ -95,7 +98,7 @@ def _build_drawing(geo: PlotGeometry) -> Drawing:
label.add(
String(
0, 0, geo.ylabel,
fontName=_FONT, fontSize=_LABEL_FONT_SIZE, fillColor=_LABEL_COLOR, textAnchor="middle",
fontName=_FONT, fontSize=_LABEL_FONT_SIZE, fillColor=label_color, textAnchor="middle",
)
)
label.translate(16, geo.height / 2)
@@ -105,19 +108,25 @@ def _build_drawing(geo: PlotGeometry) -> Drawing:
return drawing
def render_drawing(plot: FunctionPlot, width: float | None = None) -> Drawing:
def render_drawing(plot: FunctionPlot, width: float | None = None, palette=None, unlimited=False, max_height=None) -> Drawing:
"""把已解析的 FunctionPlot 渲染为 reportlab Drawing(可直接追加到 platypus story)。
``width`` 为目标输出宽度(点),用于把 640px 的几何缩放到页面内容宽;省略则按
原始尺寸输出。缩放只影响 PDF 渲染,不改动共享几何。
"""
geo = compute_geometry(plot)
drawing = _build_drawing(geo)
geo = compute_geometry(plot, unlimited=unlimited)
if palette:
from reportlab.lib.colors import HexColor as color
bg = color(palette['surface'])
if .2126*bg.red + .7152*bg.green + .0722*bg.blue < .5:
colors = ['#79c0ff','#ff9b9b','#7ee787','#d2a8ff','#f2cc60','#ffa657']
geo.colors = [value if plot.expressions[i].color else colors[i % len(colors)] for i,value in enumerate(geo.colors)]
drawing = _build_drawing(geo, palette)
legend_height = ((len(plot.expressions)+1)//2)*24
drawing.height += legend_height
for index, expression in enumerate(plot.expressions):
drawing.add(String(24+(index%2)*310,geo.height+legend_height-18-(index//2)*24,
expression.label or 'y = '+expression.expression,fontName=_FONT,fontSize=12,fillColor=HexColor(geo.colors[index])))
if width is not None and width > 0:
drawing.renderScale = min(1.0, width / geo.width)
drawing.renderScale = min(1.0, width / geo.width, max_height / drawing.height if max_height else 1.0)
return drawing