builder.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gui
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "github.com/g3n/engine/gui/assets/icon"
  13. "github.com/g3n/engine/math32"
  14. "github.com/g3n/engine/window"
  15. "gopkg.in/yaml.v2"
  16. )
  17. // Builder builds GUI objects from a declarative description in YAML format
  18. type Builder struct {
  19. am map[string]interface{} // parsed attribute map
  20. builders map[string]BuilderFunc // map of builder functions by type
  21. attribs map[string]AttribCheckFunc // map of attribute name with check functions
  22. layouts map[string]IBuilderLayout // map of layout type to layout builder
  23. imgpath string // base path for image panels files
  24. }
  25. // IBuilderLayout is the interface for all layout builders
  26. type IBuilderLayout interface {
  27. BuildLayout(b *Builder, am map[string]interface{}) (ILayout, error)
  28. BuildParams(b *Builder, am map[string]interface{}) (interface{}, error)
  29. }
  30. // BuilderFunc is type for functions which build a gui object from an attribute map
  31. type BuilderFunc func(*Builder, map[string]interface{}) (IPanel, error)
  32. // AttribCheckFunc is the type for all attribute check functions
  33. type AttribCheckFunc func(b *Builder, am map[string]interface{}, fname string) error
  34. // IgnoreSuffix specifies the suffix of ignored keys
  35. const IgnoreSuffix = "_"
  36. // Panel and layout types
  37. const (
  38. TypePanel = "panel"
  39. TypeImagePanel = "imagepanel"
  40. TypeLabel = "label"
  41. TypeImageLabel = "imagelabel"
  42. TypeButton = "button"
  43. TypeCheckBox = "checkbox"
  44. TypeRadioButton = "radiobutton"
  45. TypeEdit = "edit"
  46. TypeVList = "vlist"
  47. TypeHList = "hlist"
  48. TypeDropDown = "dropdown"
  49. TypeHSlider = "hslider"
  50. TypeVSlider = "vslider"
  51. TypeHSplitter = "hsplitter"
  52. TypeVSplitter = "vsplitter"
  53. TypeSeparator = "separator"
  54. TypeTree = "tree"
  55. TypeTreeNode = "node"
  56. TypeMenuBar = "menubar"
  57. TypeMenu = "menu"
  58. TypeWindow = "window"
  59. TypeChart = "chart"
  60. TypeTable = "table"
  61. TypeTabBar = "tabbar"
  62. TypeHBoxLayout = "hbox"
  63. TypeVBoxLayout = "vbox"
  64. TypeGridLayout = "grid"
  65. TypeDockLayout = "dock"
  66. )
  67. // Common attribute names
  68. const (
  69. AttribAlignv = "alignv" // Align
  70. AttribAlignh = "alignh" // Align
  71. AttribAspectHeight = "aspectheight" // float32
  72. AttribAspectWidth = "aspectwidth" // float32
  73. AttribBgColor = "bgcolor" // Color4
  74. AttribBorders = "borders" // RectBounds
  75. AttribBorderColor = "bordercolor" // Color4
  76. AttribChecked = "checked" // bool
  77. AttribColor = "color" // Color4
  78. AttribCols = "cols" // int GridLayout
  79. AttribColSpan = "colspan" // int GridLayout
  80. AttribColumns = "columns" // []map[string]interface{} Table
  81. AttribContent = "content" // map[string]interface{} Table
  82. AttribCountStepx = "countstepx" // float32
  83. AttribEdge = "edge" // int
  84. AttribEnabled = "enabled" // bool
  85. AttribExpand = "expand" // float32
  86. AttribExpandh = "expandh" // bool
  87. AttribExpandv = "expandv" // bool
  88. AttribFirstx = "firstx" // float32
  89. AttribFontColor = "fontcolor" // Color4
  90. AttribFontDPI = "fontdpi" // float32
  91. AttribFontSize = "fontsize" // float32
  92. AttribFormat = "format" // string
  93. AttribGroup = "group" // string
  94. AttribHeader = "header" // string
  95. AttribHeight = "height" // float32
  96. AttribHidden = "hidden" // bool Table
  97. AttribId = "id" // string
  98. AttribIcon = "icon" // string
  99. AttribImageFile = "imagefile" // string
  100. AttribImageLabel = "imagelabel" // []map[string]interface{}
  101. AttribItems = "items" // []map[string]interface{}
  102. AttribLayout = "layout" // map[string]interface{}
  103. AttribLayoutParams = "layoutparams" // map[string]interface{}
  104. AttribLineSpacing = "linespacing" // float32
  105. AttribLines = "lines" // int
  106. AttribMargin = "margin" // float32
  107. AttribMargins = "margins" // RectBounds
  108. AttribMinwidth = "minwidth" // float32 Table
  109. AttribAutoHeight = "autoheight" // bool
  110. AttribAutoWidth = "autowidth" // bool
  111. AttribName = "name" // string
  112. AttribPaddings = "paddings" // RectBounds
  113. AttribPanel0 = "panel0" // map[string]interface{}
  114. AttribPanel1 = "panel1" // map[string]interface{}
  115. AttribParentInternal = "parent_" // string (internal attribute)
  116. AttribPinned = "pinned" // bool
  117. AttribPlaceHolder = "placeholder" // string
  118. AttribPosition = "position" // []float32
  119. AttribRangeAuto = "rangeauto" // bool
  120. AttribRangeMin = "rangemin" // float32
  121. AttribRangeMax = "rangemax" // float32
  122. AttribRender = "render" // bool
  123. AttribResizeBorders = "resizeborders" // Resizable
  124. AttribResize = "resize" // bool Table
  125. AttribScaleFactor = "scalefactor" // float32
  126. AttribScalex = "scalex" // map[string]interface{}
  127. AttribScaley = "scaley" // map[string]interface{}
  128. AttribShortcut = "shortcut" // []int
  129. AttribShowHeader = "showheader" // bool
  130. AttribSortType = "sorttype" // TableSortType Table
  131. AttribSpacing = "spacing" // float32
  132. AttribSplit = "split" // float32
  133. AttribStepx = "stepx" // float32
  134. AttribText = "text" // string
  135. AttribTitle = "title" // string
  136. AttribType = "type" // string
  137. AttribUserData = "userdata" // interface{}
  138. AttribWidth = "width" // float32
  139. AttribValue = "value" // float32
  140. AttribVisible = "visible" // bool
  141. )
  142. // maps align name with align parameter
  143. var mapAlignh = map[string]Align{
  144. "none": AlignNone,
  145. "left": AlignLeft,
  146. "right": AlignRight,
  147. "width": AlignWidth,
  148. "center": AlignCenter,
  149. }
  150. // maps align name with align parameter
  151. var mapAlignv = map[string]Align{
  152. "none": AlignNone,
  153. "top": AlignTop,
  154. "bottom": AlignBottom,
  155. "height": AlignHeight,
  156. "center": AlignCenter,
  157. }
  158. // maps edge name (dock layout) with edge parameter
  159. var mapEdgeName = map[string]int{
  160. "top": DockTop,
  161. "right": DockRight,
  162. "bottom": DockBottom,
  163. "left": DockLeft,
  164. "center": DockCenter,
  165. }
  166. // maps 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. }
  368. return v, nil
  369. }
  370. // Get map[string]interface{} with lower case keys from parsed descritor
  371. res, err := visitor(mii, nil)
  372. if err != nil {
  373. return err
  374. }
  375. msi, ok := res.(map[string]interface{})
  376. if !ok {
  377. return fmt.Errorf("Parsed result is not a map")
  378. }
  379. b.am = msi
  380. //b.debugPrint(b.am, 1)
  381. return nil
  382. }
  383. // ParseFile parses a file with gui objects descriptions in YAML format
  384. // It there was a previously parsed description, it is cleared.
  385. func (b *Builder) ParseFile(filepath string) error {
  386. // Reads all file data
  387. f, err := os.Open(filepath)
  388. if err != nil {
  389. return err
  390. }
  391. data, err := ioutil.ReadAll(f)
  392. if err != nil {
  393. return err
  394. }
  395. err = f.Close()
  396. if err != nil {
  397. return err
  398. }
  399. // Parses file data
  400. return b.ParseString(string(data))
  401. }
  402. // Names returns a sorted list of names of top level previously parsed objects.
  403. // Only objects with defined types are returned.
  404. // If there is only a single object with no name, its name is returned
  405. // as an empty string
  406. func (b *Builder) Names() []string {
  407. var objs []string
  408. // Single object
  409. if b.am[AttribType] != nil {
  410. objs = append(objs, "")
  411. return objs
  412. }
  413. // Multiple objects
  414. for name := range b.am {
  415. objs = append(objs, name)
  416. }
  417. sort.Strings(objs)
  418. return objs
  419. }
  420. // Build builds a gui object and all its children recursively.
  421. // The specified name should be a top level name from a
  422. // from a previously parsed description
  423. // If the descriptions contains a single object with no name,
  424. // It should be specified the empty string to build this object.
  425. func (b *Builder) Build(name string) (IPanel, error) {
  426. // Only one object
  427. if name == "" {
  428. return b.build(b.am, nil)
  429. }
  430. // Map of gui objects
  431. am, ok := b.am[name]
  432. if !ok {
  433. return nil, fmt.Errorf("Object name:%s not found", name)
  434. }
  435. return b.build(am.(map[string]interface{}), nil)
  436. }
  437. // SetImagepath Sets the path for image panels relative image files
  438. func (b *Builder) SetImagepath(path string) {
  439. b.imgpath = path
  440. }
  441. // AddBuilderPanel adds a panel builder function for the specified type name.
  442. // If the type name already exists it is replaced.
  443. func (b *Builder) AddBuilderPanel(typename string, bf BuilderFunc) {
  444. b.builders[typename] = bf
  445. }
  446. // AddBuilderLayout adds a layout builder object for the specified type name.
  447. // If the type name already exists it is replaced.
  448. func (b *Builder) AddBuilderLayout(typename string, bl IBuilderLayout) {
  449. b.layouts[typename] = bl
  450. }
  451. // AddAttrib adds an attribute type and its checker/converte
  452. // If the attribute type name already exists it is replaced.
  453. func (b *Builder) AddAttrib(typename string, acf AttribCheckFunc) {
  454. b.attribs[typename] = acf
  455. }
  456. // build builds the gui object from the specified description.
  457. // All its children are also built recursively
  458. // Returns the built object or an error
  459. func (b *Builder) build(am map[string]interface{}, iparent IPanel) (IPanel, error) {
  460. // Get panel type
  461. itype := am[AttribType]
  462. if itype == nil {
  463. return nil, fmt.Errorf("Type not specified")
  464. }
  465. typename := itype.(string)
  466. // Get builder function for this type name
  467. builder := b.builders[typename]
  468. if builder == nil {
  469. return nil, fmt.Errorf("Invalid type:%v", typename)
  470. }
  471. // Builds panel
  472. pan, err := builder(b, am)
  473. if err != nil {
  474. return nil, err
  475. }
  476. // Adds built panel to parent
  477. if iparent != nil {
  478. iparent.GetPanel().Add(pan)
  479. }
  480. return pan, nil
  481. }
  482. // SetAttribs sets common attributes from the description to the specified panel
  483. func (b *Builder) SetAttribs(am map[string]interface{}, ipan IPanel) error {
  484. panel := ipan.GetPanel()
  485. // Set optional position
  486. if am[AttribPosition] != nil {
  487. va := am[AttribPosition].([]float32)
  488. panel.SetPosition(va[0], va[1])
  489. }
  490. // Set optional panel width
  491. if am[AttribWidth] != nil {
  492. panel.SetWidth(am[AttribWidth].(float32))
  493. }
  494. // Sets optional panel height
  495. if am[AttribHeight] != nil {
  496. panel.SetHeight(am[AttribHeight].(float32))
  497. }
  498. // Set optional margin sizes
  499. if am[AttribMargins] != nil {
  500. panel.SetMarginsFrom(am[AttribMargins].(*RectBounds))
  501. }
  502. // Set optional border sizes
  503. if am[AttribBorders] != nil {
  504. panel.SetBordersFrom(am[AttribBorders].(*RectBounds))
  505. }
  506. // Set optional border color
  507. if am[AttribBorderColor] != nil {
  508. panel.SetBordersColor4(am[AttribBorderColor].(*math32.Color4))
  509. }
  510. // Set optional paddings sizes
  511. if am[AttribPaddings] != nil {
  512. panel.SetPaddingsFrom(am[AttribPaddings].(*RectBounds))
  513. }
  514. // Set optional panel color
  515. if am[AttribColor] != nil {
  516. panel.SetColor4(am[AttribColor].(*math32.Color4))
  517. }
  518. if am[AttribName] != nil {
  519. panel.SetName(am[AttribName].(string))
  520. }
  521. if am[AttribVisible] != nil {
  522. panel.SetVisible(am[AttribVisible].(bool))
  523. }
  524. if am[AttribEnabled] != nil {
  525. panel.SetEnabled(am[AttribEnabled].(bool))
  526. }
  527. if am[AttribRender] != nil {
  528. panel.SetRenderable(am[AttribRender].(bool))
  529. }
  530. if am[AttribUserData] != nil {
  531. panel.SetUserData(am[AttribUserData])
  532. }
  533. // Sets optional layout (must pass IPanel not *Panel)
  534. err := b.setLayout(am, ipan)
  535. if err != nil {
  536. return nil
  537. }
  538. // Sets optional layout params
  539. err = b.setLayoutParams(am, panel)
  540. return err
  541. }
  542. // setLayout sets the optional layout of the specified panel
  543. func (b *Builder) setLayout(am map[string]interface{}, ipan IPanel) error {
  544. // Get layout type
  545. lai := am[AttribLayout]
  546. if lai == nil {
  547. return nil
  548. }
  549. lam := lai.(map[string]interface{})
  550. ltype := lam[AttribType]
  551. if ltype == nil {
  552. return b.err(am, AttribType, "Layout must have a type")
  553. }
  554. // Get layout builder
  555. lbuilder := b.layouts[ltype.(string)]
  556. if lbuilder == nil {
  557. return b.err(am, AttribType, "Invalid layout type")
  558. }
  559. // Builds layout builder and set to panel
  560. layout, err := lbuilder.BuildLayout(b, lam)
  561. if err != nil {
  562. return err
  563. }
  564. ipan.SetLayout(layout)
  565. return nil
  566. }
  567. // setLayoutParams sets the optional layout params of the specified panel and its attributes
  568. func (b *Builder) setLayoutParams(am map[string]interface{}, ipan IPanel) error {
  569. // Get layout params attributes
  570. lpi := am[AttribLayoutParams]
  571. if lpi == nil {
  572. return nil
  573. }
  574. lp := lpi.(map[string]interface{})
  575. // Checks if layout param specifies the layout type
  576. // This is useful when the panel has no parent yet
  577. var ltype string
  578. if v := lp[AttribType]; v != nil {
  579. ltype = v.(string)
  580. } else {
  581. // Get layout type from parent
  582. pi := am[AttribParentInternal]
  583. if pi == nil {
  584. return b.err(am, AttribType, "Panel has no parent")
  585. }
  586. par := pi.(map[string]interface{})
  587. v := par[AttribLayout]
  588. if v == nil {
  589. return b.err(am, AttribType, "Parent has no layout")
  590. }
  591. playout := v.(map[string]interface{})
  592. ltype = playout[AttribType].(string)
  593. }
  594. // Get layout builder and builds layout params
  595. lbuilder := b.layouts[ltype]
  596. params, err := lbuilder.BuildParams(b, lp)
  597. if err != nil {
  598. return err
  599. }
  600. ipan.GetPanel().SetLayoutParams(params)
  601. return nil
  602. }
  603. // AttribCheckTableSortType checks and converts attribute table column sort type
  604. func AttribCheckTableSortType(b *Builder, am map[string]interface{}, fname string) error {
  605. // If attribute not found, ignore
  606. v := am[fname]
  607. if v == nil {
  608. return nil
  609. }
  610. vs, ok := v.(string)
  611. if !ok {
  612. return b.err(am, fname, "Invalid attribute")
  613. }
  614. tstype, ok := mapTableSortType[vs]
  615. if !ok {
  616. return b.err(am, fname, "Invalid attribute")
  617. }
  618. am[fname] = tstype
  619. return nil
  620. }
  621. // AttribCheckResizeBorders checks and converts attribute with list of window resizable borders
  622. func AttribCheckResizeBorders(b *Builder, am map[string]interface{}, fname string) error {
  623. // If attribute not found, ignore
  624. v := am[fname]
  625. if v == nil {
  626. return nil
  627. }
  628. // Attribute must be string
  629. vs, ok := v.(string)
  630. if !ok {
  631. return b.err(am, fname, "Invalid resizable attribute")
  632. }
  633. // Each string field must be a valid resizable name
  634. parts := strings.Fields(vs)
  635. var res ResizeBorders
  636. for _, name := range parts {
  637. v, ok := mapResizable[name]
  638. if !ok {
  639. return b.err(am, fname, "Invalid resizable name:"+name)
  640. }
  641. res |= v
  642. }
  643. am[fname] = res
  644. return nil
  645. }
  646. // AttribCheckEdge checks and converts attribute with name of layout edge
  647. func AttribCheckEdge(b *Builder, am map[string]interface{}, fname string) error {
  648. v := am[fname]
  649. if v == nil {
  650. return nil
  651. }
  652. vs, ok := v.(string)
  653. if !ok {
  654. return b.err(am, fname, "Invalid edge name")
  655. }
  656. edge, ok := mapEdgeName[vs]
  657. if !ok {
  658. return b.err(am, fname, "Invalid edge name")
  659. }
  660. am[fname] = edge
  661. return nil
  662. }
  663. // AttribCheckLayout checks and converts layout attribute
  664. func AttribCheckLayout(b *Builder, am map[string]interface{}, fname string) error {
  665. v := am[fname]
  666. if v == nil {
  667. return nil
  668. }
  669. msi, ok := v.(map[string]interface{})
  670. if !ok {
  671. return b.err(am, fname, "Not a map")
  672. }
  673. lti := msi[AttribType]
  674. if lti == nil {
  675. return b.err(am, fname, "Layout must have a type")
  676. }
  677. lfunc := b.layouts[lti.(string)]
  678. if lfunc == nil {
  679. return b.err(am, fname, "Invalid layout type")
  680. }
  681. return nil
  682. }
  683. // AttribCheckAlign checks and converts layout align* attribute
  684. func AttribCheckAlign(b *Builder, am map[string]interface{}, fname string) error {
  685. v := am[fname]
  686. if v == nil {
  687. return nil
  688. }
  689. vs, ok := v.(string)
  690. if !ok {
  691. return b.err(am, fname, "Invalid alignment")
  692. }
  693. var align Align
  694. if fname == AttribAlignh {
  695. align, ok = mapAlignh[vs]
  696. } else {
  697. align, ok = mapAlignv[vs]
  698. }
  699. if !ok {
  700. return b.err(am, fname, "Invalid alignment")
  701. }
  702. am[fname] = align
  703. return nil
  704. }
  705. // AttribCheckMenuShortcut checks and converts attribute describing menu shortcut key
  706. func AttribCheckMenuShortcut(b *Builder, am map[string]interface{}, fname string) error {
  707. v := am[fname]
  708. if v == nil {
  709. return nil
  710. }
  711. vs, ok := v.(string)
  712. if !ok {
  713. return b.err(am, fname, "Not a string")
  714. }
  715. sc := strings.Trim(vs, " ")
  716. if sc == "" {
  717. return nil
  718. }
  719. parts := strings.Split(sc, "+")
  720. var mods window.ModifierKey
  721. for i := 0; i < len(parts)-1; i++ {
  722. switch parts[i] {
  723. case "Shift":
  724. mods |= window.ModShift
  725. case "Ctrl":
  726. mods |= window.ModControl
  727. case "Alt":
  728. mods |= window.ModAlt
  729. default:
  730. return b.err(am, fname, "Invalid shortcut:"+sc)
  731. }
  732. }
  733. // The last part must be a key
  734. keyname := parts[len(parts)-1]
  735. var keycode int
  736. found := false
  737. for kcode, kname := range mapKeyText {
  738. if kname == keyname {
  739. keycode = int(kcode)
  740. found = true
  741. break
  742. }
  743. }
  744. if !found {
  745. return b.err(am, fname, "Invalid shortcut:"+sc)
  746. }
  747. am[fname] = []int{int(mods), keycode}
  748. return nil
  749. }
  750. // AttribCheckListMap checks and converts attribute to []map[string]interface{}
  751. func AttribCheckListMap(b *Builder, am map[string]interface{}, fname string) error {
  752. v := am[fname]
  753. if v == nil {
  754. return nil
  755. }
  756. li, ok := v.([]interface{})
  757. if !ok {
  758. return b.err(am, fname, "Not a list")
  759. }
  760. lmsi := make([]map[string]interface{}, 0)
  761. for i := 0; i < len(li); i++ {
  762. item := li[i]
  763. msi, ok := item.(map[string]interface{})
  764. if !ok {
  765. return b.err(am, fname, "Item is not a map")
  766. }
  767. lmsi = append(lmsi, msi)
  768. }
  769. am[fname] = lmsi
  770. return nil
  771. }
  772. // AttribCheckMap checks and converts attribute to map[string]interface{}
  773. func AttribCheckMap(b *Builder, am map[string]interface{}, fname string) error {
  774. v := am[fname]
  775. if v == nil {
  776. return nil
  777. }
  778. msi, ok := v.(map[string]interface{})
  779. if !ok {
  780. return b.err(am, fname, "Not a map")
  781. }
  782. am[fname] = msi
  783. return nil
  784. }
  785. // AttribCheckIcons checks and converts attribute with a list of icon names or codepoints
  786. func AttribCheckIcons(b *Builder, am map[string]interface{}, fname string) error {
  787. v := am[fname]
  788. if v == nil {
  789. return nil
  790. }
  791. fs, ok := v.(string)
  792. if !ok {
  793. return b.err(am, fname, "Not a string")
  794. }
  795. text := ""
  796. parts := strings.Fields(fs)
  797. for i := 0; i < len(parts); i++ {
  798. // Try name first
  799. cp := icon.Codepoint(parts[i])
  800. if cp != "" {
  801. text += string(cp)
  802. continue
  803. }
  804. // Try to parse as hex value
  805. val, err := strconv.ParseUint(parts[i], 16, 32)
  806. if err != nil {
  807. return b.err(am, fname, fmt.Sprintf("Invalid icon codepoint value/name:%v", parts[i]))
  808. }
  809. text += string(val)
  810. }
  811. am[fname] = text
  812. return nil
  813. }
  814. // AttribCheckColor checks and converts attribute with color name or color component values
  815. func AttribCheckColor(b *Builder, am map[string]interface{}, fname string) error {
  816. // Checks if field is nil
  817. v := am[fname]
  818. if v == nil {
  819. return nil
  820. }
  821. // Converts to string
  822. fs, ok := v.(string)
  823. if !ok {
  824. return b.err(am, fname, "Not a string")
  825. }
  826. // Checks if string field is empty
  827. fs = strings.Trim(fs, " ")
  828. if fs == "" {
  829. return nil
  830. }
  831. // If string has 1 or 2 fields it must be a color name and optional alpha
  832. parts := strings.Fields(fs)
  833. if len(parts) == 1 || len(parts) == 2 {
  834. // First part must be a color name
  835. c, ok := math32.IsColorName(parts[0])
  836. if !ok {
  837. return b.err(am, fname, fmt.Sprintf("Invalid color name:%s", parts[0]))
  838. }
  839. c4 := math32.Color4{c.R, c.G, c.B, 1}
  840. if len(parts) == 2 {
  841. val, err := strconv.ParseFloat(parts[1], 32)
  842. if err != nil {
  843. return b.err(am, fname, fmt.Sprintf("Invalid float32 value:%s", parts[1]))
  844. }
  845. c4.A = float32(val)
  846. }
  847. am[fname] = &c4
  848. return nil
  849. }
  850. // Accept 3 or 4 floats values
  851. va, err := b.parseFloats(am, fname, 3, 4)
  852. if err != nil {
  853. return err
  854. }
  855. if len(va) == 3 {
  856. am[fname] = &math32.Color4{va[0], va[1], va[2], 1}
  857. return nil
  858. }
  859. am[fname] = &math32.Color4{va[0], va[1], va[2], va[3]}
  860. return nil
  861. }
  862. // AttribCheckBorderSizes checks and convert attribute with border sizes
  863. func AttribCheckBorderSizes(b *Builder, am map[string]interface{}, fname string) error {
  864. va, err := b.parseFloats(am, fname, 1, 4)
  865. if err != nil {
  866. return err
  867. }
  868. if va == nil {
  869. return nil
  870. }
  871. if len(va) == 1 {
  872. am[fname] = &RectBounds{va[0], va[0], va[0], va[0]}
  873. return nil
  874. }
  875. am[fname] = &RectBounds{va[0], va[1], va[2], va[3]}
  876. return nil
  877. }
  878. // AttribCheckPosition checks and convert attribute with x and y position
  879. func AttribCheckPosition(b *Builder, am map[string]interface{}, fname string) error {
  880. v := am[fname]
  881. if v == nil {
  882. return nil
  883. }
  884. af, err := b.parseFloats(am, fname, 2, 2)
  885. if err != nil {
  886. return err
  887. }
  888. am[fname] = af
  889. return nil
  890. }
  891. // AttribCheckStringLower checks and convert string attribute to lower case
  892. func AttribCheckStringLower(b *Builder, am map[string]interface{}, fname string) error {
  893. err := AttribCheckString(b, am, fname)
  894. if err != nil {
  895. return err
  896. }
  897. if v := am[fname]; v != nil {
  898. am[fname] = strings.ToLower(v.(string))
  899. }
  900. return nil
  901. }
  902. // AttribCheckFloat checks and convert attribute to float32
  903. func AttribCheckFloat(b *Builder, am map[string]interface{}, fname string) error {
  904. v := am[fname]
  905. if v == nil {
  906. return nil
  907. }
  908. switch n := v.(type) {
  909. case int:
  910. am[fname] = float32(n)
  911. return nil
  912. case float64:
  913. am[fname] = float32(n)
  914. return nil
  915. }
  916. return b.err(am, fname, fmt.Sprintf("Not a number:%T", v))
  917. }
  918. // AttribCheckInt checks and convert attribute to int
  919. func AttribCheckInt(b *Builder, am map[string]interface{}, fname string) error {
  920. v := am[fname]
  921. if v == nil {
  922. return nil
  923. }
  924. vint, ok := v.(int)
  925. if !ok {
  926. return b.err(am, fname, "Not an integer")
  927. }
  928. am[fname] = vint
  929. return nil
  930. }
  931. // AttribCheckString checks and convert attribute to string
  932. func AttribCheckString(b *Builder, am map[string]interface{}, fname string) error {
  933. v := am[fname]
  934. if v == nil {
  935. return nil
  936. }
  937. s, ok := v.(string)
  938. if !ok {
  939. return b.err(am, fname, "Not a string")
  940. }
  941. am[fname] = s
  942. return nil
  943. }
  944. // AttribCheckBool checks and convert attribute to bool
  945. func AttribCheckBool(b *Builder, am map[string]interface{}, fname string) error {
  946. v := am[fname]
  947. if v == nil {
  948. return nil
  949. }
  950. bv, ok := v.(bool)
  951. if !ok {
  952. return b.err(am, fname, "Not a bool")
  953. }
  954. am[fname] = bv
  955. return nil
  956. }
  957. // AttribCheckInterface accepts any attribute value
  958. func AttribCheckInterface(b *Builder, am map[string]interface{}, fname string) error {
  959. return nil
  960. }
  961. // parseFloats parses a string with a list of floats with the specified size
  962. // and returns a slice. The specified size is 0 any number of floats is allowed.
  963. // The individual values can be separated by spaces or commas
  964. func (b *Builder) parseFloats(am map[string]interface{}, fname string, min, max int) ([]float32, error) {
  965. // Checks if field is empty
  966. v := am[fname]
  967. if v == nil {
  968. return nil, nil
  969. }
  970. // If field has only one value, it is an int or a float64
  971. switch ft := v.(type) {
  972. case int:
  973. return []float32{float32(ft)}, nil
  974. case float64:
  975. return []float32{float32(ft)}, nil
  976. }
  977. // Converts to string
  978. fs, ok := v.(string)
  979. if !ok {
  980. return nil, b.err(am, fname, "Not a string")
  981. }
  982. // Checks if string field is empty
  983. fs = strings.Trim(fs, " ")
  984. if fs == "" {
  985. return nil, nil
  986. }
  987. // Separate individual fields
  988. var parts []string
  989. if strings.Index(fs, ",") < 0 {
  990. parts = strings.Fields(fs)
  991. } else {
  992. parts = strings.Split(fs, ",")
  993. }
  994. if len(parts) < min || len(parts) > max {
  995. return nil, b.err(am, fname, "Invalid number of float32 values")
  996. }
  997. // Parse each field value and appends to slice
  998. var values []float32
  999. for i := 0; i < len(parts); i++ {
  1000. val, err := strconv.ParseFloat(strings.Trim(parts[i], " "), 32)
  1001. if err != nil {
  1002. return nil, b.err(am, fname, err.Error())
  1003. }
  1004. values = append(values, float32(val))
  1005. }
  1006. return values, nil
  1007. }
  1008. // err creates and returns an error for the current object, field name and with the specified message
  1009. func (b *Builder) err(am map[string]interface{}, fname, msg string) error {
  1010. // Get path of objects till the error
  1011. names := []string{}
  1012. var name string
  1013. for {
  1014. if v := am[AttribName]; v != nil {
  1015. name = v.(string)
  1016. } else {
  1017. name = "?"
  1018. }
  1019. names = append(names, name)
  1020. var par interface{}
  1021. if par = am[AttribParentInternal]; par == nil {
  1022. break
  1023. }
  1024. am = par.(map[string]interface{})
  1025. }
  1026. path := []string{}
  1027. for i := len(names) - 1; i >= 0; i-- {
  1028. path = append(path, names[i])
  1029. }
  1030. return fmt.Errorf("Error in object:%s field:%s -> %s", strings.Join(path, "/"), fname, msg)
  1031. }
  1032. // debugPrint prints the internal attribute map of the builder for debugging.
  1033. // This map cannot be printed by fmt.Printf() because it has cycles.
  1034. // A map contains a key: _parent, which pointer to is parent map, if any.
  1035. func (b *Builder) debugPrint(v interface{}, level int) {
  1036. switch vt := v.(type) {
  1037. case map[string]interface{}:
  1038. level += 3
  1039. fmt.Printf("\n")
  1040. for mk, mv := range vt {
  1041. if mk == AttribParentInternal {
  1042. continue
  1043. }
  1044. fmt.Printf("%s%s:", strings.Repeat(" ", level), mk)
  1045. b.debugPrint(mv, level)
  1046. }
  1047. case []map[string]interface{}:
  1048. for _, v := range vt {
  1049. b.debugPrint(v, level)
  1050. }
  1051. default:
  1052. fmt.Printf(" %v (%T)\n", vt, vt)
  1053. }
  1054. }