Repository navigation
Expand file tree
/
Copy pathcell_discovery.py
More file actions
118 lines (93 loc) · 4.25 KB
/
Copy pathcell_discovery.py
File metadata and controls
118 lines (93 loc) · 4.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2026 KeithCu
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Discover ``=PY()`` / ``=PYTHON()`` formula cells on a Calc sheet.
Used by the LibrePy Python sidebar (cell list + click-to-navigate). Handles short
formulas, WriterAgent / LibrePy fully qualified add-in forms, and Collabora
``GETPY`` OriginalNames (prefix-rewritten for parse; open-rewrite evaluates them).
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from plugin.calc.address_utils import format_address, qualify_a1
from plugin.calc.calc_utils import CELL_FLAG_FORMULA
from plugin.calc.python.formula_edit import py_formula_or_none
from plugin.calc.python.formula_locator_cache import iter_range_formula_texts
from plugin.framework.errors import best_effort
MAX_PYTHON_CELLS_FOUND = 100
_MAX_CELLS_TO_SCAN = 50000
@dataclass(frozen=True)
class PythonCellInfo:
"""One discovered Python formula cell."""
sheet: str
row: int # 0-based
column: int # 0-based
address: str # e.g. "Sheet1.A1"
code: str
formula: str
@dataclass(frozen=True)
class PythonSheetDiscovery:
"""Row-major PY cells on one sheet, plus whether the scan stopped early.
``truncated`` is True only when the 100-cell find cap or the 50k
scan cap stopped discovery before the sheet was fully scanned — a
completed scan of exactly 100 is ``truncated=False``.
"""
cells: list[PythonCellInfo]
truncated: bool
def sheet_name_of(sheet: Any) -> str:
"""Sheet name, or "" when the read fails or the sheet's document has closed.
Never invents a default name: ``ScTableSheetObj::getName`` returns ``""``
when ``GetDocShell()`` is null after ``SfxHintId::Dying``
(``sc/source/ui/unoobj/cellsuno.cxx``, ``ScCellRangesBase::Notify``).
Callers skip a nameless sheet, because filing its cells under an invented
``"Sheet"`` would mix them with a real sheet of that name.
"""
if sheet is None:
return ""
return best_effort(lambda: sheet.getName(), "sheet name read failed", "")
def is_py_formula_text(formula: str) -> bool:
"""True when *formula* is PY/PYTHON, including fully qualified add-in form."""
return py_formula_or_none(formula) is not None
def discover_python_cells_on_sheet(sheet: Any) -> PythonSheetDiscovery:
"""Discover PY cells and report whether the 100 / 50k caps truncated the list.
After 100 PY cells we keep scanning for one more. Finding #101 (or hitting
the 50k scan cap) sets ``truncated=True``. An exact 100 that finishes the
formula-cell walk is complete.
"""
name = sheet_name_of(sheet)
if not name:
return PythonSheetDiscovery([], False)
found: list[PythonCellInfo] = []
truncated = False
formula_cells = sheet.queryContentCells(CELL_FLAG_FORMULA)
if formula_cells is None:
return PythonSheetDiscovery([], False)
def _formulas():
for i in range(int(formula_cells.getCount())):
yield from iter_range_formula_texts(sheet, formula_cells.getByIndex(i))
for scanned, (row, col, formula) in enumerate(_formulas()):
if scanned >= _MAX_CELLS_TO_SCAN:
truncated = True
break
parsed = py_formula_or_none(formula)
if parsed is None:
continue
if len(found) >= MAX_PYTHON_CELLS_FOUND:
# 101st PY cell: the returned list of 100 is incomplete.
truncated = True
break
# qualify_a1 quotes the sheet prefix when the name needs it (Data.2024, names with spaces)
# so downstream address parsing and navigation read the right sheet.
found.append(PythonCellInfo(sheet=name, row=row, column=col, address=qualify_a1(name, format_address(col, row)), code=parsed.code, formula=formula))
found.sort(key=lambda c: (c.row, c.column))
return PythonSheetDiscovery(found, truncated)
def list_python_cells_in_doc(doc: Any) -> list[PythonCellInfo]:
"""Enumerate Python cells on the active sheet of *doc*."""
if doc is None:
return []
controller = doc.getCurrentController()
sheet = controller.getActiveSheet() if controller is not None else None
if sheet is None:
return []
return discover_python_cells_on_sheet(sheet).cells