builder.go 32 KB

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