builder.go 33 KB

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