builder.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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. "sort"
  10. "strconv"
  11. "strings"
  12. "github.com/g3n/engine/gui/assets/icon"
  13. "github.com/g3n/engine/math32"
  14. "github.com/g3n/engine/window"
  15. "gopkg.in/yaml.v2"
  16. )
  17. // Builder builds GUI objects from a declarative description in YAML format
  18. type Builder struct {
  19. am map[string]interface{} // parsed map with gui object atttributes
  20. builders map[string]BuilderFunc // map of builder functions by type
  21. attribs map[string]AttribCheckFunc // map of attribute name with check functions
  22. layouts map[string]IBuilderLayout // map of layout type to layout builder
  23. imgpath string // base path for image panels files
  24. }
  25. // IBuilderLayout is the interface for all layout builders
  26. type IBuilderLayout interface {
  27. BuildLayout(b *Builder, am map[string]interface{}) (ILayout, error)
  28. BuildParams(b *Builder, am map[string]interface{}) (interface{}, error)
  29. }
  30. // BuilderFunc is type for functions which build a gui object from an attribute map
  31. type BuilderFunc func(*Builder, map[string]interface{}) (IPanel, error)
  32. // IgnoreSuffix specified the suffix of ignored keys
  33. const IgnoreSuffix = "_"
  34. // Panel and layout types
  35. const (
  36. TypePanel = "panel"
  37. TypeImagePanel = "imagepanel"
  38. TypeLabel = "label"
  39. TypeImageLabel = "imagelabel"
  40. TypeButton = "button"
  41. TypeCheckBox = "checkbox"
  42. TypeRadioButton = "radiobutton"
  43. TypeEdit = "edit"
  44. TypeVList = "vlist"
  45. TypeHList = "hlist"
  46. TypeDropDown = "dropdown"
  47. TypeHSlider = "hslider"
  48. TypeVSlider = "vslider"
  49. TypeHSplitter = "hsplitter"
  50. TypeVSplitter = "vsplitter"
  51. TypeSeparator = "separator"
  52. TypeTree = "tree"
  53. TypeTreeNode = "node"
  54. TypeMenuBar = "menubar"
  55. TypeMenu = "menu"
  56. TypeWindow = "window"
  57. TypeHBoxLayout = "hbox"
  58. TypeVBoxLayout = "vbox"
  59. TypeGridLayout = "grid"
  60. TypeDockLayout = "dock"
  61. )
  62. // Common attribute names
  63. const (
  64. AttribAlignv = "alignv" // Align
  65. AttribAlignh = "alignh" // Align
  66. AttribAspectHeight = "aspectheight" // float32
  67. AttribAspectWidth = "aspectwidth" // float32
  68. AttribBgColor = "bgcolor" // Color4
  69. AttribBorders = "borders" // BorderSizes
  70. AttribBorderColor = "bordercolor" // Color4
  71. AttribChecked = "checked" // bool
  72. AttribColor = "color" // Color4
  73. AttribCols = "cols" // Int
  74. AttribColSpan = "colspan" // Int
  75. AttribEdge = "edge" // int
  76. AttribEnabled = "enabled" // bool
  77. AttribExpand = "expand" // float32
  78. AttribExpandh = "expandh" // bool
  79. AttribExpandv = "expandv" // bool
  80. AttribFontColor = "fontcolor" // Color4
  81. AttribFontDPI = "fontdpi" // float32
  82. AttribFontSize = "fontsize" // float32
  83. AttribGroup = "group" // string
  84. AttribHeight = "height" // float32
  85. AttribIcon = "icon" // string
  86. AttribImageFile = "imagefile" // string
  87. AttribImageLabel = "imagelabel" // []map[string]interface{}
  88. AttribItems = "items" // []map[string]interface{}
  89. AttribLayout = "layout" // map[string]interface{}
  90. AttribLayoutParams = "layoutparams" // map[string]interface{}
  91. AttribLineSpacing = "linespacing" // float32
  92. AttribMinHeight = "minheight" // bool
  93. AttribMinWidth = "minwidth" // bool
  94. AttribMargins = "margins" // BorderSizes
  95. AttribName = "name" // string
  96. AttribPaddings = "paddings" // BorderSizes
  97. AttribPanel0 = "panel0" // map[string]interface{}
  98. AttribPanel1 = "panel1" // map[string]interface{}
  99. AttribParent_ = "parent_" // string (internal attribute)
  100. AttribPlaceHolder = "placeholder" // string
  101. AttribPosition = "position" // []float32
  102. AttribRender = "render" // bool
  103. AttribResizable = "resizable" // Resizable
  104. AttribScaleFactor = "scalefactor" // float32
  105. AttribShortcut = "shortcut" // []int
  106. AttribSpacing = "spacing" // float32
  107. AttribSplit = "split" // float32
  108. AttribText = "text" // string
  109. AttribTitle = "title" // string
  110. AttribType = "type" // string
  111. AttribWidth = "width" // float32
  112. AttribValue = "value" // float32
  113. AttribVisible = "visible" // bool
  114. )
  115. const (
  116. aPOS = 1 << iota // attribute position
  117. aSIZE = 1 << iota // attribute size
  118. aNAME = 1 << iota // attribute name
  119. aMARGINS = 1 << iota // attribute margins widths
  120. aBORDERS = 1 << iota // attribute borders widths
  121. aBORDERCOLOR = 1 << iota // attribute border color
  122. aPADDINGS = 1 << iota // attribute paddings widths
  123. aCOLOR = 1 << iota // attribute panel bgcolor
  124. aENABLED = 1 << iota // attribute enabled for events
  125. aRENDER = 1 << iota // attribute renderable
  126. aVISIBLE = 1 << iota // attribute visible
  127. asPANEL = 0xFF // attribute set for panels
  128. asWIDGET = aPOS | aNAME | aSIZE | aENABLED | aVISIBLE // attribute set for widgets
  129. )
  130. // maps align name with align parameter
  131. var mapAlignh = map[string]Align{
  132. "none": AlignNone,
  133. "left": AlignLeft,
  134. "right": AlignRight,
  135. "width": AlignWidth,
  136. "center": AlignCenter,
  137. }
  138. // maps align name with align parameter
  139. var mapAlignv = map[string]Align{
  140. "none": AlignNone,
  141. "top": AlignTop,
  142. "bottom": AlignBottom,
  143. "height": AlignHeight,
  144. "center": AlignCenter,
  145. }
  146. // maps edge name (dock layout) with edge parameter
  147. var mapEdgeName = map[string]int{
  148. "top": DockTop,
  149. "right": DockRight,
  150. "bottom": DockBottom,
  151. "left": DockLeft,
  152. "center": DockCenter,
  153. }
  154. // maps resize border name (window) with parameter value
  155. var mapResizable = map[string]Resizable{
  156. "top": ResizeTop,
  157. "right": ResizeRight,
  158. "bottom": ResizeBottom,
  159. "left": ResizeLeft,
  160. "all": ResizeAll,
  161. }
  162. // AttribCheckFunc is the type for all attribute check functions
  163. type AttribCheckFunc func(b *Builder, am map[string]interface{}, fname string) error
  164. // NewBuilder creates and returns a pointer to a new gui Builder object
  165. func NewBuilder() *Builder {
  166. b := new(Builder)
  167. // Sets map of object type to builder function
  168. b.builders = map[string]BuilderFunc{
  169. TypePanel: buildPanel,
  170. TypeImagePanel: buildImagePanel,
  171. TypeLabel: buildLabel,
  172. TypeImageLabel: buildImageLabel,
  173. TypeButton: buildButton,
  174. TypeEdit: buildEdit,
  175. TypeCheckBox: buildCheckBox,
  176. TypeRadioButton: buildRadioButton,
  177. TypeVList: buildVList,
  178. TypeHList: buildHList,
  179. TypeDropDown: buildDropDown,
  180. TypeMenu: buildMenu,
  181. TypeMenuBar: buildMenu,
  182. TypeHSlider: buildSlider,
  183. TypeVSlider: buildSlider,
  184. TypeHSplitter: buildSplitter,
  185. TypeVSplitter: buildSplitter,
  186. TypeTree: buildTree,
  187. TypeWindow: buildWindow,
  188. }
  189. // Sets map of layout type name to layout function
  190. b.layouts = map[string]IBuilderLayout{
  191. TypeHBoxLayout: &BuilderLayoutHBox{},
  192. TypeVBoxLayout: &BuilderLayoutVBox{},
  193. TypeGridLayout: &BuilderLayoutGrid{},
  194. TypeDockLayout: &BuilderLayoutDock{},
  195. }
  196. // Sets map of attribute name to check function
  197. b.attribs = map[string]AttribCheckFunc{
  198. AttribAlignv: AttribCheckAlign,
  199. AttribAlignh: AttribCheckAlign,
  200. AttribAspectWidth: AttribCheckFloat,
  201. AttribAspectHeight: AttribCheckFloat,
  202. AttribHeight: AttribCheckFloat,
  203. AttribMargins: AttribCheckBorderSizes,
  204. AttribBgColor: AttribCheckColor,
  205. AttribBorders: AttribCheckBorderSizes,
  206. AttribBorderColor: AttribCheckColor,
  207. AttribChecked: AttribCheckBool,
  208. AttribColor: AttribCheckColor,
  209. AttribCols: AttribCheckInt,
  210. AttribColSpan: AttribCheckInt,
  211. AttribEdge: AttribCheckEdge,
  212. AttribEnabled: AttribCheckBool,
  213. AttribExpand: AttribCheckFloat,
  214. AttribExpandh: AttribCheckBool,
  215. AttribExpandv: AttribCheckBool,
  216. AttribFontColor: AttribCheckColor,
  217. AttribFontDPI: AttribCheckFloat,
  218. AttribFontSize: AttribCheckFloat,
  219. AttribGroup: AttribCheckString,
  220. AttribIcon: AttribCheckIcons,
  221. AttribImageFile: AttribCheckString,
  222. AttribImageLabel: AttribCheckMap,
  223. AttribItems: AttribCheckListMap,
  224. AttribLayout: AttribCheckLayout,
  225. AttribLayoutParams: AttribCheckMap,
  226. AttribLineSpacing: AttribCheckFloat,
  227. AttribMinHeight: AttribCheckBool,
  228. AttribMinWidth: AttribCheckBool,
  229. AttribName: AttribCheckString,
  230. AttribPaddings: AttribCheckBorderSizes,
  231. AttribPanel0: AttribCheckMap,
  232. AttribPanel1: AttribCheckMap,
  233. AttribPlaceHolder: AttribCheckString,
  234. AttribPosition: AttribCheckPosition,
  235. AttribRender: AttribCheckBool,
  236. AttribResizable: AttribCheckResizable,
  237. AttribScaleFactor: AttribCheckFloat,
  238. AttribShortcut: AttribCheckMenuShortcut,
  239. AttribSpacing: AttribCheckFloat,
  240. AttribSplit: AttribCheckFloat,
  241. AttribText: AttribCheckString,
  242. AttribTitle: AttribCheckString,
  243. AttribType: AttribCheckStringLower,
  244. AttribValue: AttribCheckFloat,
  245. AttribVisible: AttribCheckBool,
  246. AttribWidth: AttribCheckFloat,
  247. }
  248. return b
  249. }
  250. // ParseString parses a string with gui objects descriptions in YAML format
  251. // It there was a previously parsed description, it is cleared.
  252. func (b *Builder) ParseString(desc string) error {
  253. // Parses descriptor string in YAML format saving result in
  254. // a map of interface{} to interface{} as YAML allows numeric keys.
  255. var mii map[interface{}]interface{}
  256. err := yaml.Unmarshal([]byte(desc), &mii)
  257. if err != nil {
  258. return err
  259. }
  260. // If all the values of the top level map keys are other maps,
  261. // then it is a description of several objects, otherwise it is
  262. // a description of a single object.
  263. single := false
  264. for _, v := range mii {
  265. _, ok := v.(map[interface{}]interface{})
  266. if !ok {
  267. single = true
  268. break
  269. }
  270. }
  271. // Internal function which converts map[interface{}]interface{} to
  272. // map[string]interface{} recursively and lower case of all map keys.
  273. // It also sets a field named "parent_", which pointer to the parent map
  274. // This field causes a circular reference in the result map which prevents
  275. // the use of Go's Printf to print the result map.
  276. var visitor func(v, par interface{}) (interface{}, error)
  277. visitor = func(v, par interface{}) (interface{}, error) {
  278. switch vt := v.(type) {
  279. case []interface{}:
  280. ls := []interface{}{}
  281. for _, item := range vt {
  282. ci, err := visitor(item, par)
  283. if err != nil {
  284. return nil, err
  285. }
  286. ls = append(ls, ci)
  287. }
  288. return ls, nil
  289. case map[interface{}]interface{}:
  290. ms := make(map[string]interface{})
  291. for k, v := range vt {
  292. // Checks key
  293. ks, ok := k.(string)
  294. if !ok {
  295. return nil, fmt.Errorf("Keys must be strings")
  296. }
  297. ks = strings.ToLower(ks)
  298. // Ignores keys suffixed by IgnoreSuffix
  299. if strings.HasSuffix(ks, IgnoreSuffix) {
  300. continue
  301. }
  302. // Checks value
  303. vi, err := visitor(v, ms)
  304. if err != nil {
  305. return nil, err
  306. }
  307. ms[ks] = vi
  308. // If has panel has parent or is a single top level panel, checks attributes
  309. if par != nil || single {
  310. // Get attribute check function
  311. acf, ok := b.attribs[ks]
  312. if !ok {
  313. return nil, fmt.Errorf("Invalid attribute:%s", ks)
  314. }
  315. // Checks attribute
  316. err = acf(b, ms, ks)
  317. if err != nil {
  318. return nil, err
  319. }
  320. }
  321. }
  322. if par != nil {
  323. ms[AttribParent_] = par
  324. }
  325. return ms, nil
  326. default:
  327. return v, nil
  328. }
  329. return nil, nil
  330. }
  331. // Get map[string]interface{} with lower case keys from parsed descritor
  332. res, err := visitor(mii, nil)
  333. if err != nil {
  334. return err
  335. }
  336. msi, ok := res.(map[string]interface{})
  337. if !ok {
  338. return fmt.Errorf("Parsed result is not a map")
  339. }
  340. b.am = msi
  341. //b.debugPrint(b.am, 1)
  342. return nil
  343. }
  344. // ParseFile parses a file with gui objects descriptions in YAML format
  345. // It there was a previously parsed description, it is cleared.
  346. func (b *Builder) ParseFile(filepath string) error {
  347. // Reads all file data
  348. f, err := os.Open(filepath)
  349. if err != nil {
  350. return err
  351. }
  352. data, err := ioutil.ReadAll(f)
  353. if err != nil {
  354. return err
  355. }
  356. err = f.Close()
  357. if err != nil {
  358. return err
  359. }
  360. // Parses file data
  361. return b.ParseString(string(data))
  362. }
  363. // Names returns a sorted list of names of top level previously parsed objects.
  364. // Only objects with defined types are returned.
  365. // If there is only a single object with no name, its name is returned
  366. // as an empty string
  367. func (b *Builder) Names() []string {
  368. var objs []string
  369. // Single object
  370. if b.am[AttribType] != nil {
  371. objs = append(objs, "")
  372. return objs
  373. }
  374. // Multiple objects
  375. for name := range b.am {
  376. objs = append(objs, name)
  377. }
  378. sort.Strings(objs)
  379. return objs
  380. }
  381. // Build builds a gui object and all its children recursively.
  382. // The specified name should be a top level name from a
  383. // from a previously parsed description
  384. // If the descriptions contains a single object with no name,
  385. // It should be specified the empty string to build this object.
  386. func (b *Builder) Build(name string) (IPanel, error) {
  387. // Only one object
  388. if name == "" {
  389. return b.build(b.am, nil)
  390. }
  391. // Map of gui objects
  392. am, ok := b.am[name]
  393. if !ok {
  394. return nil, fmt.Errorf("Object name:%s not found", name)
  395. }
  396. return b.build(am.(map[string]interface{}), nil)
  397. }
  398. // SetImagePath Sets the path for image panels relative image files
  399. func (b *Builder) SetImagepath(path string) {
  400. b.imgpath = path
  401. }
  402. func (b *Builder) AddBuilder(typename string, bf BuilderFunc) {
  403. b.builders[typename] = bf
  404. }
  405. // build builds the gui object from the specified description.
  406. // All its children are also built recursively
  407. // Returns the built object or an error
  408. func (b *Builder) build(am map[string]interface{}, iparent IPanel) (IPanel, error) {
  409. // Get panel type
  410. itype := am[AttribType]
  411. if itype == nil {
  412. return nil, fmt.Errorf("Type not specified")
  413. }
  414. typename := itype.(string)
  415. // Get builder function for this type name
  416. builder := b.builders[typename]
  417. if builder == nil {
  418. return nil, fmt.Errorf("Invalid type:%v", typename)
  419. }
  420. // Builds panel
  421. pan, err := builder(b, am)
  422. if err != nil {
  423. return nil, err
  424. }
  425. // Adds built panel to parent
  426. if iparent != nil {
  427. iparent.GetPanel().Add(pan)
  428. }
  429. return pan, nil
  430. }
  431. // setAttribs sets common attributes from the description to the specified panel
  432. // The attributes which are set can be specified by the specified bitmask.
  433. func (b *Builder) setAttribs(am map[string]interface{}, ipan IPanel, attr uint) error {
  434. panel := ipan.GetPanel()
  435. // Set optional position
  436. if attr&aPOS != 0 && am[AttribPosition] != nil {
  437. va := am[AttribPosition].([]float32)
  438. panel.SetPosition(va[0], va[1])
  439. }
  440. // Set optional panel width
  441. if attr&aSIZE != 0 && am[AttribWidth] != nil {
  442. panel.SetWidth(am[AttribWidth].(float32))
  443. log.Error("set width:%v", am[AttribWidth])
  444. }
  445. // Sets optional panel height
  446. if attr&aSIZE != 0 && am[AttribHeight] != nil {
  447. panel.SetHeight(am[AttribHeight].(float32))
  448. }
  449. // Set optional margin sizes
  450. if attr&aMARGINS != 0 && am[AttribMargins] != nil {
  451. panel.SetMarginsFrom(am[AttribMargins].(*BorderSizes))
  452. }
  453. // Set optional border sizes
  454. if attr&aBORDERS != 0 && am[AttribBorders] != nil {
  455. panel.SetBordersFrom(am[AttribBorders].(*BorderSizes))
  456. }
  457. // Set optional border color
  458. if attr&aBORDERCOLOR != 0 && am[AttribBorderColor] != nil {
  459. panel.SetBordersColor4(am[AttribBorderColor].(*math32.Color4))
  460. }
  461. // Set optional paddings sizes
  462. if attr&aPADDINGS != 0 && am[AttribPaddings] != nil {
  463. panel.SetPaddingsFrom(am[AttribPaddings].(*BorderSizes))
  464. }
  465. // Set optional panel color
  466. if attr&aCOLOR != 0 && am[AttribColor] != nil {
  467. panel.SetColor4(am[AttribColor].(*math32.Color4))
  468. }
  469. if attr&aNAME != 0 && am[AttribName] != nil {
  470. panel.SetName(am[AttribName].(string))
  471. }
  472. if attr&aVISIBLE != 0 && am[AttribVisible] != nil {
  473. panel.SetVisible(am[AttribVisible].(bool))
  474. }
  475. if attr&aENABLED != 0 && am[AttribEnabled] != nil {
  476. panel.SetEnabled(am[AttribEnabled].(bool))
  477. }
  478. if attr&aRENDER != 0 && am[AttribRender] != nil {
  479. panel.SetRenderable(am[AttribRender].(bool))
  480. }
  481. // Sets optional layout (must pass IPanel not *Panel)
  482. err := b.setLayout(am, ipan)
  483. if err != nil {
  484. return nil
  485. }
  486. // Sets optional layout params
  487. err = b.setLayoutParams(am, panel)
  488. return err
  489. }
  490. // setLayout sets the optional layout of the specified panel
  491. func (b *Builder) setLayout(am map[string]interface{}, ipan IPanel) error {
  492. // Get layout type
  493. lai := am[AttribLayout]
  494. if lai == nil {
  495. return nil
  496. }
  497. lam := lai.(map[string]interface{})
  498. ltype := lam[AttribType]
  499. if ltype == nil {
  500. return b.err(am, AttribType, "Layout must have a type")
  501. }
  502. // Get layout builder
  503. lbuilder := b.layouts[ltype.(string)]
  504. if lbuilder == nil {
  505. return b.err(am, AttribType, "Invalid layout type")
  506. }
  507. // Builds layout builder and set to panel
  508. layout, err := lbuilder.BuildLayout(b, lam)
  509. if err != nil {
  510. return err
  511. }
  512. ipan.SetLayout(layout)
  513. return nil
  514. }
  515. // setLayoutParams sets the optional layout params of the specified panel and its attributes
  516. func (b *Builder) setLayoutParams(am map[string]interface{}, ipan IPanel) error {
  517. // Get layout params attributes
  518. lpi := am[AttribLayoutParams]
  519. if lpi == nil {
  520. return nil
  521. }
  522. lp := lpi.(map[string]interface{})
  523. // Get layout type from parent
  524. pi := am[AttribParent_]
  525. if pi == nil {
  526. return b.err(am, AttribType, "Panel has no parent")
  527. }
  528. par := pi.(map[string]interface{})
  529. v := par[AttribLayout]
  530. if v == nil {
  531. return nil
  532. }
  533. playout := v.(map[string]interface{})
  534. pltype := playout[AttribType].(string)
  535. // Get layout builder and builds layout params
  536. lbuilder := b.layouts[pltype]
  537. params, err := lbuilder.BuildParams(b, lp)
  538. if err != nil {
  539. return err
  540. }
  541. ipan.GetPanel().SetLayoutParams(params)
  542. return nil
  543. }
  544. // AttribCheckResizable checks and converts attribute with list of window resizable borders
  545. func AttribCheckResizable(b *Builder, am map[string]interface{}, fname string) error {
  546. // If attribute not found, ignore
  547. v := am[fname]
  548. if v == nil {
  549. return nil
  550. }
  551. // Attribute must be string
  552. vs, ok := v.(string)
  553. if !ok {
  554. return b.err(am, fname, "Invalid resizable attribute")
  555. }
  556. // Each string field must be a valid resizable name
  557. parts := strings.Fields(vs)
  558. var res Resizable
  559. for _, name := range parts {
  560. v, ok := mapResizable[name]
  561. if !ok {
  562. return b.err(am, fname, "Invalid resizable name:"+name)
  563. }
  564. res |= v
  565. }
  566. am[fname] = res
  567. return nil
  568. }
  569. // AttributeCheckEdge checks and converts attribute with name of layout edge
  570. func AttribCheckEdge(b *Builder, am map[string]interface{}, fname string) error {
  571. v := am[fname]
  572. if v == nil {
  573. return nil
  574. }
  575. vs, ok := v.(string)
  576. if !ok {
  577. return b.err(am, fname, "Invalid edge name")
  578. }
  579. edge, ok := mapEdgeName[vs]
  580. if !ok {
  581. return b.err(am, fname, "Invalid edge name")
  582. }
  583. am[fname] = edge
  584. return nil
  585. }
  586. // AttributeCheckLayout checks and converts layout attribute
  587. func AttribCheckLayout(b *Builder, am map[string]interface{}, fname string) error {
  588. v := am[fname]
  589. if v == nil {
  590. return nil
  591. }
  592. msi, ok := v.(map[string]interface{})
  593. if !ok {
  594. return b.err(am, fname, "Not a map")
  595. }
  596. lti := msi[AttribType]
  597. if lti == nil {
  598. return b.err(am, fname, "Layout must have a type")
  599. }
  600. lfunc := b.layouts[lti.(string)]
  601. if lfunc == nil {
  602. return b.err(am, fname, "Invalid layout type")
  603. }
  604. return nil
  605. }
  606. // AttributeCheckAlignt checks and converts layout align* attribute
  607. func AttribCheckAlign(b *Builder, am map[string]interface{}, fname string) error {
  608. v := am[fname]
  609. if v == nil {
  610. return nil
  611. }
  612. vs, ok := v.(string)
  613. if !ok {
  614. return b.err(am, fname, "Invalid alignment")
  615. }
  616. var align Align
  617. if fname == AttribAlignh {
  618. align, ok = mapAlignh[vs]
  619. } else {
  620. align, ok = mapAlignv[vs]
  621. }
  622. if !ok {
  623. return b.err(am, fname, "Invalid alignment")
  624. }
  625. am[fname] = align
  626. return nil
  627. }
  628. // AttributeCheckMenuShortcut checks and converts attribute describing menu shortcut key
  629. func AttribCheckMenuShortcut(b *Builder, am map[string]interface{}, fname string) error {
  630. v := am[fname]
  631. if v == nil {
  632. return nil
  633. }
  634. vs, ok := v.(string)
  635. if !ok {
  636. return b.err(am, fname, "Not a string")
  637. }
  638. sc := strings.Trim(vs, " ")
  639. if sc == "" {
  640. return nil
  641. }
  642. parts := strings.Split(sc, "+")
  643. var mods window.ModifierKey
  644. for i := 0; i < len(parts)-1; i++ {
  645. switch parts[i] {
  646. case "Shift":
  647. mods |= window.ModShift
  648. case "Ctrl":
  649. mods |= window.ModControl
  650. case "Alt":
  651. mods |= window.ModAlt
  652. default:
  653. return b.err(am, fname, "Invalid shortcut:"+sc)
  654. }
  655. }
  656. // The last part must be a key
  657. keyname := parts[len(parts)-1]
  658. var keycode int
  659. found := false
  660. for kcode, kname := range mapKeyText {
  661. if kname == keyname {
  662. keycode = int(kcode)
  663. found = true
  664. break
  665. }
  666. }
  667. if !found {
  668. return b.err(am, fname, "Invalid shortcut:"+sc)
  669. }
  670. am[fname] = []int{int(mods), keycode}
  671. return nil
  672. }
  673. // AttributeCheckListMap checks and converts attribute to []map[string]interface{}
  674. func AttribCheckListMap(b *Builder, am map[string]interface{}, fname string) error {
  675. v := am[fname]
  676. if v == nil {
  677. return nil
  678. }
  679. li, ok := v.([]interface{})
  680. if !ok {
  681. return b.err(am, fname, "Not a list")
  682. }
  683. lmsi := make([]map[string]interface{}, 0)
  684. for i := 0; i < len(li); i++ {
  685. item := li[i]
  686. msi, ok := item.(map[string]interface{})
  687. if !ok {
  688. return b.err(am, fname, "Item is not a map")
  689. }
  690. lmsi = append(lmsi, msi)
  691. }
  692. am[fname] = lmsi
  693. return nil
  694. }
  695. // AttributeCheckMap checks and converts attribute to map[string]interface{}
  696. func AttribCheckMap(b *Builder, am map[string]interface{}, fname string) error {
  697. v := am[fname]
  698. if v == nil {
  699. return nil
  700. }
  701. msi, ok := v.(map[string]interface{})
  702. if !ok {
  703. return b.err(am, fname, "Not a map")
  704. }
  705. am[fname] = msi
  706. return nil
  707. }
  708. // AttribCheckIcons checks and converts attribute with a list of icon names or codepoints
  709. func AttribCheckIcons(b *Builder, am map[string]interface{}, fname string) error {
  710. v := am[fname]
  711. if v == nil {
  712. return nil
  713. }
  714. fs, ok := v.(string)
  715. if !ok {
  716. return b.err(am, fname, "Not a string")
  717. }
  718. text := ""
  719. parts := strings.Fields(fs)
  720. for i := 0; i < len(parts); i++ {
  721. // Try name first
  722. cp := icon.Codepoint(parts[i])
  723. if cp != "" {
  724. text += string(cp)
  725. continue
  726. }
  727. // Try to parse as hex value
  728. val, err := strconv.ParseUint(parts[i], 16, 32)
  729. if err != nil {
  730. return b.err(am, fname, fmt.Sprintf("Invalid icon codepoint value/name:%v", parts[i]))
  731. }
  732. text += string(val)
  733. }
  734. am[fname] = text
  735. return nil
  736. }
  737. // AttribCheckColor checks and converts attribute with color name or color component values
  738. func AttribCheckColor(b *Builder, am map[string]interface{}, fname string) error {
  739. // Checks if field is nil
  740. v := am[fname]
  741. if v == nil {
  742. return nil
  743. }
  744. // Converts to string
  745. fs, ok := v.(string)
  746. if !ok {
  747. return b.err(am, fname, "Not a string")
  748. }
  749. // Checks if string field is empty
  750. fs = strings.Trim(fs, " ")
  751. if fs == "" {
  752. return nil
  753. }
  754. // If string has 1 or 2 fields it must be a color name and optional alpha
  755. parts := strings.Fields(fs)
  756. if len(parts) == 1 || len(parts) == 2 {
  757. // First part must be a color name
  758. c, ok := math32.IsColorName(parts[0])
  759. if !ok {
  760. return b.err(am, fname, fmt.Sprintf("Invalid color name:%s", parts[0]))
  761. }
  762. c4 := math32.Color4{c.R, c.G, c.B, 1}
  763. if len(parts) == 2 {
  764. val, err := strconv.ParseFloat(parts[1], 32)
  765. if err != nil {
  766. return b.err(am, fname, fmt.Sprintf("Invalid float32 value:%s", parts[1]))
  767. }
  768. c4.A = float32(val)
  769. }
  770. am[fname] = &c4
  771. return nil
  772. }
  773. // Accept 3 or 4 floats values
  774. va, err := b.parseFloats(am, fname, 3, 4)
  775. if err != nil {
  776. return err
  777. }
  778. if len(va) == 3 {
  779. am[fname] = &math32.Color4{va[0], va[1], va[2], 1}
  780. return nil
  781. }
  782. am[fname] = &math32.Color4{va[0], va[1], va[2], va[3]}
  783. return nil
  784. }
  785. // AttribCheckBorderSizes checks and convert attribute with border sizes
  786. func AttribCheckBorderSizes(b *Builder, am map[string]interface{}, fname string) error {
  787. va, err := b.parseFloats(am, fname, 1, 4)
  788. if err != nil {
  789. return err
  790. }
  791. if va == nil {
  792. return nil
  793. }
  794. if len(va) == 1 {
  795. am[fname] = &BorderSizes{va[0], va[0], va[0], va[0]}
  796. return nil
  797. }
  798. am[fname] = &BorderSizes{va[0], va[1], va[2], va[3]}
  799. return nil
  800. }
  801. // AttribCheckPosition checks and convert attribute with x and y position
  802. func AttribCheckPosition(b *Builder, am map[string]interface{}, fname string) error {
  803. v := am[fname]
  804. if v == nil {
  805. return nil
  806. }
  807. af, err := b.parseFloats(am, fname, 2, 2)
  808. if err != nil {
  809. return err
  810. }
  811. am[fname] = af
  812. return nil
  813. }
  814. // AttribCheckStringLower checks and convert string attribute to lower case
  815. func AttribCheckStringLower(b *Builder, am map[string]interface{}, fname string) error {
  816. err := AttribCheckString(b, am, fname)
  817. if err != nil {
  818. return err
  819. }
  820. if v := am[fname]; v != nil {
  821. am[fname] = strings.ToLower(v.(string))
  822. }
  823. return nil
  824. }
  825. // AttribCheckFloat checks and convert attribute to float32
  826. func AttribCheckFloat(b *Builder, am map[string]interface{}, fname string) error {
  827. v := am[fname]
  828. if v == nil {
  829. return nil
  830. }
  831. switch n := v.(type) {
  832. case int:
  833. am[fname] = float32(n)
  834. return nil
  835. case float64:
  836. am[fname] = float32(n)
  837. return nil
  838. default:
  839. return b.err(am, fname, fmt.Sprintf("Not a number:%T", v))
  840. }
  841. return nil
  842. }
  843. // AttribCheckInt checks and convert attribute to int
  844. func AttribCheckInt(b *Builder, am map[string]interface{}, fname string) error {
  845. v := am[fname]
  846. if v == nil {
  847. return nil
  848. }
  849. vint, ok := v.(int)
  850. if !ok {
  851. return b.err(am, fname, "Not an integer")
  852. }
  853. am[fname] = vint
  854. return nil
  855. }
  856. // AttribCheckString checks and convert attribute to string
  857. func AttribCheckString(b *Builder, am map[string]interface{}, fname string) error {
  858. v := am[fname]
  859. if v == nil {
  860. return nil
  861. }
  862. s, ok := v.(string)
  863. if !ok {
  864. return b.err(am, fname, "Not a string")
  865. }
  866. am[fname] = s
  867. return nil
  868. }
  869. // AttribCheckBool checks and convert attribute to bool
  870. func AttribCheckBool(b *Builder, am map[string]interface{}, fname string) error {
  871. v := am[fname]
  872. if v == nil {
  873. return nil
  874. }
  875. bv, ok := v.(bool)
  876. if !ok {
  877. return b.err(am, fname, "Not a bool")
  878. }
  879. am[fname] = bv
  880. return nil
  881. }
  882. // parseFloats parses a string with a list of floats with the specified size
  883. // and returns a slice. The specified size is 0 any number of floats is allowed.
  884. // The individual values can be separated by spaces or commas
  885. func (b *Builder) parseFloats(am map[string]interface{}, fname string, min, max int) ([]float32, error) {
  886. // Checks if field is empty
  887. v := am[fname]
  888. if v == nil {
  889. return nil, nil
  890. }
  891. // If field has only one value, it is an int or a float64
  892. switch ft := v.(type) {
  893. case int:
  894. return []float32{float32(ft)}, nil
  895. case float64:
  896. return []float32{float32(ft)}, nil
  897. }
  898. // Converts to string
  899. fs, ok := v.(string)
  900. if !ok {
  901. return nil, b.err(am, fname, "Not a string")
  902. }
  903. // Checks if string field is empty
  904. fs = strings.Trim(fs, " ")
  905. if fs == "" {
  906. return nil, nil
  907. }
  908. // Separate individual fields
  909. var parts []string
  910. if strings.Index(fs, ",") < 0 {
  911. parts = strings.Fields(fs)
  912. } else {
  913. parts = strings.Split(fs, ",")
  914. }
  915. if len(parts) < min || len(parts) > max {
  916. return nil, b.err(am, fname, "Invalid number of float32 values")
  917. }
  918. // Parse each field value and appends to slice
  919. var values []float32
  920. for i := 0; i < len(parts); i++ {
  921. val, err := strconv.ParseFloat(strings.Trim(parts[i], " "), 32)
  922. if err != nil {
  923. return nil, b.err(am, fname, err.Error())
  924. }
  925. values = append(values, float32(val))
  926. }
  927. return values, nil
  928. }
  929. // err creates and returns an error for the current object, field name and with the specified message
  930. func (b *Builder) err(am map[string]interface{}, fname, msg string) error {
  931. return fmt.Errorf("Error in object:%s field:%s -> %s", am[AttribName], fname, msg)
  932. }
  933. // debugPrint prints the internal attribute map of the builder for debugging.
  934. // This map cannot be printed by fmt.Printf() because it has cycles.
  935. // A map contains a key: _parent, which pointer to is parent map, if any.
  936. func (b *Builder) debugPrint(v interface{}, level int) {
  937. switch vt := v.(type) {
  938. case map[string]interface{}:
  939. level += 3
  940. fmt.Printf("\n")
  941. for mk, mv := range vt {
  942. if mk == AttribParent_ {
  943. continue
  944. }
  945. fmt.Printf("%s%s:", strings.Repeat(" ", level), mk)
  946. b.debugPrint(mv, level)
  947. }
  948. case []map[string]interface{}:
  949. for _, v := range vt {
  950. b.debugPrint(v, level)
  951. }
  952. default:
  953. fmt.Printf(" %v (%T)\n", vt, vt)
  954. }
  955. }