interplane.Get Omega
Read in your language

hop

Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.

Brought by drakestapleton

branch main Branches Tags History

hop / Sources / SwarmView.swift

584 lines · 33006 bytes Raw Blame History
1import AppKit
2import SwiftUI
3
4// The Swarm section of the Factory screen: how a group of agents connects and coordinates, read from their
5// shared board. Four views of one snapshot: Overview, Board, Members, Graph. Read-only: nothing here posts,
6// sends or changes a swarm. What each view shows is worked out in SwarmCore; this file only draws it.
7
8enum SwarmLook {
9 static func dotColor(_ m: SwarmMember) -> Color {
10 if m.state == SwarmCore.stateStopped { return Color.secondary.opacity(0.45) }
11 if m.attention == SwarmCore.attentionError || m.attention == SwarmCore.attentionQuota { return .red }
12 if m.attention == SwarmCore.attentionStuck || m.asksYouSeq > 0 { return .orange }
13 return m.state == SwarmCore.stateWorking ? .green : .secondary
14 }
15
16 static func short(_ s: String, _ limit: Int) -> String { s.count > limit ? String(s.prefix(limit - 1)).trimmingCharacters(in: .whitespaces) + "…" : s }
17
18 static func time(_ d: Date) -> String {
19 Calendar.current.isDateInToday(d) ? d.formatted(date: .omitted, time: .shortened)
20 : d.formatted(.dateTime.month(.abbreviated).day().hour().minute())
21 }
22
23 /// "Working", "Waiting for an @mention", "Quiet", "Stopped", with what needs a look added.
24 static func stateLine(_ m: SwarmMember, hasRoster: Bool) -> String {
25 var s: String
26 switch m.state {
27 case SwarmCore.stateWorking: s = "Working"
28 case SwarmCore.stateWaiting:
29 s = !hasRoster ? "Quiet" : m.wake == SwarmCore.wakeMentions ? "Waiting for an @mention" : m.wake == SwarmCore.wakeAnything ? "Waiting for any post" : "Waiting"
30 default: s = "Stopped"
31 }
32 switch m.attention {
33 case SwarmCore.attentionStuck: s += ", no movement for \(max(1, m.idleSeconds / 60)) min"
34 case SwarmCore.attentionError: s += ", last step failed"
35 case SwarmCore.attentionQuota: s += ", out of quota"
36 default: break
37 }
38 return s
39 }
40}
41
42/// Filled when working, hollow when waiting, grey when stopped; orange or red when it needs a look.
43struct SwarmDot: View {
44 let m: SwarmMember
45 var body: some View {
46 let c = SwarmLook.dotColor(m)
47 Group {
48 if m.state == SwarmCore.stateWaiting && m.attention == SwarmCore.attentionNone && m.asksYouSeq == 0 {
49 Circle().strokeBorder(c, lineWidth: 1.5)
50 } else { Circle().fill(c) }
51 }
52 .frame(width: 8, height: 8)
53 .accessibilityLabel(SwarmReader.stateWord(m))
54 }
55}
56
57struct SwarmChip: View {
58 let text: String
59 var tint: Color = .secondary
60 var body: some View {
61 Text(text).font(.caption2.weight(.medium)).lineLimit(1)
62 .padding(.horizontal, 6).padding(.vertical, 2)
63 .background(tint.opacity(0.15), in: Capsule())
64 }
65}
66
67@MainActor
68struct SwarmSectionView: View {
69 @ObservedObject var store: SwarmStore
70 let config: HopConfig
71 @State private var pane = "Overview"
72 @State private var focus: Int? // the post to show on the Board
73
74 var body: some View {
75 VStack(spacing: 0) {
76 header
77 Divider()
78 if let s = store.snapshot {
79 Group {
80 switch pane {
81 case "Board": SwarmBoardView(s: s, focus: $focus)
82 case "Members": SwarmMembersView(s: s, open: openPost)
83 case "Graph": SwarmGraphView(s: s)
84 default: SwarmOverviewView(s: s, open: openPost)
85 }
86 }.frame(maxWidth: .infinity, maxHeight: .infinity)
87 } else {
88 VStack(alignment: .leading, spacing: 8) {
89 Text(store.note.isEmpty ? "Reading…" : store.note).font(.headline)
90 Text("I look for swarms on this Mac in the folders listed under swarmFolders in Settings, and for the factory's board on your factory host. I only read. I never post to a board.")
91 .font(.callout).foregroundStyle(.secondary)
92 Spacer()
93 }.padding(18).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
94 }
95 }
96 .onAppear { store.start(config) }
97 .onDisappear { store.stop() }
98 .onReceive(NotificationCenter.default.publisher(for: NSWindow.didBecomeKeyNotification)) { n in
99 if n.object is HopPanel { store.start(config) }
100 }
101 .onReceive(NotificationCenter.default.publisher(for: NSWindow.didResignKeyNotification)) { n in
102 if let panel = n.object as? HopPanel, NSApp.modalWindow == nil, panel.attachedSheet == nil { store.stop() }
103 }
104 }
105
106 private func openPost(_ seq: Int) { focus = seq; pane = "Board" }
107
108 /// One line: which swarm, which of its four views, and whether the last read worked.
109 private var header: some View {
110 HStack(spacing: 10) {
111 Menu {
112 ForEach(store.sources) { src in
113 Button { store.select(src.id) } label: {
114 Text(verbatim: src.title + " · " + src.place + (src.modified.map { " · " + SwarmLook.time($0) } ?? ""))
115 }
116 }
117 if store.sources.isEmpty { Text("No swarm found") }
118 } label: {
119 Label(SwarmLook.short(store.snapshot?.title ?? store.sources.first { $0.id == store.selectedID }?.title ?? "Swarm", 26),
120 systemImage: "point.3.connected.trianglepath.dotted")
121 }
122 .menuStyle(.borderlessButton).fixedSize()
123 .help(store.snapshot?.title ?? "Choose which swarm to show").accessibilityIdentifier("swarm.source")
124 if let s = store.snapshot {
125 Picker("Swarm view", selection: $pane) {
126 Text("Overview").tag("Overview")
127 Text(verbatim: "Board \(s.posts.count)").tag("Board")
128 Text(verbatim: "Members \(s.members.count)").tag("Members")
129 Text("Graph").tag("Graph")
130 }.pickerStyle(.segmented).labelsHidden().fixedSize().accessibilityIdentifier("swarm.views")
131 }
132 Spacer(minLength: 4)
133 Circle().fill(store.live ? Color.green : Color.orange).frame(width: 7, height: 7)
134 Text(store.live ? "Live" : (store.snapshot == nil ? "Not reading" : "Out of reach" + (store.read.map { ", read " + SwarmLook.time($0) } ?? "")))
135 .font(.caption).foregroundStyle(.secondary).lineLimit(1)
136 .help(store.live ? "I read this swarm again every few seconds while this section is open." : "The last read did not work. What you see is from the read before it.")
137 Button { store.reload() } label: { Image(systemName: "arrow.clockwise") }
138 .buttonStyle(.borderless).help("Read again now").accessibilityIdentifier("swarm.reload")
139 }.padding(.horizontal, 14).padding(.vertical, 7)
140 }
141}
142
143// MARK: Overview
144
145struct SwarmOverviewView: View {
146 let s: SwarmSnapshot
147 let open: (Int) -> Void
148
149 var body: some View {
150 ScrollView {
151 VStack(alignment: .leading, spacing: 14) {
152 Text(verbatim: "\(s.title) · \(s.working) working · \(s.waiting) \(s.hasRoster ? "waiting" : "quiet")" + (s.stopped > 0 ? " · \(s.stopped) stopped" : "")
153 + (s.lastPostTime.map { " · last post " + SwarmLook.time($0) } ?? ""))
154 .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
155 ForEach([SwarmCore.groupNeedsYou, SwarmCore.groupWorking, SwarmCore.groupWaitingOn, SwarmCore.groupParked], id: \.self) { g in
156 let rows = s.overviewOrder.map { s.members[$0] }.filter { $0.group == g }
157 if !rows.isEmpty || g == SwarmCore.groupNeedsYou {
158 VStack(alignment: .leading, spacing: 6) {
159 HStack(spacing: 6) {
160 Text(SwarmReader.groupTitle(g)).font(.subheadline.weight(.semibold))
161 Text(verbatim: "\(rows.count)").font(.caption.monospacedDigit()).foregroundStyle(.secondary)
162 }
163 if rows.isEmpty { Text("Nobody needs you right now.").font(.callout).foregroundStyle(.secondary) }
164 ForEach(rows) { m in row(m) }
165 }
166 }
167 }
168 if !s.notices.isEmpty {
169 VStack(alignment: .leading, spacing: 3) {
170 ForEach(s.notices, id: \.self) { Text($0).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }
171 }
172 }
173 }.padding(14).frame(maxWidth: .infinity, alignment: .leading)
174 }
175 }
176
177 private func row(_ m: SwarmMember) -> some View {
178 let seq = m.asksYouSeq > 0 ? m.asksYouSeq : (m.group == SwarmCore.groupWaitingOn ? m.waitingSeq : m.lastSeq)
179 return HStack(alignment: .firstTextBaseline, spacing: 8) {
180 SwarmDot(m: m).alignmentGuide(.firstTextBaseline) { $0[.bottom] + 1 }
181 VStack(alignment: .leading, spacing: 2) {
182 HStack(spacing: 6) {
183 Text(m.name).font(.callout.weight(.medium)).lineLimit(1)
184 if m.role == "coordinator" { SwarmChip(text: "coordinator", tint: .accentColor) }
185 if m.helper { SwarmChip(text: m.role.isEmpty || m.role == "worker" ? "helper" : m.role) }
186 if m.unread > 0 { SwarmChip(text: "\(m.unread) unread", tint: .orange) }
187 }
188 Text(SwarmReader.reason(m, hasRoster: s.hasRoster)).font(.caption).foregroundStyle(.secondary).lineLimit(2)
189 }
190 Spacer(minLength: 8)
191 if seq > 0 {
192 Button { open(seq) } label: { Text(verbatim: "#\(seq)").font(.caption.monospacedDigit()) }
193 .buttonStyle(.borderless).help("Show this post on the Board")
194 }
195 }
196 }
197}
198
199// MARK: Board
200
201struct SwarmBoardView: View {
202 let s: SwarmSnapshot
203 @Binding var focus: Int?
204 @State private var filter = ""
205 @State private var expanded: Set<Int> = []
206 @State private var flash: Int?
207
208 private var shown: [SwarmPost] {
209 let words = Array(filter.trimmingCharacters(in: .whitespaces).lowercased().utf8)
210 if words.isEmpty { return s.posts }
211 return s.posts.filter { SwarmCore.contains($0.text, words) || SwarmCore.contains(Array($0.sender.utf8), words) }
212 }
213
214 var body: some View {
215 let posts = shown
216 VStack(spacing: 0) {
217 HStack(spacing: 6) {
218 Image(systemName: "line.3.horizontal.decrease").foregroundStyle(.secondary)
219 TextField("Filter posts by a name or by words", text: $filter).textFieldStyle(.plain).font(.callout)
220 .accessibilityIdentifier("swarm.filter")
221 if !filter.isEmpty {
222 Text(verbatim: "\(posts.count) of \(s.posts.count)").font(.caption.monospacedDigit()).foregroundStyle(.secondary)
223 Button("Clear") { filter = "" }.controlSize(.small)
224 }
225 }.padding(.horizontal, 14).padding(.vertical, 6)
226 Divider()
227 if posts.isEmpty {
228 Hint(lines: [s.posts.isEmpty ? "No posts on this board yet." : "No post matches."])
229 } else {
230 ScrollViewReader { proxy in
231 ScrollView {
232 LazyVStack(alignment: .leading, spacing: 0) {
233 ForEach(Array(posts.enumerated()), id: \.element.id) { i, post in
234 let before = i > 0 ? posts[i - 1] : nil
235 SwarmPostRow(post: post, members: s.members,
236 header: post.startsGroup || !filter.isEmpty || before?.to != post.to || before?.all != post.all,
237 expanded: expanded.contains(post.id), flash: flash == post.id,
238 toggle: { if expanded.contains(post.id) { expanded.remove(post.id) } else { expanded.insert(post.id) } })
239 .id(post.id)
240 }
241 }.padding(.horizontal, 8).padding(.vertical, 6)
242 }
243 .onAppear { jump(proxy, to: focus ?? posts.last?.id, mark: focus != nil) }
244 .onChange(of: focus) { _, seq in if seq != nil { jump(proxy, to: seq, mark: true) } }
245 .onChange(of: s.posts.last?.id) { _, last in if focus == nil, filter.isEmpty { jump(proxy, to: last, mark: false) } }
246 }
247 }
248 }
249 // "#12" in a post is a link to post 12 on this board.
250 .environment(\.openURL, OpenURLAction { url in
251 guard url.scheme == "hop-swarm", let seq = Int(url.lastPathComponent) else { return .systemAction }
252 filter = ""; focus = nil
253 DispatchQueue.main.async { focus = seq }
254 return .handled
255 })
256 }
257
258 private func jump(_ proxy: ScrollViewProxy, to seq: Int?, mark: Bool) {
259 guard let seq else { return }
260 // A cited post may be older than what is shown: go to the nearest one after it.
261 guard let target = shown.first(where: { $0.id >= seq })?.id ?? shown.last?.id else { return }
262 DispatchQueue.main.async {
263 proxy.scrollTo(target, anchor: mark ? .center : .bottom)
264 guard mark else { return }
265 flash = target
266 DispatchQueue.main.asyncAfter(deadline: .now() + 1.6) { if flash == target { flash = nil }; if focus == seq { focus = nil } }
267 }
268 }
269}
270
271struct SwarmPostRow: View {
272 let post: SwarmPost
273 let members: [SwarmMember]
274 let header: Bool
275 let expanded: Bool
276 let flash: Bool
277 let toggle: () -> Void
278 static let foldBytes = 700
279
280 /// The post's text with "@name" marked and "#seq" made a link. Cut to `limit` bytes when folded.
281 static func marked(_ post: SwarmPost, limit: Int?) -> AttributedString {
282 let text = limit.map { SwarmCore.clip(post.text, $0) } ?? post.text
283 var out = AttributedString()
284 var at = 0, i = 0
285 func plain(_ from: Int, _ to: Int) -> AttributedString { AttributedString(String(decoding: text[from..<to], as: UTF8.self)) }
286 while i + 3 < post.spans.count {
287 let start = post.spans[i], length = post.spans[i + 1], kind = post.spans[i + 2], value = post.spans[i + 3]
288 i += 4
289 if start < at || start + length > text.count { continue } // a second member behind one "@prefix", or beyond the fold
290 if start > at { out += plain(at, start) }
291 var part = plain(start, start + length)
292 if kind == SwarmCore.spanCite {
293 part.link = URL(string: "hop-swarm://post/\(value)")
294 part.foregroundColor = .accentColor
295 } else {
296 part.backgroundColor = (kind == SwarmCore.spanChannel ? Color.purple : Color.accentColor).opacity(0.18)
297 part.font = .callout.weight(.medium)
298 }
299 out += part
300 at = start + length
301 }
302 if at < text.count { out += plain(at, text.count) }
303 if limit != nil, text.count < post.text.count { out += AttributedString(" …") }
304 return out
305 }
306
307 var body: some View {
308 let long = post.text.count > Self.foldBytes
309 HStack(alignment: .top, spacing: 8) {
310 VStack(alignment: .leading, spacing: 3) {
311 if header {
312 HStack(alignment: .firstTextBaseline, spacing: 6) {
313 Text(post.sender.isEmpty ? "unknown" : post.sender).font(.callout.weight(.semibold)).lineLimit(1)
314 if !post.with.isEmpty { Text(verbatim: "with " + post.with.joined(separator: ", ")).font(.caption).foregroundStyle(.secondary).lineLimit(1) }
315 if post.all || !post.to.isEmpty {
316 Text("→ " + ((post.all ? ["@all"] : []) + post.to.prefix(6).map { "@" + members[$0].name }).joined(separator: " ")
317 + (post.to.count > 6 ? " +\(post.to.count - 6)" : ""))
318 .font(.caption).foregroundStyle(.secondary).lineLimit(1).truncationMode(.tail)
319 }
320 Spacer(minLength: 4)
321 if let t = post.time { Text(SwarmLook.time(t)).font(.caption2).foregroundStyle(.tertiary) }
322 }
323 }
324 Text(Self.marked(post, limit: expanded || !long ? nil : Self.foldBytes))
325 .font(.callout).textSelection(.enabled).lineLimit(expanded ? nil : 9)
326 .frame(maxWidth: .infinity, alignment: .leading)
327 if long {
328 Button(expanded ? "Show less" : "Show more") { toggle() }.buttonStyle(.borderless).font(.caption)
329 }
330 }
331 Text(verbatim: "#\(post.id)").font(.caption2.monospacedDigit()).foregroundStyle(.tertiary).frame(minWidth: 34, alignment: .trailing)
332 }
333 .padding(.horizontal, 8).padding(.top, header ? 7 : 2).padding(.bottom, 3)
334 .background(flash ? Color.accentColor.opacity(0.16) : .clear, in: RoundedRectangle(cornerRadius: 6))
335 .animation(.easeOut(duration: 0.4), value: flash)
336 }
337}
338
339// MARK: Members
340
341struct SwarmMembersView: View {
342 let s: SwarmSnapshot
343 let open: (Int) -> Void
344 @State private var showStopped = false
345
346 var body: some View {
347 let stopped = s.members.filter { $0.state == SwarmCore.stateStopped }.count
348 let rows = s.memberOrder.map { s.members[$0] }.filter { showStopped || $0.state != SwarmCore.stateStopped }
349 VStack(spacing: 0) {
350 if stopped > 0 {
351 HStack {
352 Toggle(isOn: $showStopped) { Text(verbatim: "Show stopped (\(stopped))") }.toggleStyle(.switch).controlSize(.mini)
353 Spacer()
354 }.padding(.horizontal, 14).padding(.vertical, 6)
355 Divider()
356 }
357 if rows.isEmpty { Hint(lines: ["No member to show."]) } else {
358 ScrollView {
359 LazyVStack(alignment: .leading, spacing: 10) { ForEach(rows) { m in row(m) } }
360 .padding(14).frame(maxWidth: .infinity, alignment: .leading)
361 }
362 }
363 }
364 }
365
366 private func facts(_ m: SwarmMember) -> String {
367 var f = [SwarmLook.stateLine(m, hasRoster: s.hasRoster)]
368 if m.steps > 0 { f.append("\(m.steps) steps") }
369 f.append("\(m.posts) \(m.posts == 1 ? "post" : "posts")")
370 if m.unread >= 0 { f.append(m.unread == 0 ? "read to #\(m.lastRead)" : "\(m.unread) unread") }
371 if let t = m.lastPostTime { f.append("last post " + SwarmLook.time(t)) }
372 return f.joined(separator: " · ")
373 }
374
375 private func row(_ m: SwarmMember) -> some View {
376 HStack(alignment: .firstTextBaseline, spacing: 8) {
377 SwarmDot(m: m).alignmentGuide(.firstTextBaseline) { $0[.bottom] + 1 }
378 VStack(alignment: .leading, spacing: 2) {
379 HStack(spacing: 6) {
380 Text(m.name).font(.callout.weight(.medium)).strikethrough(m.state == SwarmCore.stateStopped).lineLimit(1)
381 if !m.role.isEmpty { SwarmChip(text: m.role, tint: m.role == "coordinator" ? .accentColor : .secondary) }
382 if m.helper && (m.role.isEmpty || m.role == "worker") { SwarmChip(text: "helper") }
383 if !m.model.isEmpty { Text(m.model).font(.caption).foregroundStyle(.secondary).lineLimit(1) }
384 if !m.detail.isEmpty { Text(m.detail).font(.caption).foregroundStyle(.secondary).lineLimit(1) }
385 if !m.alsoCalled.isEmpty { Text("also " + m.alsoCalled).font(.caption).foregroundStyle(.tertiary).lineLimit(1) }
386 }
387 Text(facts(m)).font(.caption).foregroundStyle(.secondary).lineLimit(1)
388 if m.state != SwarmCore.stateStopped, !m.activity.isEmpty {
389 Text((m.activityIsLive ? "Now: " : "Last said: ") + m.activity).font(.caption).foregroundStyle(m.activityIsLive ? .primary : .tertiary).lineLimit(1)
390 }
391 if !m.failureText.isEmpty { Text(m.failureText).font(.caption).foregroundStyle(.red).lineLimit(2) }
392 }
393 Spacer(minLength: 8)
394 if m.lastSeq > 0 {
395 Button { open(m.lastSeq) } label: { Text(verbatim: "#\(m.lastSeq)").font(.caption.monospacedDigit()) }
396 .buttonStyle(.borderless).help("Show its newest post on the Board")
397 }
398 }
399 }
400}
401
402// MARK: Graph
403
404struct SwarmGraphView: View {
405 let s: SwarmSnapshot
406 @State private var at = -1 // posts replayed so far; -1 = live, all of them
407 @State private var playing = false
408 @State private var hideInactive = false
409 @State private var showAll = false // draw "@all" posts as dashed lines to everyone
410 @State private var busiestOnly = true // with many members: only the ones with the most lines
411 static let crowd = 24 // more members than this do not fit one readable picture
412
413 private var shown: Int { at < 0 ? s.posts.count : min(at, s.posts.count) }
414
415 var body: some View {
416 let count = shown
417 let current = count > 0 ? s.posts[count - 1] : nil
418 VStack(spacing: 0) {
419 Canvas { ctx, size in draw(&ctx, size, count: count) }
420 .frame(maxWidth: .infinity, maxHeight: .infinity)
421 .accessibilityLabel("Who writes to whom")
422 .help("A line goes from the member who wrote to the member named in the post. A thicker line means more posts.")
423 Divider()
424 VStack(alignment: .leading, spacing: 4) {
425 HStack(spacing: 8) {
426 Button { playing = false; at = max(0, count - 1) } label: { Image(systemName: "backward.frame.fill") }.help("One post back")
427 Button { if !playing && at < 0 { at = 0 }; playing.toggle() } label: { Image(systemName: playing ? "pause.fill" : "play.fill") }
428 .help(playing ? "Pause" : "Replay the board post by post").accessibilityIdentifier("swarm.replay")
429 Button { playing = false; at = count + 1 >= s.posts.count ? -1 : count + 1 } label: { Image(systemName: "forward.frame.fill") }.help("One post forward")
430 Slider(value: Binding(get: { Double(count) }, set: { v in playing = false; at = Int(v) >= s.posts.count ? -1 : Int(v) }),
431 in: 0...Double(max(1, s.posts.count)), step: 1)
432 Button("Live") { playing = false; at = -1 }.disabled(at < 0).help("Back to the newest post")
433 if s.members.filter({ !$0.helper }).count > Self.crowd {
434 Toggle(isOn: $busiestOnly) { Text(verbatim: "Busiest \(Self.crowd) only") }.toggleStyle(.checkbox)
435 .help("Show only the members with the most posts to and from others")
436 }
437 Toggle("Hide inactive", isOn: $hideInactive).toggleStyle(.checkbox)
438 Toggle("Show @all", isOn: $showAll).toggleStyle(.checkbox).help("Draw posts for everyone as dashed lines to each member")
439 }.controlSize(.small).buttonStyle(.borderless)
440 Text(caption(current, count: count)).font(.caption).foregroundStyle(.secondary).lineLimit(1)
441 }.padding(.horizontal, 14).padding(.vertical, 7)
442 }
443 .task(id: playing) {
444 while playing && !Task.isCancelled {
445 try? await Task.sleep(nanoseconds: 600_000_000)
446 guard playing, !Task.isCancelled else { return }
447 if at < 0 || at + 1 >= s.posts.count { at = -1; playing = false } else { at += 1 }
448 }
449 }
450 }
451
452 private func caption(_ p: SwarmPost?, count: Int) -> String {
453 guard let p else { return "No posts yet. A line appears when one member writes to another by name." }
454 let to = (p.all ? ["everyone"] : []) + p.to.prefix(5).map { s.members[$0].name }
455 return (at < 0 ? "Live" : "Post \(count) of \(s.posts.count)") + " · #\(p.id) \(p.sender)" + (to.isEmpty ? " to nobody by name" : " to " + to.joined(separator: ", "))
456 + (p.time.map { " · " + SwarmLook.time($0) } ?? "")
457 }
458
459 private func draw(_ ctx: inout GraphicsContext, _ size: CGSize, count: Int) {
460 let n = s.members.count
461 guard n > 0, size.width > 80, size.height > 60 else { return }
462 let edges = SwarmCore.edges(memberCount: n, helper: s.helper, postSender: s.postSender, postWith: s.postWith,
463 postDirect: s.postDirect, postAll: s.postAll, upTo: count)
464 let everyone = SwarmCore.broadcasts(memberCount: n, postSender: s.postSender, postAll: s.postAll, upTo: count)
465 let current = count > 0 ? count - 1 : -1
466 var touched = [Bool](repeating: false, count: n), now = [Bool](repeating: false, count: n)
467 var e = 0
468 while e + 4 < edges.count {
469 if showAll || edges[e + 3] > 0 { touched[edges[e]] = true; touched[edges[e + 1]] = true }
470 e += 5
471 }
472 if current >= 0 {
473 if s.postSender[current] >= 0 { now[s.postSender[current]] = true }
474 for t in s.postDirect[current] { now[t] = true }
475 }
476 var nodes: [Int] = []
477 for m in s.members where !m.helper {
478 if hideInactive && !now[m.id] && (m.state == SwarmCore.stateStopped || !(touched[m.id] || everyone[m.id] > 0)) { continue }
479 nodes.append(m.id)
480 }
481 if busiestOnly && nodes.count > Self.crowd {
482 let keep = SwarmCore.busiest(memberCount: n, edges: edges, withAll: showAll, keep: Self.crowd)
483 nodes = nodes.filter { now[$0] || ($0 < keep.count && keep[$0] == 1) }
484 }
485 guard !nodes.isEmpty else {
486 ctx.draw(Text("Nobody to show.").font(.callout).foregroundColor(.secondary), at: CGPoint(x: size.width / 2, y: size.height / 2))
487 return
488 }
489 // Each member's name pill, measured first so that no two pills end up on top of each other.
490 func label(_ id: Int) -> GraphicsContext.ResolvedText {
491 let m = s.members[id]
492 let name = Text(verbatim: SwarmLook.short(m.name, 24)).font(.caption.weight(now[id] ? .semibold : .regular))
493 .foregroundColor(m.state == SwarmCore.stateStopped ? .secondary : .primary)
494 let badge = Text(verbatim: !showAll && everyone[id] > 0 ? " @all \(everyone[id])" : "").font(.caption2).foregroundColor(.secondary)
495 return ctx.resolve(Text("\(name)\(badge)"))
496 }
497 var pill = [CGSize](repeating: .zero, count: n)
498 for id in nodes {
499 let t = label(id).measure(in: CGSize(width: 260, height: 40))
500 pill[id] = CGSize(width: t.width + 26, height: t.height + 8)
501 }
502 // Members on an oval, the first one at the top; two or three rings when there are many.
503 var place = [CGPoint](repeating: .zero, count: n), visible = [Bool](repeating: false, count: n)
504 let cx = size.width / 2, cy = size.height / 2
505 let rx = max(40, size.width / 2 - 96), ry = max(30, size.height / 2 - 20)
506 let rings = nodes.count <= 14 ? 1 : (nodes.count <= 32 ? 2 : 3)
507 for (k, id) in nodes.enumerated() {
508 let a: CGFloat = -.pi / 2 + 2 * .pi * CGFloat(k) / CGFloat(nodes.count)
509 let ring: CGFloat = 1 - 0.3 * CGFloat(k % rings)
510 place[id] = CGPoint(x: cx + rx * ring * cos(a), y: cy + ry * ring * sin(a))
511 visible[id] = true
512 }
513 // Pills that still touch are pushed apart, up and down, a few times over; then everything is kept inside the picture.
514 for _ in 0..<10 {
515 var moved = false
516 for (i, a) in nodes.enumerated() {
517 for b in nodes[(i + 1)...] {
518 let overlapX = (pill[a].width + pill[b].width) / 2 + 4 - abs(place[a].x - place[b].x)
519 let overlapY = (pill[a].height + pill[b].height) / 2 + 3 - abs(place[a].y - place[b].y)
520 guard overlapX > 0, overlapY > 0 else { continue }
521 let up = place[a].y < place[b].y || (place[a].y == place[b].y && a < b) ? a : b, down = up == a ? b : a
522 place[up].y -= overlapY / 2; place[down].y += overlapY / 2
523 moved = true
524 }
525 }
526 for id in nodes {
527 place[id].x = min(max(place[id].x, pill[id].width / 2 + 2), size.width - pill[id].width / 2 - 2)
528 place[id].y = min(max(place[id].y, pill[id].height / 2 + 2), size.height - pill[id].height / 2 - 2)
529 }
530 if !moved { break }
531 }
532 var heaviest = 1
533 e = 0
534 while e + 4 < edges.count {
535 let c = showAll ? edges[e + 2] : edges[e + 3]
536 if visible[edges[e]] && visible[edges[e + 1]] && c > heaviest { heaviest = c }
537 e += 5
538 }
539 e = 0
540 while e + 4 < edges.count {
541 let from = edges[e], to = edges[e + 1], direct = edges[e + 3]
542 let c = showAll ? edges[e + 2] : direct
543 e += 5
544 guard c > 0, visible[from], visible[to] else { continue }
545 let step = SwarmCore.weightStep(count: c, heaviest: heaviest)
546 let a = place[from], b = place[to]
547 let dx = b.x - a.x, dy = b.y - a.y, len = max(1, (dx * dx + dy * dy).squareRoot())
548 // Bowed to one side, so "A to B" and "B to A" are two lines.
549 let mid = CGPoint(x: (a.x + b.x) / 2 - dy / len * len * 0.1, y: (a.y + b.y) / 2 + dx / len * len * 0.1)
550 var path = Path(); path.move(to: a); path.addQuadCurve(to: b, control: mid)
551 let live = current >= 0 && s.postSender[current] == from && s.postDirect[current].contains(to)
552 let color = live ? Color.accentColor : Color.primary.opacity(0.16 + 0.07 * Double(step))
553 ctx.stroke(path, with: .color(color), style: StrokeStyle(lineWidth: 0.6 + 0.6 * CGFloat(step), lineCap: .round, dash: direct == 0 ? [3, 4] : []))
554 // An arrow head two thirds of the way along, pointing at the receiver.
555 let t: CGFloat = 0.66
556 let p = CGPoint(x: (1 - t) * (1 - t) * a.x + 2 * (1 - t) * t * mid.x + t * t * b.x, y: (1 - t) * (1 - t) * a.y + 2 * (1 - t) * t * mid.y + t * t * b.y)
557 let tx = 2 * (1 - t) * (mid.x - a.x) + 2 * t * (b.x - mid.x), ty = 2 * (1 - t) * (mid.y - a.y) + 2 * t * (b.y - mid.y), tl = max(1, (tx * tx + ty * ty).squareRoot())
558 let ux = tx / tl, uy = ty / tl, h = 5 + CGFloat(step)
559 var head = Path()
560 head.move(to: CGPoint(x: p.x + ux * h, y: p.y + uy * h))
561 head.addLine(to: CGPoint(x: p.x - ux * h * 0.5 - uy * h * 0.6, y: p.y - uy * h * 0.5 + ux * h * 0.6))
562 head.addLine(to: CGPoint(x: p.x - ux * h * 0.5 + uy * h * 0.6, y: p.y - uy * h * 0.5 - ux * h * 0.6))
563 head.closeSubpath()
564 ctx.fill(head, with: .color(live ? Color.accentColor : Color.primary.opacity(0.4 + 0.08 * Double(step))))
565 if c > 1 && (step >= 3 || nodes.count <= 12) {
566 ctx.draw(Text(verbatim: "\(c)").font(.caption2.monospacedDigit()).foregroundColor(.secondary), at: CGPoint(x: mid.x * 0.5 + (a.x + b.x) * 0.25, y: mid.y * 0.5 + (a.y + b.y) * 0.25 - 7))
567 }
568 }
569 for id in nodes {
570 let m = s.members[id]
571 let label = label(id)
572 let box = CGRect(x: place[id].x - pill[id].width / 2, y: place[id].y - pill[id].height / 2, width: pill[id].width, height: pill[id].height)
573 let shape = Path(roundedRect: box, cornerRadius: box.height / 2)
574 ctx.fill(shape, with: .color(Color(nsColor: .windowBackgroundColor)))
575 ctx.fill(shape, with: .color(now[id] ? Color.accentColor.opacity(0.2) : Color.primary.opacity(0.06)))
576 ctx.stroke(shape, with: .color(now[id] ? Color.accentColor : Color.primary.opacity(0.18)), lineWidth: 1)
577 let dot = CGRect(x: box.minX + 8, y: box.midY - 3.5, width: 7, height: 7)
578 if m.state == SwarmCore.stateWaiting && m.attention == SwarmCore.attentionNone && m.asksYouSeq == 0 {
579 ctx.stroke(Path(ellipseIn: dot.insetBy(dx: 0.75, dy: 0.75)), with: .color(SwarmLook.dotColor(m)), lineWidth: 1.5)
580 } else { ctx.fill(Path(ellipseIn: dot), with: .color(SwarmLook.dotColor(m))) }
581 ctx.draw(label, at: CGPoint(x: box.minX + 20, y: box.midY), anchor: .leading)
582 }
583 }
584}