1
0

app.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. // Package app is the Wails service the frontend calls. It owns the current
  2. // project and returns a fresh State after every call; the frontend keeps no
  3. // project data of its own (build plan 4.6 and 5).
  4. package app
  5. import (
  6. "crypto/sha256"
  7. "encoding/hex"
  8. "errors"
  9. "fmt"
  10. "path/filepath"
  11. "strings"
  12. "sync"
  13. "git.monoexp.com/bajdev/mpckit/internal/export"
  14. "git.monoexp.com/bajdev/mpckit/internal/project"
  15. )
  16. // Version and Commit are set by production builds (Taskfile.yml) with
  17. // -ldflags "-X git.monoexp.com/bajdev/mpckit/internal/app.Version=0.5.2
  18. // -X git.monoexp.com/bajdev/mpckit/internal/app.Commit=2354f57".
  19. var (
  20. Version = "dev"
  21. Commit = ""
  22. )
  23. // DefaultName is the name of a new project.
  24. const DefaultName = "NewKit"
  25. // Pad is one pad as the frontend shows it.
  26. type Pad struct {
  27. Slot int `json:"slot"`
  28. Label string `json:"label"` // "A1" .. "H16"
  29. Name string `json:"name"` // sample name; empty for an empty pad
  30. File string `json:"file"` // pool file name
  31. Coarse int `json:"coarse"`
  32. Fine int `json:"fine"`
  33. MuteGroup int `json:"muteGroup"`
  34. HasNotes bool `json:"hasNotes"`
  35. // Audio is the URL the preview loads the sample from; empty for an
  36. // empty pad. It changes when the pad's source file changes.
  37. Audio string `json:"audio"`
  38. // Start and End are the slice's first and last frame. The preview
  39. // plays only this region, as the device does.
  40. Start int64 `json:"start"`
  41. End int64 `json:"end"`
  42. // Source is where the sample is copied from at export; Missing is set
  43. // when that file no longer exists.
  44. Source string `json:"source"`
  45. Missing bool `json:"missing"`
  46. }
  47. // Sequence is one existing sequence.
  48. type Sequence struct {
  49. Slot int `json:"slot"`
  50. Label string `json:"label"` // slot label, "A1" .. "H16"
  51. Name string `json:"name"`
  52. BPM float64 `json:"bpm"`
  53. Bars int `json:"bars"`
  54. HasNotes bool `json:"hasNotes"`
  55. }
  56. // Limits are the ranges the UI offers, from the device checks.
  57. type Limits struct {
  58. Pads int `json:"pads"`
  59. MaxSamples int `json:"maxSamples"`
  60. MaxSequences int `json:"maxSequences"`
  61. MinCoarse int `json:"minCoarse"`
  62. MaxCoarse int `json:"maxCoarse"`
  63. MinFine int `json:"minFine"`
  64. MaxFine int `json:"maxFine"`
  65. MaxMuteGroup int `json:"maxMuteGroup"`
  66. MinBPM float64 `json:"minBPM"`
  67. MaxBPM float64 `json:"maxBPM"`
  68. MaxBars int `json:"maxBars"`
  69. }
  70. // State is everything the frontend shows about the project.
  71. type State struct {
  72. Name string `json:"name"`
  73. Dirty bool `json:"dirty"`
  74. Pads []Pad `json:"pads"` // all 128, in slot order
  75. Sequences []Sequence `json:"sequences"` // existing ones, in slot order
  76. SampleCount int `json:"sampleCount"`
  77. MissingCount int `json:"missingCount"` // pool files whose source is missing
  78. SequenceCount int `json:"sequenceCount"`
  79. Limits Limits `json:"limits"`
  80. }
  81. // About is the text for the About dialog.
  82. type About struct {
  83. Version string `json:"version"`
  84. Commit string `json:"commit"` // empty in dev builds
  85. License string `json:"license"`
  86. Repo string `json:"repo"`
  87. }
  88. // LoadResult is what Load returns. Path is empty if the dialog was
  89. // cancelled. Warnings describe differences from the tested firmware.
  90. type LoadResult struct {
  91. Path string `json:"path"`
  92. State State `json:"state"`
  93. Warnings []string `json:"warnings"`
  94. }
  95. // ExportResult is what an export call returns. If Exists is not empty,
  96. // nothing was written: the frontend asks the user, then calls again with
  97. // overwrite set.
  98. type ExportResult struct {
  99. Path string `json:"path"`
  100. Exists []string `json:"exists"`
  101. }
  102. // Dialogs are the native file dialogs. Each returns "" when the user
  103. // cancels. main.go implements them with Wails; tests use a fake.
  104. type Dialogs interface {
  105. OpenWAV() (string, error)
  106. OpenProject() (string, error)
  107. ChooseFolder() (string, error)
  108. SaveZip(defaultName string) (string, error)
  109. }
  110. // Service is registered with Wails; its exported methods become the
  111. // frontend bindings.
  112. type Service struct {
  113. mu sync.Mutex
  114. p *project.Project
  115. dialogs Dialogs
  116. closer func() // closes the window without asking; set by main.go
  117. // Where the next export goes, as chosen in the dialog. The frontend
  118. // never passes a path itself, so a script in the window cannot make
  119. // MPCkit write (or, with overwrite, delete) anywhere else.
  120. exportDir, zipPath string
  121. }
  122. // SetCloser sets what CloseWindow calls.
  123. //
  124. //wails:ignore
  125. func (s *Service) SetCloser(f func()) { s.closer = f }
  126. // Dirty reports whether the project has changes not yet exported.
  127. //
  128. //wails:ignore
  129. func (s *Service) Dirty() bool {
  130. s.mu.Lock()
  131. defer s.mu.Unlock()
  132. return s.p.Dirty()
  133. }
  134. // CloseWindow closes the app without asking about unsaved changes. The
  135. // frontend calls it after the user chose to discard them.
  136. func (s *Service) CloseWindow() {
  137. if s.closer != nil {
  138. s.closer()
  139. }
  140. }
  141. // NewService returns a service holding a new, empty project.
  142. func NewService(d Dialogs) *Service {
  143. s := &Service{dialogs: d}
  144. s.reset()
  145. return s
  146. }
  147. func (s *Service) reset() {
  148. p, err := project.New(DefaultName)
  149. if err != nil {
  150. panic(err) // the embedded template and a constant name
  151. }
  152. s.use(p)
  153. }
  154. // use makes p the current project and forgets the export targets chosen
  155. // for the previous one. Callers hold s.mu.
  156. func (s *Service) use(p *project.Project) {
  157. s.p = p
  158. s.exportDir, s.zipPath = "", ""
  159. }
  160. // New replaces the current project with a new, empty one.
  161. func (s *Service) New() State {
  162. s.mu.Lock()
  163. defer s.mu.Unlock()
  164. s.reset()
  165. return s.state()
  166. }
  167. // State returns the current project's state.
  168. func (s *Service) State() State {
  169. s.mu.Lock()
  170. defer s.mu.Unlock()
  171. return s.state()
  172. }
  173. // Version returns the app version.
  174. func (s *Service) Version() string { return Version }
  175. // About returns the About dialog text.
  176. func (s *Service) About() About {
  177. return About{
  178. Version: Version,
  179. Commit: Commit,
  180. License: "MIT License, copyright (c) 2026 bajdev",
  181. Repo: "https://git.monoexp.com/bajdev/mpckit",
  182. }
  183. }
  184. func (s *Service) state() State {
  185. p := s.p
  186. st := State{
  187. Name: p.Name,
  188. Dirty: p.Dirty(),
  189. Pads: make([]Pad, 0, project.Pads),
  190. Sequences: []Sequence{},
  191. SampleCount: p.SampleCount(),
  192. Limits: Limits{
  193. Pads: project.Pads,
  194. MaxSamples: project.MaxSamples,
  195. MaxSequences: project.MaxSequences,
  196. MinCoarse: project.MinCoarse,
  197. MaxCoarse: project.MaxCoarse,
  198. MinFine: project.MinFine,
  199. MaxFine: project.MaxFine,
  200. MaxMuteGroup: project.MaxMuteGroup,
  201. MinBPM: project.MinBPM,
  202. MaxBPM: project.MaxBPM,
  203. MaxBars: project.MaxBars,
  204. },
  205. }
  206. missing := map[string]bool{} // pool file -> source missing, as export sees it
  207. for _, f := range p.PoolFiles() {
  208. src, _ := p.Source(f)
  209. missing[f] = src == "" || !export.Usable(src)
  210. }
  211. for slot := 0; slot < project.Pads; slot++ {
  212. v, err := p.Pad(slot)
  213. if err != nil {
  214. // A loaded file with an odd pad; show it as empty.
  215. st.Pads = append(st.Pads, Pad{Slot: slot, Label: project.SlotName(slot)})
  216. continue
  217. }
  218. pad := Pad{Slot: slot, Label: project.SlotName(slot), Name: v.SampleName, File: v.File,
  219. Coarse: v.Coarse, Fine: v.Fine, MuteGroup: v.MuteGroup, Start: v.Start, End: v.End}
  220. if !v.Empty() {
  221. pad.HasNotes = p.PadHasNotes(slot)
  222. pad.Source, _ = p.Source(v.File)
  223. pad.Missing = missing[v.File]
  224. if !pad.Missing {
  225. pad.Audio = audioURL(slot, pad.Source)
  226. }
  227. }
  228. st.Pads = append(st.Pads, pad)
  229. }
  230. for _, q := range p.Sequences() {
  231. st.Sequences = append(st.Sequences, Sequence{Slot: q.Slot, Label: project.SlotName(q.Slot),
  232. Name: q.Name, BPM: q.BPM, Bars: q.Bars, HasNotes: q.HasNotes})
  233. }
  234. st.SequenceCount = len(st.Sequences)
  235. for _, m := range missing {
  236. if m {
  237. st.MissingCount++
  238. }
  239. }
  240. return st
  241. }
  242. // audioURL is the preview URL for a pad. The key in the query changes with
  243. // the source file, so the frontend's cache never plays a stale sample.
  244. func audioURL(slot int, src string) string {
  245. sum := sha256.Sum256([]byte(src))
  246. return fmt.Sprintf("%s%d?k=%s", AudioPrefix, slot, hex.EncodeToString(sum[:6]))
  247. }
  248. // edit runs fn on the project under the lock and returns the new state.
  249. // The state is returned even on error, so the frontend stays in step.
  250. func (s *Service) edit(fn func(p *project.Project) error) (State, error) {
  251. s.mu.Lock()
  252. defer s.mu.Unlock()
  253. err := fn(s.p)
  254. return s.state(), err
  255. }
  256. // SetName renames the project.
  257. func (s *Service) SetName(name string) (State, error) {
  258. return s.edit(func(p *project.Project) error { return p.SetName(strings.TrimSpace(name)) })
  259. }
  260. // AssignSampleDialog asks for a WAV file and puts it on the pad in slot.
  261. // Cancelling the dialog changes nothing.
  262. func (s *Service) AssignSampleDialog(slot int) (State, error) {
  263. path, err := s.dialogs.OpenWAV()
  264. if err != nil || path == "" {
  265. return s.State(), err
  266. }
  267. return s.AssignSamplePath(slot, path)
  268. }
  269. // AssignSamplePath puts the WAV at path on the pad in slot. main.go's file
  270. // drop handler uses it; it is not bound, so the window cannot pass a path.
  271. //
  272. //wails:ignore
  273. func (s *Service) AssignSamplePath(slot int, path string) (State, error) {
  274. return s.edit(func(p *project.Project) error { return p.AssignSample(slot, path) })
  275. }
  276. // ClearPad empties the pad in slot.
  277. func (s *Service) ClearPad(slot int) (State, error) {
  278. return s.edit(func(p *project.Project) error { return p.ClearPad(slot) })
  279. }
  280. // SetTune sets a pad's tuning in semitones and cents.
  281. func (s *Service) SetTune(slot, coarse, fine int) (State, error) {
  282. return s.edit(func(p *project.Project) error { return p.SetTune(slot, coarse, fine) })
  283. }
  284. // SetMuteGroup sets a pad's mute group; 0 is off.
  285. func (s *Service) SetMuteGroup(slot, group int) (State, error) {
  286. return s.edit(func(p *project.Project) error { return p.SetMuteGroup(slot, group) })
  287. }
  288. // ChooseExportFolder asks for the folder to export into and remembers it
  289. // for ExportFolder. It returns the folder, or "" if cancelled.
  290. func (s *Service) ChooseExportFolder() (string, error) {
  291. dir, err := s.dialogs.ChooseFolder()
  292. s.mu.Lock()
  293. defer s.mu.Unlock()
  294. s.exportDir = ""
  295. if err == nil {
  296. s.exportDir = dir
  297. }
  298. return dir, err
  299. }
  300. // ChooseZipPath asks where to save the zip and remembers it for ExportZip.
  301. // It returns the path, or "" if cancelled.
  302. func (s *Service) ChooseZipPath() (string, error) {
  303. s.mu.Lock()
  304. name := s.p.Name
  305. s.mu.Unlock()
  306. path, err := s.dialogs.SaveZip(name + ".zip")
  307. if path != "" && !strings.EqualFold(filepath.Ext(path), ".zip") {
  308. path += ".zip"
  309. }
  310. s.mu.Lock()
  311. defer s.mu.Unlock()
  312. s.zipPath = ""
  313. if err == nil {
  314. s.zipPath = path
  315. }
  316. return path, err
  317. }
  318. // errNoTarget is returned by an export with no target chosen.
  319. var errNoTarget = errors.New("choose where to export first")
  320. // ExportFolder writes the project into the folder ChooseExportFolder
  321. // chose. If the project is already there and overwrite is false, nothing
  322. // is written and Exists lists it.
  323. func (s *Service) ExportFolder(overwrite bool) (ExportResult, error) {
  324. s.mu.Lock()
  325. defer s.mu.Unlock()
  326. if s.exportDir == "" {
  327. return ExportResult{}, errNoTarget
  328. }
  329. path, err := export.Folder(s.p, s.exportDir, overwrite)
  330. return s.exported(path, err)
  331. }
  332. // ExportZip writes the project as a zip where ChooseZipPath chose. If the
  333. // file exists and overwrite is false, nothing is written and Exists lists it.
  334. func (s *Service) ExportZip(overwrite bool) (ExportResult, error) {
  335. s.mu.Lock()
  336. defer s.mu.Unlock()
  337. if s.zipPath == "" {
  338. return ExportResult{}, errNoTarget
  339. }
  340. path := s.zipPath
  341. err := export.Zip(s.p, path, overwrite)
  342. return s.exported(path, err)
  343. }
  344. func (s *Service) exported(path string, err error) (ExportResult, error) {
  345. var exists *export.ExistsError
  346. if errors.As(err, &exists) {
  347. return ExportResult{Exists: exists.Paths}, nil
  348. }
  349. if err != nil {
  350. return ExportResult{}, err
  351. }
  352. s.p.MarkExported()
  353. s.exportDir, s.zipPath = "", "" // the next export asks again
  354. return ExportResult{Path: path}, nil
  355. }
  356. // MovePad moves the pad in from to slot to, replacing what was there.
  357. // Recorded notes stay on their slots; the frontend warns first.
  358. func (s *Service) MovePad(from, to int) (State, error) {
  359. return s.edit(func(p *project.Project) error { return p.MovePad(from, to) })
  360. }
  361. // CopyPad copies the pad in from to slot to, replacing what was there.
  362. func (s *Service) CopyPad(from, to int) (State, error) {
  363. return s.edit(func(p *project.Project) error { return p.CopyPad(from, to) })
  364. }
  365. // SwapPads exchanges two pads.
  366. func (s *Service) SwapPads(a, b int) (State, error) {
  367. return s.edit(func(p *project.Project) error { return p.SwapPads(a, b) })
  368. }
  369. // Load asks for a project file and opens it in place of the current one.
  370. // The frontend asks about unsaved changes first.
  371. func (s *Service) Load() (LoadResult, error) {
  372. path, err := s.dialogs.OpenProject()
  373. if err != nil || path == "" {
  374. return LoadResult{State: s.State()}, err
  375. }
  376. return s.LoadPath(path)
  377. }
  378. // LoadPath opens the project at path in place of the current one. Load
  379. // uses it after the dialog; it is not bound, so the window cannot pass a
  380. // path.
  381. //
  382. //wails:ignore
  383. func (s *Service) LoadPath(path string) (LoadResult, error) {
  384. p, warnings, err := project.Load(path)
  385. if err != nil {
  386. return LoadResult{State: s.State()}, fmt.Errorf("%s: %w", filepath.Base(path), err)
  387. }
  388. s.mu.Lock()
  389. defer s.mu.Unlock()
  390. s.use(p)
  391. if warnings == nil {
  392. warnings = []string{}
  393. }
  394. return LoadResult{Path: path, State: s.state(), Warnings: warnings}, nil
  395. }
  396. // AddSequence adds a sequence in an empty slot: "Sequence NN", 2 bars, at
  397. // the BPM of the most recently edited sequence (else 120).
  398. func (s *Service) AddSequence(slot int) (State, error) {
  399. return s.edit(func(p *project.Project) error { return p.AddSequence(slot) })
  400. }
  401. // RemoveSequence deletes a sequence and its recorded notes. The last
  402. // sequence cannot be removed.
  403. func (s *Service) RemoveSequence(slot int) (State, error) {
  404. return s.edit(func(p *project.Project) error { return p.RemoveSequence(slot) })
  405. }
  406. // SetSequence sets a sequence's name, BPM and length in bars. Notes past a
  407. // new, shorter end are left in the file.
  408. func (s *Service) SetSequence(slot int, name string, bpm float64, bars int) (State, error) {
  409. return s.edit(func(p *project.Project) error {
  410. return p.SetSequence(slot, strings.TrimSpace(name), bpm, bars)
  411. })
  412. }