File size: 34,318 Bytes
c0a7dd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
"""Scribus as an agentenv computer app, exported by REA from a desktop application capture.

Package: scribus (captured at 1.6.1-0ubuntu7). Capture Evidence: ev_d819eeeffe6b96576a6e675911321db97fd7c68c3aa2179bda8e17c4cc347ecb.
The seed was made for the task, as saved at checkpoint seed.
"""

from __future__ import annotations

import contextlib
import copy
import hashlib
import io
import json
import math
import os
import re
import sqlite3
import struct
import subprocess
import sys
import tempfile
import zipfile
import zlib
from pathlib import Path
from xml.parsers import expat

from agentenv_protocol import add_data, get_data, reset_data
from agentenv_protocol.computer import AptSource, ComputerAppEnvironment, Download, Launch, Packages, Ready, RunScript, computer_app, linux, ready_check
from agentenv_protocol.computer.app_data import INITIAL, add, get, in_thread, keep_initial, reset
from agentenv_protocol.types import DataPart

HERE = Path(__file__).resolve().parent
SEED_HOME = "/home/user"
PATHS = [".config/scribus", "Documents"]
DCONF = ""
TEXT_SEEDS = frozenset([".config/scribus/checkfonts150.xml", "Documents/jazz-night-flyer.sla"])
WINDOW_CLASS = "scribus"

XML_SUFFIXES = (".xml", ".xbel", ".plist", ".svg", ".ui")
GROUP_HEADER = re.compile(r"^\[([^\]]+)\]$")
LINE_BREAK = re.compile(r"\r?\n")
SQLITE_HEADER = b"SQLite format 3\x00"
GVDB_HEADER = b"GVariant"
ZIP_HEADER = b"PK\x03\x04"
XML_SPACE = "xml:space"
MAX_VIEW_BYTES = 64 * 1024 * 1024
MAX_SAFE_INTEGER = 2**53 - 1
MAX_TABLES = 64
MAX_ROWS = 500
MAX_LINES = 5000
MAX_XML_NODES = 5000
MAX_XML_DEPTH = 64
SQLITE_BUSY_S = 0.25
MAX_PARSED_BYTES = 4 * 1024 * 1024
MAX_JSON_VIEW_DEPTH = 500
JSON_TOO_DEEP = f"nested deeper than the {MAX_JSON_VIEW_DEPTH} levels a JSON view keeps"


def _respelled(text: str, home: Path) -> str:
    """The seed's home path respelled to this computer's home, only where a whole path segment ends after it."""
    return re.sub(re.escape(SEED_HOME) + r"(?![\w.@+~-])", lambda _: str(home), text)


def _respelled_utf16(data: bytes, home: Path) -> bytes:
    """A UTF-16 text file with a byte-order mark respelled like a text seed, its mark kept; any other bytes as given."""
    for mark, codec in ((b"\xff\xfe", "utf-16-le"), (b"\xfe\xff", "utf-16-be")):
        if data.startswith(mark):
            try:
                text = data[len(mark):].decode(codec)
            except UnicodeDecodeError:
                return data
            return mark + _respelled(text, home).encode(codec) if SEED_HOME in text else data
    return data


#: What marks a window as not yet the app's own: skipping the taskbar, as splash screens and dialogs do, or a splash type.
SPLASH_MARKS = ("_NET_WM_STATE_SKIP_TASKBAR", "_NET_WM_WINDOW_TYPE_SPLASH")


def _taskbar_window(window_class: str) -> bool:
    """Whether a top-level window of the given class that the taskbar lists is shown; a splash screen or a dialog
    skips the taskbar."""
    def xprop(*args: str) -> str:
        done = subprocess.run(["xprop", *args], capture_output=True, text=True)
        return done.stdout if done.returncode == 0 else ""

    for window in re.findall(r"0x[0-9a-f]+", xprop("-root", "_NET_CLIENT_LIST").partition("#")[2]):
        props = xprop("-id", window, "WM_CLASS", "_NET_WM_STATE", "_NET_WM_WINDOW_TYPE")
        classes = re.findall(r'"((?:[^"\\]|\\.)*)"', props.partition("WM_CLASS")[2].split("\n", 1)[0])
        if window_class in classes and not any(mark in props for mark in SPLASH_MARKS):
            return True
    return False


def _seed_home(home: Path) -> None:
    """Copy the captured files into this computer's home; text files, UTF-16 ones too, have the seed's home path
    respelled."""
    seed = HERE / "seed"
    for source in sorted(seed.rglob("*")) if seed.is_dir() else []:
        if not source.is_file():
            continue
        relative = source.relative_to(seed).as_posix()
        target = home / relative
        target.parent.mkdir(parents=True, exist_ok=True)
        data = source.read_bytes()
        if relative in TEXT_SEEDS:
            data = _respelled(data.decode("utf-8"), home).encode("utf-8")
        else:
            data = _respelled_utf16(data, home)
        target.write_bytes(data)


def _dconf(arguments: list, environment: dict) -> str:
    return subprocess.run(["dconf", *arguments], env={**os.environ, **environment}, capture_output=True, text=True,
                          check=True).stdout


def _load_dconf(home: Path) -> None:
    """Compile the captured dconf keys into the user database without D-Bus, which is not up yet. Keys already there
    stay unless captured: dconf compile reads the key files in name order and a later file wins. A failure is
    reported and the app starts without them."""
    if not DCONF:
        return
    database = home / ".config" / "dconf" / "user"
    try:
        database.parent.mkdir(parents=True, exist_ok=True)
        with tempfile.TemporaryDirectory(dir=database.parent) as scratch:
            keyfiles = Path(scratch, "keyfiles")
            keyfiles.mkdir()
            if database.is_file():
                profile = Path(scratch, "profile")
                profile.write_text(f"file-db:{database}\n")
                existing = _dconf(["dump", "/"], {"DCONF_PROFILE": str(profile)})
                (keyfiles / "00-existing").write_text(existing)
            (keyfiles / "01-captured").write_text(_respelled(DCONF, home))
            _dconf(["compile", str(Path(scratch, "user")), str(keyfiles)], {})
            os.replace(Path(scratch, "user"), database)
    except (OSError, subprocess.CalledProcessError) as error:
        detail = (getattr(error, "stderr", None) or "").strip().splitlines()
        print(f"warning: the captured dconf settings were not loaded: {detail[-1] if detail else error}",
              file=sys.stderr)


def _sqlite_text(data: bytes):
    text = data.decode("utf-8", "replace")
    return {"text": text, "bytes_hex": data.hex()} if "�" in text else text


def _cell(value):
    if isinstance(value, bytes):
        return {"blob_hex": value.hex()}
    if isinstance(value, int) and abs(value) > MAX_SAFE_INTEGER:
        return {"integer": str(value)}
    # JSON has no infinities or negative zero; REA's SQLite reader spells them as strings.
    if isinstance(value, float) and (math.isinf(value) or (value == 0 and math.copysign(1, value) < 0)):
        return "Infinity" if value == math.inf else "-Infinity" if value == -math.inf else "-0"
    return value


def _table(db, name: str, primary_key: list) -> dict:
    quoted = '"' + name.replace('"', '""') + '"'
    cursor = db.execute(f"select * from main.{quoted} not indexed limit {MAX_ROWS + 1}")
    rows = [[_cell(value) for value in row] for row in cursor]
    return {"columns": [column[0] for column in cursor.description], "primary_key": primary_key,
            "rows": rows[:MAX_ROWS], "truncated": len(rows) > MAX_ROWS}


def _sqlite(path: Path) -> dict:
    """The database's ordinary tables, in schema order, up to REA's table and row limits."""
    with contextlib.closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=SQLITE_BUSY_S)) as db:
        kinds = dict(db.execute("select name, type from pragma_table_list where schema = 'main'"))
        names = [name for (name,) in db.execute("select name from sqlite_schema where type = 'table'")
                 if kinds.get(name) == "table"]
        keys = {name: [key for (key,) in db.execute(
            "select name from pragma_table_info(?, 'main') where pk > 0 order by pk", (name,))]
            for name in names[:MAX_TABLES]}
        db.text_factory = _sqlite_text
        tables = {name: _table(db, name, keys[name]) for name in names[:MAX_TABLES]}
    cut = len(names) > MAX_TABLES
    return {"format": "sqlite", "view": {"tables": tables, "tables_truncated": cut},
            "truncated": cut or any(table["truncated"] for table in tables.values())}


def _text(text: str) -> dict:
    lines = LINE_BREAK.split(text)
    if lines[-1] == "":
        lines.pop()
    view = {"lines": lines[:MAX_LINES], "line_count": len(lines), "truncated": len(lines) > MAX_LINES}
    return {"format": "text", "view": view, "truncated": view["truncated"]}


def _keyfile_line(raw: str) -> tuple:
    """A key file line as REA reads it: skip (blank or comment), group, entry or other."""
    line = raw.strip()
    if not line or line[0] in "#;":
        return ("skip",)
    header = GROUP_HEADER.match(line)
    if header:
        return ("group", header.group(1))
    key, equals, value = line.partition("=")
    return ("entry", key.strip(), value.strip()) if equals and key else ("other",)


def _is_keyfile(text: str) -> bool:
    """REA's rule: at least one group, and nothing a key file view would drop."""
    kinds = {_keyfile_line(line)[0] for line in LINE_BREAK.split(text)}
    return "group" in kinds and "other" not in kinds


def _keyfile(text: str) -> dict:
    groups, group = {}, ""
    for line in map(_keyfile_line, LINE_BREAK.split(text)):
        if line[0] == "group":
            group = line[1]
            groups.setdefault(group, {})
        elif line[0] == "entry":
            groups.setdefault(group, {})[line[1]] = line[2]
    return groups


#: XML's whitespace, which alone can be formatting between elements; Unicode's wider set is text.
XML_WHITESPACE = " \t\r\n"
PREDEFINED_ENTITIES = ("amp", "lt", "gt", "apos", "quot")
ENTITY_REFERENCE = re.compile(r"&([^#;][^;]*);")


def _expat(namespaces: bool, doctype=None):
    """An expat parser that reads a DOCTYPE as REA does: one with an internal subset, which could declare entities,
    is refused, the DTD it names is never read, and a reference to an entity other than XML's five is refused where
    expat would skip it. With namespaces it also enforces their rules, as REA's parser does, and without them it
    reports names as the document spells them. doctype, when given, receives the declared name and identifiers."""
    parser = expat.ParserCreate(namespace_separator=" " if namespaces else None)
    parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER)

    def declared(name: str, system_id, public_id, internal_subset: bool) -> None:
        if internal_subset:
            raise ValueError("the document's DOCTYPE has an internal subset")
        if doctype is not None:
            doctype({"name": name, "public_id": public_id, "system_id": system_id})

    def undeclared(name: str, _parameter: bool) -> None:
        raise ValueError(f"the document refers to the undeclared entity {name}")

    def external(*_) -> None:
        raise ValueError("the document refers to an external entity")

    parser.StartDoctypeDeclHandler = declared
    parser.SkippedEntityHandler = undeclared
    parser.ExternalEntityRefHandler = external
    return parser


def _check_tag(markup: str) -> None:
    """expat leaves an undeclared entity out of an attribute value without a word when a DOCTYPE names a DTD; REA's
    parser refuses it. With text taken by its own handler, a start tag is the only markup expat passes here that
    starts with < and a name, and it passes it whole."""
    if markup[:1] == "<" and markup[1:2] not in ("!", "?", "/"):
        for name in ENTITY_REFERENCE.findall(markup):
            if name not in PREDEFINED_ENTITIES:
                raise ValueError(f"the document refers to the undeclared entity {name}")


def _ignore_text(_text: str) -> None:
    pass


class _XmlReader:
    """REA's XML view built as expat reads: names as spelled, declarations as attributes, text split where REA's DOM
    splits it (an empty CDATA section joins the text around it), and each node counted against REA's limits."""

    def __init__(self) -> None:
        self.remaining, self.truncated, self.root, self.doctype = MAX_XML_NODES, False, None, None
        #: Per open element: its view or None when left out, whether xml:space="preserve" applies inside it, whether
        #: it holds an element, and whether it holds text other than whitespace: whitespace-only text is formatting
        #: only in an element that holds elements and no such text.
        self.open = []
        self.text, self.cdata = [], None

    def read(self, text: str) -> None:
        parser = _expat(False, self._doctype)
        parser.buffer_text = True
        parser.StartElementHandler, parser.EndElementHandler = self._start, self._end
        parser.CharacterDataHandler = self._data
        parser.StartCdataSectionHandler, parser.EndCdataSectionHandler = self._cdata_start, self._cdata_end
        parser.CommentHandler = parser.ProcessingInstructionHandler = self._other
        parser.Parse(text, True)

    def _doctype(self, declared: dict) -> None:
        self.doctype = declared

    def _admit(self) -> bool:
        """Whether the next node inside a kept element is kept, within the node and depth limits; one past them
        marks the view truncated."""
        if self.open and self.open[-1][0] is None:
            return False
        if self.remaining <= 0 or len(self.open) > MAX_XML_DEPTH:
            self.truncated = True
            return False
        self.remaining -= 1
        return True

    def _text_node(self, text: str) -> None:
        if self.open and text.strip(XML_WHITESPACE):
            self.open[-1][3] = True
        if self._admit():
            self.open[-1][0]["children"].append(text)

    def _flush(self) -> None:
        if self.text:
            text, self.text = "".join(self.text), []
            self._text_node(text)

    def _data(self, text: str) -> None:
        (self.text if self.cdata is None else self.cdata).append(text)

    def _cdata_start(self) -> None:
        self.cdata = []

    def _cdata_end(self) -> None:
        text, self.cdata = "".join(self.cdata), None
        if text:
            self._flush()
            self._text_node(text)

    def _other(self, *_) -> None:
        """A comment or processing instruction, counted like any node and never kept."""
        self._flush()
        if self.open:
            self._admit()

    def _start(self, name: str, attributes: dict) -> None:
        self._flush()
        parent = self.open[-1] if self.open else [None, False, False, False]
        parent[2] = True
        view = {"name": name, "attributes": attributes, "children": []} if self._admit() else None
        if view is not None and parent[0] is not None:
            parent[0]["children"].append(view)
        space = attributes.get(XML_SPACE)
        self.open.append([view, space == "preserve" if space else parent[1], False, False])

    def _end(self, _name: str) -> None:
        self._flush()
        view, preserve, holds_element, holds_text = self.open.pop()
        if view is not None and holds_element and not holds_text and not preserve:
            view["children"] = [child for child in view["children"]
                                if not isinstance(child, str) or child.strip(XML_WHITESPACE)]
        if not self.open:
            self.root = view


def _xml_view(text: str):
    """REA's XML view, or None for a document REA's parser refuses: a pass with namespaces checks the document as REA's
    parser does, then a pass without them reads names as spelled, as REA's view keeps them, and the DOCTYPE."""
    reader = _XmlReader()
    try:
        check = _expat(True)
        check.CharacterDataHandler, check.DefaultHandler = _ignore_text, _check_tag
        check.Parse(text, True)
        reader.read(text)
    except (expat.ExpatError, ValueError):
        return None
    view = {"root": reader.root, "truncated": reader.truncated}
    return view if reader.doctype is None else {"doctype": reader.doctype, **view}


def _not_json(constant: str):
    raise ValueError(f"{constant} is not JSON")


class _Inexact(Exception):
    """A JSON number that REA's state view refuses, since reading it would change it."""


def _digits(text: str) -> str:
    return re.split(r"[eE]", text.lstrip("-"))[0].replace(".", "").strip("0") or "0"


def _js_string(value: float) -> str:
    """How JavaScript's String() writes a finite double: an integer below 1e21 in full, any other in shortest form."""
    return str(int(value)) if value.is_integer() and abs(value) < 1e21 else repr(value)


def _safe_number(text: str) -> bool:
    """lossless-json's isSafeNumber: an integer spelling within 2^53, or a float spelling that keeps its digits."""
    if re.fullmatch(r"-?[0-9]+", text):
        return len(text.lstrip("-")) <= 16 and abs(int(text)) <= MAX_SAFE_INTEGER
    value = float(text)
    if not math.isfinite(value):
        return False
    written = _js_string(value)
    return written == text or _digits(written) == _digits(text)


def _exact_number(text: str):
    """A JSON number read only when reading it changes nothing, as REA's state view rules: its spelling and its
    written-back form both safe, and not -0."""
    value = float(text)
    if (not _safe_number(text) or not math.isfinite(value) or not _safe_number(_js_string(value))
            or (value == 0 and math.copysign(1, value) < 0)):
        raise _Inexact(text)
    return int(text) if re.fullmatch(r"-?[0-9]+", text) else value


_INEXACT = object()
_LEVEL_END = object()


def _number_or_mark(spelling: str):
    """A JSON number read exactly, or a mark for one REA's state view refuses."""
    try:
        return _exact_number(spelling)
    except _Inexact:
        return _INEXACT


def _holds_inexact(value) -> bool:
    """Whether a parsed JSON value still holds a marked number once duplicate keys kept their last value; one
    iterator per nesting level, so no child list is copied."""
    levels = [iter((value,))]
    while levels:
        item = next(levels[-1], _LEVEL_END)
        if item is _LEVEL_END:
            levels.pop()
        elif item is _INEXACT:
            return True
        elif isinstance(item, dict):
            levels.append(iter(item.values()))
        elif isinstance(item, list):
            levels.append(iter(item))
    return False


def _deeper_than(root, limit: int) -> bool:
    """Whether a parsed JSON value nests deeper than a limit, as REA checks it: a value's depth is the number of
    iterators open above it, one per nesting level, so no child list is copied."""
    levels = [iter((root,))]
    while levels:
        item = next(levels[-1], _LEVEL_END)
        if item is _LEVEL_END:
            levels.pop()
        elif len(levels) - 1 > limit:
            return True
        elif isinstance(item, dict):
            levels.append(iter(item.values()))
        elif isinstance(item, list):
            levels.append(iter(item))
    return False


def _text_view(name: str, text: str) -> dict:
    """The format REA's state view detects for decoded text, and its view."""
    trimmed = re.sub(r"^[\s]+", "", text)
    if name.endswith(".json") or trimmed[:1] in ("[", "{"):
        # The whole text must parse, and duplicate keys settle, before an inexact number makes it JSON with an error.
        try:
            view = json.loads(text, parse_constant=_not_json, parse_float=_number_or_mark, parse_int=_number_or_mark)
        except RecursionError:
            # Nesting too deep for Python to parse is far deeper than REA's view keeps.
            return {"format": "json", "view": None, "error": JSON_TOO_DEEP}
        except ValueError:
            pass
        else:
            if _holds_inexact(view):
                return {"format": "json", "view": None,
                        "error": "a number in it cannot be read exactly, such as an integer above 2^53"}
            if _deeper_than(view, MAX_JSON_VIEW_DEPTH):
                return {"format": "json", "view": None, "error": JSON_TOO_DEEP}
            return {"format": "json", "view": view, "truncated": False}
    lowered = name.lower()
    if lowered.endswith(XML_SUFFIXES) or trimmed.startswith("<?xml"):
        view = _xml_view(text)
        return _text(text) if view is None else {"format": "xml", "view": view, "truncated": view["truncated"]}
    if _is_keyfile(text):
        return {"format": "keyfile", "view": {"groups": _keyfile(text)}, "truncated": False}
    return _text(text)


def _view(path: Path) -> dict:
    """A typed JSON view of one file in the shapes of REA's state view; truncated says the view is partial."""
    too_large = {"format": None, "view": None, "error": "larger than 64 MiB, the most the view reads"}
    if path.stat().st_size > MAX_VIEW_BYTES:
        return too_large
    with path.open("rb") as file:
        data = file.read(8192)
        whole = not data.startswith(SQLITE_HEADER) and b"\x00" not in data
        data += file.read(MAX_VIEW_BYTES + 1 - len(data)) if whole else b""
    if data.startswith(SQLITE_HEADER):
        return _sqlite(path)
    if data.startswith(ZIP_HEADER):
        return _zip(path)
    if len(data) > MAX_VIEW_BYTES:
        return too_large
    try:
        text = data.decode("utf-8-sig") if whole else None
    except UnicodeDecodeError:
        text = None
    return {"format": "binary", "view": None, "truncated": False} if text is None else _text_view(path.name, text)


def _views(home: Path, paths: list) -> dict:
    """A view of every file under the app's paths, keyed by its home-relative path."""
    files = {}
    for owned in paths:
        root = home / owned
        candidates = [root] if root.is_file() else sorted(root.rglob("*")) if root.is_dir() else []
        for path in candidates:
            if path.is_file() and not path.is_symlink():
                key = path.relative_to(home).as_posix()
                try:
                    files[key] = _view(path)
                except (OSError, ValueError, sqlite3.Error, RecursionError) as error:
                    files[key] = {"format": None, "view": None, "error": str(error)}
    return files

MAX_ZIP_ENTRIES = 1000
MAX_ZIP_ENTRY_BYTES = 16 * 1024 * 1024
MAX_ZIP_BYTES = 64 * 1024 * 1024
MAX_ZIP_RATIO = 100
ZIP_READ_CHUNK = 64 * 1024
ZIP_END = b"PK\x05\x06"
ZIP_CENTRAL = b"PK\x01\x02"
ZIP64_LOCATOR = b"PK\x06\x07"
ZIP64_END = b"PK\x06\x06"
#: Formats an archive entry may have whose reader needs a tool, a worker or another archive opened.
NOT_READ_INSIDE = ((SQLITE_HEADER, "sqlite", "a SQLite database"), (GVDB_HEADER, "dconf", "a dconf database"),
                   (ZIP_HEADER, "zip", "an archive"))


def _entry_view(name: str, data: bytes) -> dict:
    """An archive entry's format and view by the rules a file's follow; a database or an archive inside is not
    read."""
    for header, form, inside in NOT_READ_INSIDE:
        if data.startswith(header):
            return {"format": form, "view": None, "error": f"{inside} inside an archive is not read"}
    try:
        text = data.decode("utf-8-sig") if b"\x00" not in data[:8192] else None
    except UnicodeDecodeError:
        text = None
    if text is None:
        return {"format": "binary", "view": None}
    view = _text_view(name, text)
    if view["format"] in ("json", "keyfile") and len(data) > MAX_PARSED_BYTES:
        return {"format": view["format"], "view": None,
                "error": "larger than the 4 MiB limit for JSON and key file views"}
    return view


def _zip_refusal(info, spent: int):
    """Why an entry is not read, checked in REA's order, or None; spent is the archive's bytes read so far."""
    if info.flag_bits & 0x1:
        return "encrypted, so it is not read"
    if info.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):
        return f"compressed with method {info.compress_type}, which the view does not read"
    if info.file_size > MAX_ZIP_ENTRY_BYTES:
        return "larger than the 16 MiB an entry's view reads"
    if info.file_size > MAX_ZIP_RATIO * info.compress_size:
        return f"expands more than {MAX_ZIP_RATIO} times, so it is not read"
    if spent + info.file_size > MAX_ZIP_BYTES:
        return "past the 64 MiB read from one archive"
    return None


def _entry_bytes(archive, info):
    """An entry's uncompressed bytes, or None when they fail its CRC-32 or are not exactly its declared size. Reading
    stops one byte past that size, which data past a short declared size fills, and asks for a bounded chunk at a
    time, which bounds what the decompressor expands per call, so a forged small size holds no more than that."""
    probe = copy.copy(info)
    probe.file_size = info.file_size + 1
    data = bytearray()
    try:
        with archive.open(probe) as member:
            while len(data) <= info.file_size:
                chunk = member.read(min(probe.file_size - len(data), ZIP_READ_CHUNK))
                if not chunk:
                    break
                data += chunk
    except (zipfile.BadZipFile, zlib.error, EOFError, OSError, ValueError):
        return None
    return data if len(data) == info.file_size else None


def _zip_entry(archive, info, refusal):
    """One entry of a zip view: its name, size and digest, and its own format and view, or why it was not read."""
    entry = {"name": info.filename, "size": info.file_size, "sha256": None, "format": None, "view": None,
             "view_error": refusal}
    if refusal is not None:
        return entry
    data = _entry_bytes(archive, info)
    if data is None:
        return {**entry, "view_error": "its compressed data is damaged"}
    view = _entry_view(info.filename, data)
    return {**entry, "sha256": hashlib.sha256(data).hexdigest(), "format": view["format"],
            "view": view.get("view"), "view_error": view.get("error")}


def _zip_end(file, size: int):
    """Where an archive's central directory ends, how long it is and the offset it declares, from the last end
    record whose comment reaches the end of the file and, when a Zip64 locator precedes it whatever that record
    holds, the Zip64 one just before the locator; None without an end record, or when sentinels defer to a
    Zip64 record that is missing."""
    window = min(size, 22 + 0xFFFF)
    file.seek(size - window)
    tail = file.read(window)
    at = tail.rfind(ZIP_END, 0, len(tail) - 18)
    while at >= 0 and at + 22 + int.from_bytes(tail[at + 20:at + 22], "little") != len(tail):
        at = tail.rfind(ZIP_END, 0, at + 3)
    if at < 0:
        return None
    total, length, offset = struct.unpack_from("<HII", tail, at + 10)
    end = size - window + at
    record = end - 20 - 56
    if record < 0:
        return end, length, offset
    file.seek(end - 20)
    if file.read(4) != ZIP64_LOCATOR:
        return end, length, offset
    file.seek(record)
    zip64 = file.read(56)
    if len(zip64) == 56 and zip64[:4] == ZIP64_END:
        length, offset = struct.unpack_from("<QQ", zip64, 40)
        return record, length, offset
    if total == 0xFFFF or 0xFFFFFFFF in (length, offset):
        return None
    return end, length, offset


def _zip_unicode_path(raw: bytes, flags: int, extra: bytes):
    """An Info-ZIP Unicode Path when zip.js uses it: version 1, no UTF-8 flag, and the CRC-32 of the stored name."""
    at = 0
    while at + 4 <= len(extra):
        kind, length = struct.unpack_from("<HH", extra, at)
        if kind == 0x7075:
            data = extra[at + 4:at + 4 + length]
            usable = (length >= 5 and len(data) == length and data[0] == 1 and not flags & 0x800
                      and int.from_bytes(data[1:5], "little") == zlib.crc32(raw))
            return data[5:] if usable else None
        at += 4 + length
    return None


def _zip_ends_in_slash(raw: bytes, flags: int, extra: bytes):
    """Whether an entry's name, as REA decodes it, ends in a slash; None when it must be UTF-8 and is not."""
    utf8 = _zip_unicode_path(raw, flags, extra)
    if utf8 is None and flags & 0x800:
        utf8 = raw
    if utf8 is None:
        return raw.endswith(b"/")
    try:
        return utf8.decode("utf-8").endswith("/")
    except UnicodeDecodeError:
        return None


def _zip_directory(file, size: int, keep: int):
    """An archive's central directory read a record at a time, keeping the first file entries' records, as many as keep allows, and
    counting the rest, as REA reads it: (start, declared offset, records, count), or None when it cannot be read.
    Directories are told apart as zip.js tells them: a final slash, a Unix directory mode, or the MS-DOS attribute."""
    located = _zip_end(file, size)
    if located is None:
        return None
    end, length, declared = located
    start = end - length
    if start < 0:
        return None
    file.seek(start)
    records, count, at = [], 0, start
    while at < end:
        fixed = file.read(46)
        if at + 46 > end or len(fixed) < 46 or fixed[:4] != ZIP_CENTRAL:
            return None
        made_by, flags = struct.unpack_from("<H2xH", fixed, 4)
        name_length, extra_length, comment_length = struct.unpack_from("<HHH", fixed, 28)
        external = struct.unpack_from("<I", fixed, 38)[0]
        rest = file.read(name_length + extra_length + comment_length)
        at += 46 + name_length + extra_length + comment_length
        if len(rest) < name_length + extra_length + comment_length or at > end:
            return None
        slash = _zip_ends_in_slash(rest[:name_length], flags, rest[name_length:name_length + extra_length])
        if slash is None:
            return None
        if not (slash or (external >> 16) & 0o170000 == 0o040000 or (made_by >> 8 == 0 and external & 0x10)):
            count += 1
            if len(records) < keep:
                records.append(fixed + rest)
    return start, declared, records, count


class _BoundedArchive(io.RawIOBase):
    """An archive as zipfile reads it: its entries in place, then a directory of the kept records alone and end
    records for them, so zipfile parses no more records than the view lists."""

    def __init__(self, file, start: int, tail: bytes) -> None:
        super().__init__()
        self._file, self._start, self._tail, self._at = file, start, tail, 0

    def readable(self) -> bool:
        return True

    def seekable(self) -> bool:
        return True

    def tell(self) -> int:
        return self._at

    def seek(self, offset: int, whence: int = 0) -> int:
        self._at = offset + (0, self._at, self._start + len(self._tail))[whence]
        return self._at

    def readinto(self, buffer) -> int:
        view = memoryview(buffer)
        if self._at < self._start:
            self._file.seek(self._at)
            count = self._file.readinto(view[:self._start - self._at])
        else:
            chunk = self._tail[self._at - self._start:self._at - self._start + len(view)]
            count = len(chunk)
            view[:count] = chunk
        self._at += count
        return count


def _zip(path: Path) -> dict:
    """A zip archive's file entries in archive order, up to REA's entry, size, ratio and archive limits; nothing is
    extracted to disk, no archive inside is opened, and zipfile is shown only the directory records listed."""
    entries, spent = [], 0
    try:
        with path.open("rb") as file:
            directory = _zip_directory(file, os.fstat(file.fileno()).st_size, MAX_ZIP_ENTRIES)
            if directory is None:
                raise zipfile.BadZipFile("no readable central directory")
            start, declared, records, count = directory
            kept = b"".join(records)
            offset = declared if declared <= 0xFFFFFFFF else start
            # zipfile follows a Zip64 locator signature wherever one sits before the end record, and the kept records
            # may end in those bytes, so a real Zip64 end record and locator for them come first.
            tail = (kept
                    + struct.pack("<4sQ2H2I4Q", ZIP64_END, 44, 45, 45, 0, 0, len(records), len(records), len(kept), offset)
                    + struct.pack("<4sIQI", ZIP64_LOCATOR, 0, offset + len(kept), 1)
                    + struct.pack("<4s4H2IH", ZIP_END, 0, 0, len(records), len(records), len(kept), offset, 0))
            with zipfile.ZipFile(_BoundedArchive(file, start, tail)) as archive:
                for info in archive.infolist():
                    refusal = _zip_refusal(info, spent)
                    spent += info.file_size if refusal is None else 0
                    entries.append(_zip_entry(archive, info, refusal))
    except (zipfile.BadZipFile, zlib.error, EOFError, NotImplementedError, OSError, ValueError, struct.error):
        return {"format": "zip", "view": None, "error": "not a readable zip archive"}
    view = {"entries": entries, "entry_count": count, "truncated": count > len(entries)}
    return {"format": "zip", "view": view, "truncated": view["truncated"]}


@computer_app(supports=[{"os": {"type": "linux", "display": ["x11"]}, "arch": ["amd64", "arm64"]}])
@linux(
    packages=Packages(apt=["scribus"]),
    launch=Launch(at="boot", command=["sh", "-c", "cd \"$HOME\" 2>/dev/null; exec 'scribus' \"$HOME\"/'Documents/jazz-night-flyer.sla'"], window={"class": "scribus"}, ready=Ready(window=True)),
    paths=PATHS,
    skill="SKILL.md",
)
class Scribus(ComputerAppEnvironment):
    """Scribus, launched at boot with the captured state in its home.

    Declaring data hooks switches off agentenv's default data plane, so these call its helpers: the seed is kept as
    the initial state, reset restores it, add writes files under PATHS, and get returns those files plus a typed JSON
    view of each.
    """

    def __init__(self) -> None:
        super().__init__()
        if not INITIAL.exists():
            _seed_home(Path.home())
            _load_dconf(Path.home())
        keep_initial(self.paths)

    @add_data
    async def add_files(self, parts: list) -> None:
        await add(parts, self.paths)

    @get_data
    async def get_files(self, write_namespace=None) -> list:
        files = await get(self.paths, write_namespace)
        views = await in_thread(_views, Path.home(), self.paths)
        return [*files, DataPart(data={"state": views})]

    @reset_data
    async def reset_files(self) -> None:
        await reset(self.paths)

    @ready_check
    def main_window_shown(self) -> bool:
        """A window of the app's class that the taskbar lists is shown, not only a splash screen or a dialog."""
        return _taskbar_window(WINDOW_CLASS)