builder.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  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. "path/filepath"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "github.com/g3n/engine/gui/assets/icon"
  14. "github.com/g3n/engine/math32"
  15. "github.com/g3n/engine/window"
  16. "gopkg.in/yaml.v2"
  17. )
  18. // Builder builds GUI objects from a declarative description in YAML format
  19. type Builder struct {
  20. am map[string]interface{} // parsed map with gui object atttributes
  21. imgpath string // base path for image panels files
  22. builders map[string]BuilderFunc // map of builder functions by type
  23. attribs map[string]AttribCheckFunc // map of attribute name with check functions
  24. layouts map[string]IBuilderLayout // map of layout type to layout builder
  25. }
  26. // IBuilderLayout is the interface for all layout builders
  27. type IBuilderLayout interface {
  28. BuildLayout(b *Builder, am map[string]interface{}) (ILayout, error)
  29. BuildParams(b *Builder, am map[string]interface{}) (interface{}, error)
  30. }
  31. // BuilderFunc is type for functions which build a gui object from an attribute map
  32. type BuilderFunc func(*Builder, map[string]interface{}) (IPanel, error)
  33. // Panel and layout types
  34. const (
  35. TypePanel = "panel"
  36. TypeImagePanel = "imagepanel"
  37. TypeLabel = "label"
  38. TypeImageLabel = "imagelabel"
  39. TypeButton = "button"
  40. TypeCheckBox = "checkbox"
  41. TypeRadioButton = "radiobutton"
  42. TypeEdit = "edit"
  43. TypeVList = "vlist"
  44. TypeHList = "hlist"
  45. TypeDropDown = "dropdown"
  46. TypeHSlider = "hslider"
  47. TypeVSlider = "vslider"
  48. TypeHSplitter = "hsplitter"
  49. TypeVSplitter = "vsplitter"
  50. TypeSeparator = "separator"
  51. TypeTree = "tree"
  52. TypeTreeNode = "node"
  53. TypeMenuBar = "menubar"
  54. TypeMenu = "menu"
  55. TypeWindow = "window"
  56. TypeHBoxLayout = "hbox"
  57. TypeVBoxLayout = "vbox"
  58. TypeGridLayout = "grid"
  59. TypeDockLayout = "dock"
  60. )
  61. // Common attribute names
  62. const (
  63. AttribAlignv = "alignv" // Align
  64. AttribAlignh = "alignh" // Align
  65. AttribAspectHeight = "aspectheight" // float32
  66. AttribAspectWidth = "aspectwidth" // float32
  67. AttribBgColor = "bgcolor" // Color4
  68. AttribBorders = "borders" // BorderSizes
  69. AttribBorderColor = "bordercolor" // Color4
  70. AttribChecked = "checked" // bool
  71. AttribColor = "color" // Color4
  72. AttribCols = "cols" // Int
  73. AttribColSpan = "colspan" // Int
  74. AttribEdge = "edge" // int
  75. AttribEnabled = "enabled" // bool
  76. AttribExpand = "expand" // float32
  77. AttribExpandh = "expandh" // bool
  78. AttribExpandv = "expandv" // bool
  79. AttribFontColor = "fontcolor" // Color4
  80. AttribFontDPI = "fontdpi" // float32
  81. AttribFontSize = "fontsize" // float32
  82. AttribGroup = "group" // string
  83. AttribHeight = "height" // float32
  84. AttribIcon = "icon" // string
  85. AttribImageFile = "imagefile" // string
  86. AttribImageLabel = "imagelabel" // []map[string]interface{}
  87. AttribItems = "items" // []map[string]interface{}
  88. AttribLayout = "layout" // map[string]interface{}
  89. AttribLayoutParams = "layoutparams" // map[string]interface{}
  90. AttribLineSpacing = "linespacing" // float32
  91. AttribMinHeight = "minheight" // bool
  92. AttribMinWidth = "minwidth" // bool
  93. AttribMargins = "margins" // BorderSizes
  94. AttribName = "name" // string
  95. AttribPaddings = "paddings" // BorderSizes
  96. AttribPanel0 = "panel0" // map[string]interface{}
  97. AttribPanel1 = "panel1" // map[string]interface{}
  98. AttribParent_ = "parent_" // string (internal attribute)
  99. AttribPlaceHolder = "placeholder" // string
  100. AttribPosition = "position" // []float32
  101. AttribRender = "render" // bool
  102. AttribResizable = "resizable" // Resizable
  103. AttribScaleFactor = "scalefactor" // float32
  104. AttribShortcut = "shortcut" // []int
  105. AttribSpacing = "spacing" // float32
  106. AttribSplit = "split" // float32
  107. AttribText = "text" // string
  108. AttribTitle = "title" // string
  109. AttribType = "type" // string
  110. AttribWidth = "width" // float32
  111. AttribValue = "value" // float32
  112. AttribVisible = "visible" // bool
  113. )
  114. const (
  115. aPOS = 1 << iota // attribute position
  116. aSIZE = 1 << iota // attribute size
  117. aNAME = 1 << iota // attribute name
  118. aMARGINS = 1 << iota // attribute margins widths
  119. aBORDERS = 1 << iota // attribute borders widths
  120. aBORDERCOLOR = 1 << iota // attribute border color
  121. aPADDINGS = 1 << iota // attribute paddings widths
  122. aCOLOR = 1 << iota // attribute panel bgcolor
  123. aENABLED = 1 << iota // attribute enabled for events
  124. aRENDER = 1 << iota // attribute renderable
  125. aVISIBLE = 1 << iota // attribute visible
  126. asPANEL = 0xFF // attribute set for panels
  127. asWIDGET = aPOS | aNAME | aSIZE | aENABLED | aVISIBLE // attribute set for widgets
  128. )
  129. // maps align name with align parameter
  130. var mapAlignh = map[string]Align{
  131. "none": AlignNone,
  132. "left": AlignLeft,
  133. "right": AlignRight,
  134. "width": AlignWidth,
  135. "center": AlignCenter,
  136. }
  137. // maps align name with align parameter
  138. var mapAlignv = map[string]Align{
  139. "none": AlignNone,
  140. "top": AlignTop,
  141. "bottom": AlignBottom,
  142. "height": AlignHeight,
  143. "center": AlignCenter,
  144. }
  145. // maps edge name (dock layout) with edge parameter
  146. var mapEdgeName = map[string]int{
  147. "top": DockTop,
  148. "right": DockRight,
  149. "bottom": DockBottom,
  150. "left": DockLeft,
  151. "center": DockCenter,
  152. }
  153. // maps resize border name (window) with parameter value
  154. var mapResizable = map[string]Resizable{
  155. "top": ResizeTop,
  156. "right": ResizeRight,
  157. "bottom": ResizeBottom,
  158. "left": ResizeLeft,
  159. "all": ResizeAll,
  160. }
  161. type AttribCheckFunc func(b *Builder, am map[string]interface{}, fname string) error
  162. // NewBuilder creates and returns a pointer to a new gui Builder object
  163. func NewBuilder() *Builder {
  164. b := new(Builder)
  165. // Sets map of object type to builder function
  166. b.builders = map[string]BuilderFunc{
  167. TypePanel: buildPanel,
  168. TypeImagePanel: buildImagePanel,
  169. TypeLabel: buildLabel,
  170. TypeImageLabel: buildImageLabel,
  171. TypeButton: buildButton,
  172. TypeEdit: buildEdit,
  173. TypeCheckBox: buildCheckBox,
  174. TypeRadioButton: buildRadioButton,
  175. TypeVList: buildVList,
  176. TypeHList: buildHList,
  177. TypeDropDown: buildDropDown,
  178. TypeMenu: buildMenu,
  179. TypeMenuBar: buildMenu,
  180. TypeHSlider: buildSlider,
  181. TypeVSlider: buildSlider,
  182. TypeHSplitter: buildSplitter,
  183. TypeVSplitter: buildSplitter,
  184. TypeTree: buildTree,
  185. TypeWindow: buildWindow,
  186. }
  187. // Sets map of layout type name to layout function
  188. b.layouts = map[string]IBuilderLayout{
  189. TypeHBoxLayout: &BuilderLayoutHBox{},
  190. TypeVBoxLayout: &BuilderLayoutVBox{},
  191. TypeGridLayout: &BuilderLayoutGrid{},
  192. TypeDockLayout: &BuilderLayoutDock{},
  193. }
  194. // Sets map of attribute name to check function
  195. b.attribs = map[string]AttribCheckFunc{
  196. AttribAlignv: AttribCheckAlign,
  197. AttribAlignh: AttribCheckAlign,
  198. AttribAspectWidth: AttribCheckFloat,
  199. AttribAspectHeight: AttribCheckFloat,
  200. AttribHeight: AttribCheckFloat,
  201. AttribMargins: AttribCheckBorderSizes,
  202. AttribBgColor: AttribCheckColor,
  203. AttribBorders: AttribCheckBorderSizes,
  204. AttribBorderColor: AttribCheckColor,
  205. AttribChecked: AttribCheckBool,
  206. AttribColor: AttribCheckColor,
  207. AttribCols: AttribCheckInt,
  208. AttribColSpan: AttribCheckInt,
  209. AttribEdge: AttribCheckEdge,
  210. AttribEnabled: AttribCheckBool,
  211. AttribExpand: AttribCheckFloat,
  212. AttribExpandh: AttribCheckBool,
  213. AttribExpandv: AttribCheckBool,
  214. AttribFontColor: AttribCheckColor,
  215. AttribFontDPI: AttribCheckFloat,
  216. AttribFontSize: AttribCheckFloat,
  217. AttribGroup: AttribCheckString,
  218. AttribIcon: AttribCheckIcons,
  219. AttribImageFile: AttribCheckString,
  220. AttribImageLabel: AttribCheckMap,
  221. AttribItems: AttribCheckListMap,
  222. AttribLayout: AttribCheckLayout,
  223. AttribLayoutParams: AttribCheckMap,
  224. AttribLineSpacing: AttribCheckFloat,
  225. AttribMinHeight: AttribCheckBool,
  226. AttribMinWidth: AttribCheckBool,
  227. AttribName: AttribCheckString,
  228. AttribPaddings: AttribCheckBorderSizes,
  229. AttribPanel0: AttribCheckMap,
  230. AttribPanel1: AttribCheckMap,
  231. AttribPlaceHolder: AttribCheckString,
  232. AttribPosition: AttribCheckPosition,
  233. AttribRender: AttribCheckBool,
  234. AttribResizable: AttribCheckResizable,
  235. AttribScaleFactor: AttribCheckFloat,
  236. AttribShortcut: AttribCheckMenuShortcut,
  237. AttribSpacing: AttribCheckFloat,
  238. AttribSplit: AttribCheckFloat,
  239. AttribText: AttribCheckString,
  240. AttribTitle: AttribCheckString,
  241. AttribType: AttribCheckStringLower,
  242. AttribValue: AttribCheckFloat,
  243. AttribVisible: AttribCheckBool,
  244. AttribWidth: AttribCheckFloat,
  245. }
  246. return b
  247. }
  248. // ParseString parses a string with gui objects descriptions in YAML format
  249. // It there was a previously parsed description, it is cleared.
  250. func (b *Builder) ParseString(desc string) error {
  251. // Parses descriptor string in YAML format saving result in
  252. // a map of interface{} to interface{} as YAML allows numeric keys.
  253. var mii map[interface{}]interface{}
  254. err := yaml.Unmarshal([]byte(desc), &mii)
  255. if err != nil {
  256. return err
  257. }
  258. // If all the values of the top level map keys are other maps,
  259. // then it is a description of several objects, otherwise it is
  260. // a description of a single object.
  261. single := false
  262. for _, v := range mii {
  263. _, ok := v.(map[interface{}]interface{})
  264. if !ok {
  265. single = true
  266. break
  267. }
  268. }
  269. log.Error("single:%v", single)
  270. // Internal function which converts map[interface{}]interface{} to
  271. // map[string]interface{} recursively and lower case of all map keys.
  272. // It also sets a field named "parent_", which pointer to the parent map
  273. // This field causes a circular reference in the result map which prevents
  274. // the use of Go's Printf to print the result map.
  275. var visitor func(v, par interface{}) (interface{}, error)
  276. visitor = func(v, par interface{}) (interface{}, error) {
  277. switch vt := v.(type) {
  278. case []interface{}:
  279. ls := []interface{}{}
  280. for _, item := range vt {
  281. ci, err := visitor(item, par)
  282. if err != nil {
  283. return nil, err
  284. }
  285. ls = append(ls, ci)
  286. }
  287. return ls, nil
  288. case map[interface{}]interface{}:
  289. ms := make(map[string]interface{})
  290. for k, v := range vt {
  291. // Checks key
  292. ks, ok := k.(string)
  293. if !ok {
  294. return nil, fmt.Errorf("Keys must be strings")
  295. }
  296. ks = strings.ToLower(ks)
  297. // Checks value
  298. vi, err := visitor(v, ms)
  299. if err != nil {
  300. return nil, err
  301. }
  302. ms[ks] = vi
  303. // If has panel has parent or is a single top level panel, checks attributes
  304. if par != nil || single {
  305. // Get attribute check function
  306. acf, ok := b.attribs[ks]
  307. if !ok {
  308. return nil, fmt.Errorf("Invalid attribute:%s", ks)
  309. }
  310. // Checks attribute
  311. err = acf(b, ms, ks)
  312. if err != nil {
  313. return nil, err
  314. }
  315. }
  316. }
  317. if par != nil {
  318. ms[AttribParent_] = par
  319. }
  320. return ms, nil
  321. default:
  322. return v, nil
  323. }
  324. return nil, nil
  325. }
  326. // Get map[string]interface{} with lower case keys from parsed descritor
  327. res, err := visitor(mii, nil)
  328. if err != nil {
  329. return err
  330. }
  331. msi, ok := res.(map[string]interface{})
  332. if !ok {
  333. return fmt.Errorf("Parsed result is not a map")
  334. }
  335. b.am = msi
  336. //b.debugPrint(b.am, 1)
  337. return nil
  338. }
  339. // ParseFile parses a file with gui objects descriptions in YAML format
  340. // It there was a previously parsed description, it is cleared.
  341. func (b *Builder) ParseFile(filepath string) error {
  342. // Reads all file data
  343. f, err := os.Open(filepath)
  344. if err != nil {
  345. return err
  346. }
  347. data, err := ioutil.ReadAll(f)
  348. if err != nil {
  349. return err
  350. }
  351. err = f.Close()
  352. if err != nil {
  353. return err
  354. }
  355. // Parses file data
  356. return b.ParseString(string(data))
  357. }
  358. // Names returns a sorted list of names of top level previously parsed objects.
  359. // Only objects with defined types are returned.
  360. // If there is only a single object with no name, its name is returned
  361. // as an empty string
  362. func (b *Builder) Names() []string {
  363. var objs []string
  364. if b.am[AttribType] != nil {
  365. objs = append(objs, "")
  366. return objs
  367. }
  368. for name, _ := range b.am {
  369. objs = append(objs, name)
  370. }
  371. sort.Strings(objs)
  372. return objs
  373. }
  374. // Build builds a gui object and all its children recursively.
  375. // The specified name should be a top level name from a
  376. // from a previously parsed description
  377. // If the descriptions contains a single object with no name,
  378. // It should be specified the empty string to build this object.
  379. func (b *Builder) Build(name string) (IPanel, error) {
  380. // Only one object
  381. if name == "" {
  382. return b.build(b.am, nil)
  383. }
  384. // Map of gui objects
  385. am, ok := b.am[name]
  386. if !ok {
  387. return nil, fmt.Errorf("Object name:%s not found", name)
  388. }
  389. return b.build(am.(map[string]interface{}), nil)
  390. }
  391. // Sets the path for image panels relative image files
  392. func (b *Builder) SetImagepath(path string) {
  393. b.imgpath = path
  394. }
  395. func (b *Builder) AddBuilder(typename string, bf BuilderFunc) {
  396. b.builders[typename] = bf
  397. }
  398. // build builds the gui object from the specified description.
  399. // All its children are also built recursively
  400. // Returns the built object or an error
  401. func (b *Builder) build(am map[string]interface{}, iparent IPanel) (IPanel, error) {
  402. // Get panel type
  403. itype := am[AttribType]
  404. if itype == nil {
  405. return nil, fmt.Errorf("Type not specified")
  406. }
  407. typename := itype.(string)
  408. // Get builder function for this type name
  409. builder := b.builders[typename]
  410. if builder == nil {
  411. return nil, fmt.Errorf("Invalid type:%v", typename)
  412. }
  413. // Builds panel
  414. pan, err := builder(b, am)
  415. if err != nil {
  416. return nil, err
  417. }
  418. // Adds built panel to parent
  419. if iparent != nil {
  420. iparent.GetPanel().Add(pan)
  421. }
  422. return pan, nil
  423. }
  424. // buildPanel builds an object of type Panel
  425. func buildPanel(b *Builder, am map[string]interface{}) (IPanel, error) {
  426. pan := NewPanel(0, 0)
  427. err := b.setAttribs(am, pan, asPANEL)
  428. if err != nil {
  429. return nil, err
  430. }
  431. // Builds children recursively
  432. if am[AttribItems] != nil {
  433. items := am[AttribItems].([]map[string]interface{})
  434. for i := 0; i < len(items); i++ {
  435. item := items[i]
  436. child, err := b.build(item, pan)
  437. if err != nil {
  438. return nil, err
  439. }
  440. pan.Add(child)
  441. }
  442. }
  443. return pan, nil
  444. }
  445. // buildImagePanel builds a gui object of type ImagePanel
  446. func buildImagePanel(b *Builder, am map[string]interface{}) (IPanel, error) {
  447. // Checks imagefile attribute
  448. if am[AttribImageFile] == nil {
  449. return nil, b.err(am, AttribImageFile, "Must be supplied")
  450. }
  451. // If path is not absolute join with user supplied image base path
  452. imagefile := am[AttribImageFile].(string)
  453. if !filepath.IsAbs(imagefile) {
  454. imagefile = filepath.Join(b.imgpath, imagefile)
  455. }
  456. // Builds panel and set common attributes
  457. panel, err := NewImage(imagefile)
  458. if err != nil {
  459. return nil, err
  460. }
  461. err = b.setAttribs(am, panel, asPANEL)
  462. if err != nil {
  463. return nil, err
  464. }
  465. // Sets optional AspectWidth attribute
  466. if aw := am[AttribAspectWidth]; aw != nil {
  467. panel.SetContentAspectWidth(aw.(float32))
  468. }
  469. // Sets optional AspectHeight attribute
  470. if ah := am[AttribAspectHeight]; ah != nil {
  471. panel.SetContentAspectHeight(ah.(float32))
  472. }
  473. // Builds children recursively
  474. if am[AttribItems] != nil {
  475. items := am[AttribItems].([]map[string]interface{})
  476. for i := 0; i < len(items); i++ {
  477. item := items[i]
  478. child, err := b.build(item, panel)
  479. if err != nil {
  480. return nil, err
  481. }
  482. panel.Add(child)
  483. }
  484. }
  485. return panel, nil
  486. }
  487. // buildLabel builds a gui object of type Label
  488. func buildLabel(b *Builder, am map[string]interface{}) (IPanel, error) {
  489. var label *Label
  490. if am[AttribIcon] != nil {
  491. label = NewLabel(am[AttribIcon].(string), true)
  492. } else if am[AttribText] != nil {
  493. label = NewLabel(am[AttribText].(string))
  494. } else {
  495. label = NewLabel("")
  496. }
  497. // Sets common attributes
  498. err := b.setAttribs(am, label, asPANEL)
  499. if err != nil {
  500. return nil, err
  501. }
  502. // Set optional background color
  503. if bgc := am[AttribBgColor]; bgc != nil {
  504. label.SetBgColor4(bgc.(*math32.Color4))
  505. }
  506. // Set optional font color
  507. if fc := am[AttribFontColor]; fc != nil {
  508. label.SetColor4(fc.(*math32.Color4))
  509. }
  510. // Sets optional font size
  511. if fs := am[AttribFontSize]; fs != nil {
  512. label.SetFontSize(float64(fs.(float32)))
  513. }
  514. // Sets optional font dpi
  515. if fdpi := am[AttribFontDPI]; fdpi != nil {
  516. label.SetFontDPI(float64(fdpi.(float32)))
  517. }
  518. // Sets optional line spacing
  519. if ls := am[AttribLineSpacing]; ls != nil {
  520. label.SetLineSpacing(float64(ls.(float32)))
  521. }
  522. return label, nil
  523. }
  524. // buildImageLabel builds a gui object of type: ImageLabel
  525. func buildImageLabel(b *Builder, am map[string]interface{}) (IPanel, error) {
  526. // Builds image label and set common attributes
  527. var text string
  528. if am[AttribText] != nil {
  529. text = am[AttribText].(string)
  530. }
  531. imglabel := NewImageLabel(text)
  532. err := b.setAttribs(am, imglabel, asPANEL)
  533. if err != nil {
  534. return nil, err
  535. }
  536. // Sets optional icon(s)
  537. if icon := am[AttribIcon]; icon != nil {
  538. imglabel.SetIcon(icon.(string))
  539. }
  540. // Sets optional image from file
  541. // If path is not absolute join with user supplied image base path
  542. if imgf := am[AttribImageFile]; imgf != nil {
  543. path := imgf.(string)
  544. if !filepath.IsAbs(path) {
  545. path = filepath.Join(b.imgpath, path)
  546. }
  547. err := imglabel.SetImageFromFile(path)
  548. if err != nil {
  549. return nil, err
  550. }
  551. }
  552. return imglabel, nil
  553. }
  554. // buildButton builds a gui object of type: Button
  555. func buildButton(b *Builder, am map[string]interface{}) (IPanel, error) {
  556. // Builds button and set commont attributes
  557. var text string
  558. if am[AttribText] != nil {
  559. text = am[AttribText].(string)
  560. }
  561. button := NewButton(text)
  562. err := b.setAttribs(am, button, asWIDGET)
  563. if err != nil {
  564. return nil, err
  565. }
  566. // Sets optional icon(s)
  567. if icon := am[AttribIcon]; icon != nil {
  568. button.SetIcon(icon.(string))
  569. }
  570. // Sets optional image from file
  571. // If path is not absolute join with user supplied image base path
  572. if imgf := am[AttribImageFile]; imgf != nil {
  573. path := imgf.(string)
  574. if !filepath.IsAbs(path) {
  575. path = filepath.Join(b.imgpath, path)
  576. }
  577. err := button.SetImage(path)
  578. if err != nil {
  579. return nil, err
  580. }
  581. }
  582. return button, nil
  583. }
  584. // buildEdit builds a gui object of type: "Edit"
  585. func buildEdit(b *Builder, am map[string]interface{}) (IPanel, error) {
  586. // Builds button and set attributes
  587. var width float32
  588. var placeholder string
  589. if aw := am[AttribWidth]; aw != nil {
  590. width = aw.(float32)
  591. }
  592. if ph := am[AttribPlaceHolder]; ph != nil {
  593. placeholder = ph.(string)
  594. }
  595. edit := NewEdit(int(width), placeholder)
  596. err := b.setAttribs(am, edit, asWIDGET)
  597. if err != nil {
  598. return nil, err
  599. }
  600. return edit, nil
  601. }
  602. // buildCheckBox builds a gui object of type: CheckBox
  603. func buildCheckBox(b *Builder, am map[string]interface{}) (IPanel, error) {
  604. // Builds check box and set commont attributes
  605. var text string
  606. if am[AttribText] != nil {
  607. text = am[AttribText].(string)
  608. }
  609. cb := NewCheckBox(text)
  610. err := b.setAttribs(am, cb, asWIDGET)
  611. if err != nil {
  612. return nil, err
  613. }
  614. // Sets optional checked value
  615. if checked := am[AttribChecked]; checked != nil {
  616. cb.SetValue(checked.(bool))
  617. }
  618. return cb, nil
  619. }
  620. // buildRadioButton builds a gui object of type: RadioButton
  621. func buildRadioButton(b *Builder, am map[string]interface{}) (IPanel, error) {
  622. // Builds check box and set commont attributes
  623. var text string
  624. if am[AttribText] != nil {
  625. text = am[AttribText].(string)
  626. }
  627. rb := NewRadioButton(text)
  628. err := b.setAttribs(am, rb, asWIDGET)
  629. if err != nil {
  630. return nil, err
  631. }
  632. // Sets optional radio button group
  633. if gr := am[AttribGroup]; gr != nil {
  634. rb.SetGroup(gr.(string))
  635. }
  636. // Sets optional checked value
  637. if checked := am[AttribChecked]; checked != nil {
  638. rb.SetValue(checked.(bool))
  639. }
  640. return rb, nil
  641. }
  642. // buildVList builds a gui object of type: VList
  643. func buildVList(b *Builder, am map[string]interface{}) (IPanel, error) {
  644. // Builds list and set commont attributes
  645. list := NewVList(0, 0)
  646. err := b.setAttribs(am, list, asWIDGET)
  647. if err != nil {
  648. return nil, err
  649. }
  650. // Builds children
  651. if am[AttribItems] != nil {
  652. items := am[AttribItems].([]map[string]interface{})
  653. for i := 0; i < len(items); i++ {
  654. item := items[i]
  655. child, err := b.build(item, list)
  656. if err != nil {
  657. return nil, err
  658. }
  659. list.Add(child)
  660. }
  661. }
  662. return list, nil
  663. }
  664. // buildHList builds a gui object of type: VList
  665. func buildHList(b *Builder, am map[string]interface{}) (IPanel, error) {
  666. // Builds list and set commont attributes
  667. list := NewHList(0, 0)
  668. err := b.setAttribs(am, list, asWIDGET)
  669. if err != nil {
  670. return nil, err
  671. }
  672. // Builds children
  673. if am[AttribItems] != nil {
  674. items := am[AttribItems].([]map[string]interface{})
  675. for i := 0; i < len(items); i++ {
  676. item := items[i]
  677. child, err := b.build(item, list)
  678. if err != nil {
  679. return nil, err
  680. }
  681. list.Add(child)
  682. }
  683. }
  684. return list, nil
  685. }
  686. // buildDropDown builds a gui object of type: DropDown
  687. func buildDropDown(b *Builder, am map[string]interface{}) (IPanel, error) {
  688. // If image label attribute defined use it, otherwise
  689. // uses default value.
  690. var imglabel *ImageLabel
  691. if iv := am[AttribImageLabel]; iv != nil {
  692. imgl := iv.(map[string]interface{})
  693. imgl[AttribType] = TypeImageLabel
  694. ipan, err := b.build(imgl, nil)
  695. if err != nil {
  696. return nil, err
  697. }
  698. imglabel = ipan.(*ImageLabel)
  699. } else {
  700. imglabel = NewImageLabel("")
  701. }
  702. // Builds drop down and set common attributes
  703. dd := NewDropDown(0, imglabel)
  704. err := b.setAttribs(am, dd, asWIDGET)
  705. if err != nil {
  706. return nil, err
  707. }
  708. // Builds children
  709. if am[AttribItems] != nil {
  710. items := am[AttribItems].([]map[string]interface{})
  711. for i := 0; i < len(items); i++ {
  712. item := items[i]
  713. child, err := b.build(item, dd)
  714. if err != nil {
  715. return nil, err
  716. }
  717. dd.Add(child.(*ImageLabel))
  718. }
  719. }
  720. return dd, nil
  721. }
  722. // buildMenu builds a gui object of type: Menu or MenuBar from the
  723. // specified panel descriptor.
  724. func buildMenu(b *Builder, am map[string]interface{}) (IPanel, error) {
  725. // Builds menu bar or menu
  726. var menu *Menu
  727. if am[AttribType].(string) == TypeMenuBar {
  728. menu = NewMenuBar()
  729. } else {
  730. menu = NewMenu()
  731. }
  732. // Only sets attribs for top level menus
  733. if pi := am[AttribParent_]; pi != nil {
  734. par := pi.(map[string]interface{})
  735. ptype := ""
  736. if ti := par[AttribType]; ti != nil {
  737. ptype = ti.(string)
  738. }
  739. if ptype != TypeMenu && ptype != TypeMenuBar {
  740. err := b.setAttribs(am, menu, asWIDGET)
  741. if err != nil {
  742. return nil, err
  743. }
  744. }
  745. }
  746. // Builds and adds menu items
  747. if am[AttribItems] != nil {
  748. items := am[AttribItems].([]map[string]interface{})
  749. for i := 0; i < len(items); i++ {
  750. // Get the item optional type and text
  751. item := items[i]
  752. itype := ""
  753. itext := ""
  754. if iv := item[AttribType]; iv != nil {
  755. itype = iv.(string)
  756. }
  757. if iv := item[AttribText]; iv != nil {
  758. itext = iv.(string)
  759. }
  760. // Item is another menu
  761. if itype == TypeMenu {
  762. subm, err := buildMenu(b, item)
  763. if err != nil {
  764. return nil, err
  765. }
  766. menu.AddMenu(itext, subm.(*Menu))
  767. continue
  768. }
  769. // Item is a separator
  770. if itext == TypeSeparator {
  771. menu.AddSeparator()
  772. continue
  773. }
  774. // Item must be a menu option
  775. mi := menu.AddOption(itext)
  776. // Set item optional icon(s)
  777. if icon := item[AttribIcon]; icon != nil {
  778. mi.SetIcon(icon.(string))
  779. }
  780. // Sets optional menu item shortcut
  781. if sci := item[AttribShortcut]; sci != nil {
  782. sc := sci.([]int)
  783. mi.SetShortcut(window.ModifierKey(sc[0]), window.Key(sc[1]))
  784. }
  785. }
  786. }
  787. return menu, nil
  788. }
  789. // buildSlider builds a gui object of type: HSlider or VSlider
  790. func buildSlider(b *Builder, am map[string]interface{}) (IPanel, error) {
  791. // Builds horizontal or vertical slider
  792. var slider *Slider
  793. if am[AttribType].(string) == TypeHSlider {
  794. slider = NewHSlider(0, 0)
  795. } else {
  796. slider = NewVSlider(0, 0)
  797. }
  798. // Sets common attributes
  799. err := b.setAttribs(am, slider, asWIDGET)
  800. if err != nil {
  801. return nil, err
  802. }
  803. // Sets optional text
  804. if itext := am[AttribText]; itext != nil {
  805. slider.SetText(itext.(string))
  806. }
  807. // Sets optional scale factor
  808. if isf := am[AttribScaleFactor]; isf != nil {
  809. slider.SetScaleFactor(isf.(float32))
  810. }
  811. // Sets optional value
  812. if iv := am[AttribValue]; iv != nil {
  813. slider.SetValue(iv.(float32))
  814. }
  815. return slider, nil
  816. }
  817. // buildSplitter builds a gui object of type: HSplitterr or VSplitter
  818. func buildSplitter(b *Builder, am map[string]interface{}) (IPanel, error) {
  819. // Builds horizontal or vertical splitter
  820. var splitter *Splitter
  821. if am[AttribType].(string) == TypeHSplitter {
  822. splitter = NewHSplitter(0, 0)
  823. } else {
  824. splitter = NewVSplitter(0, 0)
  825. }
  826. // Sets common attributes
  827. err := b.setAttribs(am, splitter, asWIDGET)
  828. if err != nil {
  829. return nil, err
  830. }
  831. // Sets optional split value
  832. if v := am[AttribSplit]; v != nil {
  833. splitter.SetSplit(v.(float32))
  834. }
  835. // Internal function to set each of the splitter's panel attributes and items
  836. setpan := func(attrib string, pan *Panel) error {
  837. // Get internal panel attributes
  838. ipattribs := am[attrib]
  839. if ipattribs == nil {
  840. return nil
  841. }
  842. pattr := ipattribs.(map[string]interface{})
  843. // Set panel attributes
  844. err := b.setAttribs(pattr, pan, asPANEL)
  845. if err != nil {
  846. return nil
  847. }
  848. // Builds panel children
  849. if pattr[AttribItems] != nil {
  850. items := pattr[AttribItems].([]map[string]interface{})
  851. for i := 0; i < len(items); i++ {
  852. item := items[i]
  853. child, err := b.build(item, pan)
  854. if err != nil {
  855. return err
  856. }
  857. pan.Add(child)
  858. }
  859. }
  860. return nil
  861. }
  862. // Set optional splitter panel's attributes
  863. err = setpan(AttribPanel0, &splitter.P0)
  864. if err != nil {
  865. return nil, err
  866. }
  867. err = setpan(AttribPanel1, &splitter.P1)
  868. if err != nil {
  869. return nil, err
  870. }
  871. return splitter, nil
  872. }
  873. // buildTree builds a gui object of type: Tree
  874. func buildTree(b *Builder, am map[string]interface{}) (IPanel, error) {
  875. // Builds tree and sets its common attributes
  876. tree := NewTree(0, 0)
  877. err := b.setAttribs(am, tree, asWIDGET)
  878. if err != nil {
  879. return nil, err
  880. }
  881. // Internal function to build tree nodes recursively
  882. var buildItems func(am map[string]interface{}, pnode *TreeNode) error
  883. buildItems = func(am map[string]interface{}, pnode *TreeNode) error {
  884. v := am[AttribItems]
  885. if v == nil {
  886. return nil
  887. }
  888. items := v.([]map[string]interface{})
  889. for i := 0; i < len(items); i++ {
  890. // Get the item type
  891. item := items[i]
  892. itype := ""
  893. if v := item[AttribType]; v != nil {
  894. itype = v.(string)
  895. }
  896. itext := ""
  897. if v := item[AttribText]; v != nil {
  898. itext = v.(string)
  899. }
  900. // Item is a tree node
  901. if itype == "" || itype == TypeTreeNode {
  902. var node *TreeNode
  903. if pnode == nil {
  904. node = tree.AddNode(itext)
  905. } else {
  906. node = pnode.AddNode(itext)
  907. }
  908. err := buildItems(item, node)
  909. if err != nil {
  910. return err
  911. }
  912. continue
  913. }
  914. // Other controls
  915. ipan, err := b.build(item, nil)
  916. if err != nil {
  917. return err
  918. }
  919. if pnode == nil {
  920. tree.Add(ipan)
  921. } else {
  922. pnode.Add(ipan)
  923. }
  924. }
  925. return nil
  926. }
  927. // Build nodes
  928. err = buildItems(am, nil)
  929. if err != nil {
  930. return nil, err
  931. }
  932. return tree, nil
  933. }
  934. // buildWindow builds a gui object of type: Window
  935. func buildWindow(b *Builder, am map[string]interface{}) (IPanel, error) {
  936. // Builds window and sets its common attributes
  937. win := NewWindow(0, 0)
  938. err := b.setAttribs(am, win, asWIDGET)
  939. if err != nil {
  940. return nil, err
  941. }
  942. // Sets optional title
  943. if title := am[AttribTitle]; title != nil {
  944. win.SetTitle(title.(string))
  945. }
  946. // Set optional resizable borders
  947. if resiz := am[AttribResizable]; resiz != nil {
  948. win.SetResizable(resiz.(Resizable))
  949. }
  950. // Builds window children
  951. if v := am[AttribItems]; v != nil {
  952. items := v.([]map[string]interface{})
  953. for i := 0; i < len(items); i++ {
  954. item := items[i]
  955. child, err := b.build(item, win)
  956. if err != nil {
  957. return nil, err
  958. }
  959. win.Add(child)
  960. }
  961. }
  962. return win, nil
  963. }
  964. // setLayout sets the optional layout of the specified panel
  965. func (b *Builder) setLayout(am map[string]interface{}, ipan IPanel) error {
  966. // Get layout type
  967. lai := am[AttribLayout]
  968. if lai == nil {
  969. return nil
  970. }
  971. lam := lai.(map[string]interface{})
  972. ltype := lam[AttribType]
  973. if ltype == nil {
  974. return b.err(am, AttribType, "Layout must have a type")
  975. }
  976. // Get layout builder
  977. lbuilder := b.layouts[ltype.(string)]
  978. if lbuilder == nil {
  979. return b.err(am, AttribType, "Invalid layout type")
  980. }
  981. // Builds layout builder and set to panel
  982. layout, err := lbuilder.BuildLayout(b, lam)
  983. if err != nil {
  984. return err
  985. }
  986. ipan.SetLayout(layout)
  987. return nil
  988. }
  989. func (b *Builder) setLayoutParams(am map[string]interface{}, ipan IPanel) error {
  990. // Get layout params attributes
  991. lpi := am[AttribLayoutParams]
  992. if lpi == nil {
  993. return nil
  994. }
  995. lp := lpi.(map[string]interface{})
  996. // Get layout type from parent
  997. pi := am[AttribParent_]
  998. if pi == nil {
  999. return b.err(am, AttribType, "Panel has no parent")
  1000. }
  1001. par := pi.(map[string]interface{})
  1002. v := par[AttribLayout]
  1003. if v == nil {
  1004. return nil
  1005. }
  1006. playout := v.(map[string]interface{})
  1007. pltype := playout[AttribType].(string)
  1008. // Get layout builder and builds layout params
  1009. lbuilder := b.layouts[pltype]
  1010. params, err := lbuilder.BuildParams(b, lp)
  1011. if err != nil {
  1012. return err
  1013. }
  1014. ipan.GetPanel().SetLayoutParams(params)
  1015. return nil
  1016. }
  1017. func AttribCheckResizable(b *Builder, am map[string]interface{}, fname string) error {
  1018. // If attribute not found, ignore
  1019. v := am[fname]
  1020. if v == nil {
  1021. return nil
  1022. }
  1023. // Attribute must be string
  1024. vs, ok := v.(string)
  1025. if !ok {
  1026. return b.err(am, fname, "Invalid resizable attribute")
  1027. }
  1028. // Each string field must be a valid resizable name
  1029. parts := strings.Fields(vs)
  1030. var res Resizable
  1031. for _, name := range parts {
  1032. v, ok := mapResizable[name]
  1033. if !ok {
  1034. return b.err(am, fname, "Invalid resizable name:"+name)
  1035. }
  1036. res |= v
  1037. }
  1038. am[fname] = res
  1039. return nil
  1040. }
  1041. func AttribCheckEdge(b *Builder, am map[string]interface{}, fname string) error {
  1042. v := am[fname]
  1043. if v == nil {
  1044. return nil
  1045. }
  1046. vs, ok := v.(string)
  1047. if !ok {
  1048. return b.err(am, fname, "Invalid edge name")
  1049. }
  1050. edge, ok := mapEdgeName[vs]
  1051. if !ok {
  1052. return b.err(am, fname, "Invalid edge name")
  1053. }
  1054. am[fname] = edge
  1055. return nil
  1056. }
  1057. func AttribCheckLayout(b *Builder, am map[string]interface{}, fname string) error {
  1058. v := am[fname]
  1059. if v == nil {
  1060. return nil
  1061. }
  1062. msi, ok := v.(map[string]interface{})
  1063. if !ok {
  1064. return b.err(am, fname, "Not a map")
  1065. }
  1066. lti := msi[AttribType]
  1067. if lti == nil {
  1068. return b.err(am, fname, "Layout must have a type")
  1069. }
  1070. lfunc := b.layouts[lti.(string)]
  1071. if lfunc == nil {
  1072. return b.err(am, fname, "Invalid layout type")
  1073. }
  1074. return nil
  1075. }
  1076. func AttribCheckAlign(b *Builder, am map[string]interface{}, fname string) error {
  1077. v := am[fname]
  1078. if v == nil {
  1079. return nil
  1080. }
  1081. vs, ok := v.(string)
  1082. if !ok {
  1083. return b.err(am, fname, "Invalid alignment")
  1084. }
  1085. var align Align
  1086. if fname == AttribAlignh {
  1087. align, ok = mapAlignh[vs]
  1088. } else {
  1089. align, ok = mapAlignv[vs]
  1090. }
  1091. if !ok {
  1092. return b.err(am, fname, "Invalid alignment")
  1093. }
  1094. am[fname] = align
  1095. return nil
  1096. }
  1097. func AttribCheckMenuShortcut(b *Builder, am map[string]interface{}, fname string) error {
  1098. v := am[fname]
  1099. if v == nil {
  1100. return nil
  1101. }
  1102. vs, ok := v.(string)
  1103. if !ok {
  1104. return b.err(am, fname, "Not a string")
  1105. }
  1106. sc := strings.Trim(vs, " ")
  1107. if sc == "" {
  1108. return nil
  1109. }
  1110. parts := strings.Split(sc, "+")
  1111. var mods window.ModifierKey
  1112. for i := 0; i < len(parts)-1; i++ {
  1113. switch parts[i] {
  1114. case "Shift":
  1115. mods |= window.ModShift
  1116. case "Ctrl":
  1117. mods |= window.ModControl
  1118. case "Alt":
  1119. mods |= window.ModAlt
  1120. default:
  1121. return b.err(am, fname, "Invalid shortcut:"+sc)
  1122. }
  1123. }
  1124. // The last part must be a key
  1125. keyname := parts[len(parts)-1]
  1126. var keycode int
  1127. found := false
  1128. for kcode, kname := range mapKeyText {
  1129. if kname == keyname {
  1130. keycode = int(kcode)
  1131. found = true
  1132. break
  1133. }
  1134. }
  1135. if !found {
  1136. return b.err(am, fname, "Invalid shortcut:"+sc)
  1137. }
  1138. am[fname] = []int{int(mods), keycode}
  1139. return nil
  1140. }
  1141. func AttribCheckListMap(b *Builder, am map[string]interface{}, fname string) error {
  1142. v := am[fname]
  1143. if v == nil {
  1144. return nil
  1145. }
  1146. li, ok := v.([]interface{})
  1147. if !ok {
  1148. return b.err(am, fname, "Not a list")
  1149. }
  1150. lmsi := make([]map[string]interface{}, 0)
  1151. for i := 0; i < len(li); i++ {
  1152. item := li[i]
  1153. msi, ok := item.(map[string]interface{})
  1154. if !ok {
  1155. return b.err(am, fname, "Item is not a map")
  1156. }
  1157. lmsi = append(lmsi, msi)
  1158. }
  1159. am[fname] = lmsi
  1160. return nil
  1161. }
  1162. func AttribCheckMap(b *Builder, am map[string]interface{}, fname string) error {
  1163. v := am[fname]
  1164. if v == nil {
  1165. return nil
  1166. }
  1167. msi, ok := v.(map[string]interface{})
  1168. if !ok {
  1169. return b.err(am, fname, "Not a map")
  1170. }
  1171. am[fname] = msi
  1172. return nil
  1173. }
  1174. func AttribCheckIcons(b *Builder, am map[string]interface{}, fname string) error {
  1175. v := am[fname]
  1176. if v == nil {
  1177. return nil
  1178. }
  1179. fs, ok := v.(string)
  1180. if !ok {
  1181. return b.err(am, fname, "Not a string")
  1182. }
  1183. text := ""
  1184. parts := strings.Fields(fs)
  1185. for i := 0; i < len(parts); i++ {
  1186. // Try name first
  1187. cp := icon.Codepoint(parts[i])
  1188. if cp != "" {
  1189. text += string(cp)
  1190. continue
  1191. }
  1192. // Try to parse as hex value
  1193. val, err := strconv.ParseUint(parts[i], 16, 32)
  1194. if err != nil {
  1195. return b.err(am, fname, fmt.Sprintf("Invalid icon codepoint value/name:%v", parts[i]))
  1196. }
  1197. text += string(val)
  1198. }
  1199. am[fname] = text
  1200. return nil
  1201. }
  1202. func AttribCheckColor(b *Builder, am map[string]interface{}, fname string) error {
  1203. // Checks if field is nil
  1204. v := am[fname]
  1205. if v == nil {
  1206. return nil
  1207. }
  1208. // Converts to string
  1209. fs, ok := v.(string)
  1210. if !ok {
  1211. return b.err(am, fname, "Not a string")
  1212. }
  1213. // Checks if string field is empty
  1214. fs = strings.Trim(fs, " ")
  1215. if fs == "" {
  1216. return nil
  1217. }
  1218. // If string has 1 or 2 fields it must be a color name and optional alpha
  1219. parts := strings.Fields(fs)
  1220. if len(parts) == 1 || len(parts) == 2 {
  1221. // First part must be a color name
  1222. c, ok := math32.IsColorName(parts[0])
  1223. if !ok {
  1224. return b.err(am, fname, fmt.Sprintf("Invalid color name:%s", parts[0]))
  1225. }
  1226. c4 := math32.Color4{c.R, c.G, c.B, 1}
  1227. if len(parts) == 2 {
  1228. val, err := strconv.ParseFloat(parts[1], 32)
  1229. if err != nil {
  1230. return b.err(am, fname, fmt.Sprintf("Invalid float32 value:%s", parts[1]))
  1231. }
  1232. c4.A = float32(val)
  1233. }
  1234. am[fname] = &c4
  1235. return nil
  1236. }
  1237. // Accept 3 or 4 floats values
  1238. va, err := b.parseFloats(am, fname, 3, 4)
  1239. if err != nil {
  1240. return err
  1241. }
  1242. if len(va) == 3 {
  1243. am[fname] = &math32.Color4{va[0], va[1], va[2], 1}
  1244. return nil
  1245. }
  1246. am[fname] = &math32.Color4{va[0], va[1], va[2], va[3]}
  1247. return nil
  1248. }
  1249. func AttribCheckBorderSizes(b *Builder, am map[string]interface{}, fname string) error {
  1250. va, err := b.parseFloats(am, fname, 1, 4)
  1251. if err != nil {
  1252. return err
  1253. }
  1254. if va == nil {
  1255. return nil
  1256. }
  1257. if len(va) == 1 {
  1258. am[fname] = &BorderSizes{va[0], va[0], va[0], va[0]}
  1259. return nil
  1260. }
  1261. am[fname] = &BorderSizes{va[0], va[1], va[2], va[3]}
  1262. return nil
  1263. }
  1264. func AttribCheckPosition(b *Builder, am map[string]interface{}, fname string) error {
  1265. v := am[fname]
  1266. if v == nil {
  1267. return nil
  1268. }
  1269. af, err := b.parseFloats(am, fname, 2, 2)
  1270. if err != nil {
  1271. return err
  1272. }
  1273. am[fname] = af
  1274. return nil
  1275. }
  1276. func AttribCheckStringLower(b *Builder, am map[string]interface{}, fname string) error {
  1277. err := AttribCheckString(b, am, fname)
  1278. if err != nil {
  1279. return err
  1280. }
  1281. if v := am[fname]; v != nil {
  1282. am[fname] = strings.ToLower(v.(string))
  1283. }
  1284. return nil
  1285. }
  1286. func AttribCheckFloat(b *Builder, am map[string]interface{}, fname string) error {
  1287. v := am[fname]
  1288. if v == nil {
  1289. return nil
  1290. }
  1291. switch n := v.(type) {
  1292. case int:
  1293. am[fname] = float32(n)
  1294. return nil
  1295. case float64:
  1296. am[fname] = float32(n)
  1297. return nil
  1298. default:
  1299. return b.err(am, fname, fmt.Sprintf("Not a number:%T", v))
  1300. }
  1301. return nil
  1302. }
  1303. func AttribCheckInt(b *Builder, am map[string]interface{}, fname string) error {
  1304. v := am[fname]
  1305. if v == nil {
  1306. return nil
  1307. }
  1308. vint, ok := v.(int)
  1309. if !ok {
  1310. return b.err(am, fname, "Not an integer")
  1311. }
  1312. am[fname] = vint
  1313. return nil
  1314. }
  1315. func AttribCheckString(b *Builder, am map[string]interface{}, fname string) error {
  1316. v := am[fname]
  1317. if v == nil {
  1318. return nil
  1319. }
  1320. s, ok := v.(string)
  1321. if !ok {
  1322. return b.err(am, fname, "Not a string")
  1323. }
  1324. am[fname] = s
  1325. return nil
  1326. }
  1327. func AttribCheckBool(b *Builder, am map[string]interface{}, fname string) error {
  1328. v := am[fname]
  1329. if v == nil {
  1330. return nil
  1331. }
  1332. bv, ok := v.(bool)
  1333. if !ok {
  1334. return b.err(am, fname, "Not a bool")
  1335. }
  1336. am[fname] = bv
  1337. return nil
  1338. }
  1339. // setAttribs sets common attributes from the description to the specified panel
  1340. // The attributes which are set can be specified by the specified bitmask.
  1341. func (b *Builder) setAttribs(am map[string]interface{}, ipan IPanel, attr uint) error {
  1342. panel := ipan.GetPanel()
  1343. // Set optional position
  1344. if attr&aPOS != 0 && am[AttribPosition] != nil {
  1345. va := am[AttribPosition].([]float32)
  1346. panel.SetPosition(va[0], va[1])
  1347. }
  1348. // Set optional panel width
  1349. if attr&aSIZE != 0 && am[AttribWidth] != nil {
  1350. panel.SetWidth(am[AttribWidth].(float32))
  1351. log.Error("set width:%v", am[AttribWidth])
  1352. }
  1353. // Sets optional panel height
  1354. if attr&aSIZE != 0 && am[AttribHeight] != nil {
  1355. panel.SetHeight(am[AttribHeight].(float32))
  1356. }
  1357. // Set optional margin sizes
  1358. if attr&aMARGINS != 0 && am[AttribMargins] != nil {
  1359. panel.SetMarginsFrom(am[AttribMargins].(*BorderSizes))
  1360. }
  1361. // Set optional border sizes
  1362. if attr&aBORDERS != 0 && am[AttribBorders] != nil {
  1363. panel.SetBordersFrom(am[AttribBorders].(*BorderSizes))
  1364. }
  1365. // Set optional border color
  1366. if attr&aBORDERCOLOR != 0 && am[AttribBorderColor] != nil {
  1367. panel.SetBordersColor4(am[AttribBorderColor].(*math32.Color4))
  1368. }
  1369. // Set optional paddings sizes
  1370. if attr&aPADDINGS != 0 && am[AttribPaddings] != nil {
  1371. panel.SetPaddingsFrom(am[AttribPaddings].(*BorderSizes))
  1372. }
  1373. // Set optional panel color
  1374. if attr&aCOLOR != 0 && am[AttribColor] != nil {
  1375. panel.SetColor4(am[AttribColor].(*math32.Color4))
  1376. }
  1377. if attr&aNAME != 0 && am[AttribName] != nil {
  1378. panel.SetName(am[AttribName].(string))
  1379. }
  1380. if attr&aVISIBLE != 0 && am[AttribVisible] != nil {
  1381. panel.SetVisible(am[AttribVisible].(bool))
  1382. }
  1383. if attr&aENABLED != 0 && am[AttribEnabled] != nil {
  1384. panel.SetEnabled(am[AttribEnabled].(bool))
  1385. }
  1386. if attr&aRENDER != 0 && am[AttribRender] != nil {
  1387. panel.SetRenderable(am[AttribRender].(bool))
  1388. }
  1389. // Sets optional layout (must pass IPanel not *Panel)
  1390. err := b.setLayout(am, ipan)
  1391. if err != nil {
  1392. return nil
  1393. }
  1394. // Sets optional layout params
  1395. err = b.setLayoutParams(am, panel)
  1396. return err
  1397. }
  1398. // parseFloats parses a string with a list of floats with the specified size
  1399. // and returns a slice. The specified size is 0 any number of floats is allowed.
  1400. // The individual values can be separated by spaces or commas
  1401. func (b *Builder) parseFloats(am map[string]interface{}, fname string, min, max int) ([]float32, error) {
  1402. // Checks if field is empty
  1403. v := am[fname]
  1404. if v == nil {
  1405. return nil, nil
  1406. }
  1407. // If field has only one value, it is an int or a float64
  1408. switch ft := v.(type) {
  1409. case int:
  1410. return []float32{float32(ft)}, nil
  1411. case float64:
  1412. return []float32{float32(ft)}, nil
  1413. }
  1414. // Converts to string
  1415. fs, ok := v.(string)
  1416. if !ok {
  1417. return nil, b.err(am, fname, "Not a string")
  1418. }
  1419. // Checks if string field is empty
  1420. fs = strings.Trim(fs, " ")
  1421. if fs == "" {
  1422. return nil, nil
  1423. }
  1424. // Separate individual fields
  1425. var parts []string
  1426. if strings.Index(fs, ",") < 0 {
  1427. parts = strings.Fields(fs)
  1428. } else {
  1429. parts = strings.Split(fs, ",")
  1430. }
  1431. if len(parts) < min || len(parts) > max {
  1432. return nil, b.err(am, fname, "Invalid number of float32 values")
  1433. }
  1434. // Parse each field value and appends to slice
  1435. var values []float32
  1436. for i := 0; i < len(parts); i++ {
  1437. val, err := strconv.ParseFloat(strings.Trim(parts[i], " "), 32)
  1438. if err != nil {
  1439. return nil, b.err(am, fname, err.Error())
  1440. }
  1441. values = append(values, float32(val))
  1442. }
  1443. return values, nil
  1444. }
  1445. // err creates and returns an error for the current object, field name and with the specified message
  1446. func (b *Builder) err(am map[string]interface{}, fname, msg string) error {
  1447. return fmt.Errorf("Error in object:%s field:%s -> %s", am[AttribName], fname, msg)
  1448. }
  1449. // debugPrint prints the internal attribute map of the builder for debugging.
  1450. // This map cannot be printed by fmt.Printf() because it has cycles.
  1451. // A map contains a key: _parent, which pointer to is parent map, if any.
  1452. func (b *Builder) debugPrint(v interface{}, level int) {
  1453. switch vt := v.(type) {
  1454. case map[string]interface{}:
  1455. level += 3
  1456. fmt.Printf("\n")
  1457. for mk, mv := range vt {
  1458. if mk == AttribParent_ {
  1459. continue
  1460. }
  1461. fmt.Printf("%s%s:", strings.Repeat(" ", level), mk)
  1462. b.debugPrint(mv, level)
  1463. }
  1464. case []map[string]interface{}:
  1465. for _, v := range vt {
  1466. b.debugPrint(v, level)
  1467. }
  1468. default:
  1469. fmt.Printf(" %v (%T)\n", vt, vt)
  1470. }
  1471. }