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
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
|
from std/strutils import split, toUpperAscii
import std/macros
import std/nativesockets
import std/net
import std/options
import std/os
import std/posix
import std/selectors
import std/streams
import std/tables
import std/unicode
import bindings/quickjs
import config/config
import css/cascade
import css/cssparser
import css/mediaquery
import css/sheet
import css/stylednode
import css/values
import html/catom
import html/chadombuilder
import html/dom
import html/enums
import html/env
import html/event
import html/formdata as formdata_impl
import io/bufstream
import io/posixstream
import io/promise
import io/serialize
import io/serversocket
import io/socketstream
import js/fromjs
import js/javascript
import js/regex
import js/timeout
import js/tojs
import layout/renderdocument
import loader/headers
import loader/loader
import types/cell
import types/color
import types/cookie
import types/formdata
import types/opt
import types/url
import types/winattrs
import utils/strwidth
import utils/twtstr
from chagashi/decoder import newTextDecoder
import chagashi/charset
import chagashi/decodercore
import chagashi/validatorcore
import chame/tags
type
BufferCommand* = enum
bcPassFd, bcLoad, bcForceRender, bcWindowChange, bcFindAnchor,
bcReadSuccess, bcReadCanceled, bcClick, bcFindNextLink, bcFindPrevLink,
bcFindNthLink, bcFindRevNthLink, bcFindNextMatch, bcFindPrevMatch,
bcGetLines, bcUpdateHover, bcGotoAnchor, bcCancel, bcGetTitle, bcSelect,
bcClone, bcFindPrevParagraph, bcFindNextParagraph
BufferState = enum
bsLoadingPage, bsLoadingResources, bsLoaded
HoverType* = enum
htTitle = "TITLE"
htLink = "URL"
htImage = "IMAGE"
BufferMatch* = object
success*: bool
x*: int
y*: int
str*: string
Buffer* = ref object
rfd: int # file descriptor of command pipe
fd: int # file descriptor of buffer source
url: URL # URL before readFromFd
pstream: SocketStream # control stream
savetask: bool
ishtml: bool
firstBufferRead: bool
lines: FlexibleGrid
request: Request # source request
attrs: WindowAttributes
window: Window
document: Document
prevStyled: StyledNode
selector: Selector[int]
istream: PosixStream
bytesRead: int
reportedBytesRead: int
state: BufferState
prevnode: StyledNode
loader: FileLoader
config: BufferConfig
tasks: array[BufferCommand, int] #TODO this should have arguments
hoverText: array[HoverType, string]
estream: Stream # error stream
ssock: ServerSocket
factory: CAtomFactory
uastyle: CSSStylesheet
quirkstyle: CSSStylesheet
userstyle: CSSStylesheet
htmlParser: HTML5ParserWrapper
bgcolor: CellColor
needsBOMSniff: bool
decoder: TextDecoder
validator: ref TextValidatorUTF8
validateBuf: seq[char]
charsetStack: seq[Charset]
charset: Charset
cacheId: int
outputId: int
InterfaceOpaque = ref object
stream: Stream
len: int
BufferInterface* = ref object
map: PromiseMap
packetid: int
opaque: InterfaceOpaque
stream*: BufStream
proc getFromOpaque[T](opaque: pointer, res: var T) =
let opaque = cast[InterfaceOpaque](opaque)
if opaque.len != 0:
opaque.stream.sread(res)
proc newBufferInterface*(stream: SocketStream, registerFun: proc(fd: int)):
BufferInterface =
let opaque = InterfaceOpaque(stream: stream)
result = BufferInterface(
map: newPromiseMap(cast[pointer](opaque)),
packetid: 1, # ids below 1 are invalid
opaque: opaque,
stream: newBufStream(stream, registerFun)
)
# After cloning a buffer, we need a new interface to the new buffer process.
# Here we create a new interface for that clone.
proc cloneInterface*(stream: SocketStream, registerFun: proc(fd: int)):
BufferInterface =
let iface = newBufferInterface(stream, registerFun)
#TODO buffered data should probably be copied here
# We have just fork'ed the buffer process inside an interface function,
# from which the new buffer is going to return as well. So we must also
# consume the return value of the clone function, which is the pid 0.
var len: int
var pid: int
stream.sread(len)
stream.sread(iface.packetid)
stream.sread(pid)
return iface
proc resolve*(iface: BufferInterface, packetid, len: int) =
iface.opaque.len = len
iface.map.resolve(packetid)
proc hasPromises*(iface: BufferInterface): bool =
return not iface.map.empty()
# get enum identifier of proxy function
func getFunId(fun: NimNode): string =
let name = fun[0] # sym
return "bc" & name.strVal[0].toUpperAscii() & name.strVal.substr(1)
proc buildInterfaceProc(fun: NimNode, funid: string): tuple[fun, name: NimNode] =
let name = fun[0] # sym
let params = fun[3] # formalparams
let retval = params[0] # sym
var body = newStmtList()
assert params.len >= 2 # return type, this value
let nup = ident(funid) # add this to enums
let this2 = newIdentDefs(ident("iface"), ident("BufferInterface"))
let thisval = this2[0]
body.add(quote do:
`thisval`.stream.swrite(BufferCommand.`nup`)
`thisval`.stream.swrite(`thisval`.packetid)
)
var params2: seq[NimNode]
var retval2: NimNode
var addfun: NimNode
if retval.kind == nnkEmpty:
addfun = quote do:
`thisval`.map.addEmptyPromise(`thisval`.packetid)
retval2 = ident("EmptyPromise")
else:
addfun = quote do:
addPromise[`retval`](`thisval`.map, `thisval`.packetid, getFromOpaque[`retval`])
retval2 = newNimNode(nnkBracketExpr).add(
ident("Promise"),
retval)
params2.add(retval2)
params2.add(this2)
# flatten args
for i in 2 ..< params.len:
let param = params[i]
for i in 0 ..< param.len - 2:
let id2 = newIdentDefs(ident(param[i].strVal), param[^2])
params2.add(id2)
for i in 2 ..< params2.len:
let s = params2[i][0] # sym e.g. url
body.add(quote do:
when typeof(`s`) is FileHandle:
#TODO flush or something
SocketStream(`thisval`.stream.source).sendFileHandle(`s`)
else:
`thisval`.stream.swrite(`s`)
)
body.add(quote do:
let promise = `addfun`
inc `thisval`.packetid
return promise
)
var pragmas: NimNode
if retval.kind == nnkEmpty:
pragmas = newNimNode(nnkPragma).add(ident("discardable"))
else:
pragmas = newEmptyNode()
return (newProc(name, params2, body, pragmas = pragmas), nup)
type
ProxyFunction = ref object
iname: NimNode # internal name
ename: NimNode # enum name
params: seq[NimNode]
istask: bool
ProxyMap = Table[string, ProxyFunction]
# Name -> ProxyFunction
var ProxyFunctions {.compileTime.}: ProxyMap
proc getProxyFunction(funid: string): ProxyFunction =
if funid notin ProxyFunctions:
ProxyFunctions[funid] = ProxyFunction()
return ProxyFunctions[funid]
macro proxy0(fun: untyped) =
fun[0] = ident(fun[0].strVal & "_internal")
return fun
macro proxy1(fun: typed) =
let funid = getFunId(fun)
let iproc = buildInterfaceProc(fun, funid)
let pfun = getProxyFunction(funid)
pfun.iname = ident(fun[0].strVal & "_internal")
pfun.ename = iproc[1]
pfun.params.add(fun[3][0])
var params2: seq[NimNode]
params2.add(fun[3][0])
for i in 1 ..< fun[3].len:
let param = fun[3][i]
pfun.params.add(param)
for i in 0 ..< param.len - 2:
let id2 = newIdentDefs(ident(param[i].strVal), param[^2])
params2.add(id2)
ProxyFunctions[funid] = pfun
return iproc[0]
macro proxy(fun: typed) =
quote do:
proxy0(`fun`)
proxy1(`fun`)
macro task(fun: typed) =
let funid = getFunId(fun)
let pfun = getProxyFunction(funid)
pfun.istask = true
fun
proc passFd*(buffer: Buffer; fd: FileHandle; cacheId: int) {.proxy.} =
buffer.fd = fd
buffer.istream = newPosixStream(fd)
buffer.istream.setBlocking(false)
buffer.selector.registerHandle(fd, {Read}, 0)
buffer.cacheId = cacheId
func getTitleAttr(node: StyledNode): string =
if node == nil:
return ""
if node.t == STYLED_ELEMENT and node.node != nil:
let element = Element(node.node)
if element.attrb(atTitle):
return element.attr(atTitle)
if node.node != nil:
var node = node.node
for element in node.ancestors:
if element.attrb(atTitle):
return element.attr(atTitle)
#TODO pseudo-elements
return ""
const ClickableElements = {
TAG_A, TAG_INPUT, TAG_OPTION, TAG_BUTTON, TAG_TEXTAREA, TAG_LABEL
}
func isClickable(styledNode: StyledNode): bool =
if styledNode.t != STYLED_ELEMENT or styledNode.node == nil:
return false
if styledNode.computed{"visibility"} != VISIBILITY_VISIBLE:
return false
let element = Element(styledNode.node)
if element of HTMLAnchorElement:
return HTMLAnchorElement(element).href != ""
return element.tagType in ClickableElements
func getClickable(styledNode: StyledNode): Element =
var styledNode = styledNode
while styledNode != nil:
if styledNode.isClickable():
return Element(styledNode.node)
styledNode = styledNode.parent
proc submitForm(form: HTMLFormElement, submitter: Element): Option[Request]
func canSubmitOnClick(fae: FormAssociatedElement): bool =
if fae.form == nil:
return false
if fae.form.canSubmitImplicitly():
return true
if fae of HTMLButtonElement and HTMLButtonElement(fae).ctype == BUTTON_SUBMIT:
return true
if fae of HTMLInputElement and
HTMLInputElement(fae).inputType in {INPUT_SUBMIT, INPUT_BUTTON}:
return true
return false
proc getClickHover(styledNode: StyledNode): string =
let clickable = styledNode.getClickable()
if clickable != nil:
if clickable of HTMLAnchorElement:
return HTMLAnchorElement(clickable).href
elif clickable of FormAssociatedElement:
#TODO this is inefficient and also quite stupid
let fae = FormAssociatedElement(clickable)
if fae.canSubmitOnClick():
let req = fae.form.submitForm(fae)
if req.isSome:
return $req.get.url
return "<" & $clickable.tagType & ">"
elif clickable of HTMLOptionElement:
return "<option>"
""
proc getImageHover(styledNode: StyledNode): string =
var styledNode = styledNode
while styledNode != nil:
if styledNode.t == STYLED_ELEMENT:
if styledNode.node of HTMLImageElement:
let image = HTMLImageElement(styledNode.node)
let src = image.attr(atSrc)
if src != "":
let url = image.document.parseURL(src)
if url.isSome:
return $url.get
elif styledNode.node of HTMLVideoElement:
let video = HTMLVideoElement(styledNode.node)
let src = video.getSrc()
if src != "":
let url = video.document.parseURL(src)
if url.isSome:
return $url.get
elif styledNode.node of HTMLAudioElement:
let audio = HTMLAudioElement(styledNode.node)
let src = audio.getSrc()
if src != "":
let url = audio.document.parseURL(src)
if url.isSome:
return $url.get
styledNode = styledNode.parent
""
func getCursorStyledNode(buffer: Buffer, cursorx, cursory: int): StyledNode =
let i = buffer.lines[cursory].findFormatN(cursorx) - 1
if i >= 0:
return buffer.lines[cursory].formats[i].node
nil
func getCursorElement(buffer: Buffer, cursorx, cursory: int): Element =
let styledNode = buffer.getCursorStyledNode(cursorx, cursory)
if styledNode == nil or styledNode.node == nil:
return nil
if styledNode.t == STYLED_ELEMENT:
return Element(styledNode.node)
return styledNode.node.parentElement
func getCursorClickable(buffer: Buffer, cursorx, cursory: int): Element =
let styledNode = buffer.getCursorStyledNode(cursorx, cursory)
if styledNode != nil:
return styledNode.getClickable()
func cursorBytes(buffer: Buffer, y: int, cc: int): int =
let line = buffer.lines[y].str
var w = 0
var i = 0
while i < line.len and w < cc:
var r: Rune
fastRuneAt(line, i, r)
w += r.twidth(w)
return i
proc navigate(buffer: Buffer, url: URL) =
#TODO how?
stderr.write("navigate to " & $url & "\n")
proc findPrevLink*(buffer: Buffer, cursorx, cursory, n: int):
tuple[x, y: int] {.proxy.} =
if cursory >= buffer.lines.len: return (-1, -1)
var found = 0
let line = buffer.lines[cursory]
var i = line.findFormatN(cursorx) - 1
var link: Element = nil
if i >= 0:
link = line.formats[i].node.getClickable()
dec i
var ly = 0 #last y
var lx = 0 #last x
template link_beginning() =
#go to beginning of link
ly = y #last y
lx = format.pos #last x
#on the current line
let line = buffer.lines[y]
while i >= 0:
let format = line.formats[i]
let nl = format.node.getClickable()
if nl == fl:
lx = format.pos
dec i
#on previous lines
for iy in countdown(ly - 1, 0):
let line = buffer.lines[iy]
i = line.formats.len - 1
let oly = iy
let olx = lx
while i >= 0:
let format = line.formats[i]
let nl = format.node.getClickable()
if nl == fl:
ly = iy
lx = format.pos
dec i
if iy == oly and olx == lx:
# Assume multiline anchors are always placed on consecutive lines.
# This is not true, but otherwise we would have to loop through
# the entire document, which would be rather inefficient. TODO: find
# an efficient and correct way to do this.
break
template found_pos(x, y: int, fl: Element) =
inc found
link = fl
if found == n:
return (x, y)
while i >= 0:
let format = line.formats[i]
let fl = format.node.getClickable()
if fl != nil and fl != link:
let y = cursory
link_beginning
found_pos lx, ly, fl
dec i
for y in countdown(cursory - 1, 0):
let line = buffer.lines[y]
i = line.formats.len - 1
while i >= 0:
let format = line.formats[i]
let fl = format.node.getClickable()
if fl != nil and fl != link:
link_beginning
found_pos lx, ly, fl
dec i
return (-1, -1)
proc findNextLink*(buffer: Buffer, cursorx, cursory, n: int):
tuple[x, y: int] {.proxy.} =
if cursory >= buffer.lines.len: return (-1, -1)
let line = buffer.lines[cursory]
var i = line.findFormatN(cursorx) - 1
var link: Element = nil
if i >= 0:
link = line.formats[i].node.getClickable()
inc i
var found = 0
template found_pos(x, y: int, fl: Element) =
inc found
link = fl
if found == n:
return (x, y)
while i < line.formats.len:
let format = line.formats[i]
let fl = format.node.getClickable()
if fl != nil and fl != link:
found_pos format.pos, cursory, fl
inc i
for y in (cursory + 1)..(buffer.lines.len - 1):
let line = buffer.lines[y]
for i in 0 ..< line.formats.len:
let format = line.formats[i]
let fl = format.node.getClickable()
if fl != nil and fl != link:
found_pos format.pos, y, fl
return (-1, -1)
proc findPrevParagraph*(buffer: Buffer, cursory, n: int): int {.proxy.} =
var y = cursory
for i in 0 ..< n:
while y >= 0 and buffer.lines[y].str.onlyWhitespace():
dec y
while y >= 0 and not buffer.lines[y].str.onlyWhitespace():
dec y
return y
proc findNextParagraph*(buffer: Buffer, cursory, n: int): int {.proxy.} =
var y = cursory
for i in 0 ..< n:
while y < buffer.lines.len and buffer.lines[y].str.onlyWhitespace():
inc y
while y < buffer.lines.len and not buffer.lines[y].str.onlyWhitespace():
inc y
return y
proc findNthLink*(buffer: Buffer, i: int): tuple[x, y: int] {.proxy.} =
if i == 0:
return (-1, -1)
var k = 0
var link: Element
for y in 0 .. buffer.lines.high:
let line = buffer.lines[y]
for j in 0 ..< line.formats.len:
let format = line.formats[j]
let fl = format.node.getClickable()
if fl != nil and fl != link:
inc k
if k == i:
return (format.pos, y)
link = fl
return (-1, -1)
proc findRevNthLink*(buffer: Buffer, i: int): tuple[x, y: int] {.proxy.} =
if i == 0:
return (-1, -1)
var k = 0
var link: Element
for y in countdown(buffer.lines.high, 0):
let line = buffer.lines[y]
for j in countdown(line.formats.high, 0):
let format = line.formats[j]
let fl = format.node.getClickable()
if fl != nil and fl != link:
inc k
if k == i:
return (format.pos, y)
link = fl
return (-1, -1)
proc findPrevMatch*(buffer: Buffer, regex: Regex, cursorx, cursory: int,
wrap: bool, n: int): BufferMatch {.proxy.} =
if cursory >= buffer.lines.len: return
var y = cursory
let b = buffer.cursorBytes(y, cursorx)
let res = regex.exec(buffer.lines[y].str, 0, b)
var numfound = 0
if res.success and res.captures.len > 0:
let cap = res.captures[^1]
let x = buffer.lines[y].str.width(0, cap.s)
let str = buffer.lines[y].str.substr(cap.s, cap.e - 1)
inc numfound
if numfound >= n:
return BufferMatch(success: true, x: x, y: y, str: str)
dec y
while true:
if y < 0:
if wrap:
y = buffer.lines.high
else:
break
let res = regex.exec(buffer.lines[y].str)
if res.success and res.captures.len > 0:
let cap = res.captures[^1]
let x = buffer.lines[y].str.width(0, cap.s)
let str = buffer.lines[y].str.substr(cap.s, cap.e - 1)
inc numfound
if numfound >= n:
return BufferMatch(success: true, x: x, y: y, str: str)
if y == cursory:
break
dec y
proc findNextMatch*(buffer: Buffer, regex: Regex, cursorx, cursory: int,
wrap: bool, n: int): BufferMatch {.proxy.} =
if cursory >= buffer.lines.len: return
var y = cursory
let b = buffer.cursorBytes(y, cursorx + 1)
let res = regex.exec(buffer.lines[y].str, b, buffer.lines[y].str.len)
var numfound = 0
if res.success and res.captures.len > 0:
let cap = res.captures[0]
let x = buffer.lines[y].str.width(0, cap.s)
let str = buffer.lines[y].str.substr(cap.s, cap.e - 1)
inc numfound
if numfound >= n:
return BufferMatch(success: true, x: x, y: y, str: str)
inc y
while true:
if y > buffer.lines.high:
if wrap:
y = 0
else:
break
let res = regex.exec(buffer.lines[y].str)
if res.success and res.captures.len > 0:
let cap = res.captures[0]
let x = buffer.lines[y].str.width(0, cap.s)
let str = buffer.lines[y].str.substr(cap.s, cap.e - 1)
inc numfound
if numfound >= n:
return BufferMatch(success: true, x: x, y: y, str: str)
if y == cursory:
break
inc y
proc gotoAnchor*(buffer: Buffer): Opt[tuple[x, y: int]] {.proxy.} =
if buffer.document == nil:
return err()
let anchor = buffer.document.findAnchor(buffer.url.anchor)
if anchor == nil:
return err()
for y in 0 ..< buffer.lines.len:
let line = buffer.lines[y]
for i in 0 ..< line.formats.len:
let format = line.formats[i]
if format.node != nil and format.node.node in anchor:
return ok((format.pos, y))
return err()
proc do_reshape(buffer: Buffer) =
if buffer.document == nil:
return # not parsed yet, nothing to render
let uastyle = if buffer.document.mode != QUIRKS:
buffer.uastyle
else:
buffer.quirkstyle
if buffer.document.cachedSheetsInvalid:
buffer.prevStyled = nil
let styledRoot = buffer.document.applyStylesheets(uastyle,
buffer.userstyle, buffer.prevStyled)
buffer.lines.renderDocument(buffer.bgcolor, styledRoot, addr buffer.attrs)
buffer.prevStyled = styledRoot
proc processData0(buffer: Buffer, data: openArray[char]): bool =
if buffer.ishtml:
if buffer.htmlParser.parseBuffer(data) == PRES_STOP:
buffer.charsetStack = @[buffer.htmlParser.builder.charset]
return false
else:
var plaintext = buffer.document.findFirst(TAG_PLAINTEXT)
if plaintext == nil:
const s = "<plaintext>"
doAssert buffer.htmlParser.parseBuffer(s) != PRES_STOP
plaintext = buffer.document.findFirst(TAG_PLAINTEXT)
if data.len > 0:
let lastChild = plaintext.lastChild
var text = newString(data.len)
copyMem(addr text[0], unsafeAddr data[0], data.len)
if lastChild != nil and lastChild of Text:
Text(lastChild).data &= text
else:
plaintext.insert(buffer.document.createTextNode(text), nil)
plaintext.invalid = true
true
func canSwitch(buffer: Buffer): bool {.inline.} =
return buffer.htmlParser.builder.confidence == ccTentative and
buffer.charsetStack.len > 0
proc initDecoder(buffer: Buffer) =
if buffer.charset != CHARSET_UTF_8:
buffer.decoder = newTextDecoder(buffer.charset)
else:
buffer.validator = (ref TextValidatorUTF8)()
proc switchCharset(buffer: Buffer) =
buffer.charset = buffer.charsetStack.pop()
buffer.initDecoder()
buffer.htmlParser.restart(buffer.charset)
buffer.document = buffer.htmlParser.builder.document
buffer.prevStyled = nil
const BufferSize = 16384
proc decodeData(buffer: Buffer, iq: openArray[uint8]): bool =
var oq {.noinit.}: array[BufferSize, char]
var n = 0
while true:
case buffer.decoder.decode(iq, oq.toOpenArrayByte(0, oq.high), n)
of tdrDone:
if not buffer.processData0(oq.toOpenArray(0, n - 1)):
buffer.switchCharset()
return false
break
of tdrReqOutput:
# flush output buffer
if not buffer.processData0(oq.toOpenArray(0, n - 1)):
buffer.switchCharset()
return false
n = 0
of tdrError:
if buffer.canSwitch:
buffer.switchCharset()
return false
doAssert buffer.processData0("\uFFFD")
true
proc validateData(buffer: Buffer, iq: openArray[char]): bool =
var pi = 0
var n = 0
while true:
case buffer.validator[].validate(iq.toOpenArrayByte(0, iq.high), n)
of tvrDone:
if n == -1:
return true
if buffer.validateBuf.len > 0:
doAssert buffer.processData0(buffer.validateBuf)
buffer.validateBuf.setLen(0)
if not buffer.processData0(iq.toOpenArray(pi, n)):
buffer.switchCharset()
return false
buffer.validateBuf.add(iq.toOpenArray(n + 1, iq.high))
break
of tvrError:
buffer.validateBuf.setLen(0)
if buffer.canSwitch:
buffer.switchCharset()
return false
if n >= pi:
doAssert buffer.processData0(iq.toOpenArray(pi, n))
doAssert buffer.processData0("\uFFFD")
pi = buffer.validator.i
true
proc bomSniff(buffer: Buffer, iq: openArray[char]): int =
if iq[0] == '\xFE' and iq[1] == '\xFF':
buffer.charsetStack = @[CHARSET_UTF_16_BE]
buffer.switchCharset()
return 2
if iq[0] == '\xFF' and iq[1] == '\xFE':
buffer.charsetStack = @[CHARSET_UTF_16_LE]
buffer.switchCharset()
return 2
if iq[0] == '\xEF' and iq[1] == '\xBB' and iq[2] == '\xBF':
buffer.charsetStack = @[CHARSET_UTF_8]
buffer.switchCharset()
return 3
return 0
proc processData(buffer: Buffer, iq: openArray[char]): bool =
var start = 0
if buffer.needsBOMSniff:
if iq.len >= 3: # ehm... TODO
start += buffer.bomSniff(iq)
buffer.needsBOMSniff = false
if buffer.decoder != nil:
return buffer.decodeData(iq.toOpenArrayByte(start, iq.high))
return buffer.validateData(iq.toOpenArray(start, iq.high))
proc windowChange*(buffer: Buffer, attrs: WindowAttributes) {.proxy.} =
buffer.attrs = attrs
buffer.prevStyled = nil
if buffer.window != nil:
buffer.window.attrs = attrs
buffer.do_reshape()
type UpdateHoverResult* = object
hover*: seq[tuple[t: HoverType, s: string]]
repaint*: bool
const HoverFun = [
htTitle: getTitleAttr,
htLink: getClickHover,
htImage: getImageHover
]
proc updateHover*(buffer: Buffer, cursorx, cursory: int): UpdateHoverResult
{.proxy.} =
if cursory >= buffer.lines.len:
return UpdateHoverResult()
var thisnode: StyledNode
let i = buffer.lines[cursory].findFormatN(cursorx) - 1
if i >= 0:
thisnode = buffer.lines[cursory].formats[i].node
var hover: seq[tuple[t: HoverType, s: string]] = @[]
var repaint = false
let prevnode = buffer.prevnode
if thisnode != prevnode and (thisnode == nil or prevnode == nil or
thisnode.node != prevnode.node):
for styledNode in thisnode.branch:
if styledNode.t == STYLED_ELEMENT and styledNode.node != nil:
let elem = Element(styledNode.node)
if not elem.hover:
elem.hover = true
repaint = true
for ht in HoverType:
let s = HoverFun[ht](thisnode)
if buffer.hoverText[ht] != s:
hover.add((ht, s))
buffer.hoverText[ht] = s
for styledNode in prevnode.branch:
if styledNode.t == STYLED_ELEMENT and styledNode.node != nil:
let elem = Element(styledNode.node)
if elem.hover:
elem.hover = false
repaint = true
if repaint:
buffer.do_reshape()
buffer.prevnode = thisnode
return UpdateHoverResult(repaint: repaint, hover: hover)
proc loadResources(buffer: Buffer): EmptyPromise =
return buffer.window.loadingResourcePromises.all()
proc rewind(buffer: Buffer; offset: int; unregister = true): bool =
let url = newURL("cache:" & $buffer.cacheId & "?" & $offset).get
let response = buffer.loader.doRequest(newRequest(url))
if response.body == nil:
return false
if unregister:
buffer.selector.unregister(buffer.fd)
buffer.loader.unregistered.add(buffer.fd)
buffer.istream.close()
buffer.istream = response.body
buffer.istream.setBlocking(false)
buffer.fd = response.body.fd
buffer.selector.registerHandle(buffer.fd, {Read}, 0)
buffer.bytesRead = offset
return true
proc setHTML(buffer: Buffer) =
buffer.initDecoder()
let factory = newCAtomFactory()
buffer.factory = factory
let navigate = if buffer.config.scripting:
proc(url: URL) = buffer.navigate(url)
else:
nil
buffer.window = newWindow(
buffer.config.scripting,
buffer.config.images,
buffer.selector,
buffer.attrs,
factory,
navigate,
some(buffer.loader)
)
let confidence = if buffer.config.charsetOverride == CHARSET_UNKNOWN:
ccTentative
else:
ccCertain
buffer.htmlParser = newHTML5ParserWrapper(
buffer.window,
buffer.url,
buffer.factory,
confidence,
buffer.charset
)
assert buffer.htmlParser.builder.document != nil
const css = staticRead"res/ua.css"
const quirk = css & staticRead"res/quirk.css"
buffer.uastyle = css.parseStylesheet(factory)
buffer.quirkstyle = quirk.parseStylesheet(factory)
buffer.userstyle = parseStylesheet(buffer.config.userstyle, factory)
buffer.document = buffer.htmlParser.builder.document
# As defined in std/selectors: this determines whether kqueue is being used.
# On these platforms, we must not close the selector after fork, since kqueue
# fds are not inherited after a fork.
const bsdPlatform = defined(macosx) or defined(freebsd) or defined(netbsd) or
defined(openbsd) or defined(dragonfly)
proc onload(buffer: Buffer)
# Create an exact clone of the current buffer.
# This clone will share the loader process with the previous buffer.
proc clone*(buffer: Buffer, newurl: URL): int {.proxy.} =
var pipefd: array[2, cint]
if pipe(pipefd) == -1:
buffer.estream.write("Failed to open pipe.\n")
return -1
# suspend outputs before tee'ing
var ids: seq[int] = @[]
for data in buffer.loader.ongoing.values:
ids.add(data.response.outputId)
buffer.loader.suspend(ids)
# ongoing transfers are now suspended; exhaust all data in the internal buffer
# just to be safe.
for fd in buffer.loader.ongoing.keys:
buffer.loader.onRead(fd)
let pid = fork()
if pid == -1:
buffer.estream.write("Failed to clone buffer.\n")
return -1
if pid == 0: # child
discard close(pipefd[0]) # close read
let ps = newPosixStream(pipefd[1])
# We must allocate a new selector for this new process. (Otherwise we
# would interfere with operation of the other one.)
# Closing seems to suffice here.
when not bsdPlatform:
buffer.selector.close()
buffer.selector = newSelector[int]()
#TODO set buffer.window.timeouts.selector
var cfds: seq[int] = @[]
for fd in buffer.loader.connecting.keys:
cfds.add(fd)
for fd in cfds:
# connecting: just reconnect
buffer.loader.reconnect(buffer.loader.connecting[fd])
buffer.loader.connecting.del(fd)
var ongoing: seq[OngoingData] = @[]
for data in buffer.loader.ongoing.values:
ongoing.add(data)
data.response.body.close()
buffer.loader.ongoing.clear()
let myPid = getCurrentProcessId()
for data in ongoing.mitems:
# tee ongoing streams
let (stream, outputId) = buffer.loader.tee(data.response.outputId, myPid)
# if -1, well, this side hasn't exhausted the socket's buffer
doAssert outputId != -1 and stream != nil
data.response.outputId = outputId
data.response.body = stream
let fd = data.response.body.fd
buffer.loader.ongoing[fd] = data
buffer.selector.registerHandle(fd, {Read}, 0)
if buffer.istream != nil:
# We do not own our input stream, so we can't tee it.
# Luckily it is cached, so what we *can* do is to load the same thing from
# the cache. (This also lets us skip suspend/resume in this case.)
# We ignore errors; not much we can do with them here :/
discard buffer.rewind(buffer.bytesRead, unregister = false)
buffer.pstream.close()
let ssock = initServerSocket(myPid, buffered = false)
buffer.ssock = ssock
ps.write(char(0))
buffer.url = newurl
for it in buffer.tasks.mitems:
it = 0
let socks = ssock.acceptSocketStream()
buffer.loader.clientPid = myPid
socks.sread(buffer.loader.key) # get key for new buffer
buffer.pstream = socks
buffer.rfd = socks.fd
buffer.selector.registerHandle(buffer.rfd, {Read}, 0)
return 0
else: # parent
discard close(pipefd[1]) # close write
# We must wait for child to tee its ongoing streams.
let ps = newPosixStream(pipefd[0])
let c = ps.readChar()
assert c == char(0)
ps.close()
buffer.loader.resume(ids)
return pid
proc dispatchDOMContentLoadedEvent(buffer: Buffer) =
let window = buffer.window
if window == nil or not buffer.config.scripting:
return
let ctx = window.jsctx
let document = buffer.document
let event = newEvent(ctx, "DOMContentLoaded", document)
var called = false
for el in document.eventListeners:
if el.ctype == "DOMContentLoaded":
let e = el.callback(event)
if e.isErr:
ctx.writeException(buffer.estream)
called = true
if called:
buffer.do_reshape()
proc dispatchLoadEvent(buffer: Buffer) =
let window = buffer.window
if window == nil or not buffer.config.scripting:
return
let ctx = window.jsctx
let event = newEvent(ctx, "load", window)
var called = false
for el in window.eventListeners:
if el.ctype == "load":
let e = el.callback(event)
if e.isErr:
ctx.writeException(buffer.estream)
called = true
let jsWindow = toJS(ctx, window)
let jsonload = JS_GetPropertyStr(ctx, jsWindow, "onload")
var jsEvent = toJS(ctx, event)
if JS_IsFunction(ctx, jsonload):
JS_FreeValue(ctx, JS_Call(ctx, jsonload, jsWindow, 1, addr jsEvent))
called = true
JS_FreeValue(ctx, jsEvent)
JS_FreeValue(ctx, jsonload)
JS_FreeValue(ctx, jsWindow)
if called:
buffer.do_reshape()
proc dispatchEvent(buffer: Buffer, ctype: string, elem: Element): tuple[
called: bool,
canceled: bool
] =
var called = false
var canceled = false
let ctx = buffer.window.jsctx
let event = newEvent(ctx, ctype, elem)
for a in elem.branch:
event.currentTarget = a
var stop = false
for el in a.eventListeners:
if el.ctype == ctype:
let e = el.callback(event)
called = true
if e.isErr:
ctx.writeException(buffer.estream)
if FLAG_STOP_IMMEDIATE_PROPAGATION in event.flags:
stop = true
break
if FLAG_STOP_PROPAGATION in event.flags:
stop = true
if FLAG_CANCELED in event.flags:
canceled = true
if stop:
break
return (called, canceled)
proc finishLoad(buffer: Buffer): EmptyPromise =
if buffer.state != bsLoadingPage:
let p = EmptyPromise()
p.resolve()
return p
buffer.state = bsLoadingResources
if buffer.decoder != nil and buffer.decoder.finish() == tdfrError or
buffer.validator != nil and buffer.validator[].finish() == tvrError:
doAssert buffer.processData0("\uFFFD")
buffer.htmlParser.finish()
buffer.document.readyState = rsInteractive
buffer.dispatchDOMContentLoadedEvent()
buffer.selector.unregister(buffer.fd)
buffer.loader.unregistered.add(buffer.fd)
buffer.loader.removeCachedItem(buffer.cacheId)
buffer.cacheId = -1
buffer.fd = -1
buffer.outputId = -1
buffer.istream.close()
return buffer.loadResources()
# Returns:
# * -1 if loading is done
# * a positive number for reporting the number of bytes loaded and that the page
# has been partially rendered.
proc load*(buffer: Buffer): int {.proxy, task.} =
if buffer.state == bsLoaded:
return -1
elif buffer.bytesRead > buffer.reportedBytesRead:
buffer.do_reshape()
buffer.reportedBytesRead = buffer.bytesRead
return buffer.bytesRead
else:
# will be resolved in onload
buffer.savetask = true
return -2 # unused
proc resolveTask[T](buffer: Buffer, cmd: BufferCommand, res: T) =
let packetid = buffer.tasks[cmd]
if packetid == 0:
return # no task to resolve (TODO this is kind of inefficient)
let len = slen(buffer.tasks[cmd]) + slen(res)
buffer.pstream.swrite(len)
buffer.pstream.swrite(packetid)
buffer.tasks[cmd] = 0
buffer.pstream.swrite(res)
buffer.pstream.flush()
proc onload(buffer: Buffer) =
case buffer.state
of bsLoadingResources, bsLoaded:
buffer.resolveTask(bcLoad, -1)
return
of bsLoadingPage:
discard
var reprocess = false
var iq {.noinit.}: array[BufferSize, char]
var n = 0
while true:
try:
if not reprocess:
n = buffer.istream.recvData(addr iq[0], iq.len)
buffer.bytesRead += n
if n != 0:
if not buffer.processData(iq.toOpenArray(0, n - 1)):
if not buffer.firstBufferRead:
reprocess = true
continue
if buffer.rewind(0):
continue
buffer.firstBufferRead = true
reprocess = false
else: # EOF
buffer.finishLoad().then(proc() =
buffer.do_reshape()
buffer.state = bsLoaded
buffer.document.readyState = rsComplete
buffer.dispatchLoadEvent()
buffer.resolveTask(bcLoad, -1)
)
return # skip incr render
except ErrorAgain:
break
# incremental rendering: only if we cannot read the entire stream in one
# pass
if not buffer.config.isdump and buffer.tasks[bcLoad] != 0:
# only makes sense when not in dump mode (and the user has requested a load)
buffer.do_reshape()
buffer.reportedBytesRead = buffer.bytesRead
buffer.resolveTask(bcLoad, buffer.bytesRead)
proc getTitle*(buffer: Buffer): string {.proxy.} =
if buffer.document != nil:
return buffer.document.title
proc forceRender*(buffer: Buffer) {.proxy.} =
buffer.prevStyled = nil
buffer.do_reshape()
proc cancel*(buffer: Buffer): int {.proxy.} =
if buffer.state == bsLoaded:
return
buffer.state = bsLoaded
for fd, data in buffer.loader.connecting:
buffer.selector.unregister(fd)
buffer.loader.unregistered.add(fd)
data.stream.close()
buffer.loader.connecting.clear()
for fd, data in buffer.loader.ongoing:
data.response.unregisterFun()
buffer.loader.ongoing.clear()
buffer.selector.unregister(buffer.fd)
buffer.loader.unregistered.add(buffer.fd)
buffer.loader.removeCachedItem(buffer.cacheId)
buffer.fd = -1
buffer.cacheId = -1
buffer.outputId = -1
buffer.istream.close()
buffer.htmlParser.finish()
buffer.document.readyState = rsInteractive
buffer.state = bsLoaded
buffer.do_reshape()
return buffer.lines.len
#https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm
proc serializeMultipartFormData(entries: seq[FormDataEntry]): FormData =
let formData = newFormData0()
for entry in entries:
let name = makeCRLF(entry.name)
if entry.isstr:
let value = makeCRLF(entry.svalue)
formData.append(name, value)
else:
formData.append(name, entry.value, opt(entry.filename))
return formData
proc serializePlainTextFormData(kvs: seq[(string, string)]): string =
for it in kvs:
let (name, value) = it
result &= name
result &= '='
result &= value
result &= "\r\n"
func getOutputEncoding(charset: Charset): Charset =
if charset in {CHARSET_REPLACEMENT, CHARSET_UTF_16_BE, CHARSET_UTF_16_LE}:
return CHARSET_UTF_8
return charset
func pickCharset(form: HTMLFormElement): Charset =
if form.attrb(atAcceptCharset):
let input = form.attr(atAcceptCharset)
for label in input.split(AsciiWhitespace):
let charset = label.getCharset()
if charset != CHARSET_UNKNOWN:
return charset.getOutputEncoding()
return CHARSET_UTF_8
return form.document.charset.getOutputEncoding()
# https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-submission-algorithm
proc submitForm(form: HTMLFormElement, submitter: Element): Option[Request] =
if form.constructingEntryList:
return none(Request)
#TODO submit()
let charset = form.pickCharset()
discard charset #TODO pass to constructEntryList
let entrylist = form.constructEntryList(submitter)
let subAction = submitter.action()
let action = if subAction != "":
subAction
else:
$form.document.url
#TODO encoding-parse
let url = submitter.document.parseURL(action)
if url.isNone:
return none(Request)
var parsedaction = url.get
let scheme = parsedaction.scheme
let enctype = submitter.enctype()
let formmethod = submitter.formmethod()
if formmethod == FORM_METHOD_DIALOG:
#TODO
return none(Request)
let httpmethod = if formmethod == FORM_METHOD_GET:
HTTP_GET
else:
assert formmethod == FORM_METHOD_POST
HTTP_POST
#let target = if submitter.isSubmitButton() and submitter.attrb("formtarget"):
# submitter.attr("formtarget")
#else:
# submitter.target()
#let noopener = true #TODO
template mutateActionUrl() =
let kvlist = entrylist.toNameValuePairs()
#TODO with charset
let query = serializeApplicationXWWWFormUrlEncoded(kvlist)
parsedaction.query = some(query)
return some(newRequest(parsedaction, httpmethod))
template submitAsEntityBody() =
var mimetype: string
var body: Opt[string]
var multipart: Opt[FormData]
case enctype
of FORM_ENCODING_TYPE_URLENCODED:
#TODO with charset
let kvlist = entrylist.toNameValuePairs()
body.ok(serializeApplicationXWWWFormUrlEncoded(kvlist))
mimeType = $enctype
of FORM_ENCODING_TYPE_MULTIPART:
#TODO with charset
multipart.ok(serializeMultipartFormData(entrylist))
mimetype = $enctype
of FORM_ENCODING_TYPE_TEXT_PLAIN:
#TODO with charset
let kvlist = entrylist.toNameValuePairs()
body.ok(serializePlainTextFormData(kvlist))
mimetype = $enctype
let req = newRequest(parsedaction, httpmethod, @{"Content-Type": mimetype},
body, multipart)
return some(req) #TODO multipart
template getActionUrl() =
return some(newRequest(parsedaction))
template mailWithHeaders() =
let kvlist = entrylist.toNameValuePairs()
#TODO with charset
let headers = serializeApplicationXWWWFormUrlEncoded(kvlist,
spaceAsPlus = false)
parsedaction.query = some(headers)
return some(newRequest(parsedaction, httpmethod))
template mailAsBody() =
let kvlist = entrylist.toNameValuePairs()
let body = if enctype == FORM_ENCODING_TYPE_TEXT_PLAIN:
let text = serializePlainTextFormData(kvlist)
percentEncode(text, PathPercentEncodeSet)
else:
#TODO with charset
serializeApplicationXWWWFormUrlEncoded(kvlist)
if parsedaction.query.isNone:
parsedaction.query = some("")
if parsedaction.query.get != "":
parsedaction.query.get &= '&'
parsedaction.query.get &= "body=" & body
return some(newRequest(parsedaction, httpmethod))
case scheme
of "ftp", "javascript":
getActionUrl
of "data":
if formmethod == FORM_METHOD_GET:
mutateActionUrl
else:
assert formmethod == FORM_METHOD_POST
getActionUrl
of "mailto":
if formmethod == FORM_METHOD_GET:
mailWithHeaders
else:
assert formmethod == FORM_METHOD_POST
mailAsBody
else:
# Note: only http & https are defined by the standard.
# Assume an HTTP-like protocol.
if formmethod == FORM_METHOD_GET:
mutateActionUrl
else:
assert formmethod == FORM_METHOD_POST
submitAsEntityBody
proc setFocus(buffer: Buffer, e: Element): bool =
if buffer.document.focus != e:
buffer.document.focus = e
buffer.do_reshape()
return true
proc restoreFocus(buffer: Buffer): bool =
if buffer.document.focus != nil:
buffer.document.focus = nil
buffer.do_reshape()
return true
type ReadSuccessResult* = object
open*: Option[Request]
repaint*: bool
proc implicitSubmit(input: HTMLInputElement): Option[Request] =
let form = input.form
if form != nil and form.canSubmitImplicitly():
var defaultButton: Element
for element in form.elements:
if element.isSubmitButton():
defaultButton = element
break
if defaultButton != nil:
return submitForm(form, defaultButton)
else:
return submitForm(form, form)
proc readSuccess*(buffer: Buffer, s: string): ReadSuccessResult {.proxy.} =
if buffer.document.focus != nil:
case buffer.document.focus.tagType
of TAG_INPUT:
let input = HTMLInputElement(buffer.document.focus)
case input.inputType
of INPUT_SEARCH, INPUT_TEXT, INPUT_PASSWORD:
input.value = s
input.invalid = true
buffer.do_reshape()
result.repaint = true
result.open = implicitSubmit(input)
of INPUT_FILE:
let cdir = parseURL("file://" & getCurrentDir() & DirSep)
let path = parseURL(s, cdir)
if path.isSome:
input.file = path
input.invalid = true
buffer.do_reshape()
result.repaint = true
result.open = implicitSubmit(input)
else: discard
of TAG_TEXTAREA:
let textarea = HTMLTextAreaElement(buffer.document.focus)
textarea.value = s
textarea.invalid = true
buffer.do_reshape()
result.repaint = true
else: discard
let r = buffer.restoreFocus()
if not result.repaint:
result.repaint = r
type ReadLineResult* = object
prompt*: string
value*: string
hide*: bool
area*: bool
type
SelectResult* = object
multiple*: bool
options*: seq[string]
selected*: seq[int]
ClickResult* = object
open*: Option[Request]
readline*: Option[ReadLineResult]
repaint*: bool
select*: Option[SelectResult]
proc click(buffer: Buffer, clickable: Element): ClickResult
proc click(buffer: Buffer, label: HTMLLabelElement): ClickResult =
let control = label.control
if control != nil:
return buffer.click(control)
proc click(buffer: Buffer, select: HTMLSelectElement): ClickResult =
let repaint = buffer.setFocus(select)
var options: seq[string]
var selected: seq[int]
var i = 0
for option in select.options:
options.add(option.textContent.stripAndCollapse())
if option.selected:
selected.add(i)
inc i
let select = SelectResult(
multiple: select.attrb(atMultiple),
options: options,
selected: selected
)
return ClickResult(
repaint: repaint,
select: some(select)
)
func baseURL(buffer: Buffer): URL =
return buffer.document.baseURL
proc evalJSURL(buffer: Buffer, url: URL): Opt[string] =
let encodedScriptSource = ($url)["javascript:".len..^1]
let scriptSource = percentDecode(encodedScriptSource)
let ctx = buffer.window.jsctx
let ret = ctx.eval(scriptSource, $buffer.baseURL, JS_EVAL_TYPE_GLOBAL)
if JS_IsException(ret):
ctx.writeException(buffer.estream)
return err() # error
if JS_IsUndefined(ret):
return err() # no need to navigate
let s = ?fromJS[string](ctx, ret)
JS_FreeValue(ctx, ret)
# Navigate to result.
return ok(s)
proc click(buffer: Buffer, anchor: HTMLAnchorElement): ClickResult =
var repaint = buffer.restoreFocus()
let url = parseURL(anchor.href, some(buffer.baseURL))
if url.isSome:
let url = url.get
if url.scheme == "javascript":
if buffer.config.scripting:
let s = buffer.evalJSURL(url)
buffer.do_reshape()
repaint = true
if s.isSome:
let url = newURL("data:text/html," & s.get).get
let req = newRequest(url, HTTP_GET)
return ClickResult(
repaint: repaint,
open: some(req)
)
return ClickResult(
repaint: repaint
)
return ClickResult(
repaint: repaint,
open: some(newRequest(url, HTTP_GET))
)
return ClickResult(
repaint: repaint
)
proc click(buffer: Buffer, option: HTMLOptionElement): ClickResult =
let select = option.select
if select != nil:
return buffer.click(select)
proc click(buffer: Buffer, button: HTMLButtonElement): ClickResult =
if button.form != nil:
case button.ctype
of BUTTON_SUBMIT: result.open = submitForm(button.form, button)
of BUTTON_RESET:
button.form.reset()
buffer.do_reshape()
return ClickResult(repaint: true)
of BUTTON_BUTTON: discard
result.repaint = buffer.setFocus(button)
proc click(buffer: Buffer, textarea: HTMLTextAreaElement): ClickResult =
let repaint = buffer.setFocus(textarea)
let readline = ReadLineResult(
value: textarea.value,
area: true,
)
return ClickResult(
readline: some(readline),
repaint: repaint
)
proc click(buffer: Buffer, input: HTMLInputElement): ClickResult =
result.repaint = buffer.restoreFocus()
case input.inputType
of INPUT_SEARCH:
result.repaint = buffer.setFocus(input)
result.readline = some(ReadLineResult(
prompt: "SEARCH: ",
value: input.value
))
of INPUT_TEXT, INPUT_PASSWORD:
result.repaint = buffer.setFocus(input)
result.readline = some(ReadLineResult(
prompt: "TEXT: ",
value: input.value,
hide: input.inputType == INPUT_PASSWORD
))
of INPUT_FILE:
result.repaint = buffer.setFocus(input)
var path = if input.file.isSome:
input.file.get.path.serialize_unicode()
else:
""
result.readline = some(ReadLineResult(
prompt: "Filename: ",
value: path
))
of INPUT_CHECKBOX:
input.checked = not input.checked
input.invalid = true
result.repaint = true
buffer.do_reshape()
of INPUT_RADIO:
for radio in input.radiogroup:
radio.checked = false
radio.invalid = true
input.checked = true
input.invalid = true
result.repaint = true
buffer.do_reshape()
of INPUT_RESET:
if input.form != nil:
input.form.reset()
result.repaint = true
buffer.do_reshape()
of INPUT_SUBMIT, INPUT_BUTTON:
if input.form != nil:
result.open = submitForm(input.form, input)
else:
result.repaint = buffer.restoreFocus()
proc click(buffer: Buffer, clickable: Element): ClickResult =
case clickable.tagType
of TAG_LABEL:
return buffer.click(HTMLLabelElement(clickable))
of TAG_SELECT:
return buffer.click(HTMLSelectElement(clickable))
of TAG_A:
return buffer.click(HTMLAnchorElement(clickable))
of TAG_OPTION:
return buffer.click(HTMLOptionElement(clickable))
of TAG_BUTTON:
return buffer.click(HTMLButtonElement(clickable))
of TAG_TEXTAREA:
return buffer.click(HTMLTextAreaElement(clickable))
of TAG_INPUT:
return buffer.click(HTMLInputElement(clickable))
else:
result.repaint = buffer.restoreFocus()
proc click*(buffer: Buffer, cursorx, cursory: int): ClickResult {.proxy.} =
if buffer.lines.len <= cursory: return
var called = false
var canceled = false
let clickable = buffer.getCursorClickable(cursorx, cursory)
if buffer.config.scripting:
let elem = buffer.getCursorElement(cursorx, cursory)
(called, canceled) = buffer.dispatchEvent("click", elem)
if called:
buffer.do_reshape()
if not canceled:
if clickable != nil:
var res = buffer.click(clickable)
res.repaint = called
return res
return ClickResult(repaint: called)
proc select*(buffer: Buffer, selected: seq[int]): ClickResult {.proxy.} =
if buffer.document.focus != nil and
buffer.document.focus of HTMLSelectElement:
let select = HTMLSelectElement(buffer.document.focus)
var i = 0
var j = 0
var repaint = false
for option in select.options:
var wasSelected = option.selected
if i < selected.len and selected[i] == j:
option.selected = true
inc i
else:
option.selected = false
if not repaint:
repaint = wasSelected != option.selected
inc j
return ClickResult(repaint: buffer.restoreFocus())
proc readCanceled*(buffer: Buffer): bool {.proxy.} =
return buffer.restoreFocus()
proc findAnchor*(buffer: Buffer, anchor: string): bool {.proxy.} =
return buffer.document != nil and buffer.document.findAnchor(anchor) != nil
type GetLinesResult* = tuple[
numLines: int,
lines: seq[SimpleFlexibleLine],
bgcolor: CellColor
]
proc getLines*(buffer: Buffer, w: Slice[int]): GetLinesResult {.proxy.} =
var w = w
if w.b < 0 or w.b > buffer.lines.high:
w.b = buffer.lines.high
#TODO this is horribly inefficient
for y in w:
var line = SimpleFlexibleLine(str: buffer.lines[y].str)
for f in buffer.lines[y].formats:
line.formats.add(SimpleFormatCell(format: f.format, pos: f.pos))
result.lines.add(line)
result.numLines = buffer.lines.len
result.bgcolor = buffer.bgcolor
macro bufferDispatcher(funs: static ProxyMap, buffer: Buffer,
cmd: BufferCommand, packetid: int) =
let switch = newNimNode(nnkCaseStmt)
switch.add(ident("cmd"))
for k, v in funs:
let ofbranch = newNimNode(nnkOfBranch)
ofbranch.add(v.ename)
let stmts = newStmtList()
let call = newCall(v.iname, buffer)
for i in 2 ..< v.params.len:
let param = v.params[i]
for i in 0 ..< param.len - 2:
let id = ident(param[i].strVal)
let typ = param[^2]
stmts.add(quote do:
when `typ` is FileHandle:
let `id` = `buffer`.pstream.recvFileHandle()
else:
var `id`: `typ`
`buffer`.pstream.sread(`id`))
call.add(id)
var rval: NimNode
if v.params[0].kind == nnkEmpty:
stmts.add(call)
else:
rval = ident("retval")
stmts.add(quote do:
let `rval` = `call`)
var resolve = newStmtList()
if rval == nil:
resolve.add(quote do:
let len = slen(`packetid`)
buffer.pstream.swrite(len)
buffer.pstream.swrite(`packetid`)
)
else:
resolve.add(quote do:
let len = slen(`packetid`) + slen(`rval`)
buffer.pstream.swrite(len)
buffer.pstream.swrite(`packetid`)
buffer.pstream.swrite(`rval`)
)
if v.istask:
let en = v.ename
stmts.add(quote do:
if buffer.savetask:
buffer.savetask = false
buffer.tasks[BufferCommand.`en`] = `packetid`
else:
`resolve`)
else:
stmts.add(resolve)
ofbranch.add(stmts)
switch.add(ofbranch)
return switch
proc readCommand(buffer: Buffer) =
var cmd: BufferCommand
buffer.pstream.sread(cmd)
var packetid: int
buffer.pstream.sread(packetid)
bufferDispatcher(ProxyFunctions, buffer, cmd, packetid)
proc handleRead(buffer: Buffer, fd: int): bool =
if fd == buffer.rfd:
try:
buffer.readCommand()
except ErrorConnectionReset, EOFError:
#eprint "EOF error", $buffer.url & "\nMESSAGE:",
# getCurrentExceptionMsg() & "\n",
# getStackTrace(getCurrentException())
return false
elif fd == buffer.fd:
buffer.onload()
elif fd in buffer.loader.connecting:
buffer.loader.onConnected(fd)
buffer.loader.onRead(fd)
if buffer.config.scripting:
buffer.window.runJSJobs()
elif fd in buffer.loader.ongoing:
buffer.loader.onRead(fd)
if buffer.config.scripting:
buffer.window.runJSJobs()
elif fd in buffer.loader.unregistered:
discard # ignore
else: assert false
true
proc handleError(buffer: Buffer, fd: int, err: OSErrorCode): bool =
if fd == buffer.rfd:
# Connection reset by peer, probably. Close the buffer.
return false
elif fd == buffer.fd:
buffer.onload()
elif fd in buffer.loader.connecting:
# probably shouldn't happen. TODO
assert false, $fd & ": " & $err
elif fd in buffer.loader.ongoing:
buffer.loader.onError(fd)
if buffer.config.scripting:
buffer.window.runJSJobs()
elif fd in buffer.loader.unregistered:
discard # ignore
else:
assert false, $fd & ": " & $err
true
proc runBuffer(buffer: Buffer) =
var alive = true
while alive:
let events = buffer.selector.select(-1)
for event in events:
if Read in event.events:
if not buffer.handleRead(event.fd):
alive = false
break
if Error in event.events:
if not buffer.handleError(event.fd, event.errorCode):
alive = false
break
if selectors.Event.Timer in event.events:
assert buffer.window != nil
let r = buffer.window.timeouts.runTimeoutFd(event.fd)
assert r
buffer.window.runJSJobs()
buffer.do_reshape()
buffer.loader.unregistered.setLen(0)
proc cleanup(buffer: Buffer) =
buffer.pstream.close()
buffer.ssock.close()
proc launchBuffer*(config: BufferConfig; url: URL; request: Request;
attrs: WindowAttributes; ishtml: bool; charsetStack: seq[Charset];
loader: FileLoader; ssock: ServerSocket) =
let socks = ssock.acceptSocketStream()
let buffer = Buffer(
attrs: attrs,
config: config,
estream: newFileStream(stderr),
ishtml: ishtml,
loader: loader,
needsBOMSniff: config.charsetOverride == CHARSET_UNKNOWN,
pstream: socks,
request: request,
rfd: socks.fd,
selector: newSelector[int](),
ssock: ssock,
url: url,
charsetStack: charsetStack,
cacheId: -1,
outputId: -1
)
buffer.charset = buffer.charsetStack.pop()
socks.read(buffer.loader.key)
var gbuffer {.global.}: Buffer
gbuffer = buffer
onSignal SIGTERM:
discard sig
gbuffer.cleanup()
exitnow(1)
loader.registerFun = proc(fd: int) =
buffer.selector.registerHandle(fd, {Read}, 0)
loader.unregisterFun = proc(fd: int) =
buffer.selector.unregister(fd)
buffer.selector.registerHandle(buffer.rfd, {Read}, 0)
buffer.setHTML()
buffer.runBuffer()
buffer.cleanup()
quit(0)
|