-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathui.lua
4459 lines (3874 loc) · 114 KB
/
ui.lua
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--UI toolkit with styles and animations.
--Written by Cosmin Apreutesei. Public Domain.
if not ... then DEMO=true; require'ui_demo1'; return end
--pure-Lua libs.
local oo = require'oo'
local events = require'events'
local glue = require'glue'
local box2d = require'box2d'
local easing = require'easing'
local color = require'color'
local font_db = require'font_db'
--C bindings.
local ffi = require'ffi'
local bit = require'bit'
local nw = require'nw'
local time = require'time'
local cairo = require'cairo'
local C = require'layer'
local zone = glue.noop
local zone = require'jit.zone' --enable for profiling
local min = math.min
local max = math.max
local abs = math.abs
local floor = math.floor
local ceil = math.ceil
local push = table.insert
local pop = table.remove
local shr = bit.shr
local band = bit.band
local index = glue.index
local indexof = glue.indexof
local update = glue.update
local extend = glue.extend
local attr = glue.attr
local lerp = glue.lerp
local clamp = glue.clamp
local assert = glue.assert
local collect = glue.collect
local sortedpairs = glue.sortedpairs
local memoize = glue.memoize
local binsearch = glue.binsearch
local pass = glue.pass
local addr = glue.addr
local setbit = glue.setbit
local function popval(t, v)
local i = indexof(v, t)
return i and pop(t, i)
end
local nilkey = {}
local function encode_nil(x) return x == nil and nilkey or x end
local function decode_nil(x) if x == nilkey then return nil end; return x; end
local function snap(x, enable)
return enable and floor(x + .5) or x
end
local function snap_xw(x, w, enable)
if not enable then return x, w end
local x1 = floor(x + .5)
local x2 = floor(x + w + .5)
return x1, x2 - x1
end
local function snap_up(x, enable)
return enable and ceil(x) or x
end
--object system --------------------------------------------------------------
local object = oo.object()
object:inherit(events)
function object:before_init()
--Speed up class field lookup by having the final class statically inherit
--all its fields. With this change, runtime patching of non-final classes
--after the first instantiation doesn't have an effect anymore (it will
--require calling inherit() manually on all those final classes).
--That's ok, you shouldn't patch classes anyway, you should subclass them.
if not rawget(self.super, 'isfinalclass') then
self.super:inherit()
self.super.isfinalclass = true
end
--Speed up virtual property lookup without detaching/fattening the instance.
--This optimization prevents overriding of getters/setters on instances.
self.__setters = self.__setters
self.__getters = self.__getters
end
--error reporting ------------------------------------------------------------
function object:warn(...)
io.stderr:write(string.format(...))
io.stderr:write'\n'
io.stderr:write(debug.traceback())
io.stderr:write'\n'
end
function object:check(ret, ...)
if ret then return ret end
self:warn(...)
end
--method and property decorators ---------------------------------------------
--generic method memoizer that can memoize getters and setters too.
function object:memoize(method_name)
function self:after_init()
local method =
method_name:find'^get_' and self.__getters[method_name:sub(5)]
or method_name:find'^set_' and self.__setters[method_name:sub(5)]
or self[method_name]
local memfunc = memoize(function(...)
return method(self, ...)
end)
self[method_name] = function(self, ...)
return memfunc(...)
end
end
end
--install event handlers in `object` that forward events to self.
function object:forward_events(object, event_names)
for event in pairs(event_names) do
object:on({event, self}, function(object, ...)
return self:fire(event, ...)
end)
end
function self:before_free()
for _,event in ipairs(event_names) do
object:off{event, self}
end
end
end
--forward method calls to a sub-component.
function object:forward_methods(component_name, methods)
for component_method, wrap in pairs(methods) do
local method = type(wrap) == 'string' and wrap or component_method
local wrap = type(wrap) == 'function' and wrap or pass
self[method] = function(self,...)
local e = self[component_name]
return wrap(e[component_method](e, ...))
end
end
end
--create a property which reads/writes to/from a sub-component's property.
function object:forward_property(prop, sub, readonly)
assert(not self.__getters[prop])
local sub, sub_prop = sub:match'^(.-)%.(.*)$'
self['get_'..prop] = function(self)
return self[sub][sub_prop]
end
if not readonly then
self['set_'..prop] = function(self, value)
self[sub][sub_prop] = value
end
end
end
function object:forward_properties(sub, readonly, t)
if type(readonly) == 'table' then
readonly, t = false, readonly
end
for prop, sub_prop in pairs(t) do
sub_prop = type(sub_prop) == 'string' and sub_prop or prop
self:forward_property(prop, sub..'.'..sub_prop, readonly)
end
end
--create a r/w property which reads/writes to/from a private field.
function object:stored_property(prop, after_set)
assert(not self.__getters[prop])
local priv = '_'..prop
self['get_'..prop] = function(self)
local v = self[priv]
if v ~= nil then
return v
else
return self.super[prop]
end
end
if after_set then
self['set_'..prop] = function(self, val)
local val = val or false
self[priv] = val
after_set(self, val)
end
else
self['set_'..prop] = function(self, val)
self[priv] = val or false
end
end
end
function object:stored_properties(t, after_set)
for k in pairs(t) do
self:stored_property(k, after_set and after_set(k))
end
end
--change a property so that its setter is only called when the value changes.
function object:nochange_barrier(prop)
self:override('set_'..prop, function(self, inherited, val)
val = val or false
local old_val = self[prop] or false
if val ~= old_val then
inherited(self, val, old_val)
return true --useful when overriding the setter further
end
end)
end
--change a property so that its setter is only called when the value changes
--and also '<prop>_changed' event is fired.
function object:track_changes(prop)
local changed_event = prop..'_changed'
self:override('set_'..prop, function(self, inherited, val)
val = val or false
local old_val = self[prop] or false
if val ~= old_val then
inherited(self, val, old_val)
val = self[prop] --see if the value really changed.
if val ~= old_val then
self:fire(changed_event, val, old_val)
return true --useful when overriding the setter further
end
end
end)
end
--validate a property when being set against a list of allowed values.
function object:enum_property(prop, values)
if type(values) == 'string' then --'val1 ...'
local s = values
values = {}
for val in s:gmatch'[^%s]+' do
values[val] = val
end
end
local keys = index(values)
self:override('set_'..prop, function(self, inherited, key)
local val = values[key]
if self:check(val, 'invalid value "%s" for %s', key, prop) then
inherited(self, val)
end
end)
self:override('get_'..prop, function(self, inherited)
return keys[inherited(self)]
end)
end
--submodule autoloading ------------------------------------------------------
function object:autoload(autoload)
for prop, submodule in pairs(autoload) do
local getter = 'get_'..prop
local setter = 'set_'..prop
self[getter] = function(self)
require(submodule)
return rawget(self, prop)
end
self[setter] = function(self, val) --prevent "r/o property" error
rawset(self, prop, val)
end
end
end
--module object --------------------------------------------------------------
local ui = object:subclass'ui'
ui.object = object
function ui:after_init()
self.app = nw:app()
self:forward_events(self.app, {
quitting=1,
activated=1, deactivated=1, wakeup=1,
hidden=1, unhidden=1,
displays_changed=1,
})
end
function ui:before_free()
self.app = false
end
--native app proxy methods ---------------------------------------------------
function ui:native_window(t)
return self.app:window(t)
end
function ui:get_active_window()
local win = self.app:active_window()
return win and win.ui_window
end
function ui:clock() return time.clock() end
function ui:run(func) return self.app:run(func) end
function ui:poll(timeout) return self.app:poll(timeout) end
function ui:stop() return self.app:stop() end
function ui:quit() return self.app:quit() end
function ui:get_autoquit() return self.app:autoquit() end
function ui:set_autoquit(aq) return self.app:autoquit(aq or false) end
function ui:get_maxfps() return self.app:maxfps() end
function ui:set_maxfps(fps) return self.app:maxfps(fps or false) end
function ui:runevery(t, f) return self.app:runevery(t, f) end
function ui:runafter(t, f) return self.app:runafter(t, f) end
function ui:sleep(s) return self.app:sleep(s) end
function ui:get_app_active() return self.app:active() end
function ui:activate_app() return self.app:activate() end
function ui:get_app_visible() return self.app:visible() end
function ui:set_app_visible(v) return self.app:visible(v or false) end
function ui:hide_app() return self.app:hide() end
function ui:unhide_app() return self.app:unhide() end
function ui:key(query) return self.app:key(query) end
function ui:get_caret_blink_time() return self.app:caret_blink_time() end
function ui:get_displays() return self.app:displays() end
function ui:get_main_display() return self.app:main_display() end
function ui:get_active_display() return self.app:active_display() end
function ui:getclipboard(type) return self.app:getclipboard(type) end
function ui:setclipboard(s, type) return self.app:setclipboard(s, type) end
function ui:opendialog(t) return self.app:opendialog(t) end
function ui:savedialog(t) return self.app:savedialog(t) end
function ui:set_app_id(id) self.app.nw.app_id = id end
function ui:get_app_id(id) return nw.app_id end
function ui:app_already_running() return self.app:already_running() end
function ui:wakeup_other_app_instances() return self.app:wakeup_other_instances() end
function ui:check_single_app_instance() return self.app:check_single_instance() end
--local files ----------------------------------------------------------------
function ui:open_file(file)
local bundle = require'bundle'
return self:check(bundle.fs_open(file), 'file not found: "%s"', file)
end
function ui:load_file(file)
local bundle = require'bundle'
return self:check(bundle.load(file), 'file not found: "%s"', file)
end
--layerlib proxy properties & methods ----------------------------------------
ui:forward_properties('layerlib', true, {
glyph_cache_count=1,
glyph_cache_size=1,
glyph_run_cache_count=1,
glyph_run_cache_size=1,
mem_font_cache_count=1,
mem_font_cache_size=1,
mmapped_font_cache_count=1,
})
ui:forward_properties('layerlib', {
error_function=1,
font_size_resolution=1,
glyph_cache_max_size=1,
glyph_run_cache_max_size=1,
mem_font_cache_max_size=1,
mmapped_font_cache_max_count=1,
subpixel_x_resolution=1,
word_subpixel_x_resolution=1,
})
ui:forward_methods('layerlib', {
font_face_num=1,
})
--fonts ----------------------------------------------------------------------
function ui:gen_font_id()
local id = (self.font_id or 0) + 1
self.font_id = id
return id
end
function ui:add_mem_font(data, size, ...)
local font_id = self:gen_font_id()
local font = {id = font_id, data = data, size = size}
self.fonts[font_id] = font
self.font_db:add_font(font, ...)
end
function ui:add_font_file(file, ...)
local font_id = self:gen_font_id()
local font = {id = font_id, file = file}
self.fonts[font_id] = font
self.font_db:add_font(font, ...)
end
ui.use_default_fonts = true
ui.default_fonts_path = 'media/fonts'
function ui:add_default_fonts(dir)
local dir = self.default_fonts_path
--$ mgit clone fonts-open-sans
self:add_font_file(dir..'/OpenSans-Regular.ttf', 'Open Sans')
--$ mgit clone fonts-ionicons
self:add_font_file(dir..'/ionicons.ttf', 'Ionicons')
end
ui.use_google_fonts = false
ui.google_fonts_path = 'media/fonts/gfonts'
--add a font searcher for the google fonts repository.
--for this to work you need to get the fonts:
--$ git clone /~https://github.com/google/fonts media/fonts/gfonts
function ui:add_gfonts_searcher()
local gfonts = require'gfonts'
gfonts.root_dir = self.google_fonts_path
local function find_font(font_db, name, weight, slant)
local file, real_weight = gfonts.font_file(name, weight, slant, true)
local font = file and self:add_font_file(file, name, real_weight, slant)
return font, real_weight
end
push(self.font_db.searchers, find_font)
end
function ui:after_init()
self.fonts = {} --{font_id->font}
self.load_font = ffi.cast('tr_font_load_func_t', function(font_id, data_ptr, size_ptr)
local font = self.fonts[font_id]
if font.file then
font.data = self:load_file(font.file)
font.size = font.data and #font.data
end
data_ptr[0] = ffi.cast('void*', font.data)
size_ptr[0] = font.size
end)
self.unload_font = ffi.cast('tr_font_unload_func_t', function(font_id, data, size)
local font = self.fonts[font_id]
if font.file then
font.data = false
font.size = false
end
end)
self.layerlib = C.layerlib(self.load_font, self.unload_font)
self.font_db = font_db()
if self.use_default_fonts then
self:add_default_fonts()
end
if self.use_google_fonts then
self:add_gfonts_searcher()
end
end
function ui:before_free()
self.layerlib:free(); self.layerlib = false
self.font_db:free(); self.font_db = false
self.load_font:free(); self.load_font = false
self.unload_font:free(); self.unload_font = false
end
--image files ----------------------------------------------------------------
function ui:image_pattern(file)
local ext = file:match'%.([^%.]+)$'
if ext == 'jpg' or ext == 'jpeg' then
local libjpeg = require'libjpeg'
local f = self:open_file(file)
if not f then return end
local bufread = f:buffered_read()
local function read(buf, sz)
return self:check(bufread(buf, sz))
end
local img = self:check(libjpeg.open({read = read}))
if not img then
f:close()
return
end
local bmp = self:check(img:load{accept = {bgra8 = true}})
img:free()
f:close()
if not bmp then
return
end
local sr = cairo.image_surface(bmp) --bmp is Lua-pinned to sr
local patt = cairo.surface_pattern(sr) --sr is cairo-pinned to patt
return {patt = patt, sr = sr}
end
end
ui:memoize'image_pattern'
--selectors ------------------------------------------------------------------
ui.selector = ui.object:subclass'selector'
function ui.selector:override_create(inherited, ui, sel, ...)
if oo.isinstance(sel, self) then
return sel --pass-through
end
return inherited(self, ui, sel, ...)
end
local function noop() end
local function gmatch_tags(s)
return s and s:gmatch'[^%s]+' or noop
end
function ui.selector:after_init(ui, sel)
local filter
if type(sel) == 'function' then
sel, filter = '', sel
elseif sel == nil then
sel = ''
end
self.text = sel --for debugging
--parents filter.
if sel:find'>' then
self.parent_tags = {} --{{tag,...}, ...}
sel = sel:gsub('([^>]+)%s*>', function(s) -- tags... >
local tags = collect(gmatch_tags(s))
push(self.parent_tags, tags)
return ''
end)
end
--exclude tags filter.
local t
sel = sel:gsub('!([^%s]+)', function(tag)
t = t or {}
push(t, tag)
return ''
end)
self.exclude_tags = t
--tags filter.
self.tags = collect(gmatch_tags(sel))
--proc filter.
if filter then
self:filter(filter)
end
end
function ui.selector:filter(filter)
if not self._filter then
self._filter = filter
else
local prev_filter = self._filter
self._filter = function(elem)
return prev_filter(elem) and filter(elem)
end
end
return self
end
local function has_state_tags(tags)
for _,tag in ipairs(tags) do
if tag:find(':', 1, true) then
return true
end
end
end
function ui.selector:has_state_tags()
if has_state_tags(self.tags) then
return true
end
if self.parent_tags then
for _,tags in ipairs(self.parent_tags) do
if has_state_tags(tags) then
return true
end
end
end
end
--check that all needed_tags are found in tags table as keys
local function has_all_tags(needed_tags, tags)
for i,tag in ipairs(needed_tags) do
if not tags[tag] then
return false
end
end
return true
end
--check that none of the exclude_tags are found in tags table as keys
local function has_no_tags(exclude_tags, tags)
for i,tag in ipairs(exclude_tags) do
if tags[tag] then
return false
end
end
return true
end
function ui.selector:selects(elem)
if not has_all_tags(self.tags, elem.tags) then
return false
end
if self.exclude_tags then
if not has_no_tags(self.exclude_tags, elem.tags) then
return false
end
end
if self.parent_tags then
local i = #self.parent_tags
local tags = self.parent_tags[i]
local elem = elem.parent
while tags and elem do
if has_all_tags(tags, elem.tags) then
if i == 1 then
return true
end
i = i - 1
tags = self.parent_tags[i]
end
elem = elem.parent
end
return false
end
if self._filter and not self._filter(elem) then
return false
end
return true
end
--stylesheets ----------------------------------------------------------------
local stylesheet = ui.object:subclass'stylesheet'
ui.stylesheet = stylesheet
function stylesheet:after_init(ui)
self.ui = ui
self.tags = {} --{tag -> {sel1, ...}}
self.parent_tags = {} --{tag -> {sel1, ...}}
self.selectors = {} --{selector1, ...}
self.first_state_sel_index = 1 --index of first selector with :state tags
end
function stylesheet:style(sel, attrs)
if type(sel) == 'string' and sel:find(',', 1, true) then
for sel in sel:gmatch'[^,]+' do
self:style(sel, attrs)
end
return
end
local sel = self.ui:selector(sel)
sel.attrs = attrs
local is_state_sel = sel:has_state_tags()
local index = is_state_sel and #self.selectors+1 or self.first_state_sel_index
sel.index = index
push(self.selectors, index, sel)
for i = index+1, #self.selectors do --update index field on shifted selectors
self.selectors[i].index = i
end
if not is_state_sel then
self.first_state_sel_index = index+1
end
--populate the selector reverse-lookup tables
for _,tag in ipairs(sel.tags) do
push(attr(self.tags, tag), sel)
end
if sel.parent_tags then
for _,tags in ipairs(sel.parent_tags) do
for _,tag in ipairs(tags) do
push(attr(self.parent_tags, tag), sel)
end
end
end
end
function stylesheet:add_stylesheet(stylesheet)
for tag, selectors in pairs(stylesheet.tags) do
extend(attr(self.tags, tag), selectors)
end
for tag, selectors in pairs(stylesheet.parent_tags) do
extend(attr(self.parent_tags, tag), selectors)
end
end
--attr. value to use in styles for "initial value of this attr"
function ui.initial(self, attr)
return self:initial_value(attr)
end
--attr. value to use in styles for "inherit value from parent for this attr"
function ui.inherited(self, attr)
return self:parent_value(attr)
end
--attr. value to use in styles for "same as the value of this other attr"
function ui:value_of(attr)
return function(self)
return self[attr]
end
end
local function cmp_sel(sel1, sel2)
return sel1.index < sel2.index
end
function stylesheet:update_element(elem, update_children)
--gather all style selectors which select the element.
local st = {} --{sel1, ...}
local checked = {} --{sel -> true}
for tag in pairs(elem.tags) do
local selectors = self.tags[tag]
if selectors then
for _,sel in ipairs(selectors) do
if not checked[sel] then
if sel:selects(elem) then
push(st, sel)
end
checked[sel] = true
end
end
end
end
--sort selectors in style declaration order.
table.sort(st, cmp_sel)
--compute attribute values.
local attrs = {} --{attr -> val}
for _,sel in ipairs(st) do
update(attrs, sel.attrs)
end
update(attrs, elem.style)
--add the saved initial values of attributes that were changed by
--this function before but are missing from the styles this time.
local init = elem._initial_values
if init then
for attr, init_val in pairs(init) do
if attrs[attr] == nil then
attrs[attr] = init_val
end
end
end
--set transition attrs first so that elem:transition() can use them.
--also because we don't want to transition the transition attrs.
for attr, val in pairs(attrs) do
if attr:find'^transition_' then
elem:_save_initial_value(attr)
if type(val) == 'function' then --computed value
val = val(elem, attr)
end
elem[attr] = decode_nil(val)
end
end
--set all attribute values into elem via transition().
for attr, val in pairs(attrs) do
if not attr:find'^transition_' then
elem:_save_initial_value(attr)
elem:transition(attr, decode_nil(val))
end
end
--update all children of elem if elem has parent tags in any style.
--TODO: speed up the pathological case when a container with many children
--needs to be updated and there's a style which has parent tags that match
--one of the container's tags (for now, just don't make selectors with too
--generic parent filters that could match a container and not a widget).
if not update_children then
for tag in pairs(elem.tags) do
if self.parent_tags[tag] then
update_children = true
break
end
end
end
if update_children then
for _,layer in ipairs(elem) do
self:update_element(layer, true)
end
end
end
function ui:style(sel, attrs)
self.element.stylesheet:style(sel, attrs)
end
--color parsing --------------------------------------------------------------
ui.invalid_color = '#0000'
function ui:rgba(s)
if type(s) == 'string' then --from user
local r, g, b, a = color.parse(s, 'rgb')
if r then
return r, g, b, a or 1
end
elseif type(s) == 'table' then --from interpolation
return s[1], s[2], s[3], s[4] or 1
elseif type(c) == 'number' then --why not?
return
shr(c, 24) / 255,
band(shr(c, 16), 0xff) / 255,
band(shr(c, 8), 0xff) / 255,
band( c , 0xff) / 255
elseif not s then --transitioning from background_color=false to a color
return 0, 0, 0, 0
end
self:check(false, 'invalid color "%s"', tostring(s))
local s = self.invalid_color
local r, g, b, a = color.parse(s, 'rgb')
self:check(r, 'invalid invalid color "%s"', s)
if not r then
r, g, b, a = 1, 1, 0, 1
end
return r, g, b, a
end
function ui:rgba32(c)
if type(c) == 'number' then return c end
return color.format('rgba32', 'rgb', self:rgba(c))
end
ui:memoize'rgba32'
--attribute types ------------------------------------------------------------
ui.type = {} --{patt|f(attr) -> type}
--find an attribute type based on its name
function ui:attr_type(attr)
for patt, atype in pairs(self.type) do
if (type(patt) == 'string' and attr:find(patt))
or (type(patt) ~= 'string' and patt(attr))
then
return atype
end
end
return 'number'
end
ui:memoize'attr_type'
ui.type['_color$'] = 'color'
ui.type['_color_'] = 'color'
ui.type['_colors$'] = 'gradient_colors'
--interpolators --------------------------------------------------------------
ui.interpolate = {} --{attr_type -> func(self, d, x1, x2, xout) -> xout}
function ui.interpolate:number(d, x1, x2)
return lerp(d, 0, 1, tonumber(x1), tonumber(x2))
end
function ui.interpolate:color(d, c1, c2, c)
local r1, g1, b1, a1 = self.ui:rgba(c1)
local r2, g2, b2, a2 = self.ui:rgba(c2)
local r = lerp(d, 0, 1, r1, r2)
local g = lerp(d, 0, 1, g1, g2)
local b = lerp(d, 0, 1, b1, b2)
local a = lerp(d, 0, 1, a1 or 1, a2 or 1)
if type(c) == 'table' then --by-reference semantics
c[1], c[2], c[3], c[4] = r, g, b, a
return c
else --by-value semantics
return {r, g, b, a}
end
end
function ui.interpolate:gradient_colors(d, t1, t2, t)
t = t or {}
for i,arg1 in ipairs(t1) do
local arg2 = t2[i]
local atype = type(arg1) == 'number' and 'number' or 'color'
t[i] = ui.transition.interpolate[atype](self, d, arg1, arg2, t[i])
end
return t
end
function ui:interpolate_function(attr)
local atype = self:attr_type(attr)
return self.interpolate[atype]
end
--transition animation objects -----------------------------------------------
local tran = ui.object:subclass'transition'
ui.transition = tran
tran.duration = 0
tran.delay = 0
tran.ease = 'expo out'
tran.times = 1
function tran:after_init(ui, t, ...)
self.ui = ui
update(self, self.super, t, ...)
--timing model
self.clock = self.clock or ui:clock()
self.start = self.clock + self.delay
if not self.way then
self.ease, self.way = self.ease:match'^([^%s_]+)[%s_]?(.*)'
if self.way == '' then self.way = 'in' end
end
--animation model
if self.from == nil then
self.from = self.elem[self.attr]
assert(self.from ~= nil, 'transition from nil value for "%s"', self.attr)
end
assert(self.to ~= nil, 'transition to nil value for "%s"', self.attr)
self.interpolate = self.ui:interpolate_function(self.attr)
self.end_value = self.to --store it for later
--set the element value to a copy to avoid overwritting the original value
--when updating with by-ref semantics.
self.elem[self.attr] = self.interpolate(self, 1, self.from, self.from)
end
function tran:value_at(t)
local d = easing.ease(self.ease, self.way, t)
return self:interpolate(d, self.from, self.to, self.elem[self.attr])
end
function tran:update(clock)
local t = (clock - self.start) / self.duration
if t < 0 then --not started
--nothing
elseif t >= 1 then --finished, set to actual final value
self.elem[self.attr] = self.to
else --running, set to interpolated value
self.elem[self.attr] = self:value_at(t)
end
if t > 1 and self.times > 1 then --repeat in opposite direction
self.times = self.times - 1
self.start = clock + self.delay
self.from, self.to = self.to, self.from
if not self.repeated then
self.to = self.backval
self.repeated = true
end
return self:update(clock)
end
return t
end
function tran:get_end_clock()
return self.start + self.duration
end
--elements -------------------------------------------------------------------
local element = ui.object:subclass'element'
ui.element = element
function element:init_ignore(t) --class method
if self._init_ignore == self.super._init_ignore then
self._init_ignore = update({}, self.super._init_ignore)
end
if type(t) == 'string' then
self._init_ignore[t] = 1
else
update(self._init_ignore, t)
end
end
function element:_comes_after(pri, k)
end
function element:init_priority(t) --class method
if self._init_priority == self.super._init_priority then
self._init_priority = update({}, self.super._init_priority)
end
local left_pri = 0
for _,k in ipairs(t) do
local pri = self._init_priority[k]
if pri then
left_pri = pri
else