app.go 11 KB

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