Coverage for ppedit/server.py: 93.4%

647 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-11-30 17:40 +0000

1"""Editor web server 

2 

3`create_app()` returns a Flask application that serves the browser editor 

4(`ppedit/static/`) and a JSON API over one in-memory `ppedit.Case`. 

5 

6API 

7--- 

8 

9All `POST` requests must send JSON and the header `X-PPEdit: 1`; browsers 

10will not send that header cross-origin without a CORS preflight, which the 

11server does not grant, so other web pages cannot change the case or write 

12files. Requests whose `Host` is not a loopback name are refused unless the 

13app was created with `allow_remote=True`. 

14 

15When the app is created with a `token` (`ppedit serve` always makes one), 

16every request must also carry it: as the `token` query parameter of the 

17URL (`http://localhost:8050/?token=...`, what `ppedit serve` prints and 

18opens) or as the session cookie the server sets in exchange for it 

19(`ppedit_<hash>`, `HttpOnly`, `SameSite=Strict`, named after a hash of the 

20token so servers on other ports keep their own cookies). A page `GET` 

21with the token in the URL is redirected to the same URL without it, so 

22the token does not stay in the address bar. Requests without a valid 

23token get status 403. 

24 

25Every successful call returns the editor state: `case` (see 

26`ppedit.Case.to_dict`), `path`, `format`, `dirty`, `issues`, `can_undo`, 

27`can_redo`, `result` (last solution or `null`), `cascade` (whether the 

28last edit changed cells other than the one edited), and `revision` (a 

29counter that changes whenever the case changes), `source` (how the 

30open case was read, see `ppedit.Case.source`, or `null`), and `loads_off` 

31(loads switched off by `POST /api/load`, as `[bus, Pd, Qd]`). Errors return 

32`{"error": message}` with status 400. 

33 

34 - `GET /api/meta`: columns, result columns (`ppedit.case.RESULT_COLUMNS`: 

35 the read-only extended columns a solution adds to the tables), tables, 

36 built-in case names, formats (written), 

37 input formats (read), table data formats (`table_formats`: file 

38 extensions `GET /api/table/export` and `GET /api/series/export` write; 

39 `table_read_formats`: those and the other pandas formats 

40 `POST /api/table/import` and `POST /api/series/import` read, see 

41 `ppedit._tableio`), 

42 `app_name` (the name the page shows, `ppedit._branding.APP_NAME`), 

43 solvers (`ppedit.case.solvers`: the PF algorithms, 

44 the installed OPF solvers and the cvxopf solve option choices), version, 

45 `about` (package metadata shown when the page's "ppedit" title is 

46 clicked; see `about`), `instance` (a token that changes each time 

47 the server starts), and `token` (the session token, or `null`; the 

48 page shows it in the restart command so a restarted server accepts 

49 its cookie) 

50 - `GET /api/state`: current state 

51 - `GET /api/ping`: `{"instance", "revision"}`, answered without waiting 

52 for the editor lock; the page polls it to notice that the server stopped 

53 or was restarted (a different `instance`) 

54 - `POST /api/new`: `{}` empty case or `{"builtin": "case14"}` 

55 - `POST /api/open`: `{"filename": ..., "text": ...}` (upload), 

56 `{"path": ...}` (server file), or `{"url": ...}` (an `http`/`https` URL 

57 the server downloads, at most `DOWNLOAD_LIMIT` bytes; the extension of 

58 the URL path selects the format, and GitHub file page URLs are changed to 

59 raw file URLs); `.py`, `.json`, `.glm`, or PSS/E 

60 `.raw` (read only: Save needs a `.py`, `.json` or `.glm` path; uploads 

61 and downloads have no path until saved) 

62 - `POST /api/global`: `{"key": "baseMVA"|"version"|"name", "value": ...}` 

63 - `POST /api/cell`: `{"table", "row", "column", "value"}` 

64 - `POST /api/load`: `{"bus"}` switch the load at bus number `bus` off 

65 (`Pd` and `Qd` set to 0, their values kept) or back on (the kept values 

66 restored), as one undoable edit (see `Editor.toggle_load`); state 

67 `loads_off` lists the loads switched off as `[bus, Pd, Qd]` 

68 - `POST /api/rows`: `{"table", "values"?, "after"?}` add a row 

69 - `POST /api/rows/delete`: `{"table", "rows": [...], "cascade"?}` 

70 - `POST /api/table/import`: `{"table", "filename", "data", "rows"?, "dropna"?, "range"?}` 

71 read table data from a file (`data`: its contents in base64; the 

72 format comes from the `filename` extension, see 

73 `ppedit._tableio.table_format`) and append the rows, or replace the 

74 rows listed in `rows` (see `ppedit.Case.import_rows`); the state has 

75 `imported` (`{"added"|"replaced": n, "cascade"}`). `dropna` drops 

76 missing values when the file is read (see `ppedit._tableio.read_rows`), 

77 and `imported` then has `dropped` (`{"rows", "columns"}`); `range` 

78 keeps only those data rows of the file, counted from 1 (`N`, `A-B`, 

79 `A-`, `-B`), and `imported` then has `selected` (`{"rows", "of"}`) 

80 - `GET /api/table/export?table=...&format=csv&rows=1,2`: download the 

81 rows of a table (`rows`: comma-separated row indexes, default all) as 

82 a data file in the format of the extension `format` (e.g. `csv`, 

83 `csv.gz`, `parquet`, `xlsx`), named `<case>_<table>.<format>`; while a 

84 successful solution exists, the extended (result) columns the page 

85 shows follow the table columns (`Editor.extended`) 

86 - `POST /api/series/import`: `{"filename", "data", "name"?, "delta"?, 

87 "dropna"?, "range"?, "start"?, "end"?, "scale"?, "offset"?}` read a 

88 time series of case values from a file (`data`: its contents in 

89 base64; see `ppedit._tableio.read_series`) into the series `name` 

90 (default: the file name without extensions), added or replaced 

91 (`ppedit.Case.set_series`; a case holds several, combined for 

92 multistep OPF by `ppedit.Case.combined_series`; `delta`, hours per 

93 step, defaults to that of the series replaced, else of the first 

94 series, else 1); the state has `imported` (`{"name", "replaced", 

95 "steps", "columns"}`). With `"panel": {"table", "column", "keys"?, "split"?, 

96 "merge"?}` the file is a panel instead: steps in rows and one column per 

97 table row number or geohash, all giving `table.column` 

98 (`ppedit.Case.set_series_panel`; `keys` `auto`|`row`|`geohash`, 

99 `split` `proportional`|`equal`|`copy`, `merge` default true), and 

100 `imported` adds that method's report (`keys`, `ignored`, `unlocated`; 

101 `columns` is then the series total). `dropna` (`rows`, `columns`, 

102 `empty-rows`, `empty-columns`; see `ppedit._tableio.read_rows`) drops 

103 missing values when the file is read, the label column aside, and 

104 `imported` then has `dropped` (`{"rows", "columns"}`). `range` keeps 

105 the data rows counted from 1 (`N`, `A-B`, `A-`, `-B`); `start` and 

106 `end` keep the steps whose time label lies between them (dates and 

107 times, inclusive; an `end` date alone takes in that whole day); then 

108 `imported` has `selected` (`{"rows", "of"}`). Each value `x` read becomes 

109 `x*scale + offset` (default 1 and 0; for a panel before a geohash cell 

110 is shared), and `imported` then has `scaled` (`{"scale", "offset"}`) 

111 - `POST /api/series`: `{"delta", "name"?}` set the hours per step of a 

112 series (`name` may be left out when there is one), or `{"clear": true, 

113 "name"?}` remove the series `name`, or all of them (both undoable) 

114 - `POST /api/series/apply`: `{"step"}` copy the values of combined series 

115 step `step` (counted from 0) into the case (`Case.apply_step`; one undo 

116 step); the state's `applied` gives `step`, `label` and `changed`. 

117 - `GET /api/series/export?format=csv&name=...`: download the series 

118 `name`, or without `name` the combined series, as a data file (a 

119 `time` column, then the series columns), named 

120 `<case>_<name>.<format>` (`<case>_series.<format>` combined) 

121 - `POST /api/undo`, `POST /api/redo` 

122 - `POST /api/solve`: `{"kind": "pf"|"opf", "algorithm"?, "options"?, 

123 "multistep"?, "window"?}`; 

124 `algorithm` is a PF algorithm (`NR`, the default, `NR-SC`, ..., `ZG`; see 

125 `ppedit.case.PF_SOLVERS`) 

126 or an OPF solver (`PIPS`, the default, `PIPS-SC`, `DC-PIPS`, ...; see 

127 `ppedit.case.OPF_SOLVERS`); `options` are the `CVXOPF-*` solve options 

128 (see `ppedit.Case.solve`); `multistep` true solves the case time 

129 series as one multistep OPF with a `CVXOPF-*` solver (the result has 

130 `steps`), over the combined series steps `window` = `[first, last]` 

131 (counted from 0, both included; default all steps; see 

132 `ppedit.Case.series_window`). The result's `messages` (solver errors and 

133 warnings, with an optional `detail`: physical meaning and constraints 

134 involved) are listed on the page's Issues tab. With `"background": 

135 true` the request returns the state at once with `solving` true and 

136 the solve runs on a copy of the case in a server thread, so other 

137 requests (edits included) go on meanwhile; `/api/solve/progress` then 

138 reports when it ends, and the result becomes the state's `result` only 

139 if the case did not change while solving (an edit clears the result, 

140 as without `background`). One solve runs at a time: another 

141 `/api/solve` while one runs is refused (HTTP 409) 

142 - `GET /api/solve/progress`: progress of the running solve: 

143 `running`, `elapsed` (s), `stoppable` (a `CVXOPF-*` solve, run in a 

144 child process), `stopping`, `phase`, `text` (one line for display, 

145 e.g. `IPOPT iteration 120 of at most 3000, primal infeasibility 

146 3.20e-04`), and while IPOPT iterates `iteration`, `max_iter`, 

147 `objective`, `inf_pr`, `inf_du` (see `ppedit._solveproc`); only 

148 `running` false when no solve has run. A background solve also has 

149 `background` true, `kind`, `revision` (of the case it solves) and, once ended, 

150 `outcome`: `result` (the state's `result` is new), `discarded` (the 

151 case changed while solving) or `error` (with `error`, the message) 

152 - `POST /api/solve/stop`: stop the running `CVXOPF-*` solve (its child 

153 process is killed); returns `running` and `stopping` (false when 

154 there is nothing to stop). The pending `/api/solve` request (or the 

155 background solve) then gives a failed result with `stopped` true 

156 - `POST /api/apply`: `{"step"?}` copy the last solution into the case 

157 (`step`: the step of a multistep solution, counted from 0; default 0) 

158 - `POST /api/geodata`: `{"filename": ..., "text": ...}` (CSV upload), 

159 `{"path": ...}` (server CSV file), or `{"clear": true}`; replaces the 

160 case geodata (see `ppedit.Case.load_geodata`) as one undoable edit 

161 - `POST /api/save`: `{"path"?, "force"?}` write to the open file or to 

162 `path`; when the case was read from a GLM file with content ppedit does 

163 not edit (`case.notes`), overwriting an existing file returns status 409 

164 with `"confirm": true` unless `force` is true 

165 - `POST /api/folders`: `{"path"?}` list a folder on the server machine 

166 (default: the open file's folder, else the server's working directory) 

167 for the page's folder chooser; returns `{"path", "parent", "folders", 

168 "files"}` (see `list_folder`), not the editor state 

169 - `POST /api/folder`: `{"path"}` move the open file's path into that 

170 folder on the server machine without writing anything (the file name 

171 is kept, or is the case name with `.glm` when there is no path; `.raw` 

172 becomes `.glm`); the case is marked unsaved until Save writes it there 

173 - `GET /api/export?format=py|json|glm|csv`: download the case (`csv`: 

174 its geodata) 

175 - `POST /api/exit`: `{}` stop the server (unsaved changes are lost); 

176 returns `{"exit": true}` and shuts down shortly after responding 

177 

178Claude sessions (see `ppedit.claude`); each returns the editor state plus 

179`claude`, the list of sessions (`ppedit.claude.Sessions.to_dict`): 

180 

181 - `GET /api/claude`: the sessions only (polled by the Agent tab) 

182 - `POST /api/claude/new`: `{"title"?, "model"?, "web"?, "local"?, "root"?, 

183 "agent"?, "api_key"?, "api_key_file"?}`; `agent` is one of 

184 `ppedit.claude.AGENTS`, and `api_key` (key text) or `api_key_file` (a 

185 file on the server machine whose first line is the key) override the 

186 server default key for this session (see `ppedit.claude.Sessions.create`) 

187 - `POST /api/claude/send`: `{"id", "text"}` add a message; Claude works on 

188 it in the background, editing the case through undoable edits 

189 - `POST /api/claude/stop`: `{"id"}` stop after the current step 

190 - `POST /api/claude/delete`: `{"id"}` stop and remove the session 

191 

192Caveats 

193------- 

194 

195 - The development server started by `ppedit serve` is single-process and 

196 meant for local use only. 

197""" 

198 

199import base64 

200import binascii 

201import copy 

202import hashlib 

203import hmac 

204import importlib.metadata 

205import logging 

206import os 

207import re 

208import secrets 

209import signal 

210import threading 

211import urllib.error 

212import urllib.parse 

213import urllib.request 

214from html import escape as html_escape 

215 

216from flask import Flask, jsonify, request, send_from_directory, Response, redirect 

217 

218from ppedit.case import Case, CaseError, COLUMNS, RESULT_COLUMNS, TABLES, FORMATS, INPUT_FORMATS, \ 

219 builtin_cases, solvers, writable_format 

220from ppedit import _branding as branding 

221from ppedit.claude import Sessions 

222from ppedit._solveproc import SolveJob, describe 

223from ppedit._tableio import table_formats, table_read_formats, read_rows, dump_rows, \ 

224 read_series, dump_series 

225 

226_logger = logging.getLogger(__file__) 

227 

228STATIC = os.path.join(os.path.dirname(__file__),"static") 

229"""Folder of the browser editor files""" 

230 

231HISTORY = 200 

232"""Number of undo steps kept""" 

233 

234DOWNLOAD_LIMIT = 50000000 

235"""Largest case file `POST /api/open` downloads from a URL, in bytes""" 

236 

237DOWNLOAD_TIMEOUT = 60 

238"""Seconds to wait for a URL download to respond""" 

239 

240_LOOPBACK = {"localhost","127.0.0.1","::1","[::1]"} 

241 

242_SOURCE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 

243 

244_FUNDING_HEADING = re.compile(r"fund|acknowledg|sponsor",re.IGNORECASE) 

245 

246def _readme_funding(readme:str) -> str|None: 

247 """Funding acknowledgment section of a README 

248 

249 Arguments: 

250 

251 - `readme`: README text (Markdown) 

252 

253 Returns: 

254 

255 - `str|None`: text of the first section whose heading mentions 

256 funding, an acknowledgment or a sponsor, up to the next heading of 

257 the same or a higher level, or `None` when there is none 

258 

259 Example: 

260 

261 >>> _readme_funding("# Usage\\nrun it\\n# Funding\\nPaid by X.\\n# Other\\n") 

262 'Paid by X.' 

263 """ 

264 lines = readme.splitlines() 

265 for n,line in enumerate(lines): 

266 head = re.match(r"(#+)\s+(.*)",line) 

267 if head and _FUNDING_HEADING.search(head.group(2)): 

268 level = len(head.group(1)) 

269 body = [] 

270 for text in lines[n+1:]: 

271 more = re.match(r"(#+)\s",text) 

272 if more and len(more.group(1)) <= level: 

273 break 

274 body.append(text) 

275 return "\n".join(body).strip() or None 

276 return None 

277 

278def _source_text(dists,*names) -> str: 

279 # a file of an installed distribution, else of the source tree; every 

280 # distribution found is tried, since a stale in-tree `ppedit.egg-info` 

281 # (left by `pip install .`) can be found first and has no license file 

282 for dist in dists: 282 ↛ 290line 282 didn't jump to line 290 because the loop on line 282 didn't complete

283 for name in names: 

284 try: 

285 text = dist.read_text(name) 

286 except (OSError,ValueError): 

287 text = None 

288 if text: 

289 return text 

290 for name in names: 

291 path = os.path.join(_SOURCE,os.path.basename(name)) 

292 if os.path.isfile(path): 

293 with open(path,encoding="utf-8") as fh: 

294 return fh.read() 

295 return "" 

296 

297def app_page(html:str) -> str: 

298 """Put the editor name of `ppedit._branding` into the page `html` 

299 

300 `{{APP_NAME}}` becomes `branding.APP_NAME` and `{{APP_BRAND}}` the 

301 top-bar title, `APP_MARK` in the accent color (HTML escaped).""" 

302 name = branding.APP_NAME or "ppedit" 

303 mark = branding.APP_MARK if branding.APP_MARK and name.startswith(branding.APP_MARK) else "" 

304 brand = (f'<span class="mark">{html_escape(mark)}</span>' if mark else "") + html_escape(name[len(mark):]) 

305 return html.replace("{{APP_BRAND}}",brand).replace("{{APP_NAME}}",html_escape(name)) 

306 

307def about() -> dict: 

308 """Package metadata shown by the editor's "ppedit" title 

309 

310 Read from the installed `ppedit` distribution metadata (`pyproject.toml` 

311 `[project]`), its `LICENSE` file and its README (the long description), 

312 or from the source tree when the package is not installed. 

313 

314 Returns: 

315 

316 - `dict`: `name`, `version`, `summary`, `copyright` (the `Copyright` 

317 lines of `LICENSE`), `license` (the first line of `LICENSE`, e.g. 

318 `MIT License`), `repository`, `documentation`, `issues` and 

319 `license_url` (URLs, or `None` when not known), and `funding` (the 

320 funding acknowledgment section of the README, Markdown, or `None`) 

321 """ 

322 dists = list(importlib.metadata.distributions(name="ppedit")) 

323 meta = dists[0].metadata if dists else {} 

324 urls = {} 

325 for entry in (meta.get_all("Project-URL") or []) if meta else []: 

326 label,_,url = entry.partition(",") 

327 urls[label.strip().lower()] = url.strip() 

328 repository = urls.get("repository") or urls.get("homepage") 

329 if repository and repository.endswith(".git"): 329 ↛ 331line 329 didn't jump to line 331 because the condition on line 329 was always true

330 repository = repository[:-4] 

331 license_text = _source_text(dists,"licenses/LICENSE","LICENSE") 

332 readme = None 

333 if meta: 333 ↛ 335line 333 didn't jump to line 335 because the condition on line 333 was always true

334 readme = meta.get("Description") or getattr(meta,"get_payload",lambda:None)() 

335 readme = readme or _source_text([],"README.md") 

336 try: 

337 from ppedit import __version__ as version # pylint: disable=import-outside-toplevel 

338 except ImportError: 

339 version = "dev" 

340 return { 

341 "name": meta.get("Name","ppedit") if meta else "ppedit", 

342 "version": version, 

343 "summary": meta.get("Summary") if meta else None, 

344 "copyright": [x.strip() for x in license_text.splitlines() 

345 if x.strip().lower().startswith("copyright")], 

346 "license": license_text.strip().splitlines()[0].strip() if license_text.strip() else None, 

347 "repository": repository, 

348 "documentation": urls.get("documentation"), 

349 "issues": urls.get("issues") or (repository and repository+"/issues"), 

350 "license_url": repository and repository+"/blob/main/LICENSE", 

351 "funding": _readme_funding(readme or ""), 

352 } 

353 

354def _shutdown(): 

355 """Stop the server process as Ctrl-C would, or exit if `SIGINT` is ignored""" 

356 if signal.getsignal(signal.SIGINT) in (signal.SIG_IGN,None): 

357 os._exit(0) # e.g. started in the background, where SIGINT is ignored 

358 signal.raise_signal(signal.SIGINT) 

359 

360def github_raw_url(url:str) -> str: 

361 """Change a GitHub file page URL to the URL of the raw file 

362 

363 `https://github.com/OWNER/REPO/blob/REF/PATH` (or `/raw/`) becomes 

364 `https://raw.githubusercontent.com/OWNER/REPO/REF/PATH`; the query and 

365 fragment are dropped. Other URLs are returned unchanged. 

366 

367 >>> github_raw_url("https://github.com/o/r/blob/feature/x/d/case.py?plain=1#L9") 

368 'https://raw.githubusercontent.com/o/r/feature/x/d/case.py' 

369 >>> github_raw_url("https://example.org/case.glm") 

370 'https://example.org/case.glm' 

371 """ 

372 parts = urllib.parse.urlsplit(url) 

373 if parts.netloc.lower() in ("github.com","www.github.com"): 

374 path = parts.path.split("/") 

375 if len(path) > 5 and path[3] in ("blob","raw"): 375 ↛ 377line 375 didn't jump to line 377 because the condition on line 375 was always true

376 return "https://raw.githubusercontent.com/" + "/".join(path[1:3]+path[4:]) 

377 return url 

378 

379def download_case(url:str) -> Case: 

380 """Download a case file from an `http` or `https` URL and read it 

381 

382 Arguments 

383 --------- 

384 

385 - `url`: the file URL; the extension of its path selects the format. 

386 GitHub file page URLs are changed to raw file URLs 

387 (`github_raw_url`). 

388 

389 Returns 

390 ------- 

391 

392 - `Case`: the case, with `Case.source["file"]` set to the URL 

393 downloaded 

394 

395 Exceptions 

396 ---------- 

397 

398 - `CaseError`: other scheme, unsupported extension, HTTP or network 

399 error, an HTML page (`Content-Type` `text/html`), file larger than 

400 `DOWNLOAD_LIMIT`, or unreadable content 

401 """ 

402 url = github_raw_url(url.strip()) 

403 parts = urllib.parse.urlsplit(url) 

404 if parts.scheme.lower() not in ("http","https") or not parts.netloc: 

405 raise CaseError("only http and https URLs can be opened") 

406 filename = os.path.basename(urllib.parse.unquote(parts.path)) 

407 ext = os.path.splitext(filename)[1].lower() 

408 if ext not in INPUT_FORMATS: 

409 raise CaseError(f"'{url}' does not name a {', '.join(INPUT_FORMATS)} file") 

410 req = urllib.request.Request(url,headers={"User-Agent":"ppedit"}) 

411 try: 

412 with urllib.request.urlopen(req,timeout=DOWNLOAD_TIMEOUT) as res: 

413 data = res.read(DOWNLOAD_LIMIT+1) 

414 ctype = res.headers.get("Content-Type","") 

415 except urllib.error.HTTPError as err: 

416 raise CaseError(f"HTTP {err.code} from {url}") from err 

417 except (urllib.error.URLError,OSError) as err: 

418 raise CaseError(f"cannot download {url}: {getattr(err,'reason',err)}") from err 

419 if ctype.split(";")[0].strip().lower() in ("text/html","application/xhtml+xml"): 

420 raise CaseError(f"'{url}' is a web page, not a case file " 

421 "(use the link to the raw file)") 

422 if len(data) > DOWNLOAD_LIMIT: 

423 raise CaseError(f"'{url}' is larger than {DOWNLOAD_LIMIT} bytes") 

424 try: # PSS/E names may be Latin-1, as in Case.load 

425 text = data.decode("utf-8",errors="replace" if ext == ".raw" else "strict") 

426 except UnicodeDecodeError as err: 

427 raise CaseError(f"'{url}' is not UTF-8 text") from err 

428 case = Case.load(filename,text) 

429 case.source["file"] = url 

430 _logger.info("downloaded %s (%d bytes)",url,len(data)) 

431 return case 

432 

433def list_folder(path:str) -> dict: 

434 """List a folder on the server machine for the page's folder chooser 

435 

436 Arguments 

437 --------- 

438 

439 - `path`: the folder; `~` is expanded and relative paths are taken 

440 from the server's working directory 

441 

442 Returns 

443 ------- 

444 

445 - `dict`: `path` (absolute), `parent` (absolute, or `None` at the 

446 root), `folders` (names of the subfolders not starting with `.`), 

447 and `files` (names of the files ppedit can save, by `FORMATS` 

448 extension), each sorted case-insensitively 

449 

450 Exceptions 

451 ---------- 

452 

453 - `CaseError`: not a folder, or it cannot be read 

454 """ 

455 path = os.path.abspath(os.path.expanduser(path)) 

456 if not os.path.isdir(path): 

457 raise CaseError(f"'{path}' is not a folder") 

458 try: 

459 entries = list(os.scandir(path)) 

460 except OSError as err: 

461 raise CaseError(f"cannot read '{path}': {err.strerror or err}") from err 

462 def is_dir(entry): 

463 try: 

464 return entry.is_dir() 

465 except OSError: 

466 return False 

467 key = str.lower 

468 folders = sorted((e.name for e in entries if is_dir(e) and not e.name.startswith(".")),key=key) 

469 files = sorted((e.name for e in entries if not is_dir(e) 

470 and os.path.splitext(e.name)[1].lower() in FORMATS),key=key) 

471 parent = os.path.dirname(path) 

472 return {"path":path,"parent":parent if parent != path else None, 

473 "folders":folders,"files":files} 

474 

475class Editor: 

476 """In-memory editing session: the case, its file, and undo history 

477 

478 Arguments 

479 --------- 

480 

481 - `case`: initial case (default: empty case) 

482 

483 - `path`: file the case was read from, if any 

484 """ 

485 

486 def __init__(self,case:Case|None=None,path:str|None=None): 

487 self.case = case or Case(name="untitled") 

488 """The case being edited""" 

489 self.path = path 

490 """File the case is saved to (or `None`)""" 

491 self.dirty = False 

492 """Whether the case changed since it was opened or saved""" 

493 self.result = None 

494 """Last solver result (cleared by any edit)""" 

495 self.undo_stack = [] 

496 self.redo_stack = [] 

497 self.revision = 0 

498 """Counter incremented whenever the case changes (edit, undo, redo, open)""" 

499 self.loads_off = {} 

500 """Loads switched off by `toggle_load`: bus number -> `[Pd, Qd]` to restore""" 

501 self.lock = threading.RLock() 

502 self.job = None 

503 """`ppedit._solveproc.SolveJob` of the running or last solve (or `None`)""" 

504 

505 def _snapshot(self): 

506 return (copy.deepcopy(self.case.tables),self.case.baseMVA, 

507 self.case.version,self.case.name, 

508 copy.deepcopy(self.case.geodata),list(self.case.geotags), 

509 copy.deepcopy(self.loads_off),copy.deepcopy(self.case.series)) 

510 

511 def _restore(self,snap): 

512 tables,base,version,name,geodata,geotags,loads_off,series = snap 

513 self.case.tables = copy.deepcopy(tables) 

514 self.case.baseMVA,self.case.version,self.case.name = base,version,name 

515 self.case.geodata,self.case.geotags = copy.deepcopy(geodata),list(geotags) 

516 self.loads_off = copy.deepcopy(loads_off) 

517 self.case.series = copy.deepcopy(series) 

518 

519 def _prune_loads_off(self): 

520 # a switched-off load stays off only while its bus exists with Pd = Qd = 0 

521 zero = {b[0] for b in self.case.tables["bus"] if b[2] == 0 and b[3] == 0} 

522 for bus in [b for b in self.loads_off if b not in zero]: 

523 del self.loads_off[bus] 

524 

525 def edit(self,func): 

526 """Run `func()` as one undoable edit; roll back if it raises""" 

527 snap = self._snapshot() 

528 try: 

529 out = func() 

530 self._prune_loads_off() 

531 except Exception: 

532 self._restore(snap) 

533 raise 

534 if self._snapshot() != snap: 

535 self.undo_stack.append(snap) 

536 del self.undo_stack[:-HISTORY] 

537 self.redo_stack.clear() 

538 self.dirty = True 

539 self.result = None 

540 self.revision += 1 

541 return out 

542 

543 def replace(self,case:Case,path:str|None): 

544 """Open a different case (clears history)""" 

545 self.case,self.path = case,path 

546 self.dirty,self.result = False,None 

547 self.loads_off = {} 

548 self.undo_stack.clear() 

549 self.redo_stack.clear() 

550 self.revision += 1 

551 

552 def undo(self): 

553 """Undo the last edit""" 

554 if not self.undo_stack: 

555 raise CaseError("nothing to undo") 

556 self.redo_stack.append(self._snapshot()) 

557 self._restore(self.undo_stack.pop()) 

558 self.dirty,self.result = True,None 

559 self.revision += 1 

560 

561 def redo(self): 

562 """Redo the last undone edit""" 

563 if not self.redo_stack: 563 ↛ 564line 563 didn't jump to line 564 because the condition on line 563 was never true

564 raise CaseError("nothing to redo") 

565 self.undo_stack.append(self._snapshot()) 

566 self._restore(self.redo_stack.pop()) 

567 self.dirty,self.result = True,None 

568 self.revision += 1 

569 

570 def toggle_load(self,bus:int) -> bool: 

571 """Switch the load at a bus off or back on, as one undoable edit 

572 

573 A load with `Pd` or `Qd` not zero is switched off: both are set to 0 

574 and their values are kept in `loads_off`. A load switched off this way 

575 is switched back on by restoring those values. The values are kept 

576 with the undo history but not in the case file, so a saved case has 

577 `Pd = Qd = 0` there; editing `Pd` or `Qd`, or renumbering or deleting 

578 the bus, forgets them. 

579 

580 Arguments 

581 --------- 

582 

583 - `bus`: bus number (`bus_i`) 

584 

585 Returns 

586 ------- 

587 

588 - `bool`: `True` if the load is now on 

589 """ 

590 rows = [i for i,b in enumerate(self.case.tables["bus"]) if b[0] == bus] 

591 if not rows: 

592 raise CaseError(f"bus {bus} not found") 

593 row = rows[0] 

594 

595 def run(): 

596 record = self.case.tables["bus"][row] 

597 if record[2] != 0 or record[3] != 0: 

598 saved = [record[2],record[3]] 

599 self.case.set_value("bus",row,"Pd",0) 

600 self.case.set_value("bus",row,"Qd",0) 

601 self.loads_off[bus] = saved 

602 return False 

603 if bus not in self.loads_off: 

604 raise CaseError(f"bus {bus} has no switched-off load to restore") 

605 pd,qd = self.loads_off.pop(bus) 

606 self.case.set_value("bus",row,"Pd",pd) 

607 self.case.set_value("bus",row,"Qd",qd) 

608 return True 

609 

610 return self.edit(run) 

611 

612 def extended(self,table:str,index:list[int]) -> tuple[list[dict],list[list]]|None: 

613 """Extended (result) columns of the last solution for rows `index` 

614 of `table`, as `(columns, rows)` for `dump_rows`, or `None` 

615 

616 Only the columns the solver gave (not all `None` over the whole 

617 table) are included, as the page shows them (decision #56). 

618 """ 

619 res = self.result 

620 ext = res.get("extended",{}).get(table) if res and res.get("success") else None 

621 if not ext or len(ext) != len(self.case.tables[table]): 

622 return None 

623 spec = RESULT_COLUMNS[table] 

624 keep = [j for j in range(len(spec)) if any(row[j] is not None for row in ext)] 

625 if not keep: 

626 return None 

627 return [spec[j] for j in keep],[[ext[i][j] for j in keep] for i in index] 

628 

629 def state(self,cascade:bool=False) -> dict: 

630 """Return the editor state sent to the browser""" 

631 fmt = INPUT_FORMATS.get(os.path.splitext(self.path)[1].lower()) if self.path else None 

632 return { 

633 "case": self.case.to_dict(), 

634 "path": self.path, 

635 "format": fmt, 

636 "dirty": self.dirty, 

637 "issues": self.case.validate(), 

638 "can_undo": bool(self.undo_stack), 

639 "can_redo": bool(self.redo_stack), 

640 "result": self.result, 

641 "cascade": cascade, 

642 "revision": self.revision, 

643 "source": self.case.source, 

644 "loads_off": [[bus,pd,qd] for bus,(pd,qd) in sorted(self.loads_off.items())], 

645 } 

646 

647class SolveBusy(CaseError): 

648 """A solve was requested while another one runs (HTTP 409)""" 

649 

650def token_cookie(token:str) -> str: 

651 """Name of the session cookie for `token` 

652 

653 Arguments 

654 --------- 

655 

656 - `token`: session token given to `create_app` 

657 

658 Returns 

659 ------- 

660 

661 - `str`: `ppedit_` and the first 12 hex digits of the SHA-256 of the 

662 token; browsers share `localhost` cookies across ports, so each 

663 server (token) needs its own cookie name 

664 """ 

665 return "ppedit_" + hashlib.sha256(token.encode()).hexdigest()[:12] 

666 

667def create_app(case:Case|None=None,path:str|None=None,allow_remote:bool=False, 

668 shutdown=None,claude_client=None,token:str|None=None) -> Flask: 

669 """Create the editor application 

670 

671 Arguments 

672 --------- 

673 

674 - `case`: case to edit (default: empty case) 

675 

676 - `path`: file `case` was read from; "Save" writes back to it 

677 

678 - `allow_remote`: accept requests whose `Host` is not a loopback name 

679 

680 - `shutdown`: function called (shortly after responding) by 

681 `POST /api/exit` to stop the server (`ppedit serve` passes its 

682 server's `shutdown`); default raises `SIGINT` in the server 

683 process, or exits it if `SIGINT` is ignored 

684 

685 - `claude_client`: Messages API client for the Claude sessions 

686 (default: `urllib`; tests pass a fake) 

687 

688 - `token`: session token every request must carry (`?token=` in the 

689 URL, or the cookie set in exchange for it; see the module 

690 docstring); default `None` accepts requests without one 

691 

692 Returns 

693 ------- 

694 

695 - `Flask`: the application; `app.config["EDITOR"]` is the `Editor` 

696 """ 

697 app = Flask(__name__,static_folder=None) 

698 editor = Editor(case,path) 

699 app.config["EDITOR"] = editor 

700 claude = Sessions(editor,claude_client) 

701 app.config["CLAUDE"] = claude 

702 app.config["SHUTDOWN"] = shutdown or _shutdown 

703 instance = secrets.token_hex(8) # tells the page a restarted server from the one it loaded from 

704 

705 cookie = token_cookie(token) if token is not None else None 

706 

707 def _set_token(res): 

708 res.set_cookie(cookie,token,httponly=True,samesite="Strict",path="/") 

709 return res 

710 

711 @app.before_request 

712 def _guard(): 

713 host = (request.host or "").rsplit(":",1)[0] if not (request.host or "").startswith("[") \ 

714 else request.host.split("]")[0]+"]" 

715 if not allow_remote and host not in _LOOPBACK: 

716 return jsonify(error="remote access is disabled"),403 

717 if token is not None: 

718 given = request.args.get("token") 

719 if given is not None and hmac.compare_digest(given.encode(),token.encode()): 

720 if request.method == "GET" and not request.path.startswith("/api/"): 

721 query = urllib.parse.urlencode([(k,v) for k,v in request.args.items(multi=True) if k != "token"]) 

722 return _set_token(redirect(request.path + ("?"+query if query else ""),code=303)) 

723 elif not hmac.compare_digest(request.cookies.get(cookie,"").encode(),token.encode()): 

724 message = "missing or invalid session token: open the URL that ppedit serve printed" 

725 if request.path.startswith("/api/"): 

726 return jsonify(error=message),403 

727 return Response(message+"\n",status=403,mimetype="text/plain") 

728 if request.method == "POST": 

729 if request.headers.get("X-PPEdit") != "1" or not request.is_json: 

730 return jsonify(error="missing X-PPEdit header or JSON body"),403 

731 return None 

732 

733 @app.after_request 

734 def _remember_token(res): 

735 # a request authorized by ?token= (scripts, API calls) also gets the cookie 

736 if token is not None and not any(c.startswith(cookie+"=") for c in res.headers.getlist("Set-Cookie")) \ 

737 and hmac.compare_digest(request.args.get("token","").encode(),token.encode()): 

738 _set_token(res) 

739 return res 

740 

741 @app.errorhandler(CaseError) 

742 def _case_error(err): 

743 return jsonify(error=str(err)),400 

744 

745 @app.errorhandler(SolveBusy) 

746 def _solve_busy(err): 

747 return jsonify(error=str(err)),409 

748 

749 @app.errorhandler(KeyError) 

750 def _key_error(err): 

751 return jsonify(error=f"missing field {err}"),400 

752 

753 def body(): 

754 return request.get_json(silent=True) or {} 

755 

756 def no_cache(res): 

757 # browsers revalidate (ETag/Last-Modified) on every load, so an 

758 # upgraded package is picked up without a hard reload 

759 res.headers["Cache-Control"] = "no-cache" 

760 return res 

761 

762 @app.get("/") 

763 def index(): 

764 res = no_cache(send_from_directory(STATIC,"index.html")) 

765 res.direct_passthrough = False 

766 res.set_data(app_page(res.get_data(as_text=True))) 

767 return res 

768 

769 @app.get("/static/<path:name>") 

770 def static_file(name): 

771 return no_cache(send_from_directory(STATIC,name)) 

772 

773 @app.get("/api/meta") 

774 def meta(): 

775 from ppedit import __version__ # pylint: disable=import-outside-toplevel 

776 return jsonify(columns=COLUMNS,result_columns=RESULT_COLUMNS,tables=TABLES, 

777 builtin=builtin_cases(), 

778 formats=list(FORMATS.values()),input_formats=list(INPUT_FORMATS.values()), 

779 table_formats=table_formats(),table_read_formats=table_read_formats(),solvers=solvers(),version=__version__,about=about(),app_name=branding.APP_NAME or "ppedit", 

780 instance=instance,token=token) 

781 

782 @app.get("/api/ping") 

783 def ping(): 

784 # no editor.lock: a long solve or load must not look like a stopped server 

785 return jsonify(instance=instance,revision=editor.revision) 

786 

787 @app.get("/api/state") 

788 def state(): 

789 with editor.lock: 

790 return jsonify(editor.state()) 

791 

792 @app.post("/api/new") 

793 def new(): 

794 data = body() 

795 with editor.lock: 

796 if data.get("builtin"): 

797 editor.replace(Case.builtin(data["builtin"]),None) 

798 else: 

799 editor.replace(Case(name="untitled"),None) 

800 return jsonify(editor.state()) 

801 

802 @app.post("/api/open") 

803 def open_case(): 

804 data = body() 

805 if "url" in data and "text" not in data: # download outside the lock 

806 case = download_case(data["url"]) 

807 with editor.lock: 

808 editor.replace(case,None) 

809 return jsonify(editor.state()) 

810 with editor.lock: 

811 if "text" in data: 

812 case = Case.load(data["filename"],data["text"]) 

813 editor.replace(case,None) 

814 else: 

815 path = os.path.abspath(os.path.expanduser(data["path"])) 

816 if not os.path.isfile(path): 816 ↛ 817line 816 didn't jump to line 817 because the condition on line 816 was never true

817 raise CaseError(f"'{path}' not found") 

818 editor.replace(Case.load(path),path) 

819 return jsonify(editor.state()) 

820 

821 @app.post("/api/global") 

822 def set_global(): 

823 data = body() 

824 with editor.lock: 

825 editor.edit(lambda: editor.case.set_global(data["key"],data["value"])) 

826 return jsonify(editor.state()) 

827 

828 @app.post("/api/cell") 

829 def set_cell(): 

830 data = body() 

831 with editor.lock: 

832 cascade = editor.edit(lambda: editor.case.set_value( 

833 data["table"],int(data["row"]),data["column"],data["value"])) 

834 return jsonify(editor.state(cascade)) 

835 

836 @app.post("/api/load") 

837 def toggle_load(): 

838 data = body() 

839 with editor.lock: 

840 editor.toggle_load(int(data["bus"])) 

841 return jsonify(editor.state()) 

842 

843 @app.post("/api/rows") 

844 def add_row(): 

845 data = body() 

846 with editor.lock: 

847 after = data.get("after") 

848 index = editor.edit(lambda: editor.case.add_row(data["table"], 

849 data.get("values"),None if after is None else int(after))) 

850 out = editor.state(True) 

851 out["row"] = index 

852 return jsonify(out) 

853 

854 @app.post("/api/rows/delete") 

855 def delete_rows(): 

856 data = body() 

857 with editor.lock: 

858 removed = editor.edit(lambda: editor.case.delete_rows(data["table"], 

859 [int(x) for x in data["rows"]],bool(data.get("cascade")))) 

860 out = editor.state(True) 

861 out["removed"] = removed 

862 return jsonify(out) 

863 

864 @app.post("/api/table/import") 

865 def import_table(): 

866 data = body() 

867 try: 

868 content = base64.b64decode(data["data"],validate=True) 

869 except (binascii.Error,TypeError) as err: 

870 raise CaseError("data must be the file contents in base64") from err 

871 dropped = {} 

872 columns,rows = read_rows(str(data["filename"]),content,data.get("dropna") or None,dropped, 

873 data.get("range")) 

874 replace = data.get("rows") 

875 with editor.lock: 

876 result = editor.edit(lambda: editor.case.import_rows(data["table"],columns,rows, 

877 None if not replace else [int(x) for x in replace])) 

878 out = editor.state(result["cascade"]) 

879 out["imported"] = {**result,**dropped} 

880 return jsonify(out) 

881 

882 @app.get("/api/table/export") 

883 def export_table(): 

884 table = request.args.get("table","") 

885 fmt = request.args.get("format","csv").lstrip(".") 

886 text = request.args.get("rows","").strip() 

887 with editor.lock: 

888 if table not in COLUMNS: 

889 raise CaseError(f"unknown table '{table}'") 

890 rows = editor.case.tables[table] 

891 if text: 

892 try: 

893 index = sorted({int(x) for x in text.split(",")}) 

894 except ValueError as err: 

895 raise CaseError("rows must be comma-separated row indexes") from err 

896 for i in index: 

897 editor.case._check(table,i) # pylint: disable=protected-access 

898 else: 

899 index = list(range(len(rows))) 

900 rows = [rows[i] for i in index] 

901 name = f"{editor.case.name or 'untitled'}_{table}.{fmt}" 

902 content = dump_rows(table,rows,name,editor.extended(table,index)) 

903 return Response(content,mimetype="application/octet-stream",headers={ 

904 "Content-Disposition":f'attachment; filename="{name}"'}) 

905 

906 @app.post("/api/undo") 

907 def undo(): 

908 with editor.lock: 

909 editor.undo() 

910 return jsonify(editor.state(True)) 

911 

912 @app.post("/api/redo") 

913 def redo(): 

914 with editor.lock: 

915 editor.redo() 

916 return jsonify(editor.state(True)) 

917 

918 def start_background_solve(args) -> dict: 

919 """Start solving a copy of the case in a thread (editor.lock held); 

920 the result is kept only if the case revision is unchanged at the end""" 

921 job = editor.job = SolveJob() 

922 case,revision = copy.deepcopy(editor.case),editor.revision 

923 job.background_status = {"background":True,"revision":revision,"kind":args[0]} 

924 def run(): 

925 result,error = None,None 

926 try: 

927 result = case.solve(*args[:4],job=job,window=args[4]) 

928 except Exception as err: # pylint: disable=broad-exception-caught 

929 error = str(err) if isinstance(err,(CaseError,ValueError)) else f"{type(err).__name__}: {err}" 

930 with editor.lock: 

931 if error is not None: 

932 outcome = {"outcome":"error","error":error} 

933 elif editor.revision == revision: 

934 editor.result = result 

935 outcome = {"outcome":"result"} 

936 else: 

937 outcome = {"outcome":"discarded"} 

938 job.background_status = dict(job.background_status,**outcome) 

939 job.done = True 

940 threading.Thread(target=run,name="ppedit-solve",daemon=True).start() 

941 return {"revision":revision} 

942 

943 @app.post("/api/solve") 

944 def solve(): 

945 data = body() 

946 args = (data.get("kind","pf"),data.get("algorithm"),data.get("options"),bool(data.get("multistep")), 

947 data.get("window")) 

948 with editor.lock: 

949 if editor.job is not None and not editor.job.done: 

950 raise SolveBusy("a solve is already running: wait for it or stop it") 

951 if data.get("background"): 

952 return jsonify(dict(editor.state(),solving=True,**start_background_solve(args))) 

953 job = editor.job = SolveJob() 

954 try: 

955 editor.result = editor.case.solve(*args[:4],job=job,window=args[4]) 

956 finally: 

957 job.done = True 

958 return jsonify(editor.state()) 

959 

960 # no editor.lock in the two routes below: the solve request holds it 

961 @app.get("/api/solve/progress") 

962 def solve_progress(): 

963 job = editor.job 

964 if job is None: 

965 return jsonify(running=False) 

966 status = job.status() 

967 status["text"] = describe(status) 

968 status.update(getattr(job,"background_status",{})) 

969 return jsonify(status) 

970 

971 @app.post("/api/solve/stop") 

972 def solve_stop(): 

973 job = editor.job 

974 if job is None or job.done: 

975 return jsonify(running=False,stopping=False) 

976 return jsonify(running=True,stopping=job.stop()) 

977 

978 @app.post("/api/apply") 

979 def apply(): 

980 data = body() 

981 with editor.lock: 

982 if not editor.result: 982 ↛ 983line 982 didn't jump to line 983 because the condition on line 982 was never true

983 raise CaseError("no solution to apply") 

984 result = editor.result 

985 if result.get("steps"): 

986 step = int(data.get("step") or 0) 

987 if not 0 <= step < len(result["steps"]): 

988 raise CaseError(f"the solution has no step {step+1}") 

989 result = result["steps"][step] 

990 editor.edit(lambda: editor.case.apply_result(result)) 

991 return jsonify(editor.state(True)) 

992 

993 @app.post("/api/series/import") 

994 def import_series(): 

995 data = body() 

996 try: 

997 content = base64.b64decode(data["data"],validate=True) 

998 except (binascii.Error,TypeError) as err: 

999 raise CaseError("data must be the file contents in base64") from err 

1000 dropped = {} 

1001 index,columns,rows = read_series(str(data["filename"]),content,data.get("dropna") or None,dropped, 

1002 data.get("range"),data.get("start"),data.get("end"),data.get("scale"),data.get("offset")) 

1003 panel = data.get("panel") 

1004 name = str(data.get("name") or "").strip() or \ 

1005 re.sub(r"(\.[A-Za-z0-9]+)+$","",os.path.basename(str(data["filename"]))) or "series" 

1006 with editor.lock: 

1007 old = editor.case.get_series(name) 

1008 if panel: 

1009 if not isinstance(panel,dict) or not panel.get("table") or not panel.get("column"): 

1010 raise CaseError("a panel import needs the table and column it sets") 

1011 report = editor.edit(lambda: editor.case.set_series_panel(panel["table"], 

1012 panel["column"],columns,rows,index,data.get("delta"), 

1013 panel.get("keys","auto"),panel.get("split","proportional"), 

1014 bool(panel.get("merge",True)),name=name)) 

1015 else: 

1016 delta = data.get("delta") or (old["delta"] if old else 

1017 editor.case.series[0]["delta"] if editor.case.series else 1.0) 

1018 editor.edit(lambda: editor.case.set_series(columns,rows,index,delta,name=name)) 

1019 report = {} 

1020 series = editor.case.get_series(name) 

1021 out = editor.state() 

1022 out["imported"] = {"name":name,"replaced":bool(old),"steps":len(series["values"]), 

1023 "columns":len(series["columns"]),**report,**dropped} 

1024 return jsonify(out) 

1025 

1026 @app.post("/api/series") 

1027 def set_series(): 

1028 data = body() 

1029 with editor.lock: 

1030 name = data.get("name") 

1031 if data.get("clear"): 

1032 if name is not None and not editor.case.get_series(name): 

1033 raise CaseError(f"no series named '{name}'") 

1034 editor.edit(lambda: editor.case.set_series(None,name=name)) 

1035 else: 

1036 editor.edit(lambda: editor.case.set_series_delta(data.get("delta"),name)) 

1037 return jsonify(editor.state()) 

1038 

1039 @app.post("/api/series/apply") 

1040 def apply_series_step(): 

1041 data = body() 

1042 with editor.lock: 

1043 try: 

1044 step = int(data.get("step")) 

1045 except (TypeError,ValueError) as err: 

1046 raise CaseError("step must be a step number counted from 0") from err 

1047 changed = [] 

1048 editor.edit(lambda: changed.append(editor.case.apply_step(step))) 

1049 out = editor.state() 

1050 out["applied"] = {"step":step,"label":editor.case.combined_series()["index"][step], 

1051 "changed":changed[0]} 

1052 return jsonify(out) 

1053 

1054 @app.get("/api/series/export") 

1055 def export_series(): 

1056 fmt = request.args.get("format","csv").lstrip(".") 

1057 which = request.args.get("name") 

1058 with editor.lock: 

1059 if not editor.case.series: 1059 ↛ 1060line 1059 didn't jump to line 1060 because the condition on line 1059 was never true

1060 raise CaseError("the case has no time series") 

1061 if which: 

1062 ser = editor.case.get_series(which) 

1063 if not ser: 1063 ↛ 1064line 1063 didn't jump to line 1064 because the condition on line 1063 was never true

1064 raise CaseError(f"no series named '{which}'") 

1065 else: 

1066 ser = editor.case.combined_series() 

1067 safe = re.sub(r"[^A-Za-z0-9_.-]+","_",ser["name"] if which else "series") 

1068 name = f"{editor.case.name or 'untitled'}_{safe}.{fmt}" 

1069 content = dump_series(ser,name) 

1070 return Response(content,mimetype="application/octet-stream",headers={ 

1071 "Content-Disposition":f'attachment; filename="{name}"'}) 

1072 

1073 @app.post("/api/geodata") 

1074 def geodata(): 

1075 data = body() 

1076 with editor.lock: 

1077 if data.get("clear"): 

1078 editor.edit(lambda: editor.case.set_geodata([])) 

1079 elif "text" in data: 

1080 editor.edit(lambda: editor.case.load_geodata(data.get("filename","geodata.csv"),data["text"])) 

1081 else: 

1082 path = os.path.abspath(os.path.expanduser(data["path"])) 

1083 if not os.path.isfile(path): 1083 ↛ 1084line 1083 didn't jump to line 1084 because the condition on line 1083 was never true

1084 raise CaseError(f"'{path}' not found") 

1085 editor.edit(lambda: editor.case.load_geodata(path)) 

1086 return jsonify(editor.state(True)) 

1087 

1088 @app.post("/api/save") 

1089 def save(): 

1090 data = body() 

1091 with editor.lock: 

1092 path = data.get("path") or editor.path 

1093 if not path: 

1094 raise CaseError("no file name: use Save as or Download") 

1095 path = os.path.abspath(os.path.expanduser(path)) 

1096 writable_format(path) 

1097 if editor.case.notes and os.path.exists(path) and not data.get("force"): 

1098 return jsonify(error="saving would drop content that ppedit does not edit (" 

1099 + "; ".join(editor.case.notes) + ")",confirm=True),409 

1100 editor.case.save(path) 

1101 editor.case.notes = [] 

1102 editor.path,editor.dirty = path,False 

1103 return jsonify(editor.state()) 

1104 

1105 @app.post("/api/folders") 

1106 def folders(): 

1107 data = body() 

1108 with editor.lock: 

1109 default = os.path.dirname(editor.path) if editor.path else os.getcwd() 

1110 return jsonify(list_folder(data.get("path") or default)) 

1111 

1112 @app.post("/api/folder") 

1113 def folder(): 

1114 data = body() 

1115 path = os.path.abspath(os.path.expanduser(data["path"])) 

1116 if not os.path.isdir(path): 

1117 raise CaseError(f"'{path}' is not a folder") 

1118 with editor.lock: 

1119 name = os.path.basename(editor.path) if editor.path else f"{editor.case.name or 'untitled'}.glm" 

1120 if name.lower().endswith(".raw"): 1120 ↛ 1121line 1120 didn't jump to line 1121 because the condition on line 1120 was never true

1121 name = name[:-4] + ".glm" 

1122 new = os.path.join(path,name) 

1123 if new != editor.path: 

1124 editor.path,editor.dirty = new,True 

1125 return jsonify(editor.state()) 

1126 

1127 @app.get("/api/export") 

1128 def export(): 

1129 fmt = request.args.get("format","py") 

1130 with editor.lock: 

1131 text = editor.case.dumps(fmt) 

1132 name = editor.case.name 

1133 ext = {v:k for k,v in FORMATS.items()}.get(fmt,".csv") 

1134 name = name + "_geodata" if fmt == "csv" else name 

1135 mime = {"json":"application/json","csv":"text/csv"}.get(fmt,"text/plain") 

1136 return Response(text,mimetype=mime,headers={ 

1137 "Content-Disposition":f'attachment; filename="{name}{ext}"'}) 

1138 

1139 def claude_state(): 

1140 with editor.lock: 

1141 out = editor.state() 

1142 out["claude"] = claude.to_dict() 

1143 return jsonify(out) 

1144 

1145 @app.get("/api/claude") 

1146 def claude_list(): 

1147 return jsonify(claude=claude.to_dict()) 

1148 

1149 @app.post("/api/claude/new") 

1150 def claude_new(): 

1151 data = body() 

1152 claude.create(title=str(data.get("title") or ""),model=data.get("model"), 

1153 web=bool(data.get("web")),local=bool(data.get("local")),root=data.get("root") or None, 

1154 agent=data.get("agent") or None,api_key=data.get("api_key") or None, 

1155 api_key_file=data.get("api_key_file") or None) 

1156 return claude_state() 

1157 

1158 @app.post("/api/claude/send") 

1159 def claude_send(): 

1160 data = body() 

1161 claude.get(data["id"]).send(str(data.get("text",""))) 

1162 return claude_state() 

1163 

1164 @app.post("/api/claude/stop") 

1165 def claude_stop(): 

1166 claude.get(body()["id"]).stop() 

1167 return claude_state() 

1168 

1169 @app.post("/api/claude/delete") 

1170 def claude_delete(): 

1171 claude.delete(body()["id"]) 

1172 return claude_state() 

1173 

1174 @app.post("/api/exit") 

1175 def exit_server(): 

1176 _logger.info("exit requested by the editor") 

1177 threading.Timer(0.2,app.config["SHUTDOWN"]).start() 

1178 return jsonify(exit=True) 

1179 

1180 return app