builder.go 30 KB

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