builder.go 31 KB

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