app.go 13 KB

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