robotframework-mind 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- robot_mind.py +442 -0
- robot_mind_app/__init__.py +2 -0
- robot_mind_app/__main__.py +105 -0
- robot_mind_app/community_panel.py +106 -0
- robot_mind_app/editors.py +59 -0
- robot_mind_app/engine.py +24 -0
- robot_mind_app/folders.py +52 -0
- robot_mind_app/graph.py +140 -0
- robot_mind_app/graph_layout.py +97 -0
- robot_mind_app/graph_view.py +244 -0
- robot_mind_app/icons.py +141 -0
- robot_mind_app/lucide.py +71 -0
- robot_mind_app/settings.py +84 -0
- robot_mind_app/theme.py +204 -0
- robot_mind_app/widgets.py +157 -0
- robot_mind_app/window.py +621 -0
- robot_mind_app/worker.py +100 -0
- robotframework_mind-0.1.1.dist-info/METADATA +123 -0
- robotframework_mind-0.1.1.dist-info/RECORD +23 -0
- robotframework_mind-0.1.1.dist-info/WHEEL +5 -0
- robotframework_mind-0.1.1.dist-info/entry_points.txt +2 -0
- robotframework_mind-0.1.1.dist-info/licenses/NOTICE +9 -0
- robotframework_mind-0.1.1.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Which editors Open can use on this machine, found without running anything, and the command each stores."""
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import PurePath
|
|
6
|
+
|
|
7
|
+
URL_EDITORS = {"vscode": "VS Code", "cursor": "Cursor"} # open through scheme://file/path:line
|
|
8
|
+
DEFAULT_APP = "default" # the system's app for .robot files, no line jump
|
|
9
|
+
PROGRAMS = ( # (label, install path, arguments)
|
|
10
|
+
("Notepad++", "{pf}/Notepad++/notepad++.exe", "-n{line} {file}"),
|
|
11
|
+
("Sublime Text", "{pf}/Sublime Text/sublime_text.exe", "{file}:{line}"),
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class Editor:
|
|
17
|
+
label: str
|
|
18
|
+
command: str # a URL_EDITORS key, DEFAULT_APP, or a program with {file} and {line}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def has_url_handler(scheme: str) -> bool:
|
|
22
|
+
"""Whether the OS opens scheme:// links: the registry on Windows; assumed elsewhere (VS Code registers it)."""
|
|
23
|
+
if sys.platform != "win32":
|
|
24
|
+
return scheme == "vscode"
|
|
25
|
+
import winreg
|
|
26
|
+
try:
|
|
27
|
+
winreg.CloseKey(winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf"{scheme}\shell\open\command"))
|
|
28
|
+
return True
|
|
29
|
+
except OSError:
|
|
30
|
+
return False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _program_files() -> list[str]:
|
|
34
|
+
return [os.environ[name].replace("\\", "/") for name in ("ProgramFiles", "ProgramFiles(x86)") if name in os.environ]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def available(has_url=has_url_handler, exists=os.path.exists) -> list[Editor]:
|
|
38
|
+
found = [Editor(label, key) for key, label in URL_EDITORS.items() if has_url(key)]
|
|
39
|
+
for label, template, args in PROGRAMS:
|
|
40
|
+
path = next((p for p in (template.format(pf=pf) for pf in _program_files() or ["C:/Program Files"])
|
|
41
|
+
if exists(p)), None)
|
|
42
|
+
if path:
|
|
43
|
+
found.append(Editor(label, f'"{path}" {args}'))
|
|
44
|
+
return found + [Editor("System default app", DEFAULT_APP)]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def program_command(path: str) -> str:
|
|
48
|
+
"""The command for a program picked by hand: it gets the file, there is no common way to pass a line."""
|
|
49
|
+
return f'"{path}" {{file}}'
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def label_for(command: str) -> str:
|
|
53
|
+
if command in URL_EDITORS:
|
|
54
|
+
return URL_EDITORS[command]
|
|
55
|
+
if command == DEFAULT_APP:
|
|
56
|
+
return "System default app"
|
|
57
|
+
program = command.split('"')[1] if command.startswith('"') else command.split()[0]
|
|
58
|
+
known = {PurePath(t).name.lower(): label for label, t, _ in PROGRAMS}
|
|
59
|
+
return known.get(PurePath(program).name.lower(), PurePath(program).name)
|
robot_mind_app/engine.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Adapter from the desktop UI to the robot_mind query facade."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from robot_mind import Entry, Hit, default_cache, find_repos, in_scope, load_index, lookup, to_hits
|
|
5
|
+
from robot_mind_app import graph as _graph
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _entries(root, cache_dir, scope) -> list[Entry]:
|
|
9
|
+
return in_scope(load_index(Path(root), cache_dir or default_cache()), scope)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def query(root, command: str, term: str, cache_dir=None, scope=None) -> list[Hit]:
|
|
13
|
+
"""Hits for one lookup; scope limits it to some folders (posix, relative to root), None means all."""
|
|
14
|
+
return to_hits(lookup(_entries(root, cache_dir, scope), command, term))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def graph(root, command: str, term: str, cache_dir=None, scope=None) -> _graph.Graph:
|
|
18
|
+
entries = _entries(root, cache_dir, scope)
|
|
19
|
+
matches = [entry for entry, _line in lookup(entries, command, term)]
|
|
20
|
+
return _graph.focus(entries, matches)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def repos(root) -> list[str]:
|
|
24
|
+
return find_repos(Path(root))
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""The folder tree for a folder that holds several repos: untick a repo to leave it out of the search."""
|
|
2
|
+
from PySide6.QtCore import Qt
|
|
3
|
+
from PySide6.QtWidgets import QTreeWidget, QTreeWidgetItem, QTreeWidgetItemIterator
|
|
4
|
+
|
|
5
|
+
PATH = Qt.ItemDataRole.UserRole
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class FolderTree(QTreeWidget):
|
|
9
|
+
"""One row per repo, under rows for the folders that group them; long names are cut in the middle."""
|
|
10
|
+
|
|
11
|
+
def __init__(self):
|
|
12
|
+
super().__init__()
|
|
13
|
+
self.setObjectName("folders")
|
|
14
|
+
self.setHeaderHidden(True)
|
|
15
|
+
self.setIndentation(14)
|
|
16
|
+
self.setRootIsDecorated(True)
|
|
17
|
+
self.setTextElideMode(Qt.TextElideMode.ElideMiddle)
|
|
18
|
+
self.setHidden(True)
|
|
19
|
+
|
|
20
|
+
def set_repos(self, repos: list[str]):
|
|
21
|
+
self.clear()
|
|
22
|
+
groups: dict[str, QTreeWidgetItem] = {}
|
|
23
|
+
for repo in repos:
|
|
24
|
+
parent, parts = None, repo.split("/")
|
|
25
|
+
for depth, part in enumerate(parts):
|
|
26
|
+
key = "/".join(parts[: depth + 1])
|
|
27
|
+
if key not in groups:
|
|
28
|
+
groups[key] = self._item(parent, part, key if depth == len(parts) - 1 else None)
|
|
29
|
+
parent = groups[key]
|
|
30
|
+
self.expandAll()
|
|
31
|
+
|
|
32
|
+
def _item(self, parent, text, path):
|
|
33
|
+
item = QTreeWidgetItem([text])
|
|
34
|
+
item.setToolTip(0, path or text)
|
|
35
|
+
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsAutoTristate)
|
|
36
|
+
item.setCheckState(0, Qt.CheckState.Checked)
|
|
37
|
+
item.setData(0, PATH, path)
|
|
38
|
+
(parent.addChild if parent else self.addTopLevelItem)(item)
|
|
39
|
+
return item
|
|
40
|
+
|
|
41
|
+
def scope(self) -> list[str] | None:
|
|
42
|
+
"""The ticked repos, or None when every repo is ticked (search everything, loose files included)."""
|
|
43
|
+
repos, ticked = [], []
|
|
44
|
+
it = QTreeWidgetItemIterator(self)
|
|
45
|
+
while it.value():
|
|
46
|
+
item = it.value()
|
|
47
|
+
if item.data(0, PATH):
|
|
48
|
+
repos.append(item.data(0, PATH))
|
|
49
|
+
if item.checkState(0) == Qt.CheckState.Checked:
|
|
50
|
+
ticked.append(item.data(0, PATH))
|
|
51
|
+
it += 1
|
|
52
|
+
return None if len(ticked) == len(repos) else ticked
|
robot_mind_app/graph.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Build a call/use graph over a Robot Framework repo, focused on a lookup."""
|
|
2
|
+
from collections import defaultdict, deque
|
|
3
|
+
from collections.abc import Iterator
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
|
|
6
|
+
from robot_mind import Entry, norm, var_refs
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True, slots=True)
|
|
10
|
+
class Node:
|
|
11
|
+
id: str
|
|
12
|
+
label: str
|
|
13
|
+
kind: str # test | keyword | var | endpoint
|
|
14
|
+
file: str = ""
|
|
15
|
+
line: int = 0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True)
|
|
19
|
+
class Edge:
|
|
20
|
+
src: str
|
|
21
|
+
dst: str
|
|
22
|
+
kind: str # call | uses | hits
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class Graph:
|
|
27
|
+
nodes: dict[str, Node] = field(default_factory=dict)
|
|
28
|
+
edges: list[Edge] = field(default_factory=list)
|
|
29
|
+
focus: list[str] = field(default_factory=list)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _node_id(entry: Entry) -> str | None:
|
|
33
|
+
if entry.kind == "test":
|
|
34
|
+
return f"test:{entry.file}:{entry.line}"
|
|
35
|
+
if entry.kind == "keyword":
|
|
36
|
+
return f"kw:{norm(entry.name)}"
|
|
37
|
+
if entry.kind == "var":
|
|
38
|
+
refs = var_refs(entry.name)
|
|
39
|
+
return f"var:{refs[0]}" if refs else None
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _endpoints(entry: Entry) -> list[str]:
|
|
44
|
+
"""Endpoints named by op: tags, such as op:GET /api/items."""
|
|
45
|
+
return [tag[3:].strip() for tag in entry.tags if tag.lower().startswith("op:")]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _endpoint_id(endpoint: str) -> str:
|
|
49
|
+
return f"ep:{norm(endpoint)}"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _nodes(entries: list[Entry]) -> dict[str, Node]:
|
|
53
|
+
nodes: dict[str, Node] = {}
|
|
54
|
+
for e in entries:
|
|
55
|
+
nid = _node_id(e)
|
|
56
|
+
if nid is None:
|
|
57
|
+
continue
|
|
58
|
+
nodes.setdefault(nid, Node(nid, e.name, e.kind, e.file, e.line))
|
|
59
|
+
for endpoint in _endpoints(e):
|
|
60
|
+
eid = _endpoint_id(endpoint)
|
|
61
|
+
nodes.setdefault(eid, Node(eid, endpoint, "endpoint"))
|
|
62
|
+
return nodes
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _links(entry: Entry) -> Iterator[tuple[str, str]]:
|
|
66
|
+
"""(target id, edge kind) for every call, variable use and endpoint of an entry."""
|
|
67
|
+
for name, _line in entry.calls:
|
|
68
|
+
yield f"kw:{norm(name)}", "call"
|
|
69
|
+
for ref in entry.refs:
|
|
70
|
+
yield f"var:{ref}", "uses"
|
|
71
|
+
for endpoint in _endpoints(entry):
|
|
72
|
+
yield _endpoint_id(endpoint), "hits"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _edges(entries: list[Entry], nodes: dict[str, Node]) -> list[Edge]:
|
|
76
|
+
"""Edges between known nodes, once each, in index order."""
|
|
77
|
+
edges: dict[Edge, None] = {}
|
|
78
|
+
for e in entries:
|
|
79
|
+
src = _node_id(e)
|
|
80
|
+
if src is None:
|
|
81
|
+
continue
|
|
82
|
+
for dst, kind in _links(e):
|
|
83
|
+
if dst in nodes:
|
|
84
|
+
edges.setdefault(Edge(src, dst, kind))
|
|
85
|
+
return list(edges)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _neighborhood(edges: list[Edge], start: list[str], depth: int) -> set[str]:
|
|
89
|
+
adjacent: dict[str, set[str]] = defaultdict(set)
|
|
90
|
+
for ed in edges:
|
|
91
|
+
adjacent[ed.src].add(ed.dst)
|
|
92
|
+
adjacent[ed.dst].add(ed.src)
|
|
93
|
+
keep, frontier = set(start), set(start)
|
|
94
|
+
for _ in range(depth):
|
|
95
|
+
frontier = {other for node in frontier for other in adjacent[node]} - keep
|
|
96
|
+
keep |= frontier
|
|
97
|
+
return keep
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def focus(entries: list[Entry], matches: list[Entry], depth: int = 1) -> Graph:
|
|
101
|
+
"""The graph within depth links of the matched entries; empty when none is a node."""
|
|
102
|
+
nodes = _nodes(entries)
|
|
103
|
+
start = list(dict.fromkeys(nid for nid in map(_node_id, matches) if nid in nodes))
|
|
104
|
+
if not start:
|
|
105
|
+
return Graph()
|
|
106
|
+
edges = _edges(entries, nodes)
|
|
107
|
+
keep = _neighborhood(edges, start, depth)
|
|
108
|
+
return _subgraph(Graph(nodes, edges, start), keep)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _subgraph(g: Graph, keep: set[str]) -> Graph:
|
|
112
|
+
return Graph({nid: n for nid, n in g.nodes.items() if nid in keep},
|
|
113
|
+
[ed for ed in g.edges if ed.src in keep and ed.dst in keep],
|
|
114
|
+
[nid for nid in g.focus if nid in keep])
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def layers(g: Graph) -> dict[str, int]:
|
|
118
|
+
"""Signed link distance from the focus: callers go negative, what the focus calls or uses positive."""
|
|
119
|
+
steps: dict[str, list[tuple[str, int]]] = defaultdict(list)
|
|
120
|
+
for ed in g.edges:
|
|
121
|
+
steps[ed.src].append((ed.dst, 1))
|
|
122
|
+
steps[ed.dst].append((ed.src, -1))
|
|
123
|
+
layer = dict.fromkeys(g.focus, 0)
|
|
124
|
+
queue = deque(g.focus)
|
|
125
|
+
while queue:
|
|
126
|
+
nid = queue.popleft()
|
|
127
|
+
for other, step in steps[nid]:
|
|
128
|
+
if other not in layer:
|
|
129
|
+
layer[other] = layer[nid] + step
|
|
130
|
+
queue.append(other)
|
|
131
|
+
return layer
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def trim(g: Graph, limit: int) -> Graph:
|
|
135
|
+
"""At most limit nodes, nearest to the focus first; the graph itself when it already fits."""
|
|
136
|
+
if len(g.nodes) <= limit:
|
|
137
|
+
return g
|
|
138
|
+
layer = layers(g)
|
|
139
|
+
nearest = sorted(g.nodes, key=lambda nid: abs(layer[nid]))
|
|
140
|
+
return _subgraph(g, set(nearest[:limit]))
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Where each node goes and which community it joins: a seeded force layout and label propagation, pure Python."""
|
|
2
|
+
import math
|
|
3
|
+
import random
|
|
4
|
+
from collections import Counter, defaultdict
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from .graph import Graph, trim
|
|
8
|
+
|
|
9
|
+
SPACING = 60.0 # px a linked pair settles at, roughly
|
|
10
|
+
ITERATIONS = 160
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True, slots=True)
|
|
14
|
+
class Drawing:
|
|
15
|
+
graph: Graph # what gets drawn, already trimmed
|
|
16
|
+
total: int # nodes before the cap
|
|
17
|
+
pos: dict[str, tuple[float, float]]
|
|
18
|
+
group: dict[str, int] # node id to community, 0 the biggest
|
|
19
|
+
names: list[str] # community name by number
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def neighbors(g: Graph) -> dict[str, set[str]]:
|
|
23
|
+
out: dict[str, set[str]] = defaultdict(set)
|
|
24
|
+
for ed in g.edges:
|
|
25
|
+
if ed.src != ed.dst:
|
|
26
|
+
out[ed.src].add(ed.dst)
|
|
27
|
+
out[ed.dst].add(ed.src)
|
|
28
|
+
return out
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _forces(ids, pos, links, k):
|
|
32
|
+
"""Push every pair apart, pull linked pairs together, and draw everything gently to the centre."""
|
|
33
|
+
disp = {nid: [0.0, 0.0] for nid in ids}
|
|
34
|
+
for i, a in enumerate(ids):
|
|
35
|
+
for b in ids[i + 1:]:
|
|
36
|
+
dx, dy = pos[a][0] - pos[b][0], pos[a][1] - pos[b][1]
|
|
37
|
+
d2 = max(dx * dx + dy * dy, 0.01)
|
|
38
|
+
push = k * k / d2
|
|
39
|
+
disp[a][0] += dx * push; disp[a][1] += dy * push
|
|
40
|
+
disp[b][0] -= dx * push; disp[b][1] -= dy * push
|
|
41
|
+
for a, b in links:
|
|
42
|
+
dx, dy = pos[a][0] - pos[b][0], pos[a][1] - pos[b][1]
|
|
43
|
+
pull = math.hypot(dx, dy) / k
|
|
44
|
+
disp[a][0] -= dx * pull; disp[a][1] -= dy * pull
|
|
45
|
+
disp[b][0] += dx * pull; disp[b][1] += dy * pull
|
|
46
|
+
for nid in ids:
|
|
47
|
+
disp[nid][0] -= pos[nid][0] * 0.05
|
|
48
|
+
disp[nid][1] -= pos[nid][1] * 0.05
|
|
49
|
+
return disp
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def layout(g: Graph, seed: int = 7) -> dict[str, tuple[float, float]]:
|
|
53
|
+
"""Fruchterman-Reingold with a fixed seed, so one search always draws the same picture."""
|
|
54
|
+
ids = list(g.nodes)
|
|
55
|
+
if len(ids) == 1:
|
|
56
|
+
return {ids[0]: (0.0, 0.0)}
|
|
57
|
+
rng = random.Random(seed)
|
|
58
|
+
spread = SPACING * math.sqrt(len(ids))
|
|
59
|
+
pos = {nid: [rng.uniform(-spread, spread), rng.uniform(-spread, spread)] for nid in ids}
|
|
60
|
+
links = [(ed.src, ed.dst) for ed in g.edges if ed.src != ed.dst]
|
|
61
|
+
for step in range(ITERATIONS):
|
|
62
|
+
heat = spread * (1 - step / ITERATIONS) / 4 + 1
|
|
63
|
+
for nid, (dx, dy) in _forces(ids, pos, links, SPACING).items():
|
|
64
|
+
length = math.hypot(dx, dy) or 1.0
|
|
65
|
+
move = min(length, heat) / length
|
|
66
|
+
pos[nid][0] += dx * move
|
|
67
|
+
pos[nid][1] += dy * move
|
|
68
|
+
return {nid: (round(x, 2), round(y, 2)) for nid, (x, y) in pos.items()}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
ENDPOINTS = "endpoints"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def home(file: str, repos: list[str]) -> str:
|
|
75
|
+
"""Where a node lives: its repo when the root holds several, else its top folder; endpoints have no file."""
|
|
76
|
+
if not file:
|
|
77
|
+
return ENDPOINTS
|
|
78
|
+
repo = next((r for r in repos if file.startswith(r.rstrip("/") + "/")), None)
|
|
79
|
+
if repo:
|
|
80
|
+
return repo.rsplit("/", 1)[-1]
|
|
81
|
+
return file.split("/", 1)[0] if "/" in file else "(root)"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def communities(g: Graph, repos: list[str]) -> tuple[dict[str, int], list[str]]:
|
|
85
|
+
"""Node id to community number (0 the biggest) and the community names: one per repo or folder."""
|
|
86
|
+
where = {nid: home(node.file, repos) for nid, node in g.nodes.items()}
|
|
87
|
+
sizes = Counter(where.values())
|
|
88
|
+
names = sorted(sizes, key=lambda name: (-sizes[name], name))
|
|
89
|
+
number = {name: i for i, name in enumerate(names)}
|
|
90
|
+
return {nid: number[name] for nid, name in where.items()}, names
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def plan(g: Graph, limit: int, repos: list[str] = ()) -> Drawing:
|
|
94
|
+
"""Everything the view needs, computed off the UI thread."""
|
|
95
|
+
shown = trim(g, limit)
|
|
96
|
+
group, names = communities(shown, list(repos))
|
|
97
|
+
return Drawing(shown, len(g.nodes), layout(shown), group, names)
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Draws a Drawing as a force-directed cloud of dots coloured by repo or folder, with the list that filters it."""
|
|
2
|
+
from PySide6.QtCore import QPointF, QRectF, QSizeF, Qt, Signal
|
|
3
|
+
from PySide6.QtGui import QColor, QPainter, QPainterPath, QPen
|
|
4
|
+
from PySide6.QtWidgets import (QGraphicsEllipseItem, QGraphicsItem, QGraphicsScene, QGraphicsSimpleTextItem,
|
|
5
|
+
QGraphicsView, QHBoxLayout, QWidget)
|
|
6
|
+
|
|
7
|
+
from robot_mind import strip_controls
|
|
8
|
+
|
|
9
|
+
from .community_panel import CommunityPanel
|
|
10
|
+
from .graph_layout import Drawing, neighbors
|
|
11
|
+
|
|
12
|
+
COLORS = ("#5b7fbf", "#f0a04b", "#e05c5c", "#7cc4b8", "#6ab04c", "#e8c547", "#b585b5", "#f7a1a8", "#a07855",
|
|
13
|
+
"#9aa3ad")
|
|
14
|
+
LABEL_LIMIT = 28 # characters of a label drawn beside its dot
|
|
15
|
+
LABELLED_FOCUS = 12 # more nodes searched for than this: labels only on hover, or they bury the dots
|
|
16
|
+
DIMMED = 0.18 # opacity of dots and links outside a highlighted repo
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def color(group: int) -> QColor:
|
|
20
|
+
return QColor(COLORS[group % len(COLORS)])
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def place(anchor: QPointF, size: QSizeF, radius: float, taken: list[QRectF]) -> QPointF | None:
|
|
24
|
+
"""Where a label goes beside its dot (in screen pixels): right, left, above right, below right, whichever is
|
|
25
|
+
free of the labels already placed; None when all four would overlap. A placed label is added to taken."""
|
|
26
|
+
w, h, gap = size.width(), size.height(), radius + 4
|
|
27
|
+
for dx, dy in ((gap, -h / 2), (-gap - w, -h / 2), (gap, -h - radius), (gap, radius)):
|
|
28
|
+
rect = QRectF(anchor.x() + dx, anchor.y() + dy, w, h)
|
|
29
|
+
if not any(rect.intersects(other) for other in taken):
|
|
30
|
+
taken.append(rect)
|
|
31
|
+
return QPointF(dx, dy)
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def short(text: str) -> str:
|
|
36
|
+
text = strip_controls(text)
|
|
37
|
+
return text if len(text) <= LABEL_LIMIT else text[:LABEL_LIMIT] + "..."
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class NodeItem(QGraphicsEllipseItem):
|
|
41
|
+
"""A dot sized by how linked the node is; the nodes searched for get an accent ring (and a label when few)."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, node, group, view):
|
|
44
|
+
radius = 3.5 + min(view.degree(node.id), 12) * 0.45
|
|
45
|
+
super().__init__(QRectF(-radius, -radius, radius * 2, radius * 2))
|
|
46
|
+
self.node, self.group, self.view = node, group, view
|
|
47
|
+
self.focus = view.is_focus(node.id)
|
|
48
|
+
self.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsSelectable)
|
|
49
|
+
self.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIgnoresTransformations) # same dot size at any zoom
|
|
50
|
+
self.setAcceptHoverEvents(True)
|
|
51
|
+
self.setZValue(2 if self.focus else 1)
|
|
52
|
+
self.label, self.ring = None, QColor(Qt.GlobalColor.white)
|
|
53
|
+
if self.focus and view.labelled:
|
|
54
|
+
self.label = QGraphicsSimpleTextItem(short(node.label), self)
|
|
55
|
+
self.label.setPos(radius + 4, -self.label.boundingRect().height() / 2)
|
|
56
|
+
|
|
57
|
+
def retheme(self, t):
|
|
58
|
+
self.setBrush(color(self.group))
|
|
59
|
+
self.setPen(QPen(QColor(t["accent"]), 2) if self.focus else QPen(Qt.PenStyle.NoPen))
|
|
60
|
+
if self.label:
|
|
61
|
+
self.label.setBrush(QColor(t["ink"]))
|
|
62
|
+
self.ring = QColor(t["ink"])
|
|
63
|
+
|
|
64
|
+
def hoverEnterEvent(self, event):
|
|
65
|
+
self.view.hover(self)
|
|
66
|
+
|
|
67
|
+
def hoverLeaveEvent(self, event):
|
|
68
|
+
self.view.hover(None)
|
|
69
|
+
|
|
70
|
+
def paint(self, painter, option, widget=None):
|
|
71
|
+
painter.setBrush(self.brush())
|
|
72
|
+
painter.setPen(QPen(self.ring, 2.5) if self.isSelected() else self.pen())
|
|
73
|
+
painter.drawEllipse(self.rect())
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Canvas(QGraphicsView):
|
|
77
|
+
"""Pans with a drag, zooms with Ctrl and the wheel; a double click on a dot emits activated(Node)."""
|
|
78
|
+
|
|
79
|
+
activated = Signal(object)
|
|
80
|
+
|
|
81
|
+
def __init__(self):
|
|
82
|
+
super().__init__()
|
|
83
|
+
self.setObjectName("graph")
|
|
84
|
+
self.setScene(QGraphicsScene(self))
|
|
85
|
+
self.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.TextAntialiasing)
|
|
86
|
+
self.setDragMode(QGraphicsView.DragMode.ScrollHandDrag)
|
|
87
|
+
self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)
|
|
88
|
+
self.setViewportUpdateMode(QGraphicsView.ViewportUpdateMode.BoundingRectViewportUpdate)
|
|
89
|
+
|
|
90
|
+
def fit(self):
|
|
91
|
+
"""The whole cloud in view, never zoomed in past 150 percent."""
|
|
92
|
+
self.resetTransform()
|
|
93
|
+
rect = self.scene().itemsBoundingRect().adjusted(-30, -30, 30, 30)
|
|
94
|
+
self.setSceneRect(rect)
|
|
95
|
+
self.fitInView(rect, Qt.AspectRatioMode.KeepAspectRatio)
|
|
96
|
+
if self.transform().m11() > 1.5:
|
|
97
|
+
self.resetTransform()
|
|
98
|
+
self.scale(1.5, 1.5)
|
|
99
|
+
self.centerOn(rect.center())
|
|
100
|
+
|
|
101
|
+
def mouseDoubleClickEvent(self, event):
|
|
102
|
+
item = self.itemAt(event.position().toPoint())
|
|
103
|
+
while item is not None and not isinstance(item, NodeItem):
|
|
104
|
+
item = item.parentItem()
|
|
105
|
+
if item is not None:
|
|
106
|
+
self.scene().clearSelection()
|
|
107
|
+
item.setSelected(True)
|
|
108
|
+
self.activated.emit(item.node)
|
|
109
|
+
|
|
110
|
+
def wheelEvent(self, event):
|
|
111
|
+
if event.modifiers() & Qt.KeyboardModifier.ControlModifier:
|
|
112
|
+
factor = 1.15 if event.angleDelta().y() > 0 else 1 / 1.15
|
|
113
|
+
self.scale(factor, factor)
|
|
114
|
+
else:
|
|
115
|
+
super().wheelEvent(event)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class GraphView(QWidget):
|
|
119
|
+
"""The canvas beside the repos and folders list; a hovered dot names itself and its neighbours."""
|
|
120
|
+
|
|
121
|
+
activated = Signal(object)
|
|
122
|
+
|
|
123
|
+
def __init__(self, theme):
|
|
124
|
+
super().__init__()
|
|
125
|
+
self.t, self.drawing = theme, None
|
|
126
|
+
self.near, self.focus, self.labelled = {}, set(), False
|
|
127
|
+
self.edge_items, self.hover_labels, self.items = [], [], {}
|
|
128
|
+
self.canvas = Canvas()
|
|
129
|
+
self.canvas.activated.connect(self.activated)
|
|
130
|
+
self.panel = CommunityPanel()
|
|
131
|
+
self.panel.shown.connect(self._show_groups)
|
|
132
|
+
self.panel.highlighted.connect(self._highlight)
|
|
133
|
+
row = QHBoxLayout(self)
|
|
134
|
+
row.setContentsMargins(0, 0, 0, 0)
|
|
135
|
+
row.setSpacing(8)
|
|
136
|
+
row.addWidget(self.canvas, 1)
|
|
137
|
+
row.addWidget(self.panel)
|
|
138
|
+
|
|
139
|
+
# what a NodeItem asks its view
|
|
140
|
+
def degree(self, nid):
|
|
141
|
+
return len(self.near[nid])
|
|
142
|
+
|
|
143
|
+
def is_focus(self, nid):
|
|
144
|
+
return nid in self.focus
|
|
145
|
+
|
|
146
|
+
def show_graph(self, drawing: Drawing):
|
|
147
|
+
self.drawing = drawing
|
|
148
|
+
self.near, self.focus = neighbors(drawing.graph), set(drawing.graph.focus)
|
|
149
|
+
self.labelled = len(self.focus) <= LABELLED_FOCUS
|
|
150
|
+
scene = self.canvas.scene()
|
|
151
|
+
scene.clear()
|
|
152
|
+
self.edge_items, self.hover_labels, self.items = [], [], {}
|
|
153
|
+
for nid, node in drawing.graph.nodes.items():
|
|
154
|
+
item = NodeItem(node, drawing.group[nid], self)
|
|
155
|
+
item.setPos(QPointF(*drawing.pos[nid]))
|
|
156
|
+
item.setToolTip(self._tip(node, drawing.names[drawing.group[nid]]))
|
|
157
|
+
scene.addItem(item)
|
|
158
|
+
self.items[nid] = item
|
|
159
|
+
sizes = [list(drawing.group.values()).count(g) for g in range(len(drawing.names))]
|
|
160
|
+
self.panel.fill(drawing.names, sizes, [COLORS[g % len(COLORS)] for g in range(len(drawing.names))])
|
|
161
|
+
self._draw_edges()
|
|
162
|
+
self.retheme(self.t)
|
|
163
|
+
self.canvas.fit()
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _tip(node, home):
|
|
167
|
+
where = f"{node.file}:{node.line}" if node.line else node.file
|
|
168
|
+
return strip_controls("\n".join(p for p in (f"{node.kind}: {node.label}", where, f"in {home}") if p))
|
|
169
|
+
|
|
170
|
+
def hover(self, item):
|
|
171
|
+
"""Names the hovered dot and its neighbours for as long as the pointer stays on it."""
|
|
172
|
+
for label in self.hover_labels:
|
|
173
|
+
self.canvas.scene().removeItem(label)
|
|
174
|
+
self.hover_labels = []
|
|
175
|
+
if item is None:
|
|
176
|
+
return
|
|
177
|
+
taken = [QRectF(self._screen(i) + i.label.pos(), i.label.boundingRect().size())
|
|
178
|
+
for i in self.items.values() if i.label and i.isVisible()]
|
|
179
|
+
others = sorted(self.near[item.node.id], key=lambda nid: self._screen(self.items[nid]).y())
|
|
180
|
+
for nid in [item.node.id, *others]: # the hovered dot gets the first free spot
|
|
181
|
+
other = self.items[nid]
|
|
182
|
+
if other.label is None and other.isVisible():
|
|
183
|
+
label = QGraphicsSimpleTextItem(short(other.node.label), other) # beside its dot, any zoom
|
|
184
|
+
spot = place(self._screen(other), label.boundingRect().size(), other.rect().right(), taken)
|
|
185
|
+
if spot is None: # no free spot: the tooltip still names it
|
|
186
|
+
self.canvas.scene().removeItem(label)
|
|
187
|
+
continue
|
|
188
|
+
label.setBrush(QColor(self.t["ink"]))
|
|
189
|
+
label.setPos(spot)
|
|
190
|
+
self.hover_labels.append(label)
|
|
191
|
+
|
|
192
|
+
def _screen(self, item) -> QPointF:
|
|
193
|
+
return QPointF(self.canvas.mapFromScene(item.pos()))
|
|
194
|
+
|
|
195
|
+
def _show_groups(self, visible):
|
|
196
|
+
for item in self.items.values():
|
|
197
|
+
item.setVisible(item.group in visible)
|
|
198
|
+
self._draw_edges()
|
|
199
|
+
self.retheme(self.t)
|
|
200
|
+
|
|
201
|
+
def _highlight(self, group):
|
|
202
|
+
for item in self.items.values():
|
|
203
|
+
item.setOpacity(1.0 if group in (-1, item.group) else DIMMED)
|
|
204
|
+
for item in self.edge_items:
|
|
205
|
+
item.setOpacity(1.0 if group in (-1, item.data(0)) else DIMMED)
|
|
206
|
+
|
|
207
|
+
def _draw_edges(self):
|
|
208
|
+
"""One path per repo or folder, so a few hundred links stay a handful of items."""
|
|
209
|
+
for item in self.edge_items:
|
|
210
|
+
self.canvas.scene().removeItem(item)
|
|
211
|
+
visible = {nid for nid, item in self.items.items() if item.isVisible()}
|
|
212
|
+
paths: dict[int, QPainterPath] = {}
|
|
213
|
+
d = self.drawing
|
|
214
|
+
for ed in d.graph.edges:
|
|
215
|
+
if ed.src in visible and ed.dst in visible and ed.src != ed.dst:
|
|
216
|
+
path = paths.setdefault(d.group[ed.src], QPainterPath())
|
|
217
|
+
path.moveTo(*d.pos[ed.src])
|
|
218
|
+
path.lineTo(*d.pos[ed.dst])
|
|
219
|
+
self.edge_items = []
|
|
220
|
+
for group, path in paths.items():
|
|
221
|
+
item = self.canvas.scene().addPath(path)
|
|
222
|
+
item.setData(0, group)
|
|
223
|
+
item.setZValue(0)
|
|
224
|
+
self.edge_items.append(item)
|
|
225
|
+
self._highlight(self.panel.current)
|
|
226
|
+
|
|
227
|
+
def retheme(self, theme):
|
|
228
|
+
self.t = theme
|
|
229
|
+
for item in self.items.values():
|
|
230
|
+
item.retheme(theme)
|
|
231
|
+
light = QColor(theme["panel"]).lightness() > 128
|
|
232
|
+
for item in self.edge_items:
|
|
233
|
+
edge = color(item.data(0))
|
|
234
|
+
edge.setAlpha(190 if light else 110) # faint lines vanish on a white card
|
|
235
|
+
pen = QPen(edge, 1)
|
|
236
|
+
pen.setCosmetic(True)
|
|
237
|
+
item.setPen(pen)
|
|
238
|
+
|
|
239
|
+
def node_items(self) -> list[NodeItem]:
|
|
240
|
+
return list(self.items.values())
|
|
241
|
+
|
|
242
|
+
def selected_node(self):
|
|
243
|
+
chosen = [item for item in self.canvas.scene().selectedItems() if isinstance(item, NodeItem)]
|
|
244
|
+
return chosen[0].node if chosen else None
|