builder.go 33 KB

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