project.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // Package project is the mpckit domain model: one MPC Sample project and
  2. // every edit 1.0 makes to it. Edits follow the verified recipes in
  3. // docs/xpj-format-and-scope.md section 3 and change only the fields those
  4. // recipes name; everything else is written back as read.
  5. package project
  6. import (
  7. "bytes"
  8. _ "embed"
  9. "errors"
  10. "fmt"
  11. "path/filepath"
  12. "strings"
  13. "git.monoexp.com/bajdev/mpckit/internal/xpj"
  14. )
  15. //go:embed template/DemoBlank.xpj
  16. var templateXPJ []byte
  17. // Device and format limits.
  18. const (
  19. Pads = 128 // 8 banks x 16
  20. MaxSamples = 128
  21. MaxSequences = 128
  22. PulsesPerBar = 3840 // 4/4 at 960 pulses per beat
  23. FirstNote = 36 // a note event for pad slot n stores note 36 + n
  24. TestedVersion = 28 // data.version of firmware 1.3.0.12
  25. DataSuffix = "_[ProjectData]"
  26. )
  27. // Tuning ranges for 1.0 (format doc, open question 1a).
  28. const (
  29. MinCoarse, MaxCoarse = -24, 24
  30. MinFine, MaxFine = -90, 90
  31. )
  32. // MaxMuteGroup is the highest mute group the UI offers. Not yet confirmed
  33. // on the device (build plan checkpoint A3).
  34. const MaxMuteGroup = 32
  35. // DefaultBPM is used for a new sequence when no sequence has been edited.
  36. const DefaultBPM = 120.0
  37. // Project is one project: the parsed file plus what the file does not hold.
  38. type Project struct {
  39. // Name is the project name: the .xpj file name and data folder prefix.
  40. Name string
  41. // SourceDir is the data folder of a loaded project; empty for a new one.
  42. SourceDir string
  43. // Sources maps each pool file name to the absolute path it is copied
  44. // from at export.
  45. Sources map[string]string
  46. // Dirty is set by every edit.
  47. Dirty bool
  48. file *xpj.File
  49. data *xpj.Node
  50. lastBPM float64 // BPM of the most recently edited sequence; 0 if none
  51. }
  52. var template = mustTemplate()
  53. type tmpl struct {
  54. pad *xpj.Node // one blank pad (all 128 are identical)
  55. sequence *xpj.Node // the blank project's single sequence entry {key, value}
  56. }
  57. func mustTemplate() tmpl {
  58. f, err := xpj.Read(bytes.NewReader(templateXPJ))
  59. if err != nil {
  60. panic("project: embedded template: " + err.Error())
  61. }
  62. d, _ := f.Data()
  63. pad, err := d.Get("tracks[0].program.drum.instruments[0]")
  64. if err != nil {
  65. panic("project: embedded template: " + err.Error())
  66. }
  67. seq, err := d.Get("sequences[0]")
  68. if err != nil {
  69. panic("project: embedded template: " + err.Error())
  70. }
  71. return tmpl{pad: pad, sequence: seq}
  72. }
  73. // New returns a new project built from the blank template.
  74. func New(name string) (*Project, error) {
  75. if err := ValidName(name); err != nil {
  76. return nil, err
  77. }
  78. f, err := xpj.Read(bytes.NewReader(templateXPJ))
  79. if err != nil {
  80. return nil, err
  81. }
  82. return wrap(f, name, "")
  83. }
  84. // Load reads the .xpj at path. The project name is taken from the file name
  85. // and samples are expected in the sibling "<name>_[ProjectData]" folder.
  86. // The returned warnings describe differences from the tested firmware;
  87. // the project is still usable.
  88. func Load(path string) (*Project, []string, error) {
  89. abs, err := filepath.Abs(path)
  90. if err != nil {
  91. return nil, nil, err
  92. }
  93. f, err := xpj.ReadFile(abs)
  94. if err != nil {
  95. return nil, nil, err
  96. }
  97. name := strings.TrimSuffix(filepath.Base(abs), filepath.Ext(abs))
  98. dataDir := filepath.Join(filepath.Dir(abs), name+DataSuffix)
  99. p, err := wrap(f, name, dataDir)
  100. if err != nil {
  101. return nil, nil, err
  102. }
  103. var warnings []string
  104. if f.Header[1] != xpj.TestedHeader[1] {
  105. warnings = append(warnings, fmt.Sprintf("saved by firmware %s; mpckit is tested with %s", f.Header[1], xpj.TestedHeader[1]))
  106. }
  107. if v, err := p.data.Lookup("version").Int(); err != nil || v != TestedVersion {
  108. warnings = append(warnings, fmt.Sprintf("project data version %d; mpckit is tested with %d", v, TestedVersion))
  109. }
  110. for _, e := range p.pool().Items {
  111. file := e.Lookup("path").Text
  112. p.Sources[file] = filepath.Join(dataDir, file)
  113. }
  114. return p, warnings, nil
  115. }
  116. func wrap(f *xpj.File, name, sourceDir string) (*Project, error) {
  117. d, err := f.Data()
  118. if err != nil {
  119. return nil, err
  120. }
  121. p := &Project{Name: name, SourceDir: sourceDir, Sources: map[string]string{}, file: f, data: d}
  122. for _, path := range []string{"samples", "tracks[0].samples", "tracks[0].program.drum.instruments", "sequences"} {
  123. n, err := d.Get(path)
  124. if err != nil {
  125. return nil, fmt.Errorf("project: %w", err)
  126. }
  127. if n.Kind != xpj.Array {
  128. return nil, fmt.Errorf("project: %s is not a list", path)
  129. }
  130. }
  131. if n := len(p.pads().Items); n != Pads {
  132. return nil, fmt.Errorf("project: %d pads, want %d", n, Pads)
  133. }
  134. return p, nil
  135. }
  136. // File returns the project file for writing. Callers must not edit it.
  137. func (p *Project) File() *xpj.File { return p.file }
  138. // SetName renames the project. Nothing inside the file changes.
  139. func (p *Project) SetName(name string) error {
  140. if err := ValidName(name); err != nil {
  141. return err
  142. }
  143. if name != p.Name {
  144. p.Name = name
  145. p.Dirty = true
  146. }
  147. return nil
  148. }
  149. // ValidName checks a project or sequence name: not empty, and free of
  150. // characters that are illegal in file names on Windows or FAT.
  151. func ValidName(name string) error {
  152. if strings.TrimSpace(name) == "" {
  153. return errors.New("name is empty")
  154. }
  155. for _, r := range name {
  156. if r < 0x20 || strings.ContainsRune(`<>:"/\|?*`, r) {
  157. if r < 0x20 {
  158. return errors.New("name contains a control character")
  159. }
  160. return fmt.Errorf("name contains %q, which is not allowed in file names", r)
  161. }
  162. }
  163. if strings.HasSuffix(name, ".") || strings.HasSuffix(name, " ") {
  164. return errors.New("name cannot end with a dot or a space")
  165. }
  166. base := strings.ToUpper(name)
  167. if i := strings.IndexByte(base, '.'); i >= 0 {
  168. base = base[:i]
  169. }
  170. switch base {
  171. case "CON", "PRN", "AUX", "NUL",
  172. "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
  173. "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9":
  174. return fmt.Errorf("%q is a reserved name on Windows", name)
  175. }
  176. return nil
  177. }
  178. // Slot helpers. A slot is 0-127: bank x 16 + pad - 1.
  179. // SlotName returns the pad label for a slot, e.g. 0 -> "A1", 17 -> "B2".
  180. func SlotName(slot int) string {
  181. return fmt.Sprintf("%c%d", 'A'+slot/16, slot%16+1)
  182. }
  183. func checkSlot(slot int) error {
  184. if slot < 0 || slot >= Pads {
  185. return fmt.Errorf("pad slot %d out of range 0-%d", slot, Pads-1)
  186. }
  187. return nil
  188. }
  189. func (p *Project) pads() *xpj.Node {
  190. n, _ := p.data.Get("tracks[0].program.drum.instruments")
  191. return n
  192. }
  193. func (p *Project) pad(slot int) *xpj.Node { return p.pads().Items[slot] }
  194. func layer(pad *xpj.Node) (*xpj.Node, error) {
  195. return pad.Get("layersv[0]")
  196. }
  197. // pool is samples[]; trackPool is tracks[0].samples[]. The device keeps
  198. // the same entries in both, appending to the first and prepending to the
  199. // second.
  200. func (p *Project) pool() *xpj.Node {
  201. n, _ := p.data.Get("samples")
  202. return n
  203. }
  204. func (p *Project) trackPool() *xpj.Node {
  205. n, _ := p.data.Get("tracks[0].samples")
  206. return n
  207. }
  208. func (p *Project) sequences() *xpj.Node {
  209. n, _ := p.data.Get("sequences")
  210. return n
  211. }
  212. // edit applies several Sets and keeps the first error, so an operation can
  213. // list its writes plainly. Paths come from the template; a failure means the
  214. // loaded file has a different shape.
  215. type edit struct{ err error }
  216. func (e *edit) set(n *xpj.Node, path string, v *xpj.Node) {
  217. if e.err == nil {
  218. if err := n.Set(path, v); err != nil {
  219. e.err = fmt.Errorf("project: %w", err)
  220. }
  221. }
  222. }