-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lvglwasm.zig
331 lines (265 loc) · 9.65 KB
/
lvglwasm.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
//! LVGL Test App that renders an LVGL Screen and handles Touch Input
/// Import the Zig Standard Library
const std = @import("std");
/// Import the LVGL Module
const lvgl = @import("lvgl.zig");
/// Import the WebAssembly Logger
const wasmlog = @import("wasmlog.zig");
/// Import the LVGL Library from C
const c = @cImport({
// NuttX Defines
@cDefine("__NuttX__", "");
@cDefine("NDEBUG", "");
// NuttX Header Files
@cInclude("arch/types.h");
@cInclude("../../nuttx/include/limits.h");
@cInclude("stdio.h");
@cInclude("nuttx/config.h");
@cInclude("sys/boardctl.h");
@cInclude("unistd.h");
@cInclude("stddef.h");
@cInclude("stdlib.h");
// LVGL Header Files
@cInclude("lvgl/lvgl.h");
// LVGL Display Interface for Zig
@cInclude("display.h");
});
///////////////////////////////////////////////////////////////////////////////
// Main Function
/// We render an LVGL Screen with LVGL Widgets
pub export fn lv_demo_widgets() void {
debug("lv_demo_widgets: start", .{});
defer debug("lv_demo_widgets: end", .{});
// Create the Memory Allocator for malloc
memory_allocator = std.heap.FixedBufferAllocator.init(&memory_buffer);
// Set the Custom Logger for LVGL
c.lv_log_register_print_cb(custom_logger);
// Init LVGL
debug("before lv_init", .{}); ////
c.lv_init();
debug("after lv_init", .{}); ////
// Fetch pointers to Display Driver and Display Buffer
const disp_drv = c.get_disp_drv();
const disp_buf = c.get_disp_buf();
// Init Display Buffer and Display Driver as pointers
c.init_disp_buf(disp_buf);
c.init_disp_drv(disp_drv, // Display Driver
disp_buf, // Display Buffer
flushDisplay, // Callback Function to Flush Display
720, // Horizontal Resolution
1280 // Vertical Resolution
);
// Register the Display Driver
debug("before lv_disp_drv_register", .{}); ////
const disp = c.lv_disp_drv_register(disp_drv);
debug("after lv_disp_drv_register", .{}); ////
_ = disp;
// Create the widgets for display (with Zig Wrapper)
createWidgetsWrapped() catch |e| {
// In case of error, quit
std.log.err("createWidgetsWrapped failed: {}", .{e});
return;
};
// TODO: Call `lv_tick_inc(x)` every x milliseconds in an interrupt to report the elapsed time to LVGL
// TODO: Call `lv_timer_handler()` every few milliseconds to handle LVGL related tasks
var i: usize = 0;
while (i < 10) : (i += 1) {
debug("lv_timer_handler: start", .{});
_ = c.lv_timer_handler();
debug("lv_timer_handler: end", .{});
}
}
/// LVGL Callback Function to Flush Display
export fn flushDisplay(disp_drv: ?*c.lv_disp_drv_t, area: [*c]const c.lv_area_t, color_p: [*c]c.lv_color_t) void {
_ = disp_drv;
_ = area;
_ = color_p;
debug("flushDisplay: start", .{});
defer debug("flushDisplay: end", .{});
// TODO: lv_disp_flush_ready(&disp_drv)
}
///////////////////////////////////////////////////////////////////////////////
// Create Widgets
/// Create the LVGL Widgets that will be rendered on the display. Calls the
/// LVGL API that has been wrapped in Zig. Based on
/// https://docs.lvgl.io/master/widgets/label.html?highlight=lv_label_create#line-wrap-recoloring-and-scrolling
fn createWidgetsWrapped() !void {
debug("createWidgetsWrapped: start", .{});
defer debug("createWidgetsWrapped: end", .{});
// Get the Active Screen
var screen = try lvgl.getActiveScreen();
// Create a Label Widget
var label = try screen.createLabel();
// Wrap long lines in the label text
label.setLongMode(c.LV_LABEL_LONG_WRAP);
// Interpret color codes in the label text
label.setRecolor(true);
// Center align the label text
label.setAlign(c.LV_TEXT_ALIGN_CENTER);
// Set the label text and colors
label.setText("#ff0000 HELLO# " ++ // Red Text
"#00aa00 LVGL ON# " ++ // Green Text
"#0000ff PINEPHONE!# " // Blue Text
);
// Set the label width
label.setWidth(200);
// Align the label to the center of the screen, shift 30 pixels up
label.alignObject(c.LV_ALIGN_CENTER, 0, -30);
}
/// Create the LVGL Widgets that will be rendered on the display. Calls the
/// LVGL API directly, without wrapping in Zig. Based on
/// https://docs.lvgl.io/master/widgets/label.html?highlight=lv_label_create#line-wrap-recoloring-and-scrolling
fn createWidgetsUnwrapped() !void {
debug("createWidgetsUnwrapped: start", .{});
defer debug("createWidgetsUnwrapped: end", .{});
// Get the Active Screen
const screen = c.lv_scr_act().?;
// Create a Label Widget
const label = c.lv_label_create(screen).?;
// Wrap long lines in the label text
c.lv_label_set_long_mode(label, c.LV_LABEL_LONG_WRAP);
// Interpret color codes in the label text
c.lv_label_set_recolor(label, true);
// Center align the label text
c.lv_obj_set_style_text_align(label, c.LV_TEXT_ALIGN_CENTER, 0);
// Set the label text and colors
c.lv_label_set_text(label, "#ff0000 HELLO# " ++ // Red Text
"#00aa00 LVGL ON# " ++ // Green Text
"#0000ff PINEPHONE!# " // Blue Text
);
// Set the label width
c.lv_obj_set_width(label, 200);
// Align the label to the center of the screen, shift 30 pixels up
c.lv_obj_align(label, c.LV_ALIGN_CENTER, 0, -30);
}
///////////////////////////////////////////////////////////////////////////////
// LVGL Porting Layer for WebAssembly
/// TODO: Return the number of elapsed milliseconds
export fn millis() u32 {
elapsed_ms += 1;
return elapsed_ms;
}
/// Number of elapsed milliseconds
var elapsed_ms: u32 = 0;
/// On Assertion Failure, print a Stack Trace and halt
export fn lv_assert_handler() void {
@panic("*** lv_assert_handler: ASSERTION FAILED");
}
/// Custom Logger for LVGL that writes to JavaScript Console
export fn custom_logger(buf: [*c]const u8) void {
wasmlog.Console.log("{s}", .{buf});
}
///////////////////////////////////////////////////////////////////////////////
// Memory Allocator for malloc
/// Zig replacement for malloc
export fn malloc(size: usize) ?*anyopaque {
// TODO: Save the slice length
const mem = memory_allocator.allocator().alloc(u8, size) catch {
@panic("*** malloc error: out of memory");
};
return mem.ptr;
}
/// Zig replacement for realloc
export fn realloc(old_mem: [*c]u8, size: usize) ?*anyopaque {
// TODO: Call realloc instead
// const mem = memory_allocator.allocator().realloc(old_mem[0..???], size) catch {
// @panic("*** realloc error: out of memory");
// };
const mem = memory_allocator.allocator().alloc(u8, size) catch {
@panic("*** realloc error: out of memory");
};
_ = memcpy(mem.ptr, old_mem, size);
if (old_mem != null) {
// TODO: How to free without the slice length?
// memory_allocator.allocator().free(old_mem[0..???]);
}
return mem.ptr;
}
/// Zig replacement for free
export fn free(mem: [*c]u8) void {
if (mem == null) {
@panic("*** free error: pointer is null");
}
// TODO: How to free without the slice length?
// memory_allocator.allocator().free(mem[0..???]);
}
/// Memory Allocator for malloc
var memory_allocator: std.heap.FixedBufferAllocator = undefined;
/// Memory Buffer for malloc
var memory_buffer: [1024 * 1024]u8 = undefined;
///////////////////////////////////////////////////////////////////////////////
// Logging
/// Called by Zig for `std.log.debug`, `std.log.info`, `std.log.err`, ...
/// https://gist.github.com/leecannon/d6f5d7e5af5881c466161270347ce84d
pub fn log(
comptime _message_level: std.log.Level,
comptime _scope: @Type(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
_ = _message_level;
_ = _scope;
// Format the message
var buf: [100]u8 = undefined; // Limit to 100 chars
var slice = std.fmt.bufPrint(&buf, format, args) catch {
wasmlog.Console.log("*** log error: buf too small", .{});
return;
};
// Print the formatted message
wasmlog.Console.log("{s}", .{slice});
}
///////////////////////////////////////////////////////////////////////////////
// Imported Functions and Variables
/// Extern functions refer to the exterior JS namespace
/// when importing wasm code, the `print` func must be provided
extern fn print(i32) void;
/// Aliases for Zig Standard Library
const assert = std.debug.assert;
const debug = std.log.debug;
///////////////////////////////////////////////////////////////////////////////
// C Standard Library
// From zig-macos-x86_64-0.10.0-dev.2351+b64a1d5ab/lib/zig/c.zig
export fn memset(dest: ?[*]u8, c2: u8, len: usize) callconv(.C) ?[*]u8 {
@setRuntimeSafety(false);
if (len != 0) {
var d = dest.?;
var n = len;
while (true) {
d.* = c2;
n -= 1;
if (n == 0) break;
d += 1;
}
}
return dest;
}
export fn memcpy(noalias dest: ?[*]u8, noalias src: ?[*]const u8, len: usize) callconv(.C) ?[*]u8 {
@setRuntimeSafety(false);
if (len != 0) {
var d = dest.?;
var s = src.?;
var n = len;
while (true) {
d[0] = s[0];
n -= 1;
if (n == 0) break;
d += 1;
s += 1;
}
}
return dest;
}
export fn strcpy(dest: [*:0]u8, src: [*:0]const u8) callconv(.C) [*:0]u8 {
var i: usize = 0;
while (src[i] != 0) : (i += 1) {
dest[i] = src[i];
}
dest[i] = 0;
return dest;
}
export fn strcmp(s1: [*:0]const u8, s2: [*:0]const u8) callconv(.C) c_int {
return std.cstr.cmp(s1, s2);
}
export fn strlen(s: [*:0]const u8) callconv(.C) usize {
return std.mem.len(s);
}