builder.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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/gui/assets/icon"
  14. "github.com/g3n/engine/math32"
  15. "github.com/g3n/engine/window"
  16. "gopkg.in/yaml.v2"
  17. )
  18. // Builder builds GUI objects from a declarative description in YAML format
  19. type Builder struct {
  20. desc map[string]*panelDesc // parsed descriptions
  21. imgpath string // base path for image panels files
  22. objpath strStack // stack of object names being built
  23. }
  24. // descLayout describes all layout types
  25. type descLayout struct {
  26. Type string // HBox, VBox, Dock
  27. Spacing float32
  28. }
  29. // descPanel describes all panel types
  30. type panelDesc struct {
  31. Type string // Gui object type: Panel, Label, Edit, etc ...
  32. Name string // Optional name for identification
  33. Position string // Optional position as: x y | x,y
  34. Width float32 // Optional width (default = 0)
  35. Height float32 // Optional height (default = 0)
  36. AspectWidth *float32 // Optional aspectwidth (default = nil)
  37. AspectHeight *float32 // Optional aspectwidth (default = nil)
  38. Margins string // Optional margins as 1 or 4 float values
  39. Borders string // Optional borders as 1 or 4 float values
  40. BorderColor string // Optional border color as name or 3 or 4 float values
  41. Paddings string // Optional paddings as 1 or 4 float values
  42. Color string // Optional color as 1 or 4 float values
  43. Enabled bool
  44. Visible bool
  45. Renderable bool
  46. Imagefile string // For Panel, Button
  47. Children []*panelDesc // Panel
  48. Layout descLayout
  49. Text string // Label, Button
  50. Icons string // Label
  51. BgColor string // Label
  52. FontColor string // Label
  53. FontSize *float32 // Label
  54. FontDPI *float32 // Label
  55. LineSpacing *float32 // Label
  56. PlaceHolder string // Edit
  57. MaxLength *uint // Edit
  58. Icon string // Button
  59. Group string // RadioButton
  60. ImageLabel *panelDesc // DropDown
  61. Items []*panelDesc // Menu, MenuBar
  62. Shortcut string // Menu
  63. Value *float32 // Slider
  64. ScaleFactor *float32 // Slider
  65. }
  66. const (
  67. descTypePanel = "Panel"
  68. descTypeImagePanel = "ImagePanel"
  69. descTypeLabel = "Label"
  70. descTypeImageLabel = "ImageLabel"
  71. descTypeButton = "Button"
  72. descTypeCheckBox = "CheckBox"
  73. descTypeRadioButton = "RadioButton"
  74. descTypeEdit = "Edit"
  75. descTypeVList = "VList"
  76. descTypeHList = "HList"
  77. descTypeDropDown = "DropDown"
  78. descTypeHSlider = "HSlider"
  79. descTypeVSlider = "VSlider"
  80. descTypeMenuBar = "MenuBar"
  81. descTypeMenu = "Menu"
  82. fieldMargins = "margins"
  83. fieldBorders = "borders"
  84. fieldBorderColor = "bordercolor"
  85. fieldPaddings = "paddings"
  86. fieldColor = "color"
  87. fieldBgColor = "bgcolor"
  88. )
  89. // NewBuilder creates and returns a pointer to a new gui Builder object
  90. func NewBuilder() *Builder {
  91. return new(Builder)
  92. }
  93. // ParseString parses a string with gui objects descriptions in YAML format
  94. // It there was a previously parsed description, it is cleared.
  95. func (b *Builder) ParseString(desc string) error {
  96. // Try assuming the description contains a single root panel
  97. var pd panelDesc
  98. err := yaml.Unmarshal([]byte(desc), &pd)
  99. if err != nil {
  100. return err
  101. }
  102. if pd.Type != "" {
  103. b.desc = make(map[string]*panelDesc)
  104. b.desc[""] = &pd
  105. return nil
  106. }
  107. // Try assuming the description is a map of panels
  108. var pdm map[string]*panelDesc
  109. err = yaml.Unmarshal([]byte(desc), &pdm)
  110. if err != nil {
  111. return err
  112. }
  113. b.desc = pdm
  114. return nil
  115. }
  116. // ParseFile parses a file with gui objects descriptions in YAML format
  117. // It there was a previously parsed description, it is cleared.
  118. func (b *Builder) ParseFile(filepath string) error {
  119. // Reads all file data
  120. f, err := os.Open(filepath)
  121. if err != nil {
  122. return err
  123. }
  124. data, err := ioutil.ReadAll(f)
  125. if err != nil {
  126. return err
  127. }
  128. err = f.Close()
  129. if err != nil {
  130. return err
  131. }
  132. // Parses file data
  133. return b.ParseString(string(data))
  134. }
  135. // Names returns a sorted list of names of top level previously parsed objects.
  136. // Only objects with defined types are returned.
  137. // If there is only a single object with no name, its name is returned
  138. // as an empty string
  139. func (b *Builder) Names() []string {
  140. var objs []string
  141. for name, pd := range b.desc {
  142. if pd.Type != "" {
  143. objs = append(objs, name)
  144. }
  145. }
  146. sort.Strings(objs)
  147. return objs
  148. }
  149. // Build builds a gui object and all its children recursively.
  150. // The specified name should be a top level name from a
  151. // from a previously parsed description
  152. // If the descriptions contains a single object with no name,
  153. // It should be specified the empty string to build this object.
  154. func (b *Builder) Build(name string) (IPanel, error) {
  155. pd, ok := b.desc[name]
  156. if !ok {
  157. return nil, fmt.Errorf("Object name:%s not found", name)
  158. }
  159. b.objpath.clear()
  160. b.objpath.push(pd.Name)
  161. return b.build(pd, nil)
  162. }
  163. // Sets the path for image panels relative image files
  164. func (b *Builder) SetImagepath(path string) {
  165. b.imgpath = path
  166. }
  167. // build builds the gui object from the specified description.
  168. // All its children are also built recursively
  169. // Returns the built object or an error
  170. func (b *Builder) build(pd *panelDesc, iparent IPanel) (IPanel, error) {
  171. var err error
  172. var pan IPanel
  173. switch pd.Type {
  174. case descTypePanel:
  175. pan, err = b.buildPanel(pd)
  176. case descTypeImagePanel:
  177. pan, err = b.buildImagePanel(pd)
  178. case descTypeLabel:
  179. pan, err = b.buildLabel(pd)
  180. case descTypeImageLabel:
  181. pan, err = b.buildImageLabel(pd)
  182. case descTypeButton:
  183. pan, err = b.buildButton(pd)
  184. case descTypeCheckBox:
  185. pan, err = b.buildCheckBox(pd)
  186. case descTypeRadioButton:
  187. pan, err = b.buildRadioButton(pd)
  188. case descTypeEdit:
  189. pan, err = b.buildEdit(pd)
  190. case descTypeVList:
  191. pan, err = b.buildVList(pd)
  192. case descTypeHList:
  193. pan, err = b.buildHList(pd)
  194. case descTypeDropDown:
  195. pan, err = b.buildDropDown(pd)
  196. case descTypeHSlider:
  197. pan, err = b.buildSlider(pd, true)
  198. case descTypeVSlider:
  199. pan, err = b.buildSlider(pd, false)
  200. case descTypeMenuBar:
  201. pan, err = b.buildMenu(pd, false, true)
  202. case descTypeMenu:
  203. pan, err = b.buildMenu(pd, false, false)
  204. default:
  205. err = fmt.Errorf("Invalid panel type:%s", pd.Type)
  206. }
  207. if err != nil {
  208. return nil, err
  209. }
  210. if iparent != nil {
  211. iparent.GetPanel().Add(pan)
  212. }
  213. return pan, nil
  214. }
  215. // buildPanel builds a gui object of type: "Panel"
  216. func (b *Builder) buildPanel(pd *panelDesc) (IPanel, error) {
  217. // Builds panel and set common attributes
  218. pan := NewPanel(pd.Width, pd.Height)
  219. err := b.setCommon(pd, pan)
  220. if err != nil {
  221. return nil, err
  222. }
  223. // Builds panel children recursively
  224. for i := 0; i < len(pd.Children); i++ {
  225. b.objpath.push(pd.Children[i].Name)
  226. child, err := b.build(pd.Children[i], pan)
  227. b.objpath.pop()
  228. if err != nil {
  229. return nil, err
  230. }
  231. pan.Add(child)
  232. }
  233. return pan, nil
  234. }
  235. // buildImagePanel builds a gui object of type: "ImagePanel"
  236. func (b *Builder) buildImagePanel(pd *panelDesc) (IPanel, error) {
  237. // Imagefile must be supplied
  238. if pd.Imagefile == "" {
  239. return nil, b.err("Imagefile", "Imagefile must be supplied")
  240. }
  241. // If path is not absolute join with user supplied image base path
  242. path := pd.Imagefile
  243. if !filepath.IsAbs(path) {
  244. path = filepath.Join(b.imgpath, path)
  245. }
  246. // Builds panel and set common attributes
  247. panel, err := NewImage(path)
  248. if err != nil {
  249. return nil, err
  250. }
  251. err = b.setCommon(pd, panel)
  252. if err != nil {
  253. return nil, err
  254. }
  255. // AspectWidth and AspectHeight attributes
  256. if pd.AspectWidth != nil {
  257. panel.SetContentAspectWidth(*pd.AspectWidth)
  258. }
  259. if pd.AspectHeight != nil {
  260. panel.SetContentAspectHeight(*pd.AspectHeight)
  261. }
  262. // Builds panel children recursively
  263. for i := 0; i < len(pd.Children); i++ {
  264. b.objpath.push(pd.Children[i].Name)
  265. child, err := b.build(pd.Children[i], panel)
  266. b.objpath.pop()
  267. if err != nil {
  268. return nil, err
  269. }
  270. panel.Add(child)
  271. }
  272. return panel, nil
  273. }
  274. // buildLabel builds a gui object of type: "Label"
  275. func (b *Builder) buildLabel(pd *panelDesc) (IPanel, error) {
  276. // Builds label with icon or text font
  277. var label *Label
  278. icons, err := b.parseIconNames("icons", pd.Icons)
  279. if err != nil {
  280. return nil, err
  281. }
  282. if icons != "" {
  283. label = NewLabel(icons, true)
  284. } else {
  285. label = NewLabel(pd.Text)
  286. }
  287. // Sets common attributes
  288. err = b.setCommon(pd, label)
  289. if err != nil {
  290. return nil, err
  291. }
  292. // Set optional background color
  293. c, err := b.parseColor(fieldBgColor, pd.BgColor)
  294. if err != nil {
  295. return nil, err
  296. }
  297. if c != nil {
  298. label.SetBgColor4(c)
  299. }
  300. // Set optional font color
  301. c, err = b.parseColor("fontcolor", pd.FontColor)
  302. if err != nil {
  303. return nil, err
  304. }
  305. if c != nil {
  306. label.SetColor4(c)
  307. }
  308. // Sets optional font size
  309. if pd.FontSize != nil {
  310. label.SetFontSize(float64(*pd.FontSize))
  311. }
  312. // Sets optional font dpi
  313. if pd.FontDPI != nil {
  314. label.SetFontDPI(float64(*pd.FontDPI))
  315. }
  316. // Sets optional line spacing
  317. if pd.LineSpacing != nil {
  318. label.SetLineSpacing(float64(*pd.LineSpacing))
  319. }
  320. return label, nil
  321. }
  322. // buildImageLabel builds a gui object of type: ImageLabel
  323. func (b *Builder) buildImageLabel(pd *panelDesc) (IPanel, error) {
  324. // Builds image label and set common attributes
  325. imglabel := NewImageLabel(pd.Text)
  326. err := b.setCommon(pd, imglabel)
  327. if err != nil {
  328. return nil, err
  329. }
  330. // Sets optional icon(s)
  331. icons, err := b.parseIconNames("icons", pd.Icons)
  332. if err != nil {
  333. return nil, err
  334. }
  335. if icons != "" {
  336. imglabel.SetIcon(icons)
  337. }
  338. return imglabel, nil
  339. }
  340. // buildButton builds a gui object of type: Button
  341. func (b *Builder) buildButton(pd *panelDesc) (IPanel, error) {
  342. // Builds button and set commont attributes
  343. button := NewButton(pd.Text)
  344. err := b.setCommon(pd, button)
  345. if err != nil {
  346. return nil, err
  347. }
  348. // Sets optional icon
  349. if pd.Icon != "" {
  350. cp, err := b.parseIconName("icon", pd.Icon)
  351. if err != nil {
  352. return nil, err
  353. }
  354. button.SetIcon(cp)
  355. }
  356. // Sets optional image from file
  357. // If path is not absolute join with user supplied image base path
  358. if pd.Imagefile != "" {
  359. path := pd.Imagefile
  360. if !filepath.IsAbs(path) {
  361. path = filepath.Join(b.imgpath, path)
  362. }
  363. err := button.SetImage(path)
  364. if err != nil {
  365. return nil, err
  366. }
  367. }
  368. return button, nil
  369. }
  370. // buildCheckBox builds a gui object of type: CheckBox
  371. func (b *Builder) buildCheckBox(pd *panelDesc) (IPanel, error) {
  372. // Builds check box and set commont attributes
  373. cb := NewCheckBox(pd.Text)
  374. err := b.setCommon(pd, cb)
  375. if err != nil {
  376. return nil, err
  377. }
  378. return cb, nil
  379. }
  380. // buildRadioButton builds a gui object of type: RadioButton
  381. func (b *Builder) buildRadioButton(pd *panelDesc) (IPanel, error) {
  382. // Builds check box and set commont attributes
  383. rb := NewRadioButton(pd.Text)
  384. err := b.setCommon(pd, rb)
  385. if err != nil {
  386. return nil, err
  387. }
  388. // Sets optional radio button group
  389. if pd.Group != "" {
  390. rb.SetGroup(pd.Group)
  391. }
  392. return rb, nil
  393. }
  394. // buildEdit builds a gui object of type: "Edit"
  395. func (b *Builder) buildEdit(pd *panelDesc) (IPanel, error) {
  396. // Builds button and set commont attributes
  397. edit := NewEdit(int(pd.Width), pd.PlaceHolder)
  398. err := b.setCommon(pd, edit)
  399. if err != nil {
  400. return nil, err
  401. }
  402. edit.SetText(pd.Text)
  403. return edit, nil
  404. }
  405. // buildVList builds a gui object of type: VList
  406. func (b *Builder) buildVList(pd *panelDesc) (IPanel, error) {
  407. // Builds list and set commont attributes
  408. list := NewVList(pd.Width, pd.Height)
  409. err := b.setCommon(pd, list)
  410. if err != nil {
  411. return nil, err
  412. }
  413. // Builds list children
  414. for i := 0; i < len(pd.Children); i++ {
  415. b.objpath.push(pd.Children[i].Name)
  416. child, err := b.build(pd.Children[i], list)
  417. b.objpath.pop()
  418. if err != nil {
  419. return nil, err
  420. }
  421. list.Add(child)
  422. }
  423. return list, nil
  424. }
  425. // buildHList builds a gui object of type: VList
  426. func (b *Builder) buildHList(pd *panelDesc) (IPanel, error) {
  427. // Builds list and set commont attributes
  428. list := NewHList(pd.Width, pd.Height)
  429. err := b.setCommon(pd, list)
  430. if err != nil {
  431. return nil, err
  432. }
  433. // Builds list children
  434. for i := 0; i < len(pd.Children); i++ {
  435. b.objpath.push(pd.Children[i].Name)
  436. child, err := b.build(pd.Children[i], list)
  437. b.objpath.pop()
  438. if err != nil {
  439. return nil, err
  440. }
  441. list.Add(child)
  442. }
  443. return list, nil
  444. }
  445. // buildDropDown builds a gui object of type: DropDown
  446. func (b *Builder) buildDropDown(pd *panelDesc) (IPanel, error) {
  447. var imglabel *ImageLabel
  448. if pd.ImageLabel != nil {
  449. pd.ImageLabel.Type = descTypeImageLabel
  450. ipan, err := b.build(pd.ImageLabel, nil)
  451. if err != nil {
  452. return nil, err
  453. }
  454. imglabel = ipan.(*ImageLabel)
  455. } else {
  456. imglabel = NewImageLabel("")
  457. }
  458. // Builds drop down and set common attributes
  459. dd := NewDropDown(pd.Width, imglabel)
  460. err := b.setCommon(pd, dd)
  461. if err != nil {
  462. return nil, err
  463. }
  464. // Builds drop down children
  465. for i := 0; i < len(pd.Children); i++ {
  466. pdchild := pd.Children[i]
  467. pdchild.Type = descTypeImageLabel
  468. b.objpath.push(pdchild.Name)
  469. child, err := b.build(pdchild, dd)
  470. b.objpath.pop()
  471. if err != nil {
  472. return nil, err
  473. }
  474. dd.Add(child.(*ImageLabel))
  475. }
  476. return dd, nil
  477. }
  478. // buildSlider builds a gui object of type: HSlider or VSlider
  479. func (b *Builder) buildSlider(pd *panelDesc, horiz bool) (IPanel, error) {
  480. // Builds slider and sets its position
  481. var slider *Slider
  482. if horiz {
  483. slider = NewHSlider(pd.Width, pd.Height)
  484. log.Error("slider:%v/%v", pd.Width, pd.Height)
  485. } else {
  486. slider = NewVSlider(pd.Width, pd.Height)
  487. }
  488. err := b.setPosition(pd, slider)
  489. if err != nil {
  490. return nil, err
  491. }
  492. // Sets optional text
  493. if pd.Text != "" {
  494. slider.SetText(pd.Text)
  495. }
  496. // Sets optional scale factor
  497. if pd.ScaleFactor != nil {
  498. slider.SetScaleFactor(*pd.ScaleFactor)
  499. }
  500. // Sets optional value
  501. if pd.Value != nil {
  502. slider.SetValue(*pd.Value)
  503. }
  504. return slider, nil
  505. }
  506. // buildMenu builds a gui object of type: Menu or MenuBar from the
  507. // specified panel descriptor.
  508. func (b *Builder) buildMenu(pd *panelDesc, child, bar bool) (IPanel, error) {
  509. // Builds menu bar or menu
  510. var menu *Menu
  511. if bar {
  512. menu = NewMenuBar()
  513. } else {
  514. menu = NewMenu()
  515. }
  516. // Only sets position for top level menus
  517. if !child {
  518. err := b.setPosition(pd, menu)
  519. if err != nil {
  520. return nil, err
  521. }
  522. }
  523. // Builds and adds menu items
  524. for i := 0; i < len(pd.Items); i++ {
  525. item := pd.Items[i]
  526. // Item is another menu
  527. if item.Type == descTypeMenu {
  528. subm, err := b.buildMenu(item, true, false)
  529. if err != nil {
  530. return nil, err
  531. }
  532. menu.AddMenu(item.Text, subm.(*Menu))
  533. continue
  534. }
  535. // Item is a separator
  536. if item.Type == "Separator" {
  537. menu.AddSeparator()
  538. continue
  539. }
  540. // Item must be a menu option
  541. mi := menu.AddOption(item.Text)
  542. // Set item optional icon(s)
  543. icons, err := b.parseIconNames("icon", item.Icon)
  544. if err != nil {
  545. return nil, err
  546. }
  547. if icons != "" {
  548. mi.SetIcon(string(icons))
  549. }
  550. // Sets optional menu item shortcut
  551. err = b.setMenuShortcut(mi, "shortcut", item.Shortcut)
  552. if err != nil {
  553. return nil, err
  554. }
  555. }
  556. return menu, nil
  557. }
  558. // setCommon sets the common attributes in the description to the specified panel
  559. func (b *Builder) setCommon(pd *panelDesc, ipan IPanel) error {
  560. // Set optional position
  561. err := b.setPosition(pd, ipan)
  562. if err != nil {
  563. return err
  564. }
  565. panel := ipan.GetPanel()
  566. // Set optional margin sizes
  567. bs, err := b.parseBorderSizes(fieldMargins, pd.Margins)
  568. if err != nil {
  569. return err
  570. }
  571. if bs != nil {
  572. panel.SetMarginsFrom(bs)
  573. }
  574. // Set optional border sizes
  575. bs, err = b.parseBorderSizes(fieldBorders, pd.Borders)
  576. if err != nil {
  577. return err
  578. }
  579. if bs != nil {
  580. panel.SetBordersFrom(bs)
  581. }
  582. // Set optional border color
  583. c, err := b.parseColor(fieldBorderColor, pd.BorderColor)
  584. if err != nil {
  585. return err
  586. }
  587. if c != nil {
  588. panel.SetBordersColor4(c)
  589. }
  590. // Set optional paddings sizes
  591. bs, err = b.parseBorderSizes(fieldPaddings, pd.Paddings)
  592. if err != nil {
  593. return err
  594. }
  595. if bs != nil {
  596. panel.SetPaddingsFrom(bs)
  597. }
  598. // Set optional color
  599. c, err = b.parseColor(fieldColor, pd.Color)
  600. if err != nil {
  601. return err
  602. }
  603. if c != nil {
  604. panel.SetColor4(c)
  605. }
  606. return nil
  607. }
  608. // Sets the panel optional position from the specified panel descriptor
  609. func (b *Builder) setPosition(pd *panelDesc, ipan IPanel) error {
  610. if pd.Position == "" {
  611. return nil
  612. }
  613. va, err := b.parseFloats("position", pd.Position, 2, 2)
  614. if va == nil || err != nil {
  615. return err
  616. }
  617. ipan.GetPanel().SetPosition(va[0], va[1])
  618. return nil
  619. }
  620. func (b *Builder) setMenuShortcut(mi *MenuItem, fname, field string) error {
  621. field = strings.Trim(field, " ")
  622. if field == "" {
  623. return nil
  624. }
  625. parts := strings.Split(field, "+")
  626. var mods window.ModifierKey
  627. for i := 0; i < len(parts)-1; i++ {
  628. switch parts[i] {
  629. case "Shift":
  630. mods |= window.ModShift
  631. case "Ctrl":
  632. mods |= window.ModControl
  633. case "Alt":
  634. mods |= window.ModAlt
  635. default:
  636. return b.err(fname, "Invalid shortcut:"+field)
  637. }
  638. }
  639. // The last part must be a key
  640. key := parts[len(parts)-1]
  641. for kcode, kname := range mapKeyText {
  642. if kname == key {
  643. mi.SetShortcut(mods, kcode)
  644. return nil
  645. }
  646. }
  647. return b.err(fname, "Invalid shortcut:"+field)
  648. }
  649. // parseBorderSizes parses a string field which can contain one float value or
  650. // float values. In the first case all borders has the same width
  651. func (b *Builder) parseBorderSizes(fname, field string) (*BorderSizes, error) {
  652. va, err := b.parseFloats(fname, field, 1, 4)
  653. if va == nil || err != nil {
  654. return nil, err
  655. }
  656. if len(va) == 1 {
  657. return &BorderSizes{va[0], va[0], va[0], va[0]}, nil
  658. }
  659. return &BorderSizes{va[0], va[1], va[2], va[3]}, nil
  660. }
  661. // parseColor parses a string field which can contain a color name or
  662. // a list of 3 or 4 float values for the color components
  663. func (b *Builder) parseColor(fname, field string) (*math32.Color4, error) {
  664. // Checks if field is empty
  665. field = strings.Trim(field, " ")
  666. if field == "" {
  667. return nil, nil
  668. }
  669. // If string has 1 or 2 fields it must be a color name and optional alpha
  670. parts := strings.Fields(field)
  671. if len(parts) == 1 || len(parts) == 2 {
  672. // First part must be a color name
  673. if !math32.IsColor(parts[0]) {
  674. return nil, b.err(fname, fmt.Sprintf("Invalid color name:%s", parts[0]))
  675. }
  676. c := math32.ColorName(parts[0])
  677. c4 := math32.Color4{c.R, c.G, c.B, 1}
  678. if len(parts) == 2 {
  679. val, err := strconv.ParseFloat(parts[1], 32)
  680. if err != nil {
  681. return nil, b.err(fname, fmt.Sprintf("Invalid float32 value:%s", parts[1]))
  682. }
  683. c4.A = float32(val)
  684. }
  685. return &c4, nil
  686. }
  687. // Accept 3 or 4 floats values
  688. va, err := b.parseFloats(fname, field, 3, 4)
  689. if err != nil {
  690. return nil, err
  691. }
  692. if len(va) == 3 {
  693. return &math32.Color4{va[0], va[1], va[2], 1}, nil
  694. }
  695. return &math32.Color4{va[0], va[1], va[2], va[3]}, nil
  696. }
  697. // parseIconNames parses a string with a list of icon names or codepoints and
  698. // returns a string with the icons codepoints encoded in UTF8
  699. func (b *Builder) parseIconNames(fname, field string) (string, error) {
  700. text := ""
  701. parts := strings.Fields(field)
  702. for i := 0; i < len(parts); i++ {
  703. cp, err := b.parseIconName(fname, parts[i])
  704. if err != nil {
  705. return "", err
  706. }
  707. text = text + string(cp)
  708. }
  709. return text, nil
  710. }
  711. // parseIconName parses a string with an icon name or codepoint in hex
  712. // and returns the icon codepoints value and an error
  713. func (b *Builder) parseIconName(fname, field string) (string, error) {
  714. // Try name first
  715. cp := icon.Codepoint(field)
  716. if cp != "" {
  717. return cp, nil
  718. }
  719. // Try to parse as hex value
  720. cp2, err := strconv.ParseUint(field, 16, 32)
  721. if err != nil {
  722. return "", b.err(fname, fmt.Sprintf("Invalid icon codepoint value/name:%v", field))
  723. }
  724. return string(cp2), nil
  725. }
  726. // parseFloats parses a string with a list of floats with the specified size
  727. // and returns a slice. The specified size is 0 any number of floats is allowed.
  728. // The individual values can be separated by spaces or commas
  729. func (b *Builder) parseFloats(fname, field string, min, max int) ([]float32, error) {
  730. // Checks if field is empty
  731. field = strings.Trim(field, " ")
  732. if field == "" {
  733. return nil, nil
  734. }
  735. // Separate individual fields
  736. var parts []string
  737. if strings.Index(field, ",") < 0 {
  738. parts = strings.Fields(field)
  739. } else {
  740. parts = strings.Split(field, ",")
  741. }
  742. if len(parts) < min || len(parts) > max {
  743. return nil, b.err(fname, "Invalid number of float32 values")
  744. }
  745. // Parse each field value and appends to slice
  746. var values []float32
  747. for i := 0; i < len(parts); i++ {
  748. val, err := strconv.ParseFloat(strings.Trim(parts[i], " "), 32)
  749. if err != nil {
  750. return nil, b.err(fname, err.Error())
  751. }
  752. values = append(values, float32(val))
  753. }
  754. return values, nil
  755. }
  756. // err creates and returns an error for the current object, field name and with the specified message
  757. func (b *Builder) err(fname, msg string) error {
  758. return fmt.Errorf("Error in object:%s field:%s -> %s", b.objpath.path(), fname, msg)
  759. }
  760. // strStack is a stack of strings
  761. type strStack struct {
  762. stack []string
  763. }
  764. // clear removes all elements from the stack
  765. func (ss *strStack) clear() {
  766. ss.stack = []string{}
  767. }
  768. // push pushes a string to the top of the stack
  769. func (ss *strStack) push(v string) {
  770. ss.stack = append(ss.stack, v)
  771. }
  772. // pop removes and returns the string at the top of the stack.
  773. // Returns an empty string if the stack is empty
  774. func (ss *strStack) pop() string {
  775. if len(ss.stack) == 0 {
  776. return ""
  777. }
  778. length := len(ss.stack)
  779. v := ss.stack[length-1]
  780. ss.stack = ss.stack[:length-1]
  781. return v
  782. }
  783. // path returns a string composed of all the strings in the
  784. // stack separated by a forward slash.
  785. func (ss *strStack) path() string {
  786. return strings.Join(ss.stack, "/")
  787. }