124 lines
7.5 KiB
Python
124 lines
7.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Export this project's static EEZ/LVGL screens without a desktop installation.
|
|
|
|
Supports the widget/style subset used here; rejects unsupported widget types.
|
|
Application behavior stays in ui_dashboard/ui_navigation, outside generated files.
|
|
"""
|
|
from pathlib import Path
|
|
import argparse
|
|
import json
|
|
import re
|
|
|
|
root = Path(__file__).resolve().parents[2]
|
|
project = json.loads((root / 'eez/nanopsx.eez-project').read_text())
|
|
out = root / 'firmware/components/eez_gui'
|
|
|
|
def name(value):
|
|
return re.sub(r'[^a-z0-9_]', '_', value.lower())
|
|
def string(value):
|
|
return json.dumps(value, ensure_ascii=False)
|
|
def walk(widget):
|
|
yield widget
|
|
for child in widget.get('children', []):
|
|
yield from walk(child)
|
|
|
|
pages = project['userPages']
|
|
roots = [name(page['name']) for page in pages]
|
|
fields = list(roots)
|
|
for page in pages:
|
|
for widget in walk(page['components'][0]):
|
|
identifier = widget.get('identifier', '').strip()
|
|
if identifier:
|
|
assert name(identifier) not in fields, identifier
|
|
fields.append(name(identifier))
|
|
header = ['/* Generated by firmware/tools/export_display.py from the EEZ project. */',
|
|
'#pragma once', '#include <lvgl.h>', '#ifdef __cplusplus', 'extern "C" {', '#endif',
|
|
'typedef struct {', *[f' lv_obj_t *{field};' for field in fields],
|
|
'} objects_t;', 'extern objects_t objects;', 'enum ScreensEnum {',
|
|
*[f' SCREEN_ID_{r.upper()} = {i+1},' for i,r in enumerate(roots)], '};']
|
|
for r in roots:
|
|
header += [f'void create_screen_{r}(void);', f'void tick_screen_{r}(void);']
|
|
header += ['void create_screens(void);', 'void tick_screen(int screen_index);',
|
|
'void tick_screen_by_id(enum ScreensEnum screen_id);', '#ifdef __cplusplus', '}', '#endif']
|
|
source = ['/* Generated by firmware/tools/export_display.py from the EEZ project. */',
|
|
'#include "screens.h"', '#include "fonts.h"', '#include "images.h"',
|
|
'#include "vars.h"', '#include <string.h>',
|
|
'objects_t objects;', 'lv_obj_t *tick_value_change_obj;', 'uint32_t active_theme_index;']
|
|
creators = {'Screen':'lv_obj_create','Panel':'lv_obj_create','Label':'lv_label_create',
|
|
'Image':'lv_img_create','Chart':'lv_chart_create','Slider':'lv_slider_create',
|
|
'Dropdown':'lv_dropdown_create'}
|
|
color_styles = {'bg_color','border_color','text_color','line_color'}
|
|
scalar_styles = {'radius','border_width','pad_all','pad_left','pad_right','pad_top','pad_bottom',
|
|
'bg_opa','line_width','line_rounded','text_letter_space','text_line_space'}
|
|
for page,r in zip(pages, roots):
|
|
bindings = []
|
|
source.append(f'void create_screen_{r}(void) {{')
|
|
for i,widget in enumerate(walk(page['components'][0])):
|
|
kind = widget['type'].removeprefix('LVGL').removesuffix('Widget')
|
|
assert kind in creators, f'Unsupported EEZ widget: {kind}'
|
|
identifier = r if i == 0 else name(widget.get('identifier','').strip())
|
|
# Resolve parent from the actual tree, avoiding flattened-index assumptions.
|
|
def find_parent(node, target):
|
|
for child in node.get('children',[]):
|
|
if child is target: return node
|
|
found = find_parent(child,target)
|
|
if found is not None: return found
|
|
tree = list(walk(page['components'][0]))
|
|
parent = find_parent(tree[0], widget) if i else None
|
|
parent_expr = f'w{next(j for j,node in enumerate(tree) if node is parent)}' if parent else 'NULL'
|
|
v=f'w{i}'
|
|
source.append(f' lv_obj_t *{v} = {creators[kind]}({parent_expr});')
|
|
if identifier: source.append(f' objects.{identifier} = {v};')
|
|
source.append(f' lv_obj_set_pos({v}, {widget["left"]}, {widget["top"]});')
|
|
width = 'LV_SIZE_CONTENT' if widget.get('widthUnit')=='content' else widget['width']
|
|
height = 'LV_SIZE_CONTENT' if widget.get('heightUnit')=='content' else widget['height']
|
|
source.append(f' lv_obj_set_size({v}, {width}, {height});')
|
|
source.append(f' lv_obj_clear_flag({v}, LV_OBJ_FLAG_SCROLLABLE);')
|
|
if widget.get('clickableFlag'): source.append(f' lv_obj_add_flag({v}, LV_OBJ_FLAG_CLICKABLE);')
|
|
if widget.get('hiddenFlag'): source.append(f' lv_obj_add_flag({v}, LV_OBJ_FLAG_HIDDEN);')
|
|
for part,states in widget.get('localStyles',{}).get('definition',{}).items():
|
|
for state,props in states.items():
|
|
selector = f'LV_PART_{part} | LV_STATE_{state}'
|
|
for prop,value in props.items():
|
|
if prop in color_styles: cvalue=f'lv_color_hex(0x{value.lstrip("#")})'
|
|
elif prop=='text_font': cvalue='&ui_font_'+name(value)
|
|
elif prop in scalar_styles: cvalue=str(value).lower()
|
|
else: raise ValueError(f'Unsupported EEZ style: {prop}')
|
|
source.append(f' lv_obj_set_style_{prop}({v}, {cvalue}, {selector});')
|
|
if kind=='Label':
|
|
source.append(f' lv_label_set_long_mode({v}, LV_LABEL_LONG_{widget.get("longMode","WRAP")});')
|
|
if widget.get('textType')=='expression':
|
|
assert identifier
|
|
binding=f'get_var_{name(widget["text"])}()'
|
|
source.append(f' lv_label_set_text({v}, {binding});')
|
|
bindings.append((identifier,binding))
|
|
else: source.append(f' lv_label_set_text({v}, {string(widget.get("text",""))});')
|
|
elif kind=='Image': source.append(f' lv_img_set_src({v}, &img_{name(widget["image"])});')
|
|
elif kind=='Chart':
|
|
source += [f' lv_chart_set_type({v}, LV_CHART_TYPE_LINE);',f' lv_chart_set_point_count({v}, {widget["pointCount"]});',f' lv_chart_set_div_line_count({v}, {widget["divLineCountH"]}, {widget["divLineCountV"]});']
|
|
elif kind=='Slider':
|
|
source += [f' lv_slider_set_range({v}, {widget["min"]}, {widget["max"]});',f' lv_slider_set_value({v}, {widget["value"]}, LV_ANIM_OFF);']
|
|
elif kind=='Dropdown':
|
|
source += [f' lv_dropdown_set_options({v}, {string(widget["options"])});',f' lv_dropdown_set_selected({v}, {widget["selected"]});',f' lv_dropdown_set_dir({v}, LV_DIR_{widget["direction"].upper()});']
|
|
source += ['}',f'void tick_screen_{r}(void) {{']
|
|
for identifier,binding in bindings:
|
|
source += [f' if (strcmp(lv_label_get_text(objects.{identifier}), {binding}) != 0)', f' lv_label_set_text(objects.{identifier}, {binding});']
|
|
source += ['}']
|
|
source += ['void create_screens(void) {', ' lv_disp_t *display = lv_disp_get_default();',
|
|
' lv_disp_set_theme(display, lv_theme_default_init(display, lv_palette_main(LV_PALETTE_BLUE), lv_palette_main(LV_PALETTE_RED), true, LV_FONT_DEFAULT));',
|
|
*[f' create_screen_{r}();' for r in roots], '}',
|
|
'void tick_screen(int index) {', ' switch (index) {',
|
|
*[f' case {i}: tick_screen_{r}(); break;' for i,r in enumerate(roots)],
|
|
' default: break;', ' }', '}',
|
|
'void tick_screen_by_id(enum ScreensEnum id) { tick_screen(id - 1); }']
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--check', action='store_true', help='Fail if checked-in exports differ')
|
|
args=parser.parse_args()
|
|
for filename,lines in [('screens.h',header),('screens.c',source)]:
|
|
data='\n'.join(lines)+'\n'
|
|
if args.check:
|
|
assert (out/filename).read_text()==data, f'Outdated EEZ export: {filename}'
|
|
elif not (out/filename).exists() or (out/filename).read_text() != data:
|
|
(out/filename).write_text(data)
|
|
print('EEZ screen exports '+('verified' if args.check else 'generated'))
|