builder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gui
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "github.com/g3n/engine/math32"
  14. "gopkg.in/yaml.v2"
  15. )
  16. // Builder builds GUI objects from a declarative description in YAML format
  17. type Builder struct {
  18. desc map[string]*panelDesc // parsed descriptions
  19. imgpath string // base path for image panels files
  20. }
  21. type panelStyle struct {
  22. Borders string
  23. Paddings string
  24. BorderColor string
  25. BgColor string
  26. FgColor string
  27. }
  28. type panelStyles struct {
  29. Normal panelStyle
  30. Over panelStyle
  31. Focus panelStyle
  32. Pressed panelStyle
  33. Disabled panelStyle
  34. }
  35. type panelDesc struct {
  36. Type string // Gui object type: Panel, Label, Edit, etc ...
  37. Name string // Optional name for identification
  38. Position string // Optional position as: x y | x,y
  39. Width float32 // Optional width (default = 0)
  40. Height float32 // Optional height (default = 0)
  41. AspectWidth *float32 // Optional aspectwidth (default = nil)
  42. AspectHeight *float32 // Optional aspectwidth (default = nil)
  43. Margins string // Optional margins as 1 or 4 float values
  44. Borders string // Optional borders as 1 or 4 float values
  45. BorderColor string // Optional border color as name or 3 or 4 float values
  46. Paddings string // Optional paddings as 1 or 4 float values
  47. Color string // Optional color as 1 or 4 float values
  48. Enabled bool
  49. Visible bool
  50. Renderable bool
  51. Imagefile string // Optional image filepath for ImagePanel
  52. Children []*panelDesc
  53. Layout layoutAttr
  54. Styles *panelStyles
  55. Text string
  56. BgColor string
  57. FontColor string // Optional
  58. FontSize *float32
  59. FontDPI *float32
  60. LineSpacing *float32
  61. PlaceHolder string
  62. MaxLength *uint
  63. }
  64. type layoutAttr struct {
  65. Type string
  66. }
  67. const (
  68. descTypePanel = "Panel"
  69. descTypeImagePanel = "ImagePanel"
  70. descTypeLabel = "Label"
  71. descTypeEdit = "Edit"
  72. fieldMargins = "margins"
  73. fieldBorders = "borders"
  74. fieldBorderColor = "bordercolor"
  75. fieldPaddings = "paddings"
  76. fieldColor = "color"
  77. )
  78. //
  79. // NewBuilder creates and returns a pointer to a new gui Builder object
  80. //
  81. func NewBuilder() *Builder {
  82. return new(Builder)
  83. }
  84. //
  85. // ParseString parses a string with gui objects descriptions in YAML format
  86. // It there was a previously parsed description, it is cleared.
  87. //
  88. func (b *Builder) ParseString(desc string) error {
  89. // Try assuming the description contains a single root panel
  90. var pd panelDesc
  91. err := yaml.Unmarshal([]byte(desc), &pd)
  92. if err != nil {
  93. return err
  94. }
  95. if pd.Type != "" {
  96. b.desc = make(map[string]*panelDesc)
  97. b.desc[""] = &pd
  98. fmt.Printf("\n%+v\n", b.desc)
  99. return nil
  100. }
  101. // Try assuming the description is a map of panels
  102. var pdm map[string]*panelDesc
  103. err = yaml.Unmarshal([]byte(desc), &pdm)
  104. if err != nil {
  105. return err
  106. }
  107. b.desc = pdm
  108. fmt.Printf("\n%+v\n", b.desc)
  109. return nil
  110. }
  111. //
  112. // ParseFile builds gui objects from the specified file which
  113. // must contain objects descriptions in YAML format
  114. //
  115. func (b *Builder) ParseFile(filepath string) error {
  116. // Reads all file data
  117. f, err := os.Open(filepath)
  118. if err != nil {
  119. return err
  120. }
  121. data, err := ioutil.ReadAll(f)
  122. if err != nil {
  123. return err
  124. }
  125. err = f.Close()
  126. if err != nil {
  127. return err
  128. }
  129. // Parses file data
  130. return b.ParseString(string(data))
  131. }
  132. //
  133. // Names returns a sorted list of names of top level previously parsed objects.
  134. // If there is only a single object with no name, its name is returned
  135. // as an empty string
  136. //
  137. func (b *Builder) Names() []string {
  138. var objs []string
  139. for name, _ := range b.desc {
  140. objs = append(objs, name)
  141. }
  142. sort.Strings(objs)
  143. return objs
  144. }
  145. //
  146. // Build builds a gui object and all its children recursively.
  147. // The specified name should be a top level name from a
  148. // from a previously parsed description
  149. // If the descriptions contains a single object with no name,
  150. // It should be specified the empty string to build this object.
  151. //
  152. func (b *Builder) Build(name string) (IPanel, error) {
  153. pd, ok := b.desc[name]
  154. if !ok {
  155. return nil, fmt.Errorf("Object name:%s not found", name)
  156. }
  157. return b.build(pd, nil)
  158. }
  159. // Sets the path for image panels relative image files
  160. func (b *Builder) SetImagepath(path string) {
  161. b.imgpath = path
  162. }
  163. //
  164. // build builds the gui object from the specified description.
  165. // All its children are also built recursively
  166. // Returns the built object or an error
  167. //
  168. func (b *Builder) build(pd *panelDesc, iparent IPanel) (IPanel, error) {
  169. fmt.Printf("\n%+v\n\n", pd)
  170. var err error
  171. var pan IPanel
  172. switch pd.Type {
  173. case descTypePanel:
  174. pan, err = b.buildPanel(pd)
  175. case descTypeImagePanel:
  176. pan, err = b.buildImagePanel(pd)
  177. case descTypeLabel:
  178. pan, err = b.buildLabel(pd)
  179. case descTypeEdit:
  180. pan, err = b.buildEdit(pd)
  181. default:
  182. err = fmt.Errorf("Invalid panel type:%s", pd.Type)
  183. }
  184. if err != nil {
  185. return nil, err
  186. }
  187. if iparent != nil {
  188. iparent.GetPanel().Add(pan)
  189. }
  190. return pan, nil
  191. }
  192. // buildPanel builds a gui object of type: "Panel"
  193. func (b *Builder) buildPanel(pd *panelDesc) (IPanel, error) {
  194. // Builds panel and set common attributes
  195. pan := NewPanel(pd.Width, pd.Height)
  196. err := b.setCommon(pd, pan)
  197. if err != nil {
  198. return nil, err
  199. }
  200. // Builds panel children recursively
  201. for i := 0; i < len(pd.Children); i++ {
  202. child, err := b.build(pd.Children[i], pan)
  203. if err != nil {
  204. return nil, err
  205. }
  206. pan.Add(child)
  207. }
  208. return pan, nil
  209. }
  210. // buildImagePanel builds a gui object of type: "ImagePanel"
  211. func (b *Builder) buildImagePanel(pd *panelDesc) (IPanel, error) {
  212. // Imagefile must be supplied
  213. if pd.Imagefile == "" {
  214. return nil, b.err(pd.Name, "Imagefile", "Imagefile must be supplied")
  215. }
  216. // If path is not absolute join with user supplied image base path
  217. path := pd.Imagefile
  218. if !filepath.IsAbs(path) {
  219. path = filepath.Join(b.imgpath, path)
  220. }
  221. // Builds panel and set common attributes
  222. panel, err := NewImage(path)
  223. if err != nil {
  224. return nil, err
  225. }
  226. err = b.setCommon(pd, panel)
  227. if err != nil {
  228. return nil, err
  229. }
  230. // AspectWidth and AspectHeight attributes
  231. if pd.AspectWidth != nil {
  232. panel.SetContentAspectWidth(*pd.AspectWidth)
  233. }
  234. if pd.AspectHeight != nil {
  235. panel.SetContentAspectHeight(*pd.AspectHeight)
  236. }
  237. // Builds panel children recursively
  238. for i := 0; i < len(pd.Children); i++ {
  239. child, err := b.build(pd.Children[i], panel)
  240. if err != nil {
  241. return nil, err
  242. }
  243. panel.Add(child)
  244. }
  245. return panel, nil
  246. }
  247. func (b *Builder) buildLabel(pd *panelDesc) (IPanel, error) {
  248. // Builds panel and set common attributes
  249. label := NewLabel(pd.Text)
  250. err := b.setCommon(pd, label)
  251. if err != nil {
  252. return nil, err
  253. }
  254. // Set optional background color
  255. c, err := b.parseColor(pd.Name, "bgcolor", pd.BgColor)
  256. if err != nil {
  257. return nil, err
  258. }
  259. if c != nil {
  260. label.SetBgColor4(c)
  261. }
  262. // Set optional font color
  263. c, err = b.parseColor(pd.Name, "fontcolor", pd.FontColor)
  264. if err != nil {
  265. return nil, err
  266. }
  267. if c != nil {
  268. label.SetColor4(c)
  269. }
  270. // Sets optional font size
  271. if pd.FontSize != nil {
  272. label.SetFontSize(float64(*pd.FontSize))
  273. }
  274. // Sets optional font dpi
  275. if pd.FontDPI != nil {
  276. label.SetFontDPI(float64(*pd.FontDPI))
  277. }
  278. // Sets optional line spacing
  279. if pd.LineSpacing != nil {
  280. label.SetLineSpacing(float64(*pd.LineSpacing))
  281. }
  282. return label, nil
  283. }
  284. func (b *Builder) buildEdit(pa *panelDesc) (IPanel, error) {
  285. return nil, nil
  286. }
  287. // setCommon sets the common attributes in the description to the specified panel
  288. func (b *Builder) setCommon(pd *panelDesc, ipan IPanel) error {
  289. // Set optional position
  290. panel := ipan.GetPanel()
  291. if pd.Position != "" {
  292. va, err := b.parseFloats(pd.Name, "position", pd.Position, 2, 2)
  293. if va == nil || err != nil {
  294. return err
  295. }
  296. panel.SetPosition(va[0], va[1])
  297. }
  298. // Set optional margin sizes
  299. bs, err := b.parseBorderSizes(pd.Name, fieldMargins, pd.Margins)
  300. if err != nil {
  301. return err
  302. }
  303. if bs != nil {
  304. panel.SetMarginsFrom(bs)
  305. }
  306. // Set optional border sizes
  307. bs, err = b.parseBorderSizes(pd.Name, fieldBorders, pd.Borders)
  308. if err != nil {
  309. return err
  310. }
  311. if bs != nil {
  312. panel.SetBordersFrom(bs)
  313. }
  314. // Set optional border color
  315. c, err := b.parseColor(pd.Name, fieldBorderColor, pd.BorderColor)
  316. if err != nil {
  317. return err
  318. }
  319. if c != nil {
  320. panel.SetBordersColor4(c)
  321. }
  322. // Set optional paddings sizes
  323. bs, err = b.parseBorderSizes(pd.Name, fieldPaddings, pd.Paddings)
  324. if err != nil {
  325. return err
  326. }
  327. if bs != nil {
  328. panel.SetPaddingsFrom(bs)
  329. }
  330. // Set optional color
  331. c, err = b.parseColor(pd.Name, fieldColor, pd.Color)
  332. if err != nil {
  333. return err
  334. }
  335. if c != nil {
  336. panel.SetColor4(c)
  337. }
  338. return nil
  339. }
  340. // parseBorderSizes parses a string field which can contain one float value or
  341. // float values. In the first case all borders has the same width
  342. func (b *Builder) parseBorderSizes(pname, fname, field string) (*BorderSizes, error) {
  343. va, err := b.parseFloats(pname, fname, field, 1, 4)
  344. if va == nil || err != nil {
  345. return nil, err
  346. }
  347. if len(va) == 1 {
  348. return &BorderSizes{va[0], va[0], va[0], va[0]}, nil
  349. }
  350. return &BorderSizes{va[0], va[1], va[2], va[3]}, nil
  351. }
  352. //
  353. // parseColor parses a string field which can contain a color name or
  354. // a list of 3 or 4 float values for the color components
  355. //
  356. func (b *Builder) parseColor(pname, fname, field string) (*math32.Color4, error) {
  357. // Checks if field is empty
  358. field = strings.Trim(field, " ")
  359. if field == "" {
  360. return nil, nil
  361. }
  362. // Checks if field is a color name
  363. value := math32.ColorUint(field)
  364. if value != 0 {
  365. var c math32.Color
  366. c.SetName(field)
  367. return &math32.Color4{c.R, c.G, c.B, 1}, nil
  368. }
  369. // Accept 3 or 4 floats values
  370. va, err := b.parseFloats(pname, fname, field, 3, 4)
  371. if err != nil {
  372. return nil, err
  373. }
  374. if len(va) == 3 {
  375. return &math32.Color4{va[0], va[1], va[2], 1}, nil
  376. }
  377. return &math32.Color4{va[0], va[1], va[2], va[3]}, nil
  378. }
  379. //
  380. // parseFloats parses a string with a list of floats with the specified size
  381. // and returns a slice. The specified size is 0 any number of floats is allowed.
  382. // The individual values can be separated by spaces or commas
  383. //
  384. func (b *Builder) parseFloats(pname, fname, field string, min, max int) ([]float32, error) {
  385. // Checks if field is empty
  386. field = strings.Trim(field, " ")
  387. if field == "" {
  388. return nil, nil
  389. }
  390. // Separate individual fields
  391. var parts []string
  392. if strings.Index(field, ",") < 0 {
  393. parts = strings.Fields(field)
  394. } else {
  395. parts = strings.Split(field, ",")
  396. }
  397. if len(parts) < min || len(parts) > max {
  398. return nil, b.err(pname, fname, "Invalid number of float32 values")
  399. }
  400. // Parse each field value and appends to slice
  401. var values []float32
  402. for i := 0; i < len(parts); i++ {
  403. val, err := strconv.ParseFloat(strings.Trim(parts[i], " "), 32)
  404. if err != nil {
  405. return nil, fmt.Errorf("Error parsing float32 field:[%s]: %s", field, err)
  406. }
  407. values = append(values, float32(val))
  408. }
  409. return values, nil
  410. }
  411. func (b *Builder) err(pname, fname, msg string) error {
  412. return fmt.Errorf("Error in object:%s field:%s -> %s", pname, fname, msg)
  413. }