-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate.go
More file actions
280 lines (236 loc) · 10 KB
/
Copy pathstate.go
File metadata and controls
280 lines (236 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
// ┌──────────────────────────────────────────────────────────────────────┐
// │ state.go — Reactive State Management │
// │ │
// │ ImmyGo provides State[T], a generic thread-safe reactive value. │
// │ When you call state.Set(v), the UI automatically re-renders on │
// │ the next frame. Use state.Get() in your build function to read. │
// │ │
// │ Key rules: │
// │ • State is goroutine-safe (uses sync.RWMutex internally). │
// │ • Calling Set() bumps an internal version counter that ImmyGo │
// │ uses to detect changes. │
// │ • Update(fn) applies a transformation atomically. │
// │ │
// │ For stateful Gio widgets (SideNav, Toggle, Clickable, Editor), │
// │ you MUST store the widget in a package-level var so it persists │
// │ across frames. Creating a new widget every frame destroys the │
// │ click/press state and breaks interactivity. │
// └──────────────────────────────────────────────────────────────────────┘
package main
import (
"gioui.org/layout"
giowidget "gioui.org/widget"
"github.com/amken3d/Pingo/pindata"
"github.com/amken3d/immygo/ai"
"github.com/amken3d/immygo/theme"
"github.com/amken3d/immygo/ui"
"github.com/amken3d/immygo/widget"
)
// ─── Reactive State Variables ─────────────────────────────────────────
//
// ui.NewState[T](initial) creates a reactive value of any type.
// Read with .Get(), write with .Set(v) or .Update(fn).
var (
// boardChoice toggles between Pico (0) and Pico 2 (1).
// Changing this causes the entire UI to re-render with the
// correct board specifications.
boardChoice = ui.NewState(0)
// activeFilter holds the current peripheral category filter
// on the Selector page ("All", "SPI", "I2C", etc.).
activeFilter = ui.NewState("All")
// selections tracks which GPIO pins the user has selected
// and what function they chose for each one.
selections = ui.NewState(map[int]pindata.Function{})
// customNames stores user-defined descriptive names for selected pins.
customNames = ui.NewState(map[int]string{})
// exportStatus holds a message shown after an export operation.
exportStatus = ui.NewState("")
// aiApplyStatus holds the result message from applying AI suggestions.
aiApplyStatus = ui.NewState("")
// selectedPeriphFunc holds the peripheral function being assigned
// (e.g., "SPI0 RX"). Empty string means no function is active.
selectedPeriphFunc = ui.NewState("")
// isDark tracks the current theme mode for the toggle.
isDark = ui.NewState(false)
// AI settings state.
aiProviderChoice = ui.NewState("auto")
aiTemperature = ui.NewState(float32(0.7))
// aiStatus holds a human-readable status string for the AI engine.
// Values: "loading", "ready: <provider>", "error: <message>"
aiStatus = ui.NewState("loading")
)
// Persistent theme toggle widget — must live at package level.
var themeToggle = ui.Toggle(false).OnChange(func(on bool) {
isDark.Set(on)
if on {
themeRefVal.Set(theme.FluentDark())
} else {
themeRefVal.Set(theme.FluentLight())
}
})
// ─── Theme Reference ──────────────────────────────────────────────────
//
// ui.NewThemeRef(initial) creates a *ThemeRefValue that can be passed
// to ui.WithThemeRef(). Calling themeRefVal.Set(newTheme) swaps the
// theme at runtime — all widgets re-render with new colors instantly.
var themeRefVal = ui.NewThemeRef(theme.FluentLight())
// ─── Persistent SideNav Widget ────────────────────────────────────────
//
// IMPORTANT: This is a lower-level widget (widget.NewSideNav), not the
// declarative ui.SideNav(). We store it at package level because Gio's
// Clickable widgets track mouse press/release events across frames.
// If we recreated the SideNav every frame (as ui.SideNav() does),
// the Clickable that received the mouse-down would be discarded before
// the mouse-up, and clicks would never register.
//
// We wrap this in a ui.ViewFunc in layout.go to bridge it into the
// declarative View tree.
var (
currentPage int
sideNav = widget.NewSideNav(
widget.NavItem{Label: "Pinout", Icon: "\u25A0"}, // ■
widget.NavItem{Label: "My Pins", Icon: "\u2611"}, // ☑
widget.NavItem{Label: "Settings", Icon: "\u2699"}, // ⚙
).WithOnSelect(func(i int) { currentPage = i }).WithWidth(180)
)
// ─── AI Engine ────────────────────────────────────────────────────────
//
// ImmyGo's ai package supports multiple providers:
// - Yzma (local in-process LLM via GGUF models — most private)
// - Ollama (local server, e.g. qwen2.5-coder)
// - Anthropic Claude (cloud API via ANTHROPIC_API_KEY)
// - MCP server (external tool integration)
//
// The engine auto-detects available providers at startup.
// ai.NewAssistant wraps an Engine with conversation history management.
// ai.NewChatPanel provides a ready-made chat UI widget.
var (
engine *ai.Engine
assistant *ai.Assistant
chatPanel *ai.ChatPanel
)
func pingoSystemPrompt() string {
return `You are Pingo, an expert assistant for Raspberry Pi Pico and Pico 2 hardware design.
You help users choose the right GPIO pins for their projects.
When asked about pin selection:
- Consider peripheral function conflicts (SPI, I2C, UART share GPIOs)
- Note PWM slice sharing (e.g. GP0 and GP16 share PWM0A)
- Remember ADC is only on GP26-GP28
- All GPIOs are 3.3V, not 5V tolerant
- Suggest optimal pin groupings for common peripherals
Keep answers concise and practical. Use pin names like GP0, GP1, etc.
IMPORTANT: When suggesting specific pin assignments, always include a structured
summary block at the end using this exact format (one per line):
PIN: GP0 -> SPI0 RX
PIN: GP1 -> SPI0 TX
PIN: GP2 -> SPI0 SCK
This allows the app to auto-apply your suggestions.`
}
func initAI() {
cfg := ai.DefaultConfig()
cfg.SystemPrompt = pingoSystemPrompt()
// Apply saved settings to the initial AI config.
cfg.Temperature = aiTemperature.Get()
provider := aiProviderChoice.Get()
if provider != "auto" {
cfg.ProviderConfig.Provider = provider
}
engine = ai.NewEngine(cfg)
assistant = ai.NewAssistant("Pingo", engine)
chatPanel = ai.NewChatPanel(assistant)
aiStatus.Set("loading")
assistant.LoadAsync(func(err error) {
if err != nil {
aiStatus.Set("error: " + err.Error())
} else {
aiStatus.Set("ready: " + engine.ProviderName())
}
})
}
// ─── Per-Pin Name Editors ────────────────────────────────────────────
// Persistent Gio editors for inline custom name editing on My Pins page.
// One per possible GPIO (max 50 covers all board variants).
var pinNameEditors [50]giowidget.Editor
func init() {
for i := range pinNameEditors {
pinNameEditors[i].SingleLine = true
}
}
// ─── Persistent Scroll Lists ─────────────────────────────────────────
// Must persist across frames so scroll position is retained.
var myPinsScrollList = func() *giowidget.List {
l := &giowidget.List{}
l.Axis = layout.Vertical
return l
}()
var assignedPinsScrollList = func() *giowidget.List {
l := &giowidget.List{}
l.Axis = layout.Vertical
return l
}()
var settingsScrollList = func() *giowidget.List {
l := &giowidget.List{}
l.Axis = layout.Vertical
return l
}()
// ─── Board Selector Dropdown ─────────────────────────────────────────
// Persistent dropdown widget for selecting the board/chip variant.
var boardDropdown = ui.Dropdown(
"Pico", "Pico 2", "RP2040", "RP2350A", "RP2350B",
).Placeholder("Board / Chip").OnSelect(func(i int, s string) {
switchBoard(i)
})
// ─── Helpers ──────────────────────────────────────────────────────────
var boardList = []pindata.Board{
pindata.Pico,
pindata.Pico2,
pindata.RP2040Chip,
pindata.RP2350AChip,
pindata.RP2350BChip,
}
func currentSpec() pindata.BoardSpec {
idx := boardChoice.Get()
if idx >= 0 && idx < len(boardList) {
return pindata.GetSpec(boardList[idx])
}
return pindata.GetSpec(pindata.Pico)
}
func switchBoard(idx int) {
if boardChoice.Get() != idx {
boardChoice.Set(idx)
clearAllSelections()
activeFilter.Set("All")
selectedPeriphFunc.Set("")
}
}
// clearAllSelections resets selections, custom names, and editor state.
func clearAllSelections() {
selections.Set(map[int]pindata.Function{})
customNames.Set(map[int]string{})
for i := range pinNameEditors {
pinNameEditors[i].SetText("")
}
exportStatus.Set("")
}
// removePin removes a single pin from selections and custom names.
func removePin(gpio int) {
sel := selections.Get()
updated := make(map[int]pindata.Function, len(sel))
for k, v := range sel {
if k != gpio {
updated[k] = v
}
}
selections.Set(updated)
names := customNames.Get()
if _, ok := names[gpio]; ok {
updatedNames := make(map[int]string, len(names))
for k, v := range names {
if k != gpio {
updatedNames[k] = v
}
}
customNames.Set(updatedNames)
}
pinNameEditors[gpio].SetText("")
}