about summary refs log tree commit diff stats
path: root/readme.md
diff options
context:
space:
mode:
Diffstat (limited to 'readme.md')
-rw-r--r--readme.md8
1 files changed, 2 insertions, 6 deletions
diff --git a/readme.md b/readme.md
index b0b1a280..e66d6992 100644
--- a/readme.md
+++ b/readme.md
@@ -21,7 +21,7 @@ It also functions as a pager, similarly to w3m.
 
 Currently implemented features are:
 
-* a unicode, double-width capable pager
+* a multi-charset, double-width capable pager
 * a CSS-capable layout engine
 * forms, tables
 * incremental loading of plain text streams
@@ -29,20 +29,16 @@ Currently implemented features are:
 
 **Planned** features, roughly in order of importance:
 
+* cookies
 * JavaScript in html documents
-* non-unicode charsets (they currently crash the browser)
 * partial re-rendering of page layout
 * unicode normalization
-* fast streams (aka pipelines; use library?)
 * standard-compliant support for remote resources
 * iframe
 * ruby
-* cookies
 * external viewers (for audio, video, image, etc)
 * image (sixel & kitty?)
 * markdown (built-in parser)
-* color contrast correction
-* terminal color mode
 * config editor
 * user stylesheet editor
 * SOCKS proxy
s.nim?id=d26766c4c4015990703e84e8136f96d222edbc97'>d26766c4 ^
0b19885b ^
85796198 ^
f0241b2f ^
a1254648 ^
85796198 ^
d963385c ^
298a21ef ^





d963385c ^
4360d383 ^
298a21ef ^


4360d383 ^

298a21ef ^
















































4360d383 ^

298a21ef ^


























4360d383 ^

298a21ef ^
4360d383 ^


b2bf6774 ^


b13d739c ^

4360d383 ^





d91d1dda ^
4360d383 ^


150de039 ^
4360d383 ^










d1d4c751 ^

7458264e ^
6dd80b68 ^



4360d383 ^

a42f0b16 ^




5c19adf2 ^

fca4ef9b ^

5c19adf2 ^
87a47d56 ^


7dae490a ^
e0574a00 ^

7dae490a ^
339a167f ^


47b0c8df ^

b5cffb3d ^
2a223405 ^
47b0c8df ^
5b1829f1 ^


75310d68 ^


e896c692 ^


69147692 ^



6b9db7e8 ^




d54e0258 ^










4360d383 ^
85796198 ^




a42f0b16 ^


47b0c8df ^



3a245434 ^
47b0c8df ^







03fc72ab ^
7e65add5 ^
402c01d8 ^
298a21ef ^
f11c9425 ^
298a21ef ^
85796198 ^
298a21ef ^
85796198 ^
298a21ef ^
f4805eb8 ^
298a21ef ^
47b0c8df ^
298a21ef ^
47b0c8df ^
298a21ef ^
f4805eb8 ^
298a21ef ^
85796198 ^
298a21ef ^
31162225 ^
298a21ef ^
f4805eb8 ^
298a21ef ^
72e171f6 ^
298a21ef ^
a42f0b16 ^
298a21ef ^
5c19adf2 ^
298a21ef ^
87a47d56 ^
298a21ef ^
150de039 ^
298a21ef ^
7dae490a ^
298a21ef ^
339a167f ^
298a21ef ^
339a167f ^
298a21ef ^
47b0c8df ^
298a21ef ^
7146419b ^
298a21ef ^
5b1829f1 ^
298a21ef ^
75310d68 ^
298a21ef ^
e896c692 ^
298a21ef ^
69147692 ^
298a21ef ^
6b9db7e8 ^
298a21ef ^
6ec8abb1 ^
298a21ef ^
85796198 ^
7e65add5 ^
85796198 ^
ca81bbce ^




4e264e9d ^

ca81bbce ^
4e264e9d ^
ca81bbce ^
4e264e9d ^
ca81bbce ^

4e264e9d ^


7ab7f28f ^
ca81bbce ^
d963385c ^
298a21ef ^




d963385c ^

298a21ef ^





85796198 ^
7ab7f28f ^
298a21ef ^
















































85796198 ^


298a21ef ^



85796198 ^

7bea2f70 ^

85796198 ^






d963385c ^
298a21ef ^
d963385c ^
a1254648 ^
298a21ef ^
85796198 ^
a1254648 ^
85796198 ^

10bdd58b ^


64d96d51 ^


4e264e9d ^

f1814211 ^
64d96d51 ^





d4d45f41 ^
d4d45f41 ^
298a21ef ^
d4d45f41 ^
298a21ef ^
64d96d51 ^
298a21ef ^
64d96d51 ^
4e264e9d ^

d4d45f41 ^
9b69d024 ^

298a21ef ^

9b69d024 ^
e4d4e1fa ^
9b69d024 ^

96824ecd ^
298a21ef ^
4e264e9d ^
9b69d024 ^



f2a49241 ^
85796198 ^


1c6ce089 ^
c355c176 ^
d97776fb ^
1c6ce089 ^
c355c176 ^
d97776fb ^
053e1ac0 ^
1c6ce089 ^
c355c176 ^
d97776fb ^

1c6ce089 ^
c355c176 ^
d97776fb ^
4e264e9d ^

d97776fb ^
7d6c75e4 ^



9276603b ^
1c6ce089 ^











d97776fb ^
6dd80b68 ^










d1d4c751 ^

6dd80b68 ^













d1d4c751 ^





72e171f6 ^


d1d4c751 ^




72e171f6 ^
7458264e ^
7badcc1f ^
6dd80b68 ^








d1d4c751 ^



72e171f6 ^

47b0c8df ^










d54e0258 ^
5098a7a1 ^
d54e0258 ^

5098a7a1 ^
85796198 ^
c5375d2a ^
148d6ce5 ^

















37f29306 ^
c5375d2a ^
468d0823 ^
37f29306 ^
85796198 ^
4e40c70e ^

ee930b0f ^









9528f502 ^
ee930b0f ^











f11c9425 ^
412dafe1 ^



e46f0a4c ^
f11c9425 ^



















































































d963385c ^





f11c9425 ^
d963385c ^
f11c9425 ^
d963385c ^
f11c9425 ^
d963385c ^


c5f6051f ^
f11c9425 ^


37f29306 ^
85796198 ^
7dae490a ^
a42f0b16 ^
468d0823 ^

c5f6051f ^
37f29306 ^
468d0823 ^


c5f6051f ^









37f29306 ^
c5f6051f ^

37f29306 ^
c5f6051f ^

37f29306 ^
468d0823 ^
578df008 ^
37f29306 ^
6c8d4a6d ^





468d0823 ^
6c8d4a6d ^











c5f6051f ^
468d0823 ^
6c8d4a6d ^
37f29306 ^
85796198 ^
37f29306 ^
339a167f ^




468d0823 ^
339a167f ^



37f29306 ^
339a167f ^
37f29306 ^
7dae490a ^

7a2cda0e ^

54f4d713 ^
7a2cda0e ^
c5f6051f ^
468d0823 ^
7a2cda0e ^
37f29306 ^
85796198 ^
c5f6051f ^

298a21ef ^



c5f6051f ^
298a21ef ^
f4805eb8 ^
37f29306 ^
e8bb0842 ^
37f29306 ^
c5f6051f ^

47b0c8df ^



e8bb0842 ^
47b0c8df ^



e8bb0842 ^
c5f6051f ^





47b0c8df ^








e8bb0842 ^


468d0823 ^
47b0c8df ^






c5f6051f ^









47b0c8df ^


85796198 ^
37f29306 ^
468d0823 ^














b13d739c ^
468d0823 ^
c5f6051f ^
468d0823 ^

37f29306 ^
c5f6051f ^
d91d1dda ^


c5f6051f ^

85796198 ^
37f29306 ^
c5f6051f ^







468d0823 ^
37f29306 ^
7dae490a ^

85796198 ^
c5f6051f ^






85796198 ^
468d0823 ^

37f29306 ^
85796198 ^
37f29306 ^
c5f6051f ^
7dae490a ^


31162225 ^
c5f6051f ^

37f29306 ^
c5f6051f ^









37f29306 ^
c5f6051f ^
85796198 ^
37f29306 ^
c5f6051f ^





468d0823 ^
4e264e9d ^
468d0823 ^





d1d4c751 ^



468d0823 ^

6dd80b68 ^








468d0823 ^
c5f6051f ^
468d0823 ^

4e264e9d ^
7dae490a ^

a42f0b16 ^
c5f6051f ^












a42f0b16 ^
c5f6051f ^



37f29306 ^
a42f0b16 ^
37f29306 ^
7dae490a ^

a42f0b16 ^



54f4d713 ^
468d0823 ^
a42f0b16 ^
6c8d4a6d ^
37f29306 ^
468d0823 ^
37f29306 ^
468d0823 ^







c5f6051f ^
468d0823 ^

4e264e9d ^
c5f6051f ^




468d0823 ^
37f29306 ^
468d0823 ^





c5f6051f ^
468d0823 ^

37f29306 ^
468d0823 ^


468d0823 ^

c5f6051f ^
468d0823 ^

4e264e9d ^
c5f6051f ^




87a47d56 ^
37f29306 ^
e8bb0842 ^
37f29306 ^
47b0c8df ^

468d0823 ^
47b0c8df ^





e8bb0842 ^

47b0c8df ^


e8bb0842 ^

47b0c8df ^
468d0823 ^
47b0c8df ^
e8bb0842 ^

468d0823 ^
47b0c8df ^
37f29306 ^
cd83ed43 ^



c5f6051f ^
468d0823 ^
db6b5fc2 ^
e8bb0842 ^
cd83ed43 ^
37f29306 ^
cd83ed43 ^
814814ee ^







c5f6051f ^
814814ee ^











37f29306 ^
7146419b ^
814814ee ^
7146419b ^
814814ee ^
468d0823 ^
814814ee ^

468d0823 ^
37f29306 ^
7146419b ^
4e264e9d ^
b5cffb3d ^


468d0823 ^

37f29306 ^
b5cffb3d ^
37f29306 ^
c5f6051f ^





5b1829f1 ^
37f29306 ^
c5f6051f ^





75310d68 ^
37f29306 ^
e896c692 ^





69147692 ^










6b9db7e8 ^











468d0823 ^
37f29306 ^
7dae490a ^
412dafe1 ^
03fc72ab ^
37f29306 ^
7dae490a ^
339a167f ^
c62b3599 ^
298a21ef ^
468d0823 ^
298a21ef ^
a42f0b16 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^

468d0823 ^
298a21ef ^

468d0823 ^
7a2cda0e ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^

468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
c5f6051f ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
412dafe1 ^
339a167f ^



468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
e896c692 ^
298a21ef ^
69147692 ^
298a21ef ^
6b9db7e8 ^
298a21ef ^
6ec8abb1 ^
298a21ef ^
468d0823 ^

c62b3599 ^
f11c9425 ^
298a21ef ^
f11c9425 ^
ed6c9ef5 ^
85796198 ^
332dedce ^

298a21ef ^



4e40c70e ^
332dedce ^
c4b421da ^
332dedce ^
b5cffb3d ^

298a21ef ^
b5cffb3d ^
298a21ef ^
b5cffb3d ^
ed6c9ef5 ^

b5cffb3d ^
7e65add5 ^
85796198 ^
7e65add5 ^
85796198 ^
298a21ef ^
4e264e9d ^
298a21ef ^
4e264e9d ^
298a21ef ^
4e264e9d ^
298a21ef ^
4e264e9d ^
298a21ef ^
4e264e9d ^
298a21ef ^
4e264e9d ^
85796198 ^
4e264e9d ^
85796198 ^

7e65add5 ^
85796198 ^
a1254648 ^
85796198 ^
a1254648 ^
85796198 ^
c6ca5130 ^



468d0823 ^
4e264e9d ^
468d0823 ^
4e264e9d ^
298a21ef ^
4e264e9d ^
c6ca5130 ^
4e264e9d ^
a1254648 ^
468d0823 ^
4e264e9d ^
c4b421da ^





4e264e9d ^
c4b421da ^
c3e96cd1 ^
468d0823 ^

4e264e9d ^
468d0823 ^
4e264e9d ^
c3e96cd1 ^
468d0823 ^


4e264e9d ^
468d0823 ^
4e264e9d ^
c3e96cd1 ^
468d0823 ^


4e264e9d ^
468d0823 ^






4e264e9d ^
c3e96cd1 ^
468d0823 ^


4e264e9d ^
468d0823 ^
4e264e9d ^
c4b421da ^
468d0823 ^


298a21ef ^

468d0823 ^


298a21ef ^

468d0823 ^
c4b421da ^
4e264e9d ^


298a21ef ^
4e264e9d ^
d963385c ^
468d0823 ^
298a21ef ^
d963385c ^
298a21ef ^
d963385c ^

4e264e9d ^

298a21ef ^
468d0823 ^
298a21ef ^
468d0823 ^
298a21ef ^
d963385c ^
298a21ef ^

f4b53af1 ^
298a21ef ^
d963385c ^
814814ee ^

f4b53af1 ^
298a21ef ^
f4b53af1 ^
298a21ef ^
468d0823 ^
f4b53af1 ^



298a21ef ^


a1c62fc9 ^
298a21ef ^

f4b53af1 ^
298a21ef ^
a1c62fc9 ^
f4b53af1 ^
ef767b8c ^
298a21ef ^
f4b53af1 ^


ef767b8c ^
298a21ef ^
f4b53af1 ^

468d0823 ^
f4b53af1 ^



298a21ef ^

4e264e9d ^
d963385c ^
4e264e9d ^




ca81bbce ^
4e264e9d ^

ca81bbce ^

4e264e9d ^


ca81bbce ^
4e264e9d ^


ca81bbce ^



a1254648 ^
298a21ef ^
ca81bbce ^



298a21ef ^
ca81bbce ^
298a21ef ^
ca81bbce ^








298a21ef ^
ca81bbce ^



298a21ef ^
ca81bbce ^
a1254648 ^
ca81bbce ^







d4d45f41 ^
ca81bbce ^
4e264e9d ^
ca81bbce ^





ca81bbce ^






f2a49241 ^
4e264e9d ^

148d6ce5 ^
ca81bbce ^



4e264e9d ^
ca81bbce ^
4e264e9d ^

2f8ab989 ^



ca81bbce ^



4e264e9d ^



ca81bbce ^



4e264e9d ^

ca81bbce ^




4e264e9d ^

ca81bbce ^




4e264e9d ^

ca81bbce ^



4e264e9d ^
ca81bbce ^

7bea2f70 ^
ca81bbce ^
4e264e9d ^

ca81bbce ^


39e2ef52 ^

b13d739c ^

39e2ef52 ^









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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585




                   
 

                         
                 
                        
                  
                
                     
                   
 
                                
 
    
                         





                                
 
                 


                                                                           

                         
















































                                                 

                      


























                                              

                            
                                                            


                                                                   


                                                                              

                                                                    





                                                                              
                                                            


                                                                          
                   










                                                                              

                                                                          
                                                             



                                                             

                                     




                                                                               

                                                                        

                                                                 
 


                                                           
                        

                                                                    
 


                                                      

                                                            
                                                                 
                                                 
 


                                       


                                                              


                                                 



                                                                        




                                                                             










                                                                                 
    




                     


                               



                      
                







                                 
 
                                
                         
                
                       
                 
                        
                    
                              
                  
                          
                  
                               
                 
                        
                     
                                
                  
                   
                         
                                             
                    
                              
                        
                                      
                        
                                      
                    
                              
                            
                                              
                   
                            
                      
                                  
                  
                                      
                         
                                        
                       
                                         
                
                        
                
                      
                     
                                
                    
                              
                
                      
                        
                                      
                          
                            
                       
 
                                                                   
 




                     

                          
                         
                              
 
                                            

                                    


                                                             
                                 
 
                        




                              

           





                                                
 
                     
















































                                             


                             



                                                                              

 

                                                            






                                              
                                                 
                                                               
 
                                               
                                                              
 
                                                     

                         


                                            


                                      

                                                              
                         





                                        
                                          
            
              
                        
              
                        
               
                         

                   
 

                                                                 

                               
                                     
 

                                                                     
                      
                    
                  



                                                    
 


                                          
                                                                  
                          
 
                                                                  
                          
 
                                   
                                                                  
                              

                                      
                                                                  
                              
 

                                                                           
             



                                               
                                                        











                                                                     
 










                                                                                                    

                                                                         













                                                      





                                                       


                                                       




                                                              
                                              
                                                              
                                                                   








                                                                           



                                                  

                                                                        










                                      
                                                                              
                             

                                                      
    
 
               

















                    
                                                            
                   
                                                     
              
 

                                            









                                                          
                                                                











                                                                 
                                                                     



                                       
 



















































































                                                                           





                                      
                                    
                       
                                      
                     
                                        


                            
                                                                         


                                              
              
 
                                                                         
 

                                                                 
                                                                              
            


                                        









                                                                   
              

                                                                             
            

                                    
              
 
                                                                     
                                                         





                             
                                                     











                                              
                                                
                                    
                   
              
 
                                                                




                           
                                                   



                                              
              
 
                                                              

                            

                           
                                            
                       
                                              
                                
                 
              
 

                                                       



                          
   
                                                     
 
                                                   
                
                

                      



                               
                    



                              
                              





                                                








                                      


               
                






                                                     









                                                           


                                                               
 
                                                           














                                                     
                                   
                        
   

                                   
                                                               
                        


                                 

                                     
 
                                                                 







                                      
 
                                                       

                            
                                        






                                          
                                           

                                     
              
 
                                                                        
                               


                              
                                          

                                              
                        









                                                        
                      
              
 
                                                               





                                      
 
                                                                       





                                       



                                                             

                                               








                                                     
                                                          
   

                                     
                                                                       

                            
                                        












                                                 
         



                                                 
              
 
                                                             

                            



                                             
                               
                                
         
                                             
              
 
                                                               







                                        
   

                                     
                                                                               




                                             
 
                                                             





                                  
   

                                    
                                                                   


                                  

                                            
   

                                       
                                                                         




                                          
 
                                                                    
                
                

                        
                               





                                      

             


                          

                 
                               
                  
                 

           
                
 
                                                             



                            
                                            
                                
                                                                   
                                                   
                 
              
 







                                                        
                                                                            











                                                    
                                                         
                   
                       
                            
                                                                
                                                    

                        
                                                       
              
 
                                                                       


                                         

                                                          
              
 
                                                       





                                 
 
                                                                 





                                      
 
                                                               





                                         










                                                       











                                                                       
                                                               
                                                             
           
                           
                      
                
                       
       
            
              
                               
               
              
                      
                                        
                     
                                       

                                              
                                       

                                                      
                                                     
         
                                   
                  
                                       
                
                                   
                
                               
                   
                                         

                              
                                        
                                
                                                
                                
                                                 
                       
                                              
                  
                                       
                      
                                               
                      
                                               
                  
                                       
                          
                                                       
                 
                                     
                    
                                           
                       
                                                 
                
                                            
                             



                                   
                                              
               
                              
                     
                                          
              
                               
              
                               
                   
                                         
                  
                                       
              
                               
                      
                                               
                        
                                 
             

             
 
                                                     
                             
                                            
                     
 

                                                      



                                              
                        
       
                                                        
 

                                                 
                                  
            
                   
                       

            
 
                                                        
                      
                          
        
              
                                                          
                
                                                        
                  
                                                             
               
                                                            
                
                                                              
               
                                                              
       
                               

           
                                                                  
                                     
                              
 
                                    
 



                                                           
                                                                
                                                 
                           
                                      
                           
                                   
                                        
                                 
 
                                                                          
                                





                                          
                                
                
                                  

                                  
                                          
                                            
                                         
                                   


                                  
                                          
                                             
                                         
                                    


                                  
                                          






                                       
                                         
                                     


                                  
                                          
                                       
                                         
               


                            

                                                


                             

                                                   
 
 


                                                                           
             
                                    
                                
                                               
            
                             
                             

                                    

                                            
               
                                                    
                
                                                     
                   
                             

                                                   
                    
                             
                         

                                       
                                           
                                                                  
                                             
                                                                  
             



                                                          


                                                       
                             

                                                      
                    
                             
                         
                                                       
                                         
                                    


                                                     
                                     
                                

                                
             



                                

                                                          
             
 




                                                                  
 

                                                      

                      


                                                                      
 


                                                                   



                                   
             
                



                                   
                
                                 
              








                                     
               



                                       
                 
                    
 







                                                                       
                                                                   
             
                    





                                           






                                                          
 

                                                             
             



                                                          
                                                                              
                                                     

                                                                           



                                              



                                                  



                                                                         



                                                  

                                                                         




                                                     

                                                                         




                                                     

                                                                         



                                                     
                                                                              

                                           
                              
                           

                                                      


                                           

                                   

                                                                     









                                                                              
import std/macros
import std/options
import std/strutils
import std/tables
import std/unicode

import css/cssparser
import css/selectorparser
import img/bitmap
import layout/layoutunit
import types/color
import types/opt
import types/winattrs
import utils/twtstr

export selectorparser.PseudoElem

type
  CSSShorthandType = enum
    cstNone = ""
    cstAll = "all"
    cstMargin = "margin"
    cstPadding = "padding"
    cstBackground = "background"
    cstListStyle = "list-style"

  CSSUnit* = enum
    UNIT_CM, UNIT_MM, UNIT_IN, UNIT_PX, UNIT_PT, UNIT_PC, UNIT_EM, UNIT_EX,
    UNIT_CH, UNIT_REM, UNIT_VW, UNIT_VH, UNIT_VMIN, UNIT_VMAX, UNIT_PERC,
    UNIT_IC

  CSSPropertyType* = enum
    cptNone = ""
    cptColor = "color"
    cptMarginTop = "margin-top"
    cptMarginLeft = "margin-left"
    cptMarginRight = "margin-right"
    cptMarginBottom = "margin-bottom"
    cptFontStyle = "font-style"
    cptDisplay = "display"
    cptContent = "content"
    cptWhiteSpace = "white-space"
    cptFontWeight = "font-weight"
    cptTextDecoration = "text-decoration"
    cptWordBreak = "word-break"
    cptWidth = "width"
    cptHeight = "height"
    cptListStyleType = "list-style-type"
    cptPaddingTop = "padding-top"
    cptPaddingLeft = "padding-left"
    cptPaddingRight = "padding-right"
    cptPaddingBottom = "padding-bottom"
    cptWordSpacing = "word-spacing"
    cptVerticalAlign = "vertical-align"
    cptLineHeight = "line-height"
    cptTextAlign = "text-align"
    cptListStylePosition = "list-style-position"
    cptBackgroundColor = "background-color"
    cptPosition = "position"
    cptLeft = "left"
    cptRight = "right"
    cptTop = "top"
    cptBottom = "bottom"
    cptCaptionSide = "caption-side"
    cptBorderSpacing = "border-spacing"
    cptBorderCollapse = "border-collapse"
    cptQuotes = "quotes"
    cptCounterReset = "counter-reset"
    cptMaxWidth = "max-width"
    cptMaxHeight = "max-height"
    cptMinWidth = "min-width"
    cptMinHeight = "min-height"
    cptBackgroundImage = "background-image"
    cptChaColspan = "-cha-colspan"
    cptChaRowspan = "-cha-rowspan"
    cptFloat = "float"
    cptVisibility = "visibility"
    cptBoxSizing = "box-sizing"
    cptClear = "clear"
    cptTextTransform = "text-transform"
    cptBgcolorIsCanvas = "-cha-bgcolor-is-canvas"

  CSSValueType* = enum
    cvtNone = ""
    cvtLength = "length"
    cvtColor = "color"
    cvtContent = "content"
    cvtDisplay = "display"
    cvtFontStyle = "fontstyle"
    cvtWhiteSpace = "whitespace"
    cvtInteger = "integer"
    cvtTextDecoration = "textdecoration"
    cvtWordBreak = "wordbreak"
    cvtListStyleType = "liststyletype"
    cvtVerticalAlign = "verticalalign"
    cvtTextAlign = "textalign"
    cvtListStylePosition = "liststyleposition"
    cvtPosition = "position"
    cvtCaptionSide = "captionside"
    cvtLength2 = "length2"
    cvtBorderCollapse = "bordercollapse"
    cvtQuotes = "quotes"
    cvtCounterReset = "counterreset"
    cvtImage = "image"
    cvtFloat = "float"
    cvtVisibility = "visibility"
    cvtBoxSizing = "boxsizing"
    cvtClear = "clear"
    cvtTextTransform = "texttransform"
    cvtBgcolorIsCanvas = "bgcoloriscanvas"

  CSSGlobalValueType* = enum
    cvtNoglobal, cvtInitial, cvtInherit, cvtRevert, cvtUnset

  CSSDisplay* = enum
    DISPLAY_NONE, DISPLAY_INLINE, DISPLAY_BLOCK, DISPLAY_LIST_ITEM,
    DISPLAY_INLINE_BLOCK, DISPLAY_TABLE, DISPLAY_INLINE_TABLE,
    DISPLAY_TABLE_ROW_GROUP, DISPLAY_TABLE_HEADER_GROUP,
    DISPLAY_TABLE_FOOTER_GROUP, DISPLAY_TABLE_COLUMN_GROUP, DISPLAY_TABLE_ROW,
    DISPLAY_TABLE_COLUMN, DISPLAY_TABLE_CELL, DISPLAY_TABLE_CAPTION,
    DISPLAY_FLOW_ROOT

  CSSWhitespace* = enum
    WHITESPACE_NORMAL, WHITESPACE_NOWRAP, WHITESPACE_PRE, WHITESPACE_PRE_LINE,
    WHITESPACE_PRE_WRAP

  CSSFontStyle* = enum
    FONT_STYLE_NORMAL, FONT_STYLE_ITALIC, FONT_STYLE_OBLIQUE

  CSSPosition* = enum
    POSITION_STATIC, POSITION_RELATIVE, POSITION_ABSOLUTE, POSITION_FIXED,
    POSITION_STICKY

  CSSTextDecoration* = enum
    TEXT_DECORATION_NONE, TEXT_DECORATION_UNDERLINE, TEXT_DECORATION_OVERLINE,
    TEXT_DECORATION_LINE_THROUGH, TEXT_DECORATION_BLINK

  CSSWordBreak* = enum
    WORD_BREAK_NORMAL, WORD_BREAK_BREAK_ALL, WORD_BREAK_KEEP_ALL

  CSSListStyleType* = enum
    LIST_STYLE_TYPE_NONE, LIST_STYLE_TYPE_DISC, LIST_STYLE_TYPE_CIRCLE,
    LIST_STYLE_TYPE_SQUARE, LIST_STYLE_TYPE_DECIMAL,
    LIST_STYLE_TYPE_DISCLOSURE_CLOSED, LIST_STYLE_TYPE_DISCLOSURE_OPEN,
    LIST_STYLE_TYPE_CJK_EARTHLY_BRANCH, LIST_STYLE_TYPE_CJK_HEAVENLY_STEM,
    LIST_STYLE_TYPE_LOWER_ROMAN, LIST_STYLE_TYPE_UPPER_ROMAN,
    LIST_STYLE_TYPE_LOWER_ALPHA, LIST_STYLE_TYPE_UPPER_ALPHA,
    LIST_STYLE_TYPE_LOWER_GREEK,
    LIST_STYLE_TYPE_HIRAGANA, LIST_STYLE_TYPE_HIRAGANA_IROHA,
    LIST_STYLE_TYPE_KATAKANA, LIST_STYLE_TYPE_KATAKANA_IROHA,
    LIST_STYLE_TYPE_JAPANESE_INFORMAL

  CSSVerticalAlign2* = enum
    VERTICAL_ALIGN_BASELINE, VERTICAL_ALIGN_SUB, VERTICAL_ALIGN_SUPER,
    VERTICAL_ALIGN_TEXT_TOP, VERTICAL_ALIGN_TEXT_BOTTOM, VERTICAL_ALIGN_MIDDLE,
    VERTICAL_ALIGN_TOP, VERTICAL_ALIGN_BOTTOM

  CSSTextAlign* = enum
    TEXT_ALIGN_START, TEXT_ALIGN_END, TEXT_ALIGN_LEFT, TEXT_ALIGN_RIGHT,
    TEXT_ALIGN_CENTER, TEXT_ALIGN_JUSTIFY, TEXT_ALIGN_CHA_CENTER,
    TEXT_ALIGN_CHA_LEFT, TEXT_ALIGN_CHA_RIGHT

  CSSListStylePosition* = enum
    LIST_STYLE_POSITION_OUTSIDE, LIST_STYLE_POSITION_INSIDE

  CSSCaptionSide* = enum
    CAPTION_SIDE_TOP, CAPTION_SIDE_BOTTOM, CAPTION_SIDE_BLOCK_START,
    CAPTION_SIDE_BLOCK_END,

  CSSBorderCollapse* = enum
    BORDER_COLLAPSE_SEPARATE, BORDER_COLLAPSE_COLLAPSE

  CSSContentType* = enum
    CONTENT_STRING, CONTENT_OPEN_QUOTE, CONTENT_CLOSE_QUOTE,
    CONTENT_NO_OPEN_QUOTE, CONTENT_NO_CLOSE_QUOTE, CONTENT_IMAGE,
    CONTENT_VIDEO, CONTENT_AUDIO, CONTENT_NEWLINE

  CSSFloat* = enum
    FLOAT_NONE, FLOAT_LEFT, FLOAT_RIGHT

  CSSVisibility* = enum
    VISIBILITY_VISIBLE, VISIBILITY_HIDDEN, VISIBILITY_COLLAPSE

  CSSBoxSizing* = enum
    BOX_SIZING_CONTENT_BOX, BOX_SIZING_BORDER_BOX

  CSSClear* = enum
    CLEAR_NONE, CLEAR_LEFT, CLEAR_RIGHT, CLEAR_BOTH, CLEAR_INLINE_START,
    CLEAR_INLINE_END

  CSSTextTransform* = enum
    TEXT_TRANSFORM_NONE, TEXT_TRANSFORM_CAPITALIZE, TEXT_TRANSFORM_UPPERCASE,
    TEXT_TRANSFORM_LOWERCASE, TEXT_TRANSFORM_FULL_WIDTH,
    TEXT_TRANSFORM_FULL_SIZE_KANA, TEXT_TRANSFORM_CHA_HALF_WIDTH

const RowGroupBox* = {DISPLAY_TABLE_ROW_GROUP, DISPLAY_TABLE_HEADER_GROUP,
                      DISPLAY_TABLE_FOOTER_GROUP}
const ProperTableChild* = {DISPLAY_TABLE_ROW, DISPLAY_TABLE_COLUMN,
                           DISPLAY_TABLE_COLUMN_GROUP, DISPLAY_TABLE_CAPTION} +
                           RowGroupBox
const ProperTableRowParent* = {DISPLAY_TABLE, DISPLAY_INLINE_TABLE} + RowGroupBox
const InternalTableBox* = {DISPLAY_TABLE_CELL, DISPLAY_TABLE_ROW,
                           DISPLAY_TABLE_COLUMN, DISPLAY_TABLE_COLUMN_GROUP} +
                           RowGroupBox
const TabularContainer* = {DISPLAY_TABLE_ROW} + ProperTableRowParent

type
  CSSLength* = object
    num*: float64
    unit*: CSSUnit
    auto*: bool

  CSSVerticalAlign* = object
    length*: CSSLength
    keyword*: CSSVerticalAlign2

  CSSContent* = object
    t*: CSSContentType
    s*: string
    bmp*: Bitmap

  CSSQuotes* = object
    auto*: bool
    qs*: seq[tuple[s, e: string]]

  CSSCounterReset* = object
    name*: string
    num*: int

  CSSComputedValue* = ref object
    case v*: CSSValueType
    of cvtColor:
      color*: CellColor
    of cvtLength:
      length*: CSSLength
    of cvtFontStyle:
      fontstyle*: CSSFontStyle
    of cvtDisplay:
      display*: CSSDisplay
    of cvtContent:
      content*: seq[CSSContent]
    of cvtQuotes:
      quotes*: CSSQuotes
    of cvtWhiteSpace:
      whitespace*: CSSWhitespace
    of cvtInteger:
      integer*: int
    of cvtTextDecoration:
      textdecoration*: set[CSSTextDecoration]
    of cvtWordBreak:
      wordbreak*: CSSWordBreak
    of cvtListStyleType:
      liststyletype*: CSSListStyleType
    of cvtVerticalAlign:
      verticalalign*: CSSVerticalAlign
    of cvtTextAlign:
      textalign*: CSSTextAlign
    of cvtListStylePosition:
      liststyleposition*: CSSListStylePosition
    of cvtPosition:
      position*: CSSPosition
    of cvtCaptionSide:
      captionside*: CSSCaptionSide
    of cvtLength2:
      length2*: tuple[a, b: CSSLength]
    of cvtBorderCollapse:
      bordercollapse*: CSSBorderCollapse
    of cvtCounterReset:
      counterreset*: seq[CSSCounterReset]
    of cvtImage:
      image*: CSSContent
    of cvtFloat:
      float*: CSSFloat
    of cvtVisibility:
      visibility*: CSSVisibility
    of cvtBoxSizing:
      boxsizing*: CSSBoxSizing
    of cvtClear:
      clear*: CSSClear
    of cvtTextTransform:
      texttransform*: CSSTextTransform
    of cvtBgcolorIsCanvas:
      bgcoloriscanvas*: bool
    of cvtNone: discard

  CSSComputedValues* = ref array[CSSPropertyType, CSSComputedValue]

  CSSOrigin* = enum
    ORIGIN_USER_AGENT
    ORIGIN_USER
    ORIGIN_AUTHOR

  CSSComputedEntry = tuple
    t: CSSPropertyType
    val: CSSComputedValue
    global: CSSGlobalValueType

  CSSComputedEntries = seq[CSSComputedEntry]

  CSSComputedValuesBuilder* = object
    parent*: CSSComputedValues
    normalProperties: array[CSSOrigin, CSSComputedEntries]
    importantProperties: array[CSSOrigin, CSSComputedEntries]
    preshints*: CSSComputedValues

const ShorthandNames = {
  "all": cstAll,
  "margin": cstMargin,
  "padding": cstPadding,
  "background": cstBackground,
  "list-style": cstListStyle
}.toTable()

const PropertyNames = block:
  var tab = initTable[string, CSSPropertyType]()
  for t in CSSPropertyType:
    if $t != "":
      tab[$t] = t
  tab

const ValueTypes* = [
  cptNone: cvtNone,
  cptColor: cvtColor,
  cptMarginTop: cvtLength,
  cptMarginLeft: cvtLength,
  cptMarginRight: cvtLength,
  cptMarginBottom: cvtLength,
  cptFontStyle: cvtFontStyle,
  cptDisplay: cvtDisplay,
  cptContent: cvtContent,
  cptWhiteSpace: cvtWhiteSpace,
  cptFontWeight: cvtInteger,
  cptTextDecoration: cvtTextDecoration,
  cptWordBreak: cvtWordBreak,
  cptWidth: cvtLength,
  cptHeight: cvtLength,
  cptListStyleType: cvtListStyleType,
  cptPaddingTop: cvtLength,
  cptPaddingLeft: cvtLength,
  cptPaddingRight: cvtLength,
  cptPaddingBottom: cvtLength,
  cptWordSpacing: cvtLength,
  cptVerticalAlign: cvtVerticalAlign,
  cptLineHeight: cvtLength,
  cptTextAlign: cvtTextAlign,
  cptListStylePosition: cvtListStylePosition,
  cptBackgroundColor: cvtColor,
  cptPosition: cvtPosition,
  cptLeft: cvtLength,
  cptRight: cvtLength,
  cptTop: cvtLength,
  cptBottom: cvtLength,
  cptCaptionSide: cvtCaptionSide,
  cptBorderSpacing: cvtLength2,
  cptBorderCollapse: cvtBorderCollapse,
  cptQuotes: cvtQuotes,
  cptCounterReset: cvtCounterReset,
  cptMaxWidth: cvtLength,
  cptMaxHeight: cvtLength,
  cptMinWidth: cvtLength,
  cptMinHeight: cvtLength,
  cptBackgroundImage: cvtImage,
  cptChaColspan: cvtInteger,
  cptChaRowspan: cvtInteger,
  cptFloat: cvtFloat,
  cptVisibility: cvtVisibility,
  cptBoxSizing: cvtBoxSizing,
  cptClear: cvtClear,
  cptTextTransform: cvtTextTransform,
  cptBgcolorIsCanvas: cvtBgcolorIsCanvas
]

const InheritedProperties = {
  cptColor, cptFontStyle, cptWhiteSpace, cptFontWeight, cptTextDecoration,
  cptWordBreak, cptListStyleType, cptWordSpacing, cptLineHeight, cptTextAlign,
  cptListStylePosition, cptCaptionSide, cptBorderSpacing, cptBorderCollapse,
  cptQuotes, cptVisibility, cptTextTransform
}

func getPropInheritedArray(): array[CSSPropertyType, bool] =
  for prop in CSSPropertyType:
    if prop in InheritedProperties:
      result[prop] = true
    else:
      result[prop] = false

const InheritedArray = getPropInheritedArray()

func shorthandType(s: string): CSSShorthandType =
  return ShorthandNames.getOrDefault(s.toLowerAscii(), cstNone)

func propertyType(s: string): CSSPropertyType =
  return PropertyNames.getOrDefault(s.toLowerAscii(), cptNone)

func valueType(prop: CSSPropertyType): CSSValueType =
  return ValueTypes[prop]

func isSupportedProperty*(s: string): bool =
  return s in PropertyNames

func `$`*(length: CSSLength): string =
  if length.auto:
    return "auto"
  let ss = ($length.unit).split('_')
  let us = ss.toOpenArray(1, ss.high).join('_').toLowerAscii()
  return $length.num & us

func `$`*(content: CSSContent): string =
  if content.s != "":
    return "url(" & content.s & ")"
  return "none"

func `$`*(val: CSSComputedValue): string =
  case val.v
  of cvtColor:
    result &= $val.color
  of cvtImage:
    result &= $val.image
  of cvtLength:
    result &= $val.length
  else:
    result = $val.v

macro `{}`*(vals: CSSComputedValues; s: static string): untyped =
  let t = propertyType(s)
  let vs = ident($valueType(t))
  return quote do:
    `vals`[CSSPropertyType(`t`)].`vs`

macro `{}=`*(vals: CSSComputedValues, s: static string, val: typed) =
  let t = propertyType(s)
  let v = valueType(t)
  let vs = ident($v)
  return quote do:
    `vals`[CSSPropertyType(`t`)] = CSSComputedValue(
      v: CSSValueType(`v`),
      `vs`: `val`
    )

func inherited(t: CSSPropertyType): bool =
  return InheritedArray[t]

func em_to_px(em: float64, window: WindowAttributes): LayoutUnit =
  em * float64(window.ppl)

func ch_to_px(ch: float64, window: WindowAttributes): LayoutUnit =
  ch * float64(window.ppc)

# 水 width, we assume it's 2 chars
func ic_to_px(ic: float64, window: WindowAttributes): LayoutUnit =
  ic * float64(window.ppc) * 2

# x-letter height, we assume it's em/2
func ex_to_px(ex: float64, window: WindowAttributes): LayoutUnit =
  ex * float64(window.ppc) / 2

func px*(l: CSSLength, window: WindowAttributes, p: LayoutUnit): LayoutUnit
    {.inline.} =
  case l.unit
  of UNIT_EM, UNIT_REM: em_to_px(l.num, window)
  of UNIT_CH: ch_to_px(l.num, window)
  of UNIT_IC: ic_to_px(l.num, window)
  of UNIT_EX: ex_to_px(l.num, window)
  of UNIT_PERC: toLayoutUnit(toFloat64(p) * l.num / 100)
  of UNIT_PX: toLayoutUnit(l.num)
  of UNIT_CM: toLayoutUnit(l.num * 37.8)
  of UNIT_MM: toLayoutUnit(l.num * 3.78)
  of UNIT_IN: toLayoutUnit(l.num * 96)
  of UNIT_PC: toLayoutUnit(l.num * 16)
  of UNIT_PT: toLayoutUnit(l.num * 4 / 3)
  of UNIT_VW: toLayoutUnit(float64(window.width_px) * l.num / 100)
  of UNIT_VH: toLayoutUnit(float64(window.height_px) * l.num / 100)
  of UNIT_VMIN:
    toLayoutUnit(min(window.width_px, window.width_px) / 100 * l.num)
  of UNIT_VMAX:
    toLayoutUnit(max(window.width_px, window.width_px) / 100 * l.num)

const UpperAlphaMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toRunes()
const LowerAlphaMap = "abcdefghijklmnopqrstuvwxyz".toRunes()
const LowerGreekMap = "αβγδεζηθικλμνξοπρστυφχψω".toRunes()
const HiraganaMap = ("あいうえおかきくけこさしすせそたちつてとなにぬねの" &
  "はひふへほまみむめもやゆよらりるれろわゐゑをん").toRunes()
const HiraganaIrohaMap = ("いろはにほへとちりぬるをわかよたれそつねならむ" &
  "うゐのおくやまけふこえてあさきゆめみしゑひもせす").toRunes()
const KatakanaMap = ("アイウエオカキクケコサシスセソタチツテトナニヌネノ" &
  "ハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン").toRunes()
const KatakanaIrohaMap = ("イロハニホヘトチリヌルヲワカヨタレソツネナラム" &
  "ウヰノオクヤマケフコエテアサキユメミシヱヒモセス").toRunes()
const EarthlyBranchMap = "子丑寅卯辰巳午未申酉戌亥".toRunes()
const HeavenlyStemMap = "甲乙丙丁戊己庚辛壬癸".toRunes()

func numToBase(n: int, map: openArray[Rune]): string =
  if n <= 0:
    return $n
  var tmp: seq[Rune]
  var n = n
  while n != 0:
    n -= 1
    tmp &= map[n mod map.len]
    n = n div map.len
  result = ""
  for i in countdown(tmp.high, 0):
    result &= $tmp[i]

func numToFixed(n: int, map: openArray[Rune]): string =
  let n = n - 1
  if n notin 0 .. map.high:
    return $n
  return $map[n]

func listMarker*(t: CSSListStyleType, i: int): string =
  case t
  of LIST_STYLE_TYPE_NONE: return ""
  of LIST_STYLE_TYPE_DISC: return "• " # U+2022
  of LIST_STYLE_TYPE_CIRCLE: return "○ " # U+25CB
  of LIST_STYLE_TYPE_SQUARE: return "□ " # U+25A1
  of LIST_STYLE_TYPE_DISCLOSURE_OPEN: return "▶ " # U+25B6
  of LIST_STYLE_TYPE_DISCLOSURE_CLOSED: return "▼ " # U+25BC
  of LIST_STYLE_TYPE_DECIMAL: return $i & ". "
  of LIST_STYLE_TYPE_UPPER_ROMAN: return romanNumber(i) & ". "
  of LIST_STYLE_TYPE_LOWER_ROMAN: return romanNumberLower(i) & ". "
  of LIST_STYLE_TYPE_UPPER_ALPHA: return numToBase(i, UpperAlphaMap) & ". "
  of LIST_STYLE_TYPE_LOWER_ALPHA: return numToBase(i, LowerAlphaMap) & ". "
  of LIST_STYLE_TYPE_LOWER_GREEK: return numToBase(i, LowerGreekMap) & ". "
  of LIST_STYLE_TYPE_HIRAGANA: return numToBase(i, HiraganaMap) & "、"
  of LIST_STYLE_TYPE_HIRAGANA_IROHA:
    return numToBase(i, HiraganaIrohaMap) & "、"
  of LIST_STYLE_TYPE_KATAKANA: return numToBase(i, KatakanaMap) & "、"
  of LIST_STYLE_TYPE_KATAKANA_IROHA:
    return numToBase(i, KatakanaIrohaMap) & "、"
  of LIST_STYLE_TYPE_CJK_EARTHLY_BRANCH:
    return numToFixed(i, EarthlyBranchMap) & "、"
  of LIST_STYLE_TYPE_CJK_HEAVENLY_STEM:
    return numToFixed(i, HeavenlyStemMap) & "、"
  of LIST_STYLE_TYPE_JAPANESE_INFORMAL: return japaneseNumber(i) & "、"

#TODO this should change by language
func quoteStart*(level: int): string =
  if level == 0:
    return "“"
  return "‘"

func quoteEnd*(level: int): string =
  if level == 0:
    return "“"
  return "‘"

const Colors: Table[string, RGBAColor] = ((func (): Table[string, RGBAColor] =
  for name, rgb in ColorsRGB:
    result[name] = rgb
  result["transparent"] = rgba(0x00, 0x00, 0x00, 0x00)
)())

const Units = {
  "%": UNIT_PERC,
  "cm": UNIT_CM,
  "mm": UNIT_MM,
  "in": UNIT_IN,
  "px": UNIT_PX,
  "pt": UNIT_PT,
  "pc": UNIT_PC,
  "em": UNIT_EM,
  "ex": UNIT_EX,
  "ch": UNIT_CH,
  "ic": UNIT_CH,
  "rem": UNIT_REM,
  "vw": UNIT_VW,
  "vh": UNIT_VH,
  "vmin": UNIT_VMIN,
  "vmax": UNIT_VMAX,
}.toTable()

func cssLength(val: float64, unit: string): Opt[CSSLength] =
  if unit in Units:
    return ok(CSSLength(num: val, unit: Units[unit]))
  return err()

const CSSLengthAuto* = CSSLength(auto: true)

func parseDimensionValues*(s: string): Option[CSSLength] =
  if s == "": return
  var i = 0
  while s[i] in AsciiWhitespace: inc i
  if i >= s.len or s[i] notin AsciiDigit: return
  var n: float64
  while s[i] in AsciiDigit:
    n *= 10
    n += float64(decValue(s[i]))
    inc i
    if i >= s.len: return some(CSSLength(num: n, unit: UNIT_PX))
  if s[i] == '.':
    inc i
    if i >= s.len: return some(CSSLength(num: n, unit: UNIT_PX))
    var d = 1
    while i < s.len and s[i] in AsciiDigit:
      n += float64(decValue(s[i])) / float64(d)
      inc d
      inc i
  if i >= s.len: return some(CSSLength(num: n, unit: UNIT_PX))
  if s[i] == '%': return some(CSSLength(num: n, unit: UNIT_PERC))
  return some(CSSLength(num: n, unit: UNIT_PX))

func skipWhitespace(vals: openArray[CSSComponentValue], i: var int) =
  while i < vals.len:
    if vals[i] != CSS_WHITESPACE_TOKEN:
      break
    inc i

func parseRGBA(value: openArray[CSSComponentValue]): Opt[CellColor] =
  var i = 0
  var commaMode = false
  template check_err(slash: bool) =
    #TODO calc, percentages, etc (cssnumber function or something)
    if not slash and i >= value.len or i < value.len and
        value[i] != CSS_NUMBER_TOKEN:
      return err()
  template next_value(first = false, slash = false) =
    inc i
    value.skipWhitespace(i)
    if i < value.len:
      if value[i] == CSS_COMMA_TOKEN and (commaMode or first):
        # legacy compatibility
        inc i
        value.skipWhitespace(i)
        commaMode = true
      elif commaMode:
        return err()
      elif slash:
        let tok = value[i]
        if tok != CSS_DELIM_TOKEN or CSSToken(tok).cvalue != '/':
          return err()
        inc i
        value.skipWhitespace(i)
    check_err slash
  value.skipWhitespace(i)
  check_err false
  let r = CSSToken(value[i]).nvalue
  next_value true
  let g = CSSToken(value[i]).nvalue
  next_value
  let b = CSSToken(value[i]).nvalue
  next_value false, true
  let a = if i < value.len:
    CSSToken(value[i]).nvalue
  else:
    1
  value.skipWhitespace(i)
  if i < value.len:
    return err()
  return ok(rgba(int(r), int(g), int(b), int(a * 255)).cellColor())

# syntax: -cha-ansi( number | ident )
# where number is an ANSI color (0..255)
# and ident is in NameTable and may start with "bright-"
func parseANSI(value: openArray[CSSComponentValue]): Opt[CellColor] =
  var i = 0
  value.skipWhitespace(i)
  if i != value.high or not (value[i] of CSSToken): # only 1 param is valid
    #TODO numeric functions
    return err()
  let tok = CSSToken(value[i])
  if tok.tokenType == CSS_NUMBER_TOKEN:
    if tok.nvalue notin 0..255:
      return err() # invalid numeric ANSI color
    return ok(ANSIColor(tok.nvalue).cellColor())
  elif tok.tokenType == CSS_IDENT_TOKEN:
    var name = tok.value
    if name.equalsIgnoreCase("default"):
      return ok(defaultColor)
    var bright = false
    if name.startsWithIgnoreCase("bright-"):
      bright = true
      name = name.substr("bright-".len)
    const NameTable = [
      "black",
      "red",
      "green",
      "yellow",
      "blue",
      "magenta",
      "cyan",
      "white"
    ]
    for i, it in NameTable:
      if it.equalsIgnoreCase(name):
        var i = int(i)
        if bright:
          i += 8
        return ok(ANSIColor(i).cellColor())
  return err()

func cssColor*(val: CSSComponentValue): Opt[CellColor] =
  if val of CSSToken:
    let tok = CSSToken(val)
    case tok.tokenType
    of CSS_HASH_TOKEN:
      let c = parseHexColor(tok.value)
      if c.isSome:
        return ok(c.get.cellColor())
    of CSS_IDENT_TOKEN:
      let s = tok.value.toLowerAscii()
      if s in Colors:
        return ok(Colors[s].cellColor())
    else: discard
  elif val of CSSFunction:
    let f = CSSFunction(val)
    if f.name.equalsIgnoreCase("rgb") or f.name.equalsIgnoreCase("rgba"):
      return parseRGBA(f.value)
    elif f.name.equalsIgnoreCase("-cha-ansi"):
      return parseANSI(f.value)
  return err()

func isToken(cval: CSSComponentValue): bool {.inline.} = cval of CSSToken

func getToken(cval: CSSComponentValue): CSSToken = (CSSToken)cval

func cssIdent[T](map: static openArray[(string, T)], cval: CSSComponentValue):
    Opt[T] =
  if isToken(cval):
    let tok = getToken(cval)
    if tok.tokenType == CSS_IDENT_TOKEN:
      # cmp when len is small enough, otherwise lowercase & hashmap
      when map.len <= 4:
        for (k, v) in map:
          if k.equalsIgnoreCase(tok.value):
            return ok(v)
      else:
        const MapTable = map.toTable()
        let val = tok.value.toLowerAscii()
        if val in MapTable:
          return ok(MapTable[val])
  return err()

func cssIdentFirst[T](map: static openArray[(string, T)], d: CSSDeclaration):
    Opt[T] =
  if d.value.len == 1:
    return cssIdent(map, d.value[0])
  return err()

func cssLength*(val: CSSComponentValue, has_auto: static bool = true,
    allow_negative: static bool = true): Opt[CSSLength] =
  block nofail:
    if val of CSSToken:
      let tok = CSSToken(val)
      case tok.tokenType
      of CSS_NUMBER_TOKEN:
        if tok.nvalue == 0:
          return ok(CSSLength(num: 0, unit: UNIT_PX))
      of CSS_PERCENTAGE_TOKEN:
        when not allow_negative:
          if tok.nvalue < 0:
            break nofail
        return cssLength(tok.nvalue, "%")
      of CSS_DIMENSION_TOKEN:
        when not allow_negative:
          if tok.nvalue < 0:
            break nofail
        return cssLength(tok.nvalue, tok.unit)
      of CSS_IDENT_TOKEN:
        when has_auto:
          if tok.value.equalsIgnoreCase("auto"):
            return ok(CSSLengthAuto)
      else: discard
  return err()

func cssAbsoluteLength(val: CSSComponentValue): Opt[CSSLength] =
  if val of CSSToken:
    let tok = CSSToken(val)
    case tok.tokenType
    of CSS_NUMBER_TOKEN:
      if tok.nvalue == 0:
        return ok(CSSLength(num: 0, unit: UNIT_PX))
    of CSS_DIMENSION_TOKEN:
      if tok.nvalue >= 0:
        return cssLength(tok.nvalue, tok.unit)
    else: discard
  return err()

func cssWordSpacing(cval: CSSComponentValue): Opt[CSSLength] =
  if cval of CSSToken:
    let tok = CSSToken(cval)
    case tok.tokenType
    of CSS_DIMENSION_TOKEN:
      return cssLength(tok.nvalue, tok.unit)
    of CSS_IDENT_TOKEN:
      if tok.value.equalsIgnoreCase("normal"):
        return ok(CSSLengthAuto)
    else: discard
  return err()

func cssGlobal(d: CSSDeclaration): CSSGlobalValueType =
  const GlobalMap = {
    "inherit": cvtInherit,
    "initial": cvtInitial,
    "unset": cvtUnset,
    "revert": cvtRevert
  }
  return cssIdentFirst(GlobalMap, d).get(cvtNoglobal)

func cssQuotes(d: CSSDeclaration): Opt[CSSQuotes] =
  template die =
    return err()
  if d.value.len == 0:
    die
  var res: CSSQuotes
  var sa = false
  var pair: tuple[s, e: string]
  for cval in d.value:
    if res.auto: die
    if isToken(cval):
      let tok = getToken(cval)
      case tok.tokenType
      of CSS_IDENT_TOKEN:
        if res.qs.len > 0: die
        if tok.value.equalsIgnoreCase("auto"):
          res.auto = true
        elif tok.value.equalsIgnoreCase("none"):
          if d.value.len != 1:
            die
        die
      of CSS_STRING_TOKEN:
        if sa:
          pair.e = tok.value
          res.qs.add(pair)
          sa = false
        else:
          pair.s = tok.value
          sa = true
      of CSS_WHITESPACE_TOKEN: discard
      else: die
  if sa:
    die
  return ok(res)

func cssContent(d: CSSDeclaration): seq[CSSContent] =
  for cval in d.value:
    if isToken(cval):
      let tok = getToken(cval)
      case tok.tokenType
      of CSS_IDENT_TOKEN:
        if tok.value == "/":
          break
        elif tok.value.equalsIgnoreCase("open-quote"):
          result.add(CSSContent(t: CONTENT_OPEN_QUOTE))
        elif tok.value.equalsIgnoreCase("no-open-quote"):
          result.add(CSSContent(t: CONTENT_NO_OPEN_QUOTE))
        elif tok.value.equalsIgnoreCase("close-quote"):
          result.add(CSSContent(t: CONTENT_CLOSE_QUOTE))
        elif tok.value.equalsIgnoreCase("no-close-quote"):
          result.add(CSSContent(t: CONTENT_NO_CLOSE_QUOTE))
      of CSS_STRING_TOKEN:
        result.add(CSSContent(t: CONTENT_STRING, s: tok.value))
      else: return

func cssDisplay(cval: CSSComponentValue): Opt[CSSDisplay] =
  const DisplayMap = {
    "block": DISPLAY_BLOCK,
    "inline": DISPLAY_INLINE,
    "list-item": DISPLAY_LIST_ITEM,
    "inline-block": DISPLAY_INLINE_BLOCK,
    "table": DISPLAY_TABLE,
    "table-row": DISPLAY_TABLE_ROW,
    "table-cell": DISPLAY_TABLE_CELL,
    "table-column": DISPLAY_TABLE_COLUMN,
    "table-column-group": DISPLAY_TABLE_COLUMN_GROUP,
    "inline-table": DISPLAY_INLINE_TABLE,
    "table-row-group": DISPLAY_TABLE_ROW_GROUP,
    "table-header-group": DISPLAY_TABLE_HEADER_GROUP,
    "table-footer-group": DISPLAY_TABLE_FOOTER_GROUP,
    "table-caption": DISPLAY_TABLE_CAPTION,
    "flow-root": DISPLAY_FLOW_ROOT,
    "none": DISPLAY_NONE
  }
  return cssIdent(DisplayMap, cval)

func cssFontStyle(cval: CSSComponentValue): Opt[CSSFontStyle] =
  const FontStyleMap = {
    "normal": FONT_STYLE_NORMAL,
    "italic": FONT_STYLE_ITALIC,
    "oblique": FONT_STYLE_OBLIQUE
  }
  return cssIdent(FontStyleMap, cval)

func cssWhiteSpace(cval: CSSComponentValue): Opt[CSSWhitespace] =
  const WhiteSpaceMap = {
    "normal": WHITESPACE_NORMAL,
    "nowrap": WHITESPACE_NOWRAP,
    "pre": WHITESPACE_PRE,
    "pre-line": WHITESPACE_PRE_LINE,
    "pre-wrap": WHITESPACE_PRE_WRAP
  }
  return cssIdent(WhiteSpaceMap, cval)

func cssFontWeight(cval: CSSComponentValue): Opt[int] =
  if isToken(cval):
    let tok = getToken(cval)
    if tok.tokenType == CSS_IDENT_TOKEN:
      const FontWeightMap = {
        "normal": 400,
        "bold": 700,
        "lighter": 400,
        "bolder": 700
      }
      return cssIdent(FontWeightMap, cval)
    elif tok.tokenType == CSS_NUMBER_TOKEN:
      if tok.nvalue in 1f64..1000f64:
        return ok(int(tok.nvalue))
  return err()

func cssTextDecoration(d: CSSDeclaration): Opt[set[CSSTextDecoration]] =
  var s: set[CSSTextDecoration]
  for cval in d.value:
    if isToken(cval):
      let tok = getToken(cval)
      if tok.tokenType == CSS_IDENT_TOKEN:
        if tok.value.equalsIgnoreCase("none"):
          if d.value.len != 1:
            return err()
          return ok(s)
        elif tok.value.equalsIgnoreCase("underline"):
          s.incl(TEXT_DECORATION_UNDERLINE)
        elif tok.value.equalsIgnoreCase("overline"):
          s.incl(TEXT_DECORATION_OVERLINE)
        elif tok.value.equalsIgnoreCase("line-through"):
          s.incl(TEXT_DECORATION_LINE_THROUGH)
        elif tok.value.equalsIgnoreCase("blink"):
          s.incl(TEXT_DECORATION_BLINK)
        else:
          return err()
  return ok(s)

func cssWordBreak(cval: CSSComponentValue): Opt[CSSWordBreak] =
  const WordBreakMap = {
    "normal": WORD_BREAK_NORMAL,
    "break-all": WORD_BREAK_BREAK_ALL,
    "keep-all": WORD_BREAK_KEEP_ALL
  }
  return cssIdent(WordBreakMap, cval)

func cssListStyleType(cval: CSSComponentValue): Opt[CSSListStyleType] =
  const ListStyleMap = {
    "none": LIST_STYLE_TYPE_NONE,
    "disc": LIST_STYLE_TYPE_DISC,
    "circle": LIST_STYLE_TYPE_CIRCLE,
    "square": LIST_STYLE_TYPE_SQUARE,
    "decimal": LIST_STYLE_TYPE_DECIMAL,
    "disclosure-open": LIST_STYLE_TYPE_DISCLOSURE_OPEN,
    "disclosure-closed": LIST_STYLE_TYPE_DISCLOSURE_CLOSED,
    "cjk-earthly-branch": LIST_STYLE_TYPE_CJK_EARTHLY_BRANCH,
    "cjk-heavenly-stem": LIST_STYLE_TYPE_CJK_HEAVENLY_STEM,
    "upper-roman": LIST_STYLE_TYPE_UPPER_ROMAN,
    "lower-roman": LIST_STYLE_TYPE_LOWER_ROMAN,
    "upper-latin": LIST_STYLE_TYPE_UPPER_ALPHA,
    "lower-latin": LIST_STYLE_TYPE_LOWER_ALPHA,
    "upper-alpha": LIST_STYLE_TYPE_UPPER_ALPHA,
    "lower-alpha": LIST_STYLE_TYPE_UPPER_ALPHA,
    "lower-greek": LIST_STYLE_TYPE_LOWER_GREEK,
    "hiragana": LIST_STYLE_TYPE_HIRAGANA,
    "hiragana-iroha": LIST_STYLE_TYPE_HIRAGANA_IROHA,
    "katakana": LIST_STYLE_TYPE_KATAKANA,
    "katakana-iroha": LIST_STYLE_TYPE_KATAKANA_IROHA,
    "japanese-informal": LIST_STYLE_TYPE_JAPANESE_INFORMAL
  }
  return cssIdent(ListStyleMap, cval)

func cssVerticalAlign(cval: CSSComponentValue): Opt[CSSVerticalAlign] =
  if isToken(cval):
    let tok = getToken(cval)
    if tok.tokenType == CSS_IDENT_TOKEN:
      const VerticalAlignMap = {
        "baseline": VERTICAL_ALIGN_BASELINE,
        "sub": VERTICAL_ALIGN_SUB,
        "super": VERTICAL_ALIGN_SUPER,
        "text-top": VERTICAL_ALIGN_TEXT_BOTTOM,
        "middle": VERTICAL_ALIGN_MIDDLE,
        "top": VERTICAL_ALIGN_TOP,
        "bottom": VERTICAL_ALIGN_BOTTOM
      }
      let va2 = ?cssIdent(VerticalAlignMap, cval)
      return ok(CSSVerticalAlign(
        keyword: va2
      ))
    else:
      return ok(CSSVerticalAlign(
        keyword: VERTICAL_ALIGN_BASELINE,
        length: ?cssLength(tok, has_auto = false)
      ))
  return err()

func cssLineHeight(cval: CSSComponentValue): Opt[CSSLength] =
  if cval of CSSToken:
    let tok = CSSToken(cval)
    case tok.tokenType
    of CSS_NUMBER_TOKEN:
      return cssLength(tok.nvalue * 100, "%")
    of CSS_IDENT_TOKEN:
      if tok.value == "normal":
        return ok(CSSLengthAuto)
    else:
      return cssLength(tok, has_auto = false)
  return err()

func cssTextAlign(cval: CSSComponentValue): Opt[CSSTextAlign] =
  const TextAlignMap = {
    "start": TEXT_ALIGN_START,
    "end": TEXT_ALIGN_END,
    "left": TEXT_ALIGN_LEFT,
    "right": TEXT_ALIGN_RIGHT,
    "center": TEXT_ALIGN_CENTER,
    "justify": TEXT_ALIGN_JUSTIFY,
    "-cha-center": TEXT_ALIGN_CHA_CENTER
  }
  return cssIdent(TextAlignMap, cval)

func cssListStylePosition(cval: CSSComponentValue): Opt[CSSListStylePosition] =
  const ListStylePositionMap = {
    "inside": LIST_STYLE_POSITION_INSIDE,
    "outside": LIST_STYLE_POSITION_OUTSIDE
  }
  return cssIdent(ListStylePositionMap, cval)

func cssPosition(cval: CSSComponentValue): Opt[CSSPosition] =
  const PositionMap = {
    "static": POSITION_STATIC,
    "relative": POSITION_RELATIVE,
    "absolute": POSITION_ABSOLUTE,
    "fixed": POSITION_FIXED,
    "sticky": POSITION_STICKY
  }
  return cssIdent(PositionMap, cval)

func cssCaptionSide(cval: CSSComponentValue): Opt[CSSCaptionSide] =
  const CaptionSideMap = {
    "top": CAPTION_SIDE_TOP,
    "bottom": CAPTION_SIDE_BOTTOM,
    "block-start": CAPTION_SIDE_BLOCK_START,
    "block-end": CAPTION_SIDE_BLOCK_END,
  }
  return cssIdent(CaptionSideMap, cval)

func cssBorderCollapse(cval: CSSComponentValue): Opt[CSSBorderCollapse] =
  const BorderCollapseMap = {
    "collapse": BORDER_COLLAPSE_COLLAPSE,
    "separate": BORDER_COLLAPSE_SEPARATE
  }
  return cssIdent(BorderCollapseMap, cval)

func cssCounterReset(d: CSSDeclaration): Opt[seq[CSSCounterReset]] =
  template die =
    return err()
  var r: CSSCounterReset
  var s = false
  var res: seq[CSSCounterReset]
  for cval in d.value:
    if isToken(cval):
      let tok = getToken(cval)
      case tok.tokenType
      of CSS_WHITESPACE_TOKEN: discard
      of CSS_IDENT_TOKEN:
        if s:
          die
        r.name = tok.value
        s = true
      of CSS_NUMBER_TOKEN:
        if not s:
          die
        r.num = int(tok.nvalue)
        res.add(r)
        s = false
      else:
        die
  return ok(res)

func cssMaxMinSize(cval: CSSComponentValue): Opt[CSSLength] =
  if isToken(cval):
    let tok = getToken(cval)
    case tok.tokenType
    of CSS_IDENT_TOKEN:
      if tok.value.equalsIgnoreCase("none"):
        return ok(CSSLengthAuto)
    of CSS_NUMBER_TOKEN, CSS_DIMENSION_TOKEN, CSS_PERCENTAGE_TOKEN:
      return cssLength(tok, allow_negative = false)
    else: discard
  return err()

#TODO should be URL (parsed with baseurl of document...)
func cssURL(cval: CSSComponentValue): Option[string] =
  if isToken(cval):
    let tok = getToken(cval)
    if tok == CSS_URL_TOKEN:
      return some(tok.value)
  elif cval of CSSFunction:
    let fun = CSSFunction(cval)
    if fun.name.equalsIgnoreCase("url") or fun.name.equalsIgnoreCase("src"):
      for x in fun.value:
        if not isToken(x):
          break
        let x = getToken(x)
        if x == CSS_WHITESPACE_TOKEN:
          discard
        elif x == CSS_STRING_TOKEN:
          return some(x.value)
        else:
          break

#TODO this should be bg-image, add gradient, etc etc
func cssImage(cval: CSSComponentValue): Opt[CSSContent] =
  if isToken(cval):
    #TODO bg-image only
    let tok = getToken(cval)
    if tok.tokenType == CSS_IDENT_TOKEN and tok.value == "none":
      return ok(CSSContent(t: CONTENT_IMAGE, s: ""))
  let url = cssURL(cval)
  if url.isSome:
    return ok(CSSContent(t: CONTENT_IMAGE, s: url.get))
  return err()

func cssInteger(cval: CSSComponentValue, range: Slice[int]): Opt[int] =
  if isToken(cval):
    let tok = getToken(cval)
    if tok.tokenType == CSS_NUMBER_TOKEN:
      if tok.nvalue in float64(range.a)..float64(range.b):
        return ok(int(tok.nvalue))
  return err()

func cssFloat(cval: CSSComponentValue): Opt[CSSFloat] =
  const FloatMap = {
    "none": FLOAT_NONE,
    "left": FLOAT_LEFT,
    "right": FLOAT_RIGHT
  }
  return cssIdent(FloatMap, cval)

func cssVisibility(cval: CSSComponentValue): Opt[CSSVisibility] =
  const VisibilityMap = {
    "visible": VISIBILITY_VISIBLE,
    "hidden": VISIBILITY_HIDDEN,
    "collapse": VISIBILITY_COLLAPSE
  }
  return cssIdent(VisibilityMap, cval)

func cssBoxSizing(cval: CSSComponentValue): Opt[CSSBoxSizing] =
  const BoxSizingMap = {
    "border-box": BOX_SIZING_BORDER_BOX,
    "content-box": BOX_SIZING_CONTENT_BOX
  }
  return cssIdent(BoxSizingMap, cval)

func cssClear(cval: CSSComponentValue): Opt[CSSClear] =
  const ClearMap = {
    "none": CLEAR_NONE,
    "left": CLEAR_LEFT,
    "right": CLEAR_RIGHT,
    "both": CLEAR_BOTH,
    "inline-start": CLEAR_INLINE_START,
    "inline-end": CLEAR_INLINE_END
  }
  return cssIdent(ClearMap, cval)

func cssTextTransform(cval: CSSComponentValue): Opt[CSSTextTransform] =
  const TextTransformMap = {
    "none": TEXT_TRANSFORM_NONE,
    "capitalize": TEXT_TRANSFORM_CAPITALIZE,
    "uppercase": TEXT_TRANSFORM_UPPERCASE,
    "lowercase": TEXT_TRANSFORM_LOWERCASE,
    "full-width": TEXT_TRANSFORM_FULL_WIDTH,
    "full-size-kana": TEXT_TRANSFORM_FULL_SIZE_KANA,
    "-cha-half-width": TEXT_TRANSFORM_CHA_HALF_WIDTH
  }
  return cssIdent(TextTransformMap, cval)

proc getValueFromDecl(val: CSSComputedValue, d: CSSDeclaration,
    vtype: CSSValueType, ptype: CSSPropertyType): Err[void] =
  var i = 0
  d.value.skipWhitespace(i)
  if i >= d.value.len:
    return err()
  let cval = d.value[i]
  inc i
  case vtype
  of cvtColor:
    val.color = ?cssColor(cval)
  of cvtLength:
    case ptype
    of cptWordSpacing:
      val.length = ?cssWordSpacing(cval)
    of cptLineHeight:
      val.length = ?cssLineHeight(cval)
    of cptMaxWidth, cptMaxHeight, cptMinWidth,
       cptMinHeight:
      val.length = ?cssMaxMinSize(cval)
    of cptPaddingLeft, cptPaddingRight, cptPaddingTop,
       cptPaddingBottom:
      val.length = ?cssLength(cval, has_auto = false)
    else:
      val.length = ?cssLength(cval)
  of cvtFontStyle:
    val.fontstyle = ?cssFontStyle(cval)
  of cvtDisplay:
    val.display = ?cssDisplay(cval)
  of cvtContent:
    val.content = cssContent(d)
  of cvtWhiteSpace:
    val.whitespace = ?cssWhiteSpace(cval)
  of cvtInteger:
    if ptype == cptFontWeight:
      val.integer = ?cssFontWeight(cval)
    elif ptype == cptChaColspan:
      val.integer = ?cssInteger(cval, 1 .. 1000)
    elif ptype == cptChaRowspan:
      val.integer = ?cssInteger(cval, 0 .. 65534)
  of cvtTextDecoration:
    val.textdecoration = ?cssTextDecoration(d)
  of cvtWordBreak:
    val.wordbreak = ?cssWordBreak(cval)
  of cvtListStyleType:
    val.liststyletype = ?cssListStyleType(cval)
  of cvtVerticalAlign:
    val.verticalalign = ?cssVerticalAlign(cval)
  of cvtTextAlign:
    val.textalign = ?cssTextAlign(cval)
  of cvtListStylePosition:
    val.liststyleposition = ?cssListStylePosition(cval)
  of cvtPosition:
    val.position = ?cssPosition(cval)
  of cvtCaptionSide:
    val.captionside = ?cssCaptionSide(cval)
  of cvtBorderCollapse:
    val.bordercollapse = ?cssBorderCollapse(cval)
  of cvtLength2:
    val.length2.a = ?cssAbsoluteLength(cval)
    d.value.skipWhitespace(i)
    if i >= d.value.len:
      val.length2.b = val.length2.a
    else:
      let cval = d.value[i]
      val.length2.b = ?cssAbsoluteLength(cval)
  of cvtQuotes:
    val.quotes = ?cssQuotes(d)
  of cvtCounterReset:
    val.counterreset = ?cssCounterReset(d)
  of cvtImage:
    val.image = ?cssImage(cval)
  of cvtFloat:
    val.float = ?cssFloat(cval)
  of cvtVisibility:
    val.visibility = ?cssVisibility(cval)
  of cvtBoxSizing:
    val.boxsizing = ?cssBoxSizing(cval)
  of cvtClear:
    val.clear = ?cssClear(cval)
  of cvtTextTransform:
    val.texttransform = ?cssTextTransform(cval)
  of cvtBgcolorIsCanvas:
    return err() # internal value
  of cvtNone:
    discard
  return ok()

func getInitialColor(t: CSSPropertyType): CellColor =
  if t == cptBackgroundColor:
    return Colors["transparent"].cellColor()
  return defaultColor

func getInitialLength(t: CSSPropertyType): CSSLength =
  case t
  of cptWidth, cptHeight, cptWordSpacing,
     cptLineHeight, cptLeft, cptRight, cptTop,
     cptBottom, cptMaxWidth, cptMaxHeight,
     cptMinWidth, cptMinHeight:
    return CSSLengthAuto
  else:
    return CSSLength(auto: false, unit: UNIT_PX, num: 0)

func getInitialInteger(t: CSSPropertyType): int =
  case t
  of cptChaColspan, cptChaRowspan:
    return 1
  of cptFontWeight:
    return 400 # normal
  else:
    return 0

func calcInitial(t: CSSPropertyType): CSSComputedValue =
  let v = valueType(t)
  var nv: CSSComputedValue
  case v
  of cvtColor:
    nv = CSSComputedValue(v: v, color: getInitialColor(t))
  of cvtDisplay:
    nv = CSSComputedValue(v: v, display: DISPLAY_INLINE)
  of cvtWordBreak:
    nv = CSSComputedValue(v: v, wordbreak: WORD_BREAK_NORMAL)
  of cvtLength:
    nv = CSSComputedValue(v: v, length: getInitialLength(t))
  of cvtInteger:
    nv = CSSComputedValue(v: v, integer: getInitialInteger(t))
  of cvtQuotes:
    nv = CSSComputedValue(v: v, quotes: CSSQuotes(auto: true))
  else:
    nv = CSSComputedValue(v: v)
  return nv

func getInitialTable(): array[CSSPropertyType, CSSComputedValue] =
  for i in low(result)..high(result):
    result[i] = calcInitial(i)

let defaultTable = getInitialTable()

template getDefault(t: CSSPropertyType): CSSComputedValue =
  {.cast(noSideEffect).}:
    defaultTable[t]

func getComputedValue(d: CSSDeclaration, ptype: CSSPropertyType,
    vtype: CSSValueType): Opt[CSSComputedEntry] =
  let global = cssGlobal(d)
  let val = CSSComputedValue(v: vtype)
  if global != cvtNoglobal:
    return ok((ptype, val, global))
  ?val.getValueFromDecl(d, vtype, ptype)
  return ok((ptype, val, global))

func lengthShorthand(d: CSSDeclaration, props: array[4, CSSPropertyType]):
    Opt[seq[CSSComputedEntry]] =
  var i = 0
  var cvals: seq[CSSComponentValue]
  while i < d.value.len:
    if d.value[i] != CSS_WHITESPACE_TOKEN:
      cvals.add(d.value[i])
    inc i
  var res: seq[CSSComputedEntry]
  case cvals.len
  of 1: # top, bottom, left, right
    for ptype in props:
      let vtype = valueType(ptype)
      let val = CSSComputedValue(v: vtype)
      ?val.getValueFromDecl(d, vtype, ptype)
      res.add((ptype, val, cssGlobal(d)))
  of 2: # top, bottom | left, right
    for i in 0 ..< props.len:
      let ptype = props[i]
      let vtype = valueType(ptype)
      let val = CSSComputedValue(v: vtype)
      val.length = ?cssLength(cvals[i mod 2])
      res.add((ptype, val, cssGlobal(d)))
  of 3: # top | left, right | bottom
    for i in 0 ..< props.len:
      let ptype = props[i]
      let vtype = valueType(ptype)
      let val = CSSComputedValue(v: vtype)
      let j = if i == 0:
        0 # top
      elif i == 3:
        2 # bottom
      else:
        1 # left, right
      val.length = ?cssLength(cvals[j])
      res.add((ptype, val, cssGlobal(d)))
  of 4: # top | right | bottom | left
    for i in 0 ..< props.len:
      let ptype = props[i]
      let vtype = valueType(ptype)
      let val = CSSComputedValue(v: vtype)
      val.length = ?cssLength(cvals[i])
      res.add((ptype, val, cssGlobal(d)))
  else: discard
  return ok(res)

const PropertyMarginSpec = [
  cptMarginTop, cptMarginRight, cptMarginBottom,
  cptMarginLeft
]

const PropertyPaddingSpec = [
  cptPaddingTop, cptPaddingRight, cptPaddingBottom,
  cptPaddingLeft
]

proc getComputedValues0(res: var seq[CSSComputedEntry], d: CSSDeclaration):
    Err[void] =
  case shorthandType(d.name)
  of cstNone:
    let ptype = propertyType(d.name)
    let vtype = valueType(ptype)
    res.add(?getComputedValue(d, ptype, vtype))
  of cstAll:
    let global = cssGlobal(d)
    if global != cvtNoglobal:
      for ptype in CSSPropertyType:
        let vtype = valueType(ptype)
        let val = CSSComputedValue(v: vtype)
        res.add((ptype, val, global))
  of cstMargin:
    res.add(?lengthShorthand(d, PropertyMarginSpec))
  of cstPadding:
    res.add(?lengthShorthand(d, PropertyPaddingSpec))
  of cstBackground:
    let global = cssGlobal(d)
    var bgcolorval = getDefault(cptBackgroundColor)
    var bgimageval = getDefault(cptBackgroundImage)
    var valid = true
    if global == cvtNoglobal:
      for tok in d.value:
        if tok == CSS_WHITESPACE_TOKEN:
          continue
        if (let r = cssImage(tok); r.isOk):
          bgimageval = CSSComputedValue(v: cvtImage, image: r.get)
        elif (let r = cssColor(tok); r.isOk):
          bgcolorval = CSSComputedValue(v: cvtColor, color: r.get)
        else:
          #TODO when we implement the other shorthands too
          #valid = false
          discard
    if valid:
      res.add((cptBackgroundColor, bgcolorval, global))
      res.add((cptBackgroundImage, bgimageval, global))
  of cstListStyle:
    let global = cssGlobal(d)
    var positionVal = getDefault(cptListStylePosition)
    var typeVal = getDefault(cptListStyleType)
    var valid = true
    if global == cvtNoglobal:
      for tok in d.value:
        if (let r = cssListStylePosition(tok); r.isOk):
          positionVal = CSSComputedValue(
            v: cvtListStylePosition,
            liststyleposition: r.get
          )
        elif (let r = cssListStyleType(tok); r.isOk):
          typeVal = CSSComputedValue(
            v: cvtListStyleType,
            liststyletype: r.get
          )
        else:
          #TODO list-style-image
          #valid = false
          discard
    if valid:
      res.add((cptListStylePosition, positionVal, global))
      res.add((cptListStyleType, typeVal, global))
  return ok()

proc getComputedValues(d: CSSDeclaration): seq[CSSComputedEntry] =
  var res: seq[CSSComputedEntry] = @[]
  if res.getComputedValues0(d).isOk:
    return res
  return @[]

proc addValues*(builder: var CSSComputedValuesBuilder,
    decls: seq[CSSDeclaration], origin: CSSOrigin) =
  for decl in decls:
    if decl.important:
      builder.importantProperties[origin].add(getComputedValues(decl))
    else:
      builder.normalProperties[origin].add(getComputedValues(decl))

proc applyValue(vals: CSSComputedValues, prop: CSSPropertyType,
    val: CSSComputedValue, global: CSSGlobalValueType,
    parent: CSSComputedValues, previousOrigin: CSSComputedValues) =
  let parentVal = if parent != nil:
    parent[prop]
  else:
    nil
  case global
  of cvtInherit:
    if parentVal != nil:
      vals[prop] = parentVal
    else:
      vals[prop] = getDefault(prop)
  of cvtInitial:
    vals[prop] = getDefault(prop)
  of cvtUnset:
    if inherited(prop):
      # inherit
      if parentVal != nil:
        vals[prop] = parentVal
      else:
        vals[prop] = getDefault(prop)
    else:
      # initial
      vals[prop] = getDefault(prop)
  of cvtRevert:
    if previousOrigin != nil:
      vals[prop] = previousOrigin[prop]
    else:
      vals[prop] = getDefault(prop)
  of cvtNoglobal:
    vals[prop] = val

func inheritProperties*(parent: CSSComputedValues): CSSComputedValues =
  new(result)
  for prop in CSSPropertyType:
    if inherited(prop) and parent[prop] != nil:
      result[prop] = parent[prop]
    else:
      result[prop] = getDefault(prop)

func copyProperties*(props: CSSComputedValues): CSSComputedValues =
  new(result)
  result[] = props[]

func rootProperties*(): CSSComputedValues =
  new(result)
  for prop in CSSPropertyType:
    result[prop] = getDefault(prop)

func hasValues*(builder: CSSComputedValuesBuilder): bool =
  for origin in CSSOrigin:
    if builder.normalProperties[origin].len > 0:
      return true
    if builder.importantProperties[origin].len > 0:
      return true
  return false

func buildComputedValues*(builder: CSSComputedValuesBuilder):
    CSSComputedValues =
  new(result)
  var previousOrigins: array[CSSOrigin, CSSComputedValues]
  block:
    let origin = ORIGIN_USER_AGENT
    for build in builder.normalProperties[origin]:
      result.applyValue(build.t, build.val, build.global, builder.parent, nil)
    previousOrigins[origin] = result.copyProperties()
  # Presentational hints override user agent style, but respect user/author
  # style.
  if builder.preshints != nil:
    for prop in CSSPropertyType:
      if builder.preshints[prop] != nil:
        result[prop] = builder.preshints[prop]
  block:
    let origin = ORIGIN_USER
    let prevOrigin = ORIGIN_USER_AGENT
    for build in builder.normalProperties[origin]:
      result.applyValue(build.t, build.val, build.global, builder.parent,
        previousOrigins[prevOrigin])
    # save user origins so author can use them
    previousOrigins[origin] = result.copyProperties()
  block:
    let origin = ORIGIN_AUTHOR
    let prevOrigin = ORIGIN_USER
    for build in builder.normalProperties[origin]:
      result.applyValue(build.t, build.val, build.global, builder.parent,
        previousOrigins[prevOrigin])
    # no need to save user origins
  block:
    let origin = ORIGIN_AUTHOR
    let prevOrigin = ORIGIN_USER
    for build in builder.importantProperties[origin]:
      result.applyValue(build.t, build.val, build.global, builder.parent,
        previousOrigins[prevOrigin])
    # important, so no need to save origins
  block:
    let origin = ORIGIN_USER
    let prevOrigin = ORIGIN_USER_AGENT
    for build in builder.importantProperties[origin]:
      result.applyValue(build.t, build.val, build.global, builder.parent,
        previousOrigins[prevOrigin])
    # important, so no need to save origins
  block:
    let origin = ORIGIN_USER_AGENT
    for build in builder.importantProperties[origin]:
      result.applyValue(build.t, build.val, build.global, builder.parent, nil)
    # important, so no need to save origins
  # set defaults
  for prop in CSSPropertyType:
    if result[prop] == nil:
      if inherited(prop) and builder.parent != nil and
          builder.parent[prop] != nil:
        result[prop] = builder.parent[prop]
      else:
        result[prop] = getDefault(prop)
  if result{"float"} != FLOAT_NONE:
    case result{"display"}
    of DISPLAY_BLOCK, DISPLAY_TABLE, DISPLAY_LIST_ITEM, DISPLAY_NONE,
        DISPLAY_FLOW_ROOT:
       #TODO flex, grid
      discard
      {.linearScanEnd.}
    of DISPLAY_INLINE, DISPLAY_INLINE_BLOCK, DISPLAY_TABLE_ROW,
        DISPLAY_TABLE_ROW_GROUP, DISPLAY_TABLE_COLUMN,
        DISPLAY_TABLE_COLUMN_GROUP, DISPLAY_TABLE_CELL, DISPLAY_TABLE_CAPTION,
        DISPLAY_TABLE_HEADER_GROUP, DISPLAY_TABLE_FOOTER_GROUP:
      result{"display"} = DISPLAY_BLOCK
    of DISPLAY_INLINE_TABLE:
      result{"display"} = DISPLAY_TABLE