builder.go 33 KB

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