builder.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  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. params.ColSpan = dlp.ColSpan
  847. // Sets optional alignh parameter
  848. if dlp.AlignH != "" {
  849. align, ok := mapAlignName[dlp.AlignH]
  850. if !ok {
  851. return b.err("alignh", "Invalid align name:"+dlp.AlignH)
  852. }
  853. params.AlignH = align
  854. }
  855. // Sets optional alignv parameter
  856. if dlp.AlignV != "" {
  857. align, ok := mapAlignName[dlp.AlignV]
  858. if !ok {
  859. return b.err("alignv", "Invalid align name:"+dlp.AlignV)
  860. }
  861. params.AlignV = align
  862. }
  863. panel.SetLayoutParams(&params)
  864. return nil
  865. }
  866. return b.err("layoutparams", "Invalid parent layout:"+playout.Type)
  867. }
  868. // setLayout sets the optional panel layout and layout parameters
  869. func (b *Builder) setLayout(dp *descPanel, ipan IPanel) error {
  870. // If layout types not declared, nothing to do
  871. if dp.Layout == nil {
  872. return nil
  873. }
  874. dl := dp.Layout
  875. panel := ipan.GetPanel()
  876. // HBox layout
  877. if dl.Type == descTypeHBoxLayout {
  878. hbl := NewHBoxLayout()
  879. hbl.SetSpacing(dl.Spacing)
  880. if dl.AlignH != "" {
  881. align, ok := mapAlignName[dl.AlignH]
  882. if !ok {
  883. return b.err("align", "Invalid align name:"+dl.AlignV)
  884. }
  885. hbl.SetAlignH(align)
  886. }
  887. hbl.SetMinHeight(dl.MinHeight)
  888. hbl.SetMinWidth(dl.MinWidth)
  889. panel.SetLayout(hbl)
  890. return nil
  891. }
  892. // VBox layout
  893. if dl.Type == descTypeVBoxLayout {
  894. vbl := NewVBoxLayout()
  895. vbl.SetSpacing(dl.Spacing)
  896. if dl.AlignV != "" {
  897. align, ok := mapAlignName[dl.AlignV]
  898. if !ok {
  899. return b.err("align", "Invalid align name:"+dl.AlignV)
  900. }
  901. vbl.SetAlignV(align)
  902. }
  903. vbl.SetMinHeight(dl.MinHeight)
  904. vbl.SetMinWidth(dl.MinWidth)
  905. panel.SetLayout(vbl)
  906. return nil
  907. }
  908. // Grid layout
  909. if dl.Type == descTypeGridLayout {
  910. // Number of columns
  911. if dl.Cols == 0 {
  912. return b.err("cols", "Invalid number of columns:"+dl.AlignH)
  913. }
  914. grl := NewGridLayout(dl.Cols)
  915. // Global horizontal alignment
  916. if dl.AlignH != "" {
  917. alignh, ok := mapAlignName[dl.AlignH]
  918. if !ok {
  919. return b.err("alignh", "Invalid horizontal align:"+dl.AlignH)
  920. }
  921. grl.SetAlignH(alignh)
  922. }
  923. // Global vertical alignment
  924. if dl.AlignV != "" {
  925. alignv, ok := mapAlignName[dl.AlignV]
  926. if !ok {
  927. return b.err("alignv", "Invalid vertical align:"+dl.AlignH)
  928. }
  929. grl.SetAlignV(alignv)
  930. }
  931. // Expansion flags
  932. grl.SetExpandH(dl.ExpandH)
  933. grl.SetExpandV(dl.ExpandV)
  934. panel.SetLayout(grl)
  935. return nil
  936. }
  937. return b.err("layout", "Invalid layout type:"+dl.Type)
  938. }
  939. func (b *Builder) setMenuShortcut(mi *MenuItem, fname, field string) error {
  940. field = strings.Trim(field, " ")
  941. if field == "" {
  942. return nil
  943. }
  944. parts := strings.Split(field, "+")
  945. var mods window.ModifierKey
  946. for i := 0; i < len(parts)-1; i++ {
  947. switch parts[i] {
  948. case "Shift":
  949. mods |= window.ModShift
  950. case "Ctrl":
  951. mods |= window.ModControl
  952. case "Alt":
  953. mods |= window.ModAlt
  954. default:
  955. return b.err(fname, "Invalid shortcut:"+field)
  956. }
  957. }
  958. // The last part must be a key
  959. key := parts[len(parts)-1]
  960. for kcode, kname := range mapKeyText {
  961. if kname == key {
  962. mi.SetShortcut(mods, kcode)
  963. return nil
  964. }
  965. }
  966. return b.err(fname, "Invalid shortcut:"+field)
  967. }
  968. // parseBorderSizes parses a string field which can contain one float value or
  969. // float values. In the first case all borders has the same width
  970. func (b *Builder) parseBorderSizes(fname, field string) (*BorderSizes, error) {
  971. va, err := b.parseFloats(fname, field, 1, 4)
  972. if va == nil || err != nil {
  973. return nil, err
  974. }
  975. if len(va) == 1 {
  976. return &BorderSizes{va[0], va[0], va[0], va[0]}, nil
  977. }
  978. return &BorderSizes{va[0], va[1], va[2], va[3]}, nil
  979. }
  980. // parseColor parses a string field which can contain a color name or
  981. // a list of 3 or 4 float values for the color components
  982. func (b *Builder) parseColor(fname, field string) (*math32.Color4, error) {
  983. // Checks if field is empty
  984. field = strings.Trim(field, " ")
  985. if field == "" {
  986. return nil, nil
  987. }
  988. // If string has 1 or 2 fields it must be a color name and optional alpha
  989. parts := strings.Fields(field)
  990. if len(parts) == 1 || len(parts) == 2 {
  991. // First part must be a color name
  992. if !math32.IsColor(parts[0]) {
  993. return nil, b.err(fname, fmt.Sprintf("Invalid color name:%s", parts[0]))
  994. }
  995. c := math32.ColorName(parts[0])
  996. c4 := math32.Color4{c.R, c.G, c.B, 1}
  997. if len(parts) == 2 {
  998. val, err := strconv.ParseFloat(parts[1], 32)
  999. if err != nil {
  1000. return nil, b.err(fname, fmt.Sprintf("Invalid float32 value:%s", parts[1]))
  1001. }
  1002. c4.A = float32(val)
  1003. }
  1004. return &c4, nil
  1005. }
  1006. // Accept 3 or 4 floats values
  1007. va, err := b.parseFloats(fname, field, 3, 4)
  1008. if err != nil {
  1009. return nil, err
  1010. }
  1011. if len(va) == 3 {
  1012. return &math32.Color4{va[0], va[1], va[2], 1}, nil
  1013. }
  1014. return &math32.Color4{va[0], va[1], va[2], va[3]}, nil
  1015. }
  1016. // parseIconNames parses a string with a list of icon names or codepoints and
  1017. // returns a string with the icons codepoints encoded in UTF8
  1018. func (b *Builder) parseIconNames(fname, field string) (string, error) {
  1019. text := ""
  1020. parts := strings.Fields(field)
  1021. for i := 0; i < len(parts); i++ {
  1022. cp, err := b.parseIconName(fname, parts[i])
  1023. if err != nil {
  1024. return "", err
  1025. }
  1026. text = text + string(cp)
  1027. }
  1028. return text, nil
  1029. }
  1030. // parseIconName parses a string with an icon name or codepoint in hex
  1031. // and returns the icon codepoints value and an error
  1032. func (b *Builder) parseIconName(fname, field string) (string, error) {
  1033. // Try name first
  1034. cp := icon.Codepoint(field)
  1035. if cp != "" {
  1036. return cp, nil
  1037. }
  1038. // Try to parse as hex value
  1039. cp2, err := strconv.ParseUint(field, 16, 32)
  1040. if err != nil {
  1041. return "", b.err(fname, fmt.Sprintf("Invalid icon codepoint value/name:%v", field))
  1042. }
  1043. return string(cp2), nil
  1044. }
  1045. // parseFloats parses a string with a list of floats with the specified size
  1046. // and returns a slice. The specified size is 0 any number of floats is allowed.
  1047. // The individual values can be separated by spaces or commas
  1048. func (b *Builder) parseFloats(fname, field string, min, max int) ([]float32, error) {
  1049. // Checks if field is empty
  1050. field = strings.Trim(field, " ")
  1051. if field == "" {
  1052. return nil, nil
  1053. }
  1054. // Separate individual fields
  1055. var parts []string
  1056. if strings.Index(field, ",") < 0 {
  1057. parts = strings.Fields(field)
  1058. } else {
  1059. parts = strings.Split(field, ",")
  1060. }
  1061. if len(parts) < min || len(parts) > max {
  1062. return nil, b.err(fname, "Invalid number of float32 values")
  1063. }
  1064. // Parse each field value and appends to slice
  1065. var values []float32
  1066. for i := 0; i < len(parts); i++ {
  1067. val, err := strconv.ParseFloat(strings.Trim(parts[i], " "), 32)
  1068. if err != nil {
  1069. return nil, b.err(fname, err.Error())
  1070. }
  1071. values = append(values, float32(val))
  1072. }
  1073. return values, nil
  1074. }
  1075. // err creates and returns an error for the current object, field name and with the specified message
  1076. func (b *Builder) err(fname, msg string) error {
  1077. return fmt.Errorf("Error in object:%s field:%s -> %s", b.objpath.path(), fname, msg)
  1078. }
  1079. // setupDescTree sets the types of all description tree elements to lower case and
  1080. // sets the items "parent" attribute pointing the respective parent description
  1081. func (b *Builder) setupDescTree(dp *descPanel) {
  1082. dp.Type = strings.ToLower(dp.Type)
  1083. if dp.Layout != nil {
  1084. dp.Layout.Type = strings.ToLower(dp.Layout.Type)
  1085. }
  1086. for i := 0; i < len(dp.Items); i++ {
  1087. dp.Items[i].parent = dp
  1088. b.setupDescTree(dp.Items[i])
  1089. }
  1090. }
  1091. // Returns the width and height attributes of the specified descriptor
  1092. // if defined or the defaul value (0).
  1093. func (b *Builder) size(dp *descPanel) (float32, float32) {
  1094. var width, height float32
  1095. if dp.Width != nil {
  1096. width = *dp.Width
  1097. }
  1098. if dp.Height != nil {
  1099. height = *dp.Height
  1100. }
  1101. return width, height
  1102. }
  1103. // strStack is a stack of strings
  1104. type strStack struct {
  1105. stack []string
  1106. }
  1107. // clear removes all elements from the stack
  1108. func (ss *strStack) clear() {
  1109. ss.stack = []string{}
  1110. }
  1111. // push pushes a string to the top of the stack
  1112. func (ss *strStack) push(v string) {
  1113. ss.stack = append(ss.stack, v)
  1114. }
  1115. // pop removes and returns the string at the top of the stack.
  1116. // Returns an empty string if the stack is empty
  1117. func (ss *strStack) pop() string {
  1118. if len(ss.stack) == 0 {
  1119. return ""
  1120. }
  1121. length := len(ss.stack)
  1122. v := ss.stack[length-1]
  1123. ss.stack = ss.stack[:length-1]
  1124. return v
  1125. }
  1126. // path returns a string composed of all the strings in the
  1127. // stack separated by a forward slash.
  1128. func (ss *strStack) path() string {
  1129. return strings.Join(ss.stack, "/")
  1130. }