builder.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  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 = 0xFFFFFFF // 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. // Checks if layout param specifies the layout type
  589. // This is useful when the panel has no parent yet
  590. var ltype string
  591. if v := lp[AttribType]; v != nil {
  592. ltype = v.(string)
  593. } else {
  594. // Get layout type from parent
  595. pi := am[AttribParentInternal]
  596. if pi == nil {
  597. return b.err(am, AttribType, "Panel has no parent")
  598. }
  599. par := pi.(map[string]interface{})
  600. v := par[AttribLayout]
  601. if v == nil {
  602. return b.err(am, AttribType, "Parent has no layout")
  603. }
  604. playout := v.(map[string]interface{})
  605. ltype = playout[AttribType].(string)
  606. }
  607. // Get layout builder and builds layout params
  608. lbuilder := b.layouts[ltype]
  609. params, err := lbuilder.BuildParams(b, lp)
  610. if err != nil {
  611. return err
  612. }
  613. ipan.GetPanel().SetLayoutParams(params)
  614. return nil
  615. }
  616. // AttribCheckTableSortType checks and converts attribute table column sort type
  617. func AttribCheckTableSortType(b *Builder, am map[string]interface{}, fname string) error {
  618. // If attribute not found, ignore
  619. v := am[fname]
  620. if v == nil {
  621. return nil
  622. }
  623. vs, ok := v.(string)
  624. if !ok {
  625. return b.err(am, fname, "Invalid attribute")
  626. }
  627. tstype, ok := mapTableSortType[vs]
  628. if !ok {
  629. return b.err(am, fname, "Invalid attribute")
  630. }
  631. am[fname] = tstype
  632. return nil
  633. }
  634. // AttribCheckResizeBorders checks and converts attribute with list of window resizable borders
  635. func AttribCheckResizeBorders(b *Builder, am map[string]interface{}, fname string) error {
  636. // If attribute not found, ignore
  637. v := am[fname]
  638. if v == nil {
  639. return nil
  640. }
  641. // Attribute must be string
  642. vs, ok := v.(string)
  643. if !ok {
  644. return b.err(am, fname, "Invalid resizable attribute")
  645. }
  646. // Each string field must be a valid resizable name
  647. parts := strings.Fields(vs)
  648. var res ResizeBorders
  649. for _, name := range parts {
  650. v, ok := mapResizable[name]
  651. if !ok {
  652. return b.err(am, fname, "Invalid resizable name:"+name)
  653. }
  654. res |= v
  655. }
  656. am[fname] = res
  657. return nil
  658. }
  659. // AttribCheckEdge checks and converts attribute with name of layout edge
  660. func AttribCheckEdge(b *Builder, am map[string]interface{}, fname string) error {
  661. v := am[fname]
  662. if v == nil {
  663. return nil
  664. }
  665. vs, ok := v.(string)
  666. if !ok {
  667. return b.err(am, fname, "Invalid edge name")
  668. }
  669. edge, ok := mapEdgeName[vs]
  670. if !ok {
  671. return b.err(am, fname, "Invalid edge name")
  672. }
  673. am[fname] = edge
  674. return nil
  675. }
  676. // AttribCheckLayout checks and converts layout attribute
  677. func AttribCheckLayout(b *Builder, am map[string]interface{}, fname string) error {
  678. v := am[fname]
  679. if v == nil {
  680. return nil
  681. }
  682. msi, ok := v.(map[string]interface{})
  683. if !ok {
  684. return b.err(am, fname, "Not a map")
  685. }
  686. lti := msi[AttribType]
  687. if lti == nil {
  688. return b.err(am, fname, "Layout must have a type")
  689. }
  690. lfunc := b.layouts[lti.(string)]
  691. if lfunc == nil {
  692. return b.err(am, fname, "Invalid layout type")
  693. }
  694. return nil
  695. }
  696. // AttribCheckAlign checks and converts layout align* attribute
  697. func AttribCheckAlign(b *Builder, am map[string]interface{}, fname string) error {
  698. v := am[fname]
  699. if v == nil {
  700. return nil
  701. }
  702. vs, ok := v.(string)
  703. if !ok {
  704. return b.err(am, fname, "Invalid alignment")
  705. }
  706. var align Align
  707. if fname == AttribAlignh {
  708. align, ok = mapAlignh[vs]
  709. } else {
  710. align, ok = mapAlignv[vs]
  711. }
  712. if !ok {
  713. return b.err(am, fname, "Invalid alignment")
  714. }
  715. am[fname] = align
  716. return nil
  717. }
  718. // AttribCheckMenuShortcut checks and converts attribute describing menu shortcut key
  719. func AttribCheckMenuShortcut(b *Builder, am map[string]interface{}, fname string) error {
  720. v := am[fname]
  721. if v == nil {
  722. return nil
  723. }
  724. vs, ok := v.(string)
  725. if !ok {
  726. return b.err(am, fname, "Not a string")
  727. }
  728. sc := strings.Trim(vs, " ")
  729. if sc == "" {
  730. return nil
  731. }
  732. parts := strings.Split(sc, "+")
  733. var mods window.ModifierKey
  734. for i := 0; i < len(parts)-1; i++ {
  735. switch parts[i] {
  736. case "Shift":
  737. mods |= window.ModShift
  738. case "Ctrl":
  739. mods |= window.ModControl
  740. case "Alt":
  741. mods |= window.ModAlt
  742. default:
  743. return b.err(am, fname, "Invalid shortcut:"+sc)
  744. }
  745. }
  746. // The last part must be a key
  747. keyname := parts[len(parts)-1]
  748. var keycode int
  749. found := false
  750. for kcode, kname := range mapKeyText {
  751. if kname == keyname {
  752. keycode = int(kcode)
  753. found = true
  754. break
  755. }
  756. }
  757. if !found {
  758. return b.err(am, fname, "Invalid shortcut:"+sc)
  759. }
  760. am[fname] = []int{int(mods), keycode}
  761. return nil
  762. }
  763. // AttribCheckListMap checks and converts attribute to []map[string]interface{}
  764. func AttribCheckListMap(b *Builder, am map[string]interface{}, fname string) error {
  765. v := am[fname]
  766. if v == nil {
  767. return nil
  768. }
  769. li, ok := v.([]interface{})
  770. if !ok {
  771. return b.err(am, fname, "Not a list")
  772. }
  773. lmsi := make([]map[string]interface{}, 0)
  774. for i := 0; i < len(li); i++ {
  775. item := li[i]
  776. msi, ok := item.(map[string]interface{})
  777. if !ok {
  778. return b.err(am, fname, "Item is not a map")
  779. }
  780. lmsi = append(lmsi, msi)
  781. }
  782. am[fname] = lmsi
  783. return nil
  784. }
  785. // AttribCheckMap checks and converts attribute to map[string]interface{}
  786. func AttribCheckMap(b *Builder, am map[string]interface{}, fname string) error {
  787. v := am[fname]
  788. if v == nil {
  789. return nil
  790. }
  791. msi, ok := v.(map[string]interface{})
  792. if !ok {
  793. return b.err(am, fname, "Not a map")
  794. }
  795. am[fname] = msi
  796. return nil
  797. }
  798. // AttribCheckIcons checks and converts attribute with a list of icon names or codepoints
  799. func AttribCheckIcons(b *Builder, am map[string]interface{}, fname string) error {
  800. v := am[fname]
  801. if v == nil {
  802. return nil
  803. }
  804. fs, ok := v.(string)
  805. if !ok {
  806. return b.err(am, fname, "Not a string")
  807. }
  808. text := ""
  809. parts := strings.Fields(fs)
  810. for i := 0; i < len(parts); i++ {
  811. // Try name first
  812. cp := icon.Codepoint(parts[i])
  813. if cp != "" {
  814. text += string(cp)
  815. continue
  816. }
  817. // Try to parse as hex value
  818. val, err := strconv.ParseUint(parts[i], 16, 32)
  819. if err != nil {
  820. return b.err(am, fname, fmt.Sprintf("Invalid icon codepoint value/name:%v", parts[i]))
  821. }
  822. text += string(val)
  823. }
  824. am[fname] = text
  825. return nil
  826. }
  827. // AttribCheckColor checks and converts attribute with color name or color component values
  828. func AttribCheckColor(b *Builder, am map[string]interface{}, fname string) error {
  829. // Checks if field is nil
  830. v := am[fname]
  831. if v == nil {
  832. return nil
  833. }
  834. // Converts to string
  835. fs, ok := v.(string)
  836. if !ok {
  837. return b.err(am, fname, "Not a string")
  838. }
  839. // Checks if string field is empty
  840. fs = strings.Trim(fs, " ")
  841. if fs == "" {
  842. return nil
  843. }
  844. // If string has 1 or 2 fields it must be a color name and optional alpha
  845. parts := strings.Fields(fs)
  846. if len(parts) == 1 || len(parts) == 2 {
  847. // First part must be a color name
  848. c, ok := math32.IsColorName(parts[0])
  849. if !ok {
  850. return b.err(am, fname, fmt.Sprintf("Invalid color name:%s", parts[0]))
  851. }
  852. c4 := math32.Color4{c.R, c.G, c.B, 1}
  853. if len(parts) == 2 {
  854. val, err := strconv.ParseFloat(parts[1], 32)
  855. if err != nil {
  856. return b.err(am, fname, fmt.Sprintf("Invalid float32 value:%s", parts[1]))
  857. }
  858. c4.A = float32(val)
  859. }
  860. am[fname] = &c4
  861. return nil
  862. }
  863. // Accept 3 or 4 floats values
  864. va, err := b.parseFloats(am, fname, 3, 4)
  865. if err != nil {
  866. return err
  867. }
  868. if len(va) == 3 {
  869. am[fname] = &math32.Color4{va[0], va[1], va[2], 1}
  870. return nil
  871. }
  872. am[fname] = &math32.Color4{va[0], va[1], va[2], va[3]}
  873. return nil
  874. }
  875. // AttribCheckBorderSizes checks and convert attribute with border sizes
  876. func AttribCheckBorderSizes(b *Builder, am map[string]interface{}, fname string) error {
  877. va, err := b.parseFloats(am, fname, 1, 4)
  878. if err != nil {
  879. return err
  880. }
  881. if va == nil {
  882. return nil
  883. }
  884. if len(va) == 1 {
  885. am[fname] = &BorderSizes{va[0], va[0], va[0], va[0]}
  886. return nil
  887. }
  888. am[fname] = &BorderSizes{va[0], va[1], va[2], va[3]}
  889. return nil
  890. }
  891. // AttribCheckPosition checks and convert attribute with x and y position
  892. func AttribCheckPosition(b *Builder, am map[string]interface{}, fname string) error {
  893. v := am[fname]
  894. if v == nil {
  895. return nil
  896. }
  897. af, err := b.parseFloats(am, fname, 2, 2)
  898. if err != nil {
  899. return err
  900. }
  901. am[fname] = af
  902. return nil
  903. }
  904. // AttribCheckStringLower checks and convert string attribute to lower case
  905. func AttribCheckStringLower(b *Builder, am map[string]interface{}, fname string) error {
  906. err := AttribCheckString(b, am, fname)
  907. if err != nil {
  908. return err
  909. }
  910. if v := am[fname]; v != nil {
  911. am[fname] = strings.ToLower(v.(string))
  912. }
  913. return nil
  914. }
  915. // AttribCheckFloat checks and convert attribute to float32
  916. func AttribCheckFloat(b *Builder, am map[string]interface{}, fname string) error {
  917. v := am[fname]
  918. if v == nil {
  919. return nil
  920. }
  921. switch n := v.(type) {
  922. case int:
  923. am[fname] = float32(n)
  924. return nil
  925. case float64:
  926. am[fname] = float32(n)
  927. return nil
  928. default:
  929. return b.err(am, fname, fmt.Sprintf("Not a number:%T", v))
  930. }
  931. return nil
  932. }
  933. // AttribCheckInt checks and convert attribute to int
  934. func AttribCheckInt(b *Builder, am map[string]interface{}, fname string) error {
  935. v := am[fname]
  936. if v == nil {
  937. return nil
  938. }
  939. vint, ok := v.(int)
  940. if !ok {
  941. return b.err(am, fname, "Not an integer")
  942. }
  943. am[fname] = vint
  944. return nil
  945. }
  946. // AttribCheckString checks and convert attribute to string
  947. func AttribCheckString(b *Builder, am map[string]interface{}, fname string) error {
  948. v := am[fname]
  949. if v == nil {
  950. return nil
  951. }
  952. s, ok := v.(string)
  953. if !ok {
  954. return b.err(am, fname, "Not a string")
  955. }
  956. am[fname] = s
  957. return nil
  958. }
  959. // AttribCheckBool checks and convert attribute to bool
  960. func AttribCheckBool(b *Builder, am map[string]interface{}, fname string) error {
  961. v := am[fname]
  962. if v == nil {
  963. return nil
  964. }
  965. bv, ok := v.(bool)
  966. if !ok {
  967. return b.err(am, fname, "Not a bool")
  968. }
  969. am[fname] = bv
  970. return nil
  971. }
  972. // parseFloats parses a string with a list of floats with the specified size
  973. // and returns a slice. The specified size is 0 any number of floats is allowed.
  974. // The individual values can be separated by spaces or commas
  975. func (b *Builder) parseFloats(am map[string]interface{}, fname string, min, max int) ([]float32, error) {
  976. // Checks if field is empty
  977. v := am[fname]
  978. if v == nil {
  979. return nil, nil
  980. }
  981. // If field has only one value, it is an int or a float64
  982. switch ft := v.(type) {
  983. case int:
  984. return []float32{float32(ft)}, nil
  985. case float64:
  986. return []float32{float32(ft)}, nil
  987. }
  988. // Converts to string
  989. fs, ok := v.(string)
  990. if !ok {
  991. return nil, b.err(am, fname, "Not a string")
  992. }
  993. // Checks if string field is empty
  994. fs = strings.Trim(fs, " ")
  995. if fs == "" {
  996. return nil, nil
  997. }
  998. // Separate individual fields
  999. var parts []string
  1000. if strings.Index(fs, ",") < 0 {
  1001. parts = strings.Fields(fs)
  1002. } else {
  1003. parts = strings.Split(fs, ",")
  1004. }
  1005. if len(parts) < min || len(parts) > max {
  1006. return nil, b.err(am, fname, "Invalid number of float32 values")
  1007. }
  1008. // Parse each field value and appends to slice
  1009. var values []float32
  1010. for i := 0; i < len(parts); i++ {
  1011. val, err := strconv.ParseFloat(strings.Trim(parts[i], " "), 32)
  1012. if err != nil {
  1013. return nil, b.err(am, fname, err.Error())
  1014. }
  1015. values = append(values, float32(val))
  1016. }
  1017. return values, nil
  1018. }
  1019. // err creates and returns an error for the current object, field name and with the specified message
  1020. func (b *Builder) err(am map[string]interface{}, fname, msg string) error {
  1021. // Get path of objects till the error
  1022. names := []string{}
  1023. var name string
  1024. for {
  1025. if v := am[AttribName]; v != nil {
  1026. name = v.(string)
  1027. } else {
  1028. name = "?"
  1029. }
  1030. names = append(names, name)
  1031. var par interface{}
  1032. if par = am[AttribParentInternal]; par == nil {
  1033. break
  1034. }
  1035. am = par.(map[string]interface{})
  1036. }
  1037. path := []string{}
  1038. for i := len(names) - 1; i >= 0; i-- {
  1039. path = append(path, names[i])
  1040. }
  1041. return fmt.Errorf("Error in object:%s field:%s -> %s", strings.Join(path, "/"), fname, msg)
  1042. }
  1043. // debugPrint prints the internal attribute map of the builder for debugging.
  1044. // This map cannot be printed by fmt.Printf() because it has cycles.
  1045. // A map contains a key: _parent, which pointer to is parent map, if any.
  1046. func (b *Builder) debugPrint(v interface{}, level int) {
  1047. switch vt := v.(type) {
  1048. case map[string]interface{}:
  1049. level += 3
  1050. fmt.Printf("\n")
  1051. for mk, mv := range vt {
  1052. if mk == AttribParentInternal {
  1053. continue
  1054. }
  1055. fmt.Printf("%s%s:", strings.Repeat(" ", level), mk)
  1056. b.debugPrint(mv, level)
  1057. }
  1058. case []map[string]interface{}:
  1059. for _, v := range vt {
  1060. b.debugPrint(v, level)
  1061. }
  1062. default:
  1063. fmt.Printf(" %v (%T)\n", vt, vt)
  1064. }
  1065. }