builder.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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]*descPanel // parsed descriptions
  21. imgpath string // base path for image panels files
  22. objpath strStack // stack of object names being built (used for error messages)
  23. }
  24. // descLayout contains all layout attributes
  25. type descLayout struct {
  26. Type string // Type of the layout: HBox, VBox, Grid, Dock, others...
  27. Cols int // Number of columns for Grid layout
  28. Spacing float32 // Spacing in pixels for HBox and VBox
  29. AlignH string // HBox group alignment type
  30. AlignV string // VBox group alignment type
  31. MinHeight bool // HBox, VBox minimum height flag
  32. MinWidth bool // HBox, VBox minimum width flag
  33. ExpandH bool // Grid
  34. ExpandV bool // Grid
  35. }
  36. // descLayoutParam describes all layout parameters types
  37. type descLayoutParams struct {
  38. Expand *float32 // HBox, VBox expand factor
  39. ColSpan int // Grid layout colspan
  40. AlignH string // horizontal alignment
  41. AlignV string // vertical alignment
  42. }
  43. // descPanel describes all panel types
  44. type descPanel struct {
  45. Type string // Gui object type: Panel, Label, Edit, etc ...
  46. Name string // Optional name for identification
  47. Position string // Optional position as: x y | x,y
  48. Width *float32 // Optional width (default = 0)
  49. Height *float32 // Optional height (default = 0)
  50. AspectWidth *float32 // Optional aspectwidth (default = nil)
  51. AspectHeight *float32 // Optional aspectwidth (default = nil)
  52. Margins string // Optional margins as 1 or 4 float values
  53. Borders string // Optional borders as 1 or 4 float values
  54. BorderColor string // Optional border color as name or 3 or 4 float values
  55. Paddings string // Optional paddings as 1 or 4 float values
  56. Color string // Optional color as 1 or 4 float values
  57. Enabled *bool
  58. Visible *bool
  59. Renderable *bool
  60. Imagefile string // For Panel, Button
  61. Layout *descLayout // Optional pointer to layout
  62. LayoutParams *descLayoutParams // Optional layout parameters
  63. Text string // Label, Button
  64. Icons string // Label
  65. BgColor string // Label
  66. FontColor string // Label
  67. FontSize *float32 // Label
  68. FontDPI *float32 // Label
  69. LineSpacing *float32 // Label
  70. PlaceHolder string // Edit
  71. MaxLength *uint // Edit
  72. Icon string // Button
  73. Group string // RadioButton
  74. Checked bool // CheckBox, RadioButton
  75. ImageLabel *descPanel // DropDown
  76. Items []*descPanel // Menu, MenuBar
  77. Shortcut string // Menu
  78. Value *float32 // Slider
  79. ScaleFactor *float32 // Slider
  80. parent *descPanel // used internally
  81. }
  82. const (
  83. descTypePanel = "panel"
  84. descTypeImagePanel = "imagepanel"
  85. descTypeLabel = "label"
  86. descTypeImageLabel = "imagelabel"
  87. descTypeButton = "button"
  88. descTypeCheckBox = "checkbox"
  89. descTypeRadioButton = "radiobutton"
  90. descTypeEdit = "edit"
  91. descTypeVList = "vlist"
  92. descTypeHList = "hlist"
  93. descTypeDropDown = "dropdown"
  94. descTypeHSlider = "hslider"
  95. descTypeVSlider = "vslider"
  96. descTypeHSplitter = "hsplitter"
  97. descTypeVSplitter = "vsplitter"
  98. descTypeTree = "tree"
  99. descTypeTreeNode = "node"
  100. descTypeMenuBar = "menubar"
  101. descTypeMenu = "menu"
  102. descTypeHBoxLayout = "hbox"
  103. descTypeVBoxLayout = "vbox"
  104. descTypeGridLayout = "grid"
  105. fieldMargins = "margins"
  106. fieldBorders = "borders"
  107. fieldBorderColor = "bordercolor"
  108. fieldPaddings = "paddings"
  109. fieldColor = "color"
  110. fieldBgColor = "bgcolor"
  111. )
  112. const (
  113. aPOS = 1 << iota // attribute position
  114. aSIZE = 1 << iota // attribute size
  115. aNAME = 1 << iota // attribute name
  116. aMARGINS = 1 << iota // attribute margins widths
  117. aBORDERS = 1 << iota // attribute borders widths
  118. aBORDERCOLOR = 1 << iota // attribute border color
  119. aPADDINGS = 1 << iota // attribute paddings widths
  120. aCOLOR = 1 << iota // attribute panel bgcolor
  121. aENABLED = 1 << iota // attribute enabled for events
  122. aRENDER = 1 << iota // attribute renderable
  123. aVISIBLE = 1 << iota // attribute visible
  124. asPANEL = 0xFF // attribute set for panels
  125. asWIDGET = aPOS | aNAME | aENABLED | aVISIBLE // attribute set for widgets
  126. asBUTTON = aPOS | aSIZE | aNAME | aENABLED | aVISIBLE // attribute set for buttons
  127. )
  128. // maps align name with align parameter
  129. var mapAlignName = map[string]Align{
  130. "none": AlignNone,
  131. "left": AlignLeft,
  132. "right": AlignRight,
  133. "width": AlignWidth,
  134. "top": AlignTop,
  135. "bottom": AlignBottom,
  136. "height": AlignHeight,
  137. "center": AlignCenter,
  138. }
  139. // NewBuilder creates and returns a pointer to a new gui Builder object
  140. func NewBuilder() *Builder {
  141. return new(Builder)
  142. }
  143. // ParseString parses a string with gui objects descriptions in YAML format
  144. // It there was a previously parsed description, it is cleared.
  145. func (b *Builder) ParseString(desc string) error {
  146. // Try assuming the description contains a single root panel
  147. var dp descPanel
  148. err := yaml.Unmarshal([]byte(desc), &dp)
  149. if err != nil {
  150. return err
  151. }
  152. if dp.Type != "" {
  153. b.desc = make(map[string]*descPanel)
  154. b.desc[""] = &dp
  155. b.setupDescTree(&dp)
  156. return nil
  157. }
  158. // Try assuming the description is a map of panels
  159. var dpm map[string]*descPanel
  160. err = yaml.Unmarshal([]byte(desc), &dpm)
  161. if err != nil {
  162. return err
  163. }
  164. b.desc = dpm
  165. for _, v := range dpm {
  166. b.setupDescTree(v)
  167. }
  168. return nil
  169. }
  170. // ParseFile parses a file with gui objects descriptions in YAML format
  171. // It there was a previously parsed description, it is cleared.
  172. func (b *Builder) ParseFile(filepath string) error {
  173. // Reads all file data
  174. f, err := os.Open(filepath)
  175. if err != nil {
  176. return err
  177. }
  178. data, err := ioutil.ReadAll(f)
  179. if err != nil {
  180. return err
  181. }
  182. err = f.Close()
  183. if err != nil {
  184. return err
  185. }
  186. // Parses file data
  187. return b.ParseString(string(data))
  188. }
  189. // Names returns a sorted list of names of top level previously parsed objects.
  190. // Only objects with defined types are returned.
  191. // If there is only a single object with no name, its name is returned
  192. // as an empty string
  193. func (b *Builder) Names() []string {
  194. var objs []string
  195. for name, pd := range b.desc {
  196. if pd.Type != "" {
  197. objs = append(objs, name)
  198. }
  199. }
  200. sort.Strings(objs)
  201. return objs
  202. }
  203. // Build builds a gui object and all its children recursively.
  204. // The specified name should be a top level name from a
  205. // from a previously parsed description
  206. // If the descriptions contains a single object with no name,
  207. // It should be specified the empty string to build this object.
  208. func (b *Builder) Build(name string) (IPanel, error) {
  209. pd, ok := b.desc[name]
  210. if !ok {
  211. return nil, fmt.Errorf("Object name:%s not found", name)
  212. }
  213. b.objpath.clear()
  214. b.objpath.push(pd.Name)
  215. return b.build(pd, nil)
  216. }
  217. // Sets the path for image panels relative image files
  218. func (b *Builder) SetImagepath(path string) {
  219. b.imgpath = path
  220. }
  221. // build builds the gui object from the specified description.
  222. // All its children are also built recursively
  223. // Returns the built object or an error
  224. func (b *Builder) build(pd *descPanel, iparent IPanel) (IPanel, error) {
  225. var err error
  226. var pan IPanel
  227. switch pd.Type {
  228. case descTypePanel:
  229. pan, err = b.buildPanel(pd)
  230. case descTypeImagePanel:
  231. pan, err = b.buildImagePanel(pd)
  232. case descTypeLabel:
  233. pan, err = b.buildLabel(pd)
  234. case descTypeImageLabel:
  235. pan, err = b.buildImageLabel(pd)
  236. case descTypeButton:
  237. pan, err = b.buildButton(pd)
  238. case descTypeCheckBox:
  239. pan, err = b.buildCheckBox(pd)
  240. case descTypeRadioButton:
  241. pan, err = b.buildRadioButton(pd)
  242. case descTypeEdit:
  243. pan, err = b.buildEdit(pd)
  244. case descTypeVList:
  245. pan, err = b.buildVList(pd)
  246. case descTypeHList:
  247. pan, err = b.buildHList(pd)
  248. case descTypeDropDown:
  249. pan, err = b.buildDropDown(pd)
  250. case descTypeHSlider:
  251. pan, err = b.buildSlider(pd, true)
  252. case descTypeVSlider:
  253. pan, err = b.buildSlider(pd, false)
  254. case descTypeHSplitter:
  255. pan, err = b.buildSplitter(pd, true)
  256. case descTypeVSplitter:
  257. pan, err = b.buildSplitter(pd, false)
  258. case descTypeTree:
  259. pan, err = b.buildTree(pd)
  260. case descTypeMenuBar:
  261. pan, err = b.buildMenu(pd, false, true)
  262. case descTypeMenu:
  263. pan, err = b.buildMenu(pd, false, false)
  264. default:
  265. err = fmt.Errorf("Invalid panel type:%s", pd.Type)
  266. }
  267. if err != nil {
  268. return nil, err
  269. }
  270. if iparent != nil {
  271. iparent.GetPanel().Add(pan)
  272. }
  273. return pan, nil
  274. }
  275. // buildPanel builds a gui object of type: "Panel"
  276. func (b *Builder) buildPanel(dp *descPanel) (IPanel, error) {
  277. // Builds panel and set attributes
  278. width, height := b.size(dp)
  279. pan := NewPanel(width, height)
  280. err := b.setAttribs(dp, pan, asPANEL)
  281. if err != nil {
  282. return nil, err
  283. }
  284. // Builds panel children recursively
  285. for i := 0; i < len(dp.Items); i++ {
  286. item := dp.Items[i]
  287. b.objpath.push(item.Name)
  288. child, err := b.build(item, pan)
  289. b.objpath.pop()
  290. if err != nil {
  291. return nil, err
  292. }
  293. pan.Add(child)
  294. }
  295. return pan, nil
  296. }
  297. // buildImagePanel builds a gui object of type: "ImagePanel"
  298. func (b *Builder) buildImagePanel(pd *descPanel) (IPanel, error) {
  299. // Imagefile must be supplied
  300. if pd.Imagefile == "" {
  301. return nil, b.err("Imagefile", "Imagefile must be supplied")
  302. }
  303. // If path is not absolute join with user supplied image base path
  304. path := pd.Imagefile
  305. if !filepath.IsAbs(path) {
  306. path = filepath.Join(b.imgpath, path)
  307. }
  308. // Builds panel and set common attributes
  309. panel, err := NewImage(path)
  310. if err != nil {
  311. return nil, err
  312. }
  313. err = b.setAttribs(pd, panel, asPANEL)
  314. if err != nil {
  315. return nil, err
  316. }
  317. // AspectWidth and AspectHeight attributes
  318. if pd.AspectWidth != nil {
  319. panel.SetContentAspectWidth(*pd.AspectWidth)
  320. }
  321. if pd.AspectHeight != nil {
  322. panel.SetContentAspectHeight(*pd.AspectHeight)
  323. }
  324. // Builds panel children recursively
  325. for i := 0; i < len(pd.Items); i++ {
  326. item := pd.Items[i]
  327. b.objpath.push(item.Name)
  328. child, err := b.build(item, panel)
  329. b.objpath.pop()
  330. if err != nil {
  331. return nil, err
  332. }
  333. panel.Add(child)
  334. }
  335. return panel, nil
  336. }
  337. // buildLabel builds a gui object of type: "Label"
  338. func (b *Builder) buildLabel(pd *descPanel) (IPanel, error) {
  339. // Builds label with icon or text font
  340. var label *Label
  341. icons, err := b.parseIconNames("icons", pd.Icons)
  342. if err != nil {
  343. return nil, err
  344. }
  345. if icons != "" {
  346. label = NewLabel(icons, true)
  347. } else {
  348. label = NewLabel(pd.Text)
  349. }
  350. // Sets common attributes
  351. err = b.setAttribs(pd, label, asPANEL)
  352. if err != nil {
  353. return nil, err
  354. }
  355. // Set optional background color
  356. c, err := b.parseColor(fieldBgColor, pd.BgColor)
  357. if err != nil {
  358. return nil, err
  359. }
  360. if c != nil {
  361. label.SetBgColor4(c)
  362. }
  363. // Set optional font color
  364. c, err = b.parseColor("fontcolor", pd.FontColor)
  365. if err != nil {
  366. return nil, err
  367. }
  368. if c != nil {
  369. label.SetColor4(c)
  370. }
  371. // Sets optional font size
  372. if pd.FontSize != nil {
  373. label.SetFontSize(float64(*pd.FontSize))
  374. }
  375. // Sets optional font dpi
  376. if pd.FontDPI != nil {
  377. label.SetFontDPI(float64(*pd.FontDPI))
  378. }
  379. // Sets optional line spacing
  380. if pd.LineSpacing != nil {
  381. label.SetLineSpacing(float64(*pd.LineSpacing))
  382. }
  383. return label, nil
  384. }
  385. // buildImageLabel builds a gui object of type: ImageLabel
  386. func (b *Builder) buildImageLabel(pd *descPanel) (IPanel, error) {
  387. // Builds image label and set common attributes
  388. imglabel := NewImageLabel(pd.Text)
  389. err := b.setAttribs(pd, imglabel, asPANEL)
  390. if err != nil {
  391. return nil, err
  392. }
  393. // Sets optional icon(s)
  394. icons, err := b.parseIconNames("icons", pd.Icons)
  395. if err != nil {
  396. return nil, err
  397. }
  398. if icons != "" {
  399. imglabel.SetIcon(icons)
  400. }
  401. return imglabel, nil
  402. }
  403. // buildButton builds a gui object of type: Button
  404. func (b *Builder) buildButton(pd *descPanel) (IPanel, error) {
  405. // Builds button and set commont attributes
  406. button := NewButton(pd.Text)
  407. err := b.setAttribs(pd, button, asBUTTON)
  408. if err != nil {
  409. return nil, err
  410. }
  411. // Sets optional icon
  412. if pd.Icon != "" {
  413. cp, err := b.parseIconName("icon", pd.Icon)
  414. if err != nil {
  415. return nil, err
  416. }
  417. button.SetIcon(cp)
  418. }
  419. // Sets optional image from file
  420. // If path is not absolute join with user supplied image base path
  421. if pd.Imagefile != "" {
  422. path := pd.Imagefile
  423. if !filepath.IsAbs(path) {
  424. path = filepath.Join(b.imgpath, path)
  425. }
  426. err := button.SetImage(path)
  427. if err != nil {
  428. return nil, err
  429. }
  430. }
  431. return button, nil
  432. }
  433. // buildCheckBox builds a gui object of type: CheckBox
  434. func (b *Builder) buildCheckBox(pd *descPanel) (IPanel, error) {
  435. // Builds check box and set commont attributes
  436. cb := NewCheckBox(pd.Text)
  437. err := b.setAttribs(pd, cb, asWIDGET)
  438. if err != nil {
  439. return nil, err
  440. }
  441. cb.SetValue(pd.Checked)
  442. return cb, nil
  443. }
  444. // buildRadioButton builds a gui object of type: RadioButton
  445. func (b *Builder) buildRadioButton(pd *descPanel) (IPanel, error) {
  446. // Builds check box and set commont attributes
  447. rb := NewRadioButton(pd.Text)
  448. err := b.setAttribs(pd, rb, asWIDGET)
  449. if err != nil {
  450. return nil, err
  451. }
  452. // Sets optional radio button group
  453. if pd.Group != "" {
  454. rb.SetGroup(pd.Group)
  455. }
  456. rb.SetValue(pd.Checked)
  457. return rb, nil
  458. }
  459. // buildEdit builds a gui object of type: "Edit"
  460. func (b *Builder) buildEdit(dp *descPanel) (IPanel, error) {
  461. // Builds button and set attributes
  462. width, _ := b.size(dp)
  463. edit := NewEdit(int(width), dp.PlaceHolder)
  464. err := b.setAttribs(dp, edit, asWIDGET)
  465. if err != nil {
  466. return nil, err
  467. }
  468. edit.SetText(dp.Text)
  469. return edit, nil
  470. }
  471. // buildVList builds a gui object of type: VList
  472. func (b *Builder) buildVList(dp *descPanel) (IPanel, error) {
  473. // Builds list and set commont attributes
  474. width, height := b.size(dp)
  475. list := NewVList(width, height)
  476. err := b.setAttribs(dp, list, asWIDGET)
  477. if err != nil {
  478. return nil, err
  479. }
  480. // Builds list children
  481. for i := 0; i < len(dp.Items); i++ {
  482. item := dp.Items[i]
  483. b.objpath.push(item.Name)
  484. child, err := b.build(item, list)
  485. b.objpath.pop()
  486. if err != nil {
  487. return nil, err
  488. }
  489. list.Add(child)
  490. }
  491. return list, nil
  492. }
  493. // buildHList builds a gui object of type: VList
  494. func (b *Builder) buildHList(dp *descPanel) (IPanel, error) {
  495. // Builds list and set commont attributes
  496. width, height := b.size(dp)
  497. list := NewHList(width, height)
  498. err := b.setAttribs(dp, list, asWIDGET)
  499. if err != nil {
  500. return nil, err
  501. }
  502. // Builds list children
  503. for i := 0; i < len(dp.Items); i++ {
  504. item := dp.Items[i]
  505. b.objpath.push(item.Name)
  506. child, err := b.build(item, list)
  507. b.objpath.pop()
  508. if err != nil {
  509. return nil, err
  510. }
  511. list.Add(child)
  512. }
  513. return list, nil
  514. }
  515. // buildDropDown builds a gui object of type: DropDown
  516. func (b *Builder) buildDropDown(pd *descPanel) (IPanel, error) {
  517. // If image label attribute defined use it, otherwise
  518. // uses default value.
  519. var imglabel *ImageLabel
  520. if pd.ImageLabel != nil {
  521. pd.ImageLabel.Type = descTypeImageLabel
  522. ipan, err := b.build(pd.ImageLabel, nil)
  523. if err != nil {
  524. return nil, err
  525. }
  526. imglabel = ipan.(*ImageLabel)
  527. } else {
  528. imglabel = NewImageLabel("")
  529. }
  530. // Builds drop down and set common attributes
  531. width, _ := b.size(pd)
  532. dd := NewDropDown(width, imglabel)
  533. err := b.setAttribs(pd, dd, asWIDGET)
  534. if err != nil {
  535. return nil, err
  536. }
  537. // Builds drop down children
  538. for i := 0; i < len(pd.Items); i++ {
  539. item := pd.Items[i]
  540. item.Type = descTypeImageLabel
  541. b.objpath.push(item.Name)
  542. child, err := b.build(item, dd)
  543. b.objpath.pop()
  544. if err != nil {
  545. return nil, err
  546. }
  547. dd.Add(child.(*ImageLabel))
  548. }
  549. return dd, nil
  550. }
  551. // buildSlider builds a gui object of type: HSlider or VSlider
  552. func (b *Builder) buildSlider(pd *descPanel, horiz bool) (IPanel, error) {
  553. // Builds slider and sets its position
  554. width, height := b.size(pd)
  555. var slider *Slider
  556. if horiz {
  557. slider = NewHSlider(width, height)
  558. } else {
  559. slider = NewVSlider(width, height)
  560. }
  561. err := b.setAttribs(pd, slider, asWIDGET)
  562. if err != nil {
  563. return nil, err
  564. }
  565. // Sets optional text
  566. if pd.Text != "" {
  567. slider.SetText(pd.Text)
  568. }
  569. // Sets optional scale factor
  570. if pd.ScaleFactor != nil {
  571. slider.SetScaleFactor(*pd.ScaleFactor)
  572. }
  573. // Sets optional value
  574. if pd.Value != nil {
  575. slider.SetValue(*pd.Value)
  576. }
  577. return slider, nil
  578. }
  579. // buildSplitter builds a gui object of type: HSplitterr or VSplitter
  580. func (b *Builder) buildSplitter(pd *descPanel, horiz bool) (IPanel, error) {
  581. // Builds splitter and sets its common attributes
  582. width, height := b.size(pd)
  583. var splitter *Splitter
  584. if horiz {
  585. splitter = NewHSplitter(width, height)
  586. } else {
  587. splitter = NewVSplitter(width, height)
  588. }
  589. err := b.setAttribs(pd, splitter, asWIDGET)
  590. if err != nil {
  591. return nil, err
  592. }
  593. return splitter, nil
  594. }
  595. // buildTree builds a gui object of type: Tree
  596. func (b *Builder) buildTree(dp *descPanel) (IPanel, error) {
  597. // Builds tree and sets its common attributes
  598. width, height := b.size(dp)
  599. tree := NewTree(width, height)
  600. err := b.setAttribs(dp, tree, asWIDGET)
  601. if err != nil {
  602. return nil, err
  603. }
  604. // Internal function to build tree nodes recursively
  605. var buildItems func(dp *descPanel, pnode *TreeNode) error
  606. buildItems = func(dp *descPanel, pnode *TreeNode) error {
  607. for i := 0; i < len(dp.Items); i++ {
  608. item := dp.Items[i]
  609. // Item is a tree node
  610. if item.Type == "" || item.Type == descTypeTreeNode {
  611. var node *TreeNode
  612. if pnode == nil {
  613. node = tree.AddNode(item.Text)
  614. } else {
  615. node = pnode.AddNode(item.Text)
  616. }
  617. err := buildItems(item, node)
  618. if err != nil {
  619. return err
  620. }
  621. continue
  622. }
  623. // Other controls
  624. ipan, err := b.build(item, nil)
  625. if err != nil {
  626. return err
  627. }
  628. if pnode == nil {
  629. tree.Add(ipan)
  630. } else {
  631. pnode.Add(ipan)
  632. }
  633. }
  634. return nil
  635. }
  636. // Build nodes
  637. err = buildItems(dp, nil)
  638. if err != nil {
  639. return nil, err
  640. }
  641. return tree, nil
  642. }
  643. // buildMenu builds a gui object of type: Menu or MenuBar from the
  644. // specified panel descriptor.
  645. func (b *Builder) buildMenu(pd *descPanel, child, bar bool) (IPanel, error) {
  646. // Builds menu bar or menu
  647. var menu *Menu
  648. if bar {
  649. menu = NewMenuBar()
  650. } else {
  651. menu = NewMenu()
  652. }
  653. // Only sets attribs for top level menus
  654. if !child {
  655. err := b.setAttribs(pd, menu, asWIDGET)
  656. if err != nil {
  657. return nil, err
  658. }
  659. }
  660. // Builds and adds menu items
  661. for i := 0; i < len(pd.Items); i++ {
  662. item := pd.Items[i]
  663. // Item is another menu
  664. if item.Type == descTypeMenu {
  665. subm, err := b.buildMenu(item, true, false)
  666. if err != nil {
  667. return nil, err
  668. }
  669. menu.AddMenu(item.Text, subm.(*Menu))
  670. continue
  671. }
  672. // Item is a separator
  673. if item.Type == "Separator" {
  674. menu.AddSeparator()
  675. continue
  676. }
  677. // Item must be a menu option
  678. mi := menu.AddOption(item.Text)
  679. // Set item optional icon(s)
  680. icons, err := b.parseIconNames("icon", item.Icon)
  681. if err != nil {
  682. return nil, err
  683. }
  684. if icons != "" {
  685. mi.SetIcon(string(icons))
  686. }
  687. // Sets optional menu item shortcut
  688. err = b.setMenuShortcut(mi, "shortcut", item.Shortcut)
  689. if err != nil {
  690. return nil, err
  691. }
  692. }
  693. return menu, nil
  694. }
  695. // setAttribs sets common attributes from the description to the specified panel
  696. // The attributes which are set can be specified by the specified bitmask.
  697. func (b *Builder) setAttribs(pd *descPanel, ipan IPanel, attr uint) error {
  698. panel := ipan.GetPanel()
  699. // Set optional position
  700. if attr&aPOS != 0 && pd.Position != "" {
  701. va, err := b.parseFloats("position", pd.Position, 2, 2)
  702. if va == nil || err != nil {
  703. return err
  704. }
  705. panel.SetPosition(va[0], va[1])
  706. }
  707. // Set optional size
  708. if attr&aSIZE != 0 {
  709. if pd.Width != nil {
  710. panel.SetWidth(*pd.Width)
  711. }
  712. if pd.Height != nil {
  713. panel.SetHeight(*pd.Height)
  714. }
  715. }
  716. // Set optional margin sizes
  717. if attr&aMARGINS != 0 {
  718. bs, err := b.parseBorderSizes(fieldMargins, pd.Margins)
  719. if err != nil {
  720. return err
  721. }
  722. if bs != nil {
  723. panel.SetMarginsFrom(bs)
  724. }
  725. }
  726. // Set optional border sizes
  727. if attr&aBORDERS != 0 {
  728. bs, err := b.parseBorderSizes(fieldBorders, pd.Borders)
  729. if err != nil {
  730. return err
  731. }
  732. if bs != nil {
  733. panel.SetBordersFrom(bs)
  734. }
  735. }
  736. // Set optional border color
  737. if attr&aBORDERCOLOR != 0 {
  738. c, err := b.parseColor(fieldBorderColor, pd.BorderColor)
  739. if err != nil {
  740. return err
  741. }
  742. if c != nil {
  743. panel.SetBordersColor4(c)
  744. }
  745. }
  746. // Set optional paddings sizes
  747. if attr&aPADDINGS != 0 {
  748. bs, err := b.parseBorderSizes(fieldPaddings, pd.Paddings)
  749. if err != nil {
  750. return err
  751. }
  752. if bs != nil {
  753. panel.SetPaddingsFrom(bs)
  754. }
  755. }
  756. // Set optional color
  757. if attr&aCOLOR != 0 {
  758. c, err := b.parseColor(fieldColor, pd.Color)
  759. if err != nil {
  760. return err
  761. }
  762. if c != nil {
  763. panel.SetColor4(c)
  764. }
  765. }
  766. if attr&aNAME != 0 && pd.Name != "" {
  767. panel.SetName(pd.Name)
  768. }
  769. if attr&aVISIBLE != 0 && pd.Visible != nil {
  770. panel.SetVisible(*pd.Visible)
  771. }
  772. if attr&aENABLED != 0 && pd.Enabled != nil {
  773. panel.SetEnabled(*pd.Enabled)
  774. }
  775. if attr&aRENDER != 0 && pd.Renderable != nil {
  776. panel.SetRenderable(*pd.Renderable)
  777. }
  778. err := b.setLayoutParams(pd, ipan)
  779. if err != nil {
  780. return err
  781. }
  782. return b.setLayout(pd, ipan)
  783. }
  784. // setLayoutParams sets the optional layout params attribute for specified the panel
  785. func (b *Builder) setLayoutParams(dp *descPanel, ipan IPanel) error {
  786. // If layout params not declared, nothing to do
  787. if dp.LayoutParams == nil {
  788. return nil
  789. }
  790. // Get the parent layout
  791. if dp.parent == nil {
  792. return b.err("layoutparams", "No parent defined")
  793. }
  794. playout := dp.parent.Layout
  795. if playout == nil {
  796. return b.err("layoutparams", "Parent does not have layout")
  797. }
  798. panel := ipan.GetPanel()
  799. dlp := dp.LayoutParams
  800. // HBoxLayout parameters
  801. if playout.Type == descTypeHBoxLayout {
  802. // Creates layout parameter
  803. params := HBoxLayoutParams{Expand: 0, AlignV: AlignTop}
  804. // Sets optional expand parameter
  805. if dlp.Expand != nil {
  806. params.Expand = *dlp.Expand
  807. }
  808. // Sets optional align parameter
  809. if dlp.AlignV != "" {
  810. align, ok := mapAlignName[dlp.AlignV]
  811. if !ok {
  812. return b.err("align", "Invalid align name:"+dlp.AlignV)
  813. }
  814. params.AlignV = align
  815. }
  816. panel.SetLayoutParams(&params)
  817. return nil
  818. }
  819. // VBoxLayout parameters
  820. if playout.Type == descTypeVBoxLayout {
  821. // Creates layout parameter
  822. params := VBoxLayoutParams{Expand: 0, AlignH: AlignLeft}
  823. // Sets optional expand parameter
  824. if dlp.Expand != nil {
  825. params.Expand = *dlp.Expand
  826. }
  827. // Sets optional align parameter
  828. if dlp.AlignH != "" {
  829. align, ok := mapAlignName[dlp.AlignH]
  830. if !ok {
  831. return b.err("align", "Invalid align name:"+dlp.AlignH)
  832. }
  833. params.AlignH = align
  834. }
  835. panel.SetLayoutParams(&params)
  836. return nil
  837. }
  838. // GridLayout parameters
  839. if playout.Type == descTypeGridLayout {
  840. // Creates layout parameter
  841. params := GridLayoutParams{
  842. ColSpan: 0,
  843. AlignH: AlignNone,
  844. AlignV: AlignNone,
  845. }
  846. log.Error("colspan:%v", dlp.ColSpan)
  847. params.ColSpan = dlp.ColSpan
  848. // Sets optional alignh parameter
  849. if dlp.AlignH != "" {
  850. align, ok := mapAlignName[dlp.AlignH]
  851. if !ok {
  852. return b.err("alignh", "Invalid align name:"+dlp.AlignH)
  853. }
  854. params.AlignH = align
  855. }
  856. // Sets optional alignv parameter
  857. if dlp.AlignV != "" {
  858. align, ok := mapAlignName[dlp.AlignV]
  859. if !ok {
  860. return b.err("alignv", "Invalid align name:"+dlp.AlignV)
  861. }
  862. params.AlignV = align
  863. }
  864. panel.SetLayoutParams(&params)
  865. return nil
  866. }
  867. return b.err("layoutparams", "Invalid parent layout:"+playout.Type)
  868. }
  869. // setLayout sets the optional panel layout and layout parameters
  870. func (b *Builder) setLayout(dp *descPanel, ipan IPanel) error {
  871. // If layout types not declared, nothing to do
  872. if dp.Layout == nil {
  873. return nil
  874. }
  875. dl := dp.Layout
  876. panel := ipan.GetPanel()
  877. // HBox layout
  878. if dl.Type == descTypeHBoxLayout {
  879. hbl := NewHBoxLayout()
  880. hbl.SetSpacing(dl.Spacing)
  881. if dl.AlignH != "" {
  882. align, ok := mapAlignName[dl.AlignH]
  883. if !ok {
  884. return b.err("align", "Invalid align name:"+dl.AlignV)
  885. }
  886. hbl.SetAlignH(align)
  887. }
  888. hbl.SetMinHeight(dl.MinHeight)
  889. hbl.SetMinWidth(dl.MinWidth)
  890. panel.SetLayout(hbl)
  891. return nil
  892. }
  893. // VBox layout
  894. if dl.Type == descTypeVBoxLayout {
  895. vbl := NewVBoxLayout()
  896. vbl.SetSpacing(dl.Spacing)
  897. if dl.AlignV != "" {
  898. align, ok := mapAlignName[dl.AlignV]
  899. if !ok {
  900. return b.err("align", "Invalid align name:"+dl.AlignV)
  901. }
  902. vbl.SetAlignV(align)
  903. }
  904. vbl.SetMinHeight(dl.MinHeight)
  905. vbl.SetMinWidth(dl.MinWidth)
  906. panel.SetLayout(vbl)
  907. return nil
  908. }
  909. // Grid layout
  910. if dl.Type == descTypeGridLayout {
  911. log.Error("set grid layout")
  912. // Number of columns
  913. if dl.Cols == 0 {
  914. return b.err("cols", "Invalid number of columns:"+dl.AlignH)
  915. }
  916. grl := NewGridLayout(dl.Cols)
  917. // Global horizontal alignment
  918. if dl.AlignH != "" {
  919. alignh, ok := mapAlignName[dl.AlignH]
  920. if !ok {
  921. return b.err("alignh", "Invalid horizontal align:"+dl.AlignH)
  922. }
  923. grl.SetAlignH(alignh)
  924. }
  925. // Global vertical alignment
  926. if dl.AlignV != "" {
  927. alignv, ok := mapAlignName[dl.AlignV]
  928. if !ok {
  929. return b.err("alignv", "Invalid vertical align:"+dl.AlignH)
  930. }
  931. grl.SetAlignV(alignv)
  932. }
  933. // Expansion flags
  934. grl.SetExpandH(dl.ExpandH)
  935. grl.SetExpandV(dl.ExpandV)
  936. panel.SetLayout(grl)
  937. return nil
  938. }
  939. return b.err("layout", "Invalid layout type:"+dl.Type)
  940. }
  941. func (b *Builder) setMenuShortcut(mi *MenuItem, fname, field string) error {
  942. field = strings.Trim(field, " ")
  943. if field == "" {
  944. return nil
  945. }
  946. parts := strings.Split(field, "+")
  947. var mods window.ModifierKey
  948. for i := 0; i < len(parts)-1; i++ {
  949. switch parts[i] {
  950. case "Shift":
  951. mods |= window.ModShift
  952. case "Ctrl":
  953. mods |= window.ModControl
  954. case "Alt":
  955. mods |= window.ModAlt
  956. default:
  957. return b.err(fname, "Invalid shortcut:"+field)
  958. }
  959. }
  960. // The last part must be a key
  961. key := parts[len(parts)-1]
  962. for kcode, kname := range mapKeyText {
  963. if kname == key {
  964. mi.SetShortcut(mods, kcode)
  965. return nil
  966. }
  967. }
  968. return b.err(fname, "Invalid shortcut:"+field)
  969. }
  970. // parseBorderSizes parses a string field which can contain one float value or
  971. // float values. In the first case all borders has the same width
  972. func (b *Builder) parseBorderSizes(fname, field string) (*BorderSizes, error) {
  973. va, err := b.parseFloats(fname, field, 1, 4)
  974. if va == nil || err != nil {
  975. return nil, err
  976. }
  977. if len(va) == 1 {
  978. return &BorderSizes{va[0], va[0], va[0], va[0]}, nil
  979. }
  980. return &BorderSizes{va[0], va[1], va[2], va[3]}, nil
  981. }
  982. // parseColor parses a string field which can contain a color name or
  983. // a list of 3 or 4 float values for the color components
  984. func (b *Builder) parseColor(fname, field string) (*math32.Color4, error) {
  985. // Checks if field is empty
  986. field = strings.Trim(field, " ")
  987. if field == "" {
  988. return nil, nil
  989. }
  990. // If string has 1 or 2 fields it must be a color name and optional alpha
  991. parts := strings.Fields(field)
  992. if len(parts) == 1 || len(parts) == 2 {
  993. // First part must be a color name
  994. if !math32.IsColor(parts[0]) {
  995. return nil, b.err(fname, fmt.Sprintf("Invalid color name:%s", parts[0]))
  996. }
  997. c := math32.ColorName(parts[0])
  998. c4 := math32.Color4{c.R, c.G, c.B, 1}
  999. if len(parts) == 2 {
  1000. val, err := strconv.ParseFloat(parts[1], 32)
  1001. if err != nil {
  1002. return nil, b.err(fname, fmt.Sprintf("Invalid float32 value:%s", parts[1]))
  1003. }
  1004. c4.A = float32(val)
  1005. }
  1006. return &c4, nil
  1007. }
  1008. // Accept 3 or 4 floats values
  1009. va, err := b.parseFloats(fname, field, 3, 4)
  1010. if err != nil {
  1011. return nil, err
  1012. }
  1013. if len(va) == 3 {
  1014. return &math32.Color4{va[0], va[1], va[2], 1}, nil
  1015. }
  1016. return &math32.Color4{va[0], va[1], va[2], va[3]}, nil
  1017. }
  1018. // parseIconNames parses a string with a list of icon names or codepoints and
  1019. // returns a string with the icons codepoints encoded in UTF8
  1020. func (b *Builder) parseIconNames(fname, field string) (string, error) {
  1021. text := ""
  1022. parts := strings.Fields(field)
  1023. for i := 0; i < len(parts); i++ {
  1024. cp, err := b.parseIconName(fname, parts[i])
  1025. if err != nil {
  1026. return "", err
  1027. }
  1028. text = text + string(cp)
  1029. }
  1030. return text, nil
  1031. }
  1032. // parseIconName parses a string with an icon name or codepoint in hex
  1033. // and returns the icon codepoints value and an error
  1034. func (b *Builder) parseIconName(fname, field string) (string, error) {
  1035. // Try name first
  1036. cp := icon.Codepoint(field)
  1037. if cp != "" {
  1038. return cp, nil
  1039. }
  1040. // Try to parse as hex value
  1041. cp2, err := strconv.ParseUint(field, 16, 32)
  1042. if err != nil {
  1043. return "", b.err(fname, fmt.Sprintf("Invalid icon codepoint value/name:%v", field))
  1044. }
  1045. return string(cp2), nil
  1046. }
  1047. // parseFloats parses a string with a list of floats with the specified size
  1048. // and returns a slice. The specified size is 0 any number of floats is allowed.
  1049. // The individual values can be separated by spaces or commas
  1050. func (b *Builder) parseFloats(fname, field string, min, max int) ([]float32, error) {
  1051. // Checks if field is empty
  1052. field = strings.Trim(field, " ")
  1053. if field == "" {
  1054. return nil, nil
  1055. }
  1056. // Separate individual fields
  1057. var parts []string
  1058. if strings.Index(field, ",") < 0 {
  1059. parts = strings.Fields(field)
  1060. } else {
  1061. parts = strings.Split(field, ",")
  1062. }
  1063. if len(parts) < min || len(parts) > max {
  1064. return nil, b.err(fname, "Invalid number of float32 values")
  1065. }
  1066. // Parse each field value and appends to slice
  1067. var values []float32
  1068. for i := 0; i < len(parts); i++ {
  1069. val, err := strconv.ParseFloat(strings.Trim(parts[i], " "), 32)
  1070. if err != nil {
  1071. return nil, b.err(fname, err.Error())
  1072. }
  1073. values = append(values, float32(val))
  1074. }
  1075. return values, nil
  1076. }
  1077. // err creates and returns an error for the current object, field name and with the specified message
  1078. func (b *Builder) err(fname, msg string) error {
  1079. return fmt.Errorf("Error in object:%s field:%s -> %s", b.objpath.path(), fname, msg)
  1080. }
  1081. // setupDescTree sets the types of all description tree elements to lower case and
  1082. // sets the items "parent" attribute pointing the respective parent description
  1083. func (b *Builder) setupDescTree(dp *descPanel) {
  1084. dp.Type = strings.ToLower(dp.Type)
  1085. if dp.Layout != nil {
  1086. dp.Layout.Type = strings.ToLower(dp.Layout.Type)
  1087. }
  1088. for i := 0; i < len(dp.Items); i++ {
  1089. dp.Items[i].parent = dp
  1090. b.setupDescTree(dp.Items[i])
  1091. }
  1092. }
  1093. // Returns the width and height attributes of the specified descriptor
  1094. // if defined or the defaul value (0).
  1095. func (b *Builder) size(dp *descPanel) (float32, float32) {
  1096. var width, height float32
  1097. if dp.Width != nil {
  1098. width = *dp.Width
  1099. }
  1100. if dp.Height != nil {
  1101. height = *dp.Height
  1102. }
  1103. return width, height
  1104. }
  1105. // strStack is a stack of strings
  1106. type strStack struct {
  1107. stack []string
  1108. }
  1109. // clear removes all elements from the stack
  1110. func (ss *strStack) clear() {
  1111. ss.stack = []string{}
  1112. }
  1113. // push pushes a string to the top of the stack
  1114. func (ss *strStack) push(v string) {
  1115. ss.stack = append(ss.stack, v)
  1116. }
  1117. // pop removes and returns the string at the top of the stack.
  1118. // Returns an empty string if the stack is empty
  1119. func (ss *strStack) pop() string {
  1120. if len(ss.stack) == 0 {
  1121. return ""
  1122. }
  1123. length := len(ss.stack)
  1124. v := ss.stack[length-1]
  1125. ss.stack = ss.stack[:length-1]
  1126. return v
  1127. }
  1128. // path returns a string composed of all the strings in the
  1129. // stack separated by a forward slash.
  1130. func (ss *strStack) path() string {
  1131. return strings.Join(ss.stack, "/")
  1132. }