builder.go 32 KB

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