builder.go 31 KB

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