ul-sys 1.3.1

Bindings to Ultralight Framework (Ultralight, AppCore)
Documentation
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
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
///
/// @file CAPI.h
///
/// @brief The C-language API for Ultralight
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2020 Ultralight, Inc. All rights reserved.
///
#ifndef ULTRALIGHT_CAPI_H
#define ULTRALIGHT_CAPI_H

#ifndef __cplusplus
//#include <stdbool.h>
#endif

#include <stddef.h>
#include "JavaScriptCore/JavaScript.h"
#ifdef __OBJC__
#import <AppKit/NSEvent.h>
#endif

#if defined(__WIN32__) || defined(_WIN32)
#  if defined(ULTRALIGHT_IMPLEMENTATION)
#    define ULExport __declspec(dllexport)
#  else
#    define ULExport __declspec(dllimport)
#  endif
#define _thread_local __declspec(thread)
#ifndef _NATIVE_WCHAR_T_DEFINED
#define DISABLE_NATIVE_WCHAR_T
typedef unsigned short ULChar16;
#else
typedef wchar_t ULChar16;
#endif
#else
#  define ULExport __attribute__((visibility("default")))
#define _thread_local __thread
typedef unsigned short ULChar16;
#endif

#ifdef __cplusplus
extern "C" {
#endif

typedef struct C_Config* ULConfig;
typedef struct C_Renderer* ULRenderer;
typedef struct C_Session* ULSession;
typedef struct C_ViewConfig* ULViewConfig;
typedef struct C_View* ULView;
typedef struct C_Bitmap* ULBitmap;
typedef struct C_String* ULString;
typedef struct C_Buffer* ULBuffer;
typedef struct C_KeyEvent* ULKeyEvent;
typedef struct C_MouseEvent* ULMouseEvent;
typedef struct C_ScrollEvent* ULScrollEvent;
typedef struct C_Surface* ULSurface;
typedef struct C_Surface* ULBitmapSurface;

typedef enum {
  kMessageSource_XML = 0,
  kMessageSource_JS,
  kMessageSource_Network,
  kMessageSource_ConsoleAPI,
  kMessageSource_Storage,
  kMessageSource_AppCache,
  kMessageSource_Rendering,
  kMessageSource_CSS,
  kMessageSource_Security,
  kMessageSource_ContentBlocker,
  kMessageSource_Other,
} ULMessageSource;

typedef enum {
  kMessageLevel_Log = 1,
  kMessageLevel_Warning = 2,
  kMessageLevel_Error = 3,
  kMessageLevel_Debug = 4,
  kMessageLevel_Info = 5,
} ULMessageLevel;

typedef enum {
  kCursor_Pointer = 0,
  kCursor_Cross,
  kCursor_Hand,
  kCursor_IBeam,
  kCursor_Wait,
  kCursor_Help,
  kCursor_EastResize,
  kCursor_NorthResize,
  kCursor_NorthEastResize,
  kCursor_NorthWestResize,
  kCursor_SouthResize,
  kCursor_SouthEastResize,
  kCursor_SouthWestResize,
  kCursor_WestResize,
  kCursor_NorthSouthResize,
  kCursor_EastWestResize,
  kCursor_NorthEastSouthWestResize,
  kCursor_NorthWestSouthEastResize,
  kCursor_ColumnResize,
  kCursor_RowResize,
  kCursor_MiddlePanning,
  kCursor_EastPanning,
  kCursor_NorthPanning,
  kCursor_NorthEastPanning,
  kCursor_NorthWestPanning,
  kCursor_SouthPanning,
  kCursor_SouthEastPanning,
  kCursor_SouthWestPanning,
  kCursor_WestPanning,
  kCursor_Move,
  kCursor_VerticalText,
  kCursor_Cell,
  kCursor_ContextMenu,
  kCursor_Alias,
  kCursor_Progress,
  kCursor_NoDrop,
  kCursor_Copy,
  kCursor_None,
  kCursor_NotAllowed,
  kCursor_ZoomIn,
  kCursor_ZoomOut,
  kCursor_Grab,
  kCursor_Grabbing,
  kCursor_Custom
} ULCursor;

typedef enum {
  ///
  /// Alpha channel only, 8-bits per pixel.
  ///
  /// Encoding: 8-bits per channel, unsigned normalized.
  ///
  /// Color-space: Linear (no gamma), alpha-coverage only.
  ///
  kBitmapFormat_A8_UNORM,

  ///
  /// Blue Green Red Alpha channels, 32-bits per pixel.
  ///
  /// Encoding: 8-bits per channel, unsigned normalized.
  ///
  /// Color-space: sRGB gamma with premultiplied linear alpha channel.
  ///
  kBitmapFormat_BGRA8_UNORM_SRGB
} ULBitmapFormat;

typedef enum {
  ///
  /// Key-Down event type. (Does not trigger accelerator commands in WebCore)
  ///
  /// @NOTE: You should probably use RawKeyDown instead when a physical key
  ///        is pressed. This member is only here for historic compatibility
  ///        with WebCore's key event types.
  ///
  kKeyEventType_KeyDown,

  ///
  /// Key-Up event type. Use this when a physical key is released.
  ///
  kKeyEventType_KeyUp,

  ///
  /// Raw Key-Down type. Use this when a physical key is pressed.
  ///
  /// @NOTE: You should use RawKeyDown for physical key presses since it
  ///        allows WebCore to do additional command translation.
  ///
  kKeyEventType_RawKeyDown,

  ///
  /// Character input event type. Use this when the OS generates text from
  /// a physical key being pressed (eg, WM_CHAR on Windows).
  ///
  kKeyEventType_Char,
} ULKeyEventType;

typedef enum {
  kMouseEventType_MouseMoved,
  kMouseEventType_MouseDown,
  kMouseEventType_MouseUp,
} ULMouseEventType;

typedef enum {
  kMouseButton_None = 0,
  kMouseButton_Left,
  kMouseButton_Middle,
  kMouseButton_Right,
} ULMouseButton;

typedef enum {
  kScrollEventType_ScrollByPixel,
  kScrollEventType_ScrollByPage,
} ULScrollEventType;

typedef enum {
  kFaceWinding_Clockwise,
  kFaceWindow_CounterClockwise,
} ULFaceWinding;

typedef enum {
  ///
  /// Lighter hinting algorithm-- glyphs are slightly fuzzier but better
  /// resemble their original shape. This is achieved by snapping glyphs to the
  /// pixel grid only vertically which better preserves inter-glyph spacing.
  ///
  kFontHinting_Smooth,

  ///
  /// Default hinting algorithm-- offers a good balance between sharpness and
  /// shape at smaller font sizes.
  ///
  kFontHinting_Normal,

  ///
  /// Strongest hinting algorithm-- outputs only black/white glyphs. The result
  /// is usually unpleasant if the underlying TTF does not contain hints for
  /// this type of rendering.
  ///
  kFontHinting_Monochrome,
} ULFontHinting;

typedef struct {
  float left;
  float top;
  float right;
  float bottom;
} ULRect;

typedef struct {
  int left;
  int top;
  int right;
  int bottom;
} ULIntRect;

typedef struct {
  bool is_empty;
  unsigned int width;
  unsigned int height;
  unsigned int texture_id;
  unsigned int texture_width;
  unsigned int texture_height;
  ULBitmapFormat texture_format;
  ULRect uv_coords;
  unsigned int render_buffer_id;
} ULRenderTarget;


/******************************************************************************
 * API Note:
 *
 * You should only destroy objects that you explicitly create. Do not destroy
 * any objects returned from the API or callbacks unless otherwise noted.
 *****************************************************************************/

/******************************************************************************
 * Version
 *****************************************************************************/

///
/// Get the version string of the library in MAJOR.MINOR.PATCH format.
///
ULExport const char* ulVersionString();

///
/// Get the numeric major version of the library.
///
ULExport unsigned int ulVersionMajor();

///
/// Get the numeric minor version of the library.
///
ULExport unsigned int ulVersionMinor();

///
/// Get the numeric patch version of the library.
///
ULExport unsigned int ulVersionPatch();

/******************************************************************************
 * Config
 *****************************************************************************/

///
/// Create config with default values (see <Ultralight/platform/Config.h>).
///
ULExport ULConfig ulCreateConfig();

///
/// Destroy config.
///
ULExport void ulDestroyConfig(ULConfig config);

///
/// Set the file path to a writable directory that will be used to store
/// cookies, cached resources, and other persistent data.
///
ULExport void ulConfigSetCachePath(ULConfig config, ULString cache_path);

///
/// The winding order for front-facing triangles. @see FaceWinding
///
/// Note: This is only used with custom GPUDrivers
///
ULExport void ulConfigSetFaceWinding(ULConfig config, ULFaceWinding winding);

///
/// The hinting algorithm to use when rendering fonts. (Default = kFontHinting_Normal)
/// @see ULFontHinting
///
ULExport void ulConfigSetFontHinting(ULConfig config, ULFontHinting font_hinting);

///
/// The gamma to use when compositing font glyphs, change this value to
/// adjust contrast (Adobe and Apple prefer 1.8, others may prefer 2.2).
/// (Default = 1.8)
///
ULExport void ulConfigSetFontGamma(ULConfig config, double font_gamma);

///
/// Set user stylesheet (CSS) (Default = Empty).
///
ULExport void ulConfigSetUserStylesheet(ULConfig config, ULString css_string);

///
/// Set whether or not we should continuously repaint any Views or compositor
/// layers, regardless if they are dirty or not. This is mainly used to
/// diagnose painting/shader issues. (Default = False)
///
ULExport void ulConfigSetForceRepaint(ULConfig config, bool enabled);

///
/// Set the amount of time to wait before triggering another repaint when a
/// CSS animation is active. (Default = 1.0 / 60.0)
///
ULExport void ulConfigSetAnimationTimerDelay(ULConfig config, double delay);

///
/// When a smooth scroll animation is active, the amount of time (in seconds)
/// to wait before triggering another repaint. Default is 60 Hz.
///
ULExport void ulConfigSetScrollTimerDelay(ULConfig config, double delay);

///
/// The amount of time (in seconds) to wait before running the recycler (will
/// attempt to return excess memory back to the system). (Default = 4.0)
///
ULExport void ulConfigSetRecycleDelay(ULConfig config, double delay);

///
/// Set the size of WebCore's memory cache for decoded images, scripts, and
/// other assets in bytes. (Default = 64 * 1024 * 1024)
///
ULExport void ulConfigSetMemoryCacheSize(ULConfig config, unsigned int size);

///
/// Set the number of pages to keep in the cache. (Default = 0)
///
ULExport void ulConfigSetPageCacheSize(ULConfig config, unsigned int size);

///
/// JavaScriptCore tries to detect the system's physical RAM size to set
/// reasonable allocation limits. Set this to anything other than 0 to
/// override the detected value. Size is in bytes.
///
/// This can be used to force JavaScriptCore to be more conservative with
/// its allocation strategy (at the cost of some performance).
///
ULExport void ulConfigSetOverrideRAMSize(ULConfig config, unsigned int size);

///
/// The minimum size of large VM heaps in JavaScriptCore. Set this to a
/// lower value to make these heaps start with a smaller initial value.
///
ULExport void ulConfigSetMinLargeHeapSize(ULConfig config, unsigned int size);

///
/// The minimum size of small VM heaps in JavaScriptCore. Set this to a
/// lower value to make these heaps start with a smaller initial value.
///
ULExport void ulConfigSetMinSmallHeapSize(ULConfig config, unsigned int size);

/******************************************************************************
 * Renderer
 *****************************************************************************/

///
/// Create the Ultralight Renderer directly.
///
/// Unlike ulCreateApp(), this does not use any native windows for drawing
/// and allows you to manage your own runloop and painting. This method is
/// recommended for those wishing to integrate the library into a game.
///
/// This singleton manages the lifetime of all Views and coordinates all
/// painting, rendering, network requests, and event dispatch.
///
/// You should only call this once per process lifetime.
///
/// You shoud set up your platform handlers (eg, ulPlatformSetLogger,
/// ulPlatformSetFileSystem, etc.) before calling this.
///
/// You will also need to define a font loader before calling this--
/// as of this writing (v1.2) the only way to do this in C API is by calling
/// ulEnablePlatformFontLoader() (available in <AppCore/CAPI.h>).
///
/// @NOTE:  You should not call this if you are using ulCreateApp(), it
///         creates its own renderer and provides default implementations for
///         various platform handlers automatically.
///
ULExport ULRenderer ulCreateRenderer(ULConfig config);

///
/// Destroy the renderer.
///
ULExport void ulDestroyRenderer(ULRenderer renderer);

///
/// Update timers and dispatch internal callbacks (JavaScript and network).
///
ULExport void ulUpdate(ULRenderer renderer);

///
/// Render all active Views.
///
ULExport void ulRender(ULRenderer renderer);

///
/// Attempt to release as much memory as possible. Don't call this from any
/// callbacks or driver code.
///
ULExport void ulPurgeMemory(ULRenderer renderer);

///
/// Print detailed memory usage statistics to the log.
/// (@see ulPlatformSetLogger)
///
ULExport void ulLogMemoryUsage(ULRenderer renderer);

/******************************************************************************
 * Session
 *****************************************************************************/

///
/// Create a Session to store local data in (such as cookies, local storage,
/// application cache, indexed db, etc).
///
ULExport ULSession ulCreateSession(ULRenderer renderer, bool is_persistent,
                                   ULString name);

///
/// Destroy a Session.
///
ULExport void ulDestroySession(ULSession session);

///
/// Get the default session (persistent session named "default").
///
/// @note  This session is owned by the Renderer, you shouldn't destroy it.
///
ULExport ULSession ulDefaultSession(ULRenderer renderer);

///
/// Whether or not is persistent (backed to disk).
///
ULExport bool ulSessionIsPersistent(ULSession session);

///
/// Unique name identifying the session (used for unique disk path).
///
ULExport ULString ulSessionGetName(ULSession session);

///
/// Unique numeric Id for the session.
///
ULExport unsigned long long ulSessionGetId(ULSession session);

///
/// The disk path to write to (used by persistent sessions only).
///
ULExport ULString ulSessionGetDiskPath(ULSession session);

/******************************************************************************
 * ViewConfig
 *****************************************************************************/

///
/// Create view configuration with default values (see <Ultralight/platform/View.h>).
///
ULExport ULViewConfig ulCreateViewConfig();

///
/// Destroy view configuration.
///
ULExport void ulDestroyViewConfig(ULViewConfig config);

///
/// When enabled, the View will be rendered to an offscreen GPU texture
/// using the GPU driver set in ulPlatformSetGPUDriver. You can fetch
/// details for the texture via ulViewGetRenderTarget.
///
/// When disabled (the default), the View will be rendered to an offscreen
/// pixel buffer surface. This pixel buffer can optionally be provided by the user--
/// for more info see ulViewGetSurface.
///
ULExport void ulViewConfigSetIsAccelerated(ULViewConfig config, bool is_accelerated);

///
/// Set whether images should be enabled (Default = True).
///
ULExport void ulViewConfigSetIsTransparent(ULViewConfig config, bool is_transparent);

///
/// Set the amount that the application DPI has been scaled, used for
/// scaling device coordinates to pixels and oversampling raster shapes
/// (Default = 1.0).
///
ULExport void ulViewConfigSetInitialDeviceScale(ULViewConfig config, double initial_device_scale);

ULExport void ulViewConfigSetInitialFocus(ULViewConfig config, bool is_focused);

///
/// Set whether images should be enabled (Default = True).
///
ULExport void ulViewConfigSetEnableImages(ULViewConfig config, bool enabled);

///
/// Set whether JavaScript should be eanbled (Default = True).
///
ULExport void ulViewConfigSetEnableJavaScript(ULViewConfig config, bool enabled);

///
/// Set default font-family to use (Default = Times New Roman).
///
ULExport void ulViewConfigSetFontFamilyStandard(ULViewConfig config, ULString font_name);

///
/// Set default font-family to use for fixed fonts, eg <pre> and <code>
/// (Default = Courier New).
///
ULExport void ulViewConfigSetFontFamilyFixed(ULViewConfig config, ULString font_name);

///
/// Set default font-family to use for serif fonts (Default = Times New Roman).
///
ULExport void ulViewConfigSetFontFamilySerif(ULViewConfig config, ULString font_name);

///
/// Set default font-family to use for sans-serif fonts (Default = Arial).
///
ULExport void ulViewConfigSetFontFamilySansSerif(ULViewConfig config, ULString font_name);

///
/// Set user agent string (See <Ultralight/platform/Config.h> for the default).
///
ULExport void ulViewConfigSetUserAgent(ULViewConfig config, ULString agent_string);

/******************************************************************************
 * View
 *****************************************************************************/

///
/// Create a View with certain size (in pixels).
///
/// @note  You can pass null to 'session' to use the default session.
///
ULExport ULView ulCreateView(ULRenderer renderer, unsigned int width, unsigned int height,
                             ULViewConfig view_config, ULSession session);

///
/// Destroy a View.
///
ULExport void ulDestroyView(ULView view);

///
/// Get current URL.
///
/// @note Don't destroy the returned string, it is owned by the View.
///
ULExport ULString ulViewGetURL(ULView view);

///
/// Get current title.
///
/// @note Don't destroy the returned string, it is owned by the View.
///
ULExport ULString ulViewGetTitle(ULView view);

///
/// Get the width, in pixels.
///
ULExport unsigned int ulViewGetWidth(ULView view);

///
/// Get the height, in pixels.
///
ULExport unsigned int ulViewGetHeight(ULView view);

///
/// Check if main frame is loading.
///
ULExport bool ulViewIsLoading(ULView view);

///
/// Get the RenderTarget for the View.
///
/// @note  Only valid when the GPU renderer is enabled in Config.
///
ULExport ULRenderTarget ulViewGetRenderTarget(ULView view);

///
/// Get the Surface for the View (native pixel buffer container).
///
/// @note  Only valid when the GPU renderer is disabled in Config.
///
///        (Will return a nullptr when the GPU renderer is enabled.)
///
///        The default Surface is BitmapSurface but you can provide your
///        own Surface implementation via ulPlatformSetSurfaceDefinition.
///
///        When using the default Surface, you can retrieve the underlying
///        bitmap by casting ULSurface to ULBitmapSurface and calling
///        ulBitmapSurfaceGetBitmap().
///
ULExport ULSurface ulViewGetSurface(ULView view);

///
/// Load a raw string of HTML.
///
ULExport void ulViewLoadHTML(ULView view, ULString html_string);

///
/// Load a URL into main frame.
///
ULExport void ulViewLoadURL(ULView view, ULString url_string);

///
/// Resize view to a certain width and height (in pixels).
///
ULExport void ulViewResize(ULView view, unsigned int width,
                           unsigned int height);

///
/// Acquire the page's JSContext for use with JavaScriptCore API.
///
/// @note  This call locks the context for the current thread. You should
///        call ulViewUnlockJSContext() after using the context so other
///        worker threads can modify JavaScript state.
///
/// @note  The lock is recusive, it's okay to call this multiple times as long
///        as you call ulViewUnlockJSContext() the same number of times.
///
ULExport JSContextRef ulViewLockJSContext(ULView view);

///
/// Unlock the page's JSContext after a previous call to ulViewLockJSContext().
///
ULExport void ulViewUnlockJSContext(ULView view);

///
/// Evaluate a string of JavaScript and return result.
///
/// @param  js_string  The string of JavaScript to evaluate.
///
/// @param  exception  The address of a ULString to store a description of the
///                    last exception. Pass NULL to ignore this. Don't destroy
///                    the exception string returned, it's owned by the View.
///
/// @note Don't destroy the returned string, it's owned by the View. This value
///       is reset with every call-- if you want to retain it you should copy
///       the result to a new string via ulCreateStringFromCopy().
///
/// @note An example of using this API:
///       <pre>
///         ULString script = ulCreateString("1 + 1");
///         ULString exception;
///         ULString result = ulViewEvaluateScript(view, script, &exception);
///         /* Use the result ("2") and exception description (if any) here. */
///         ulDestroyString(script);
///       </pre>
///
ULExport ULString ulViewEvaluateScript(ULView view, ULString js_string, ULString* exception);

///
/// Check if can navigate backwards in history.
///
ULExport bool ulViewCanGoBack(ULView view);

///
/// Check if can navigate forwards in history.
///
ULExport bool ulViewCanGoForward(ULView view);

///
/// Navigate backwards in history.
///
ULExport void ulViewGoBack(ULView view);

///
/// Navigate forwards in history.
///
ULExport void ulViewGoForward(ULView view);

///
/// Navigate to arbitrary offset in history.
///
ULExport void ulViewGoToHistoryOffset(ULView view, int offset);

///
/// Reload current page.
///
ULExport void ulViewReload(ULView view);

///
/// Stop all page loads.
///
ULExport void ulViewStop(ULView view);

///
/// Give focus to the View.
///
/// You should call this to give visual indication that the View has input
/// focus (changes active text selection colors, for example).
///
ULExport void ulViewFocus(ULView view);

///
/// Remove focus from the View and unfocus any focused input elements.
///
/// You should call this to give visual indication that the View has lost
/// input focus.
///
ULExport void ulViewUnfocus(ULView view);

///
/// Whether or not the View has focus.
///
ULExport bool ulViewHasFocus(ULView view);

///
/// Whether or not the View has an input element with visible keyboard focus
/// (indicated by a blinking caret).
///
/// You can use this to decide whether or not the View should consume
/// keyboard input events (useful in games with mixed UI and key handling).
///
ULExport bool ulViewHasInputFocus(ULView view);

///
/// Fire a keyboard event.
///
ULExport void ulViewFireKeyEvent(ULView view, ULKeyEvent key_event);

///
/// Fire a mouse event.
///
ULExport void ulViewFireMouseEvent(ULView view, ULMouseEvent mouse_event);

///
/// Fire a scroll event.
///
ULExport void ulViewFireScrollEvent(ULView view, ULScrollEvent scroll_event);

typedef void
(*ULChangeTitleCallback) (void* user_data, ULView caller, ULString title);

///
/// Set callback for when the page title changes.
///
ULExport void ulViewSetChangeTitleCallback(ULView view,
                                           ULChangeTitleCallback callback,
                                           void* user_data);

typedef void
(*ULChangeURLCallback) (void* user_data, ULView caller, ULString url);

///
/// Set callback for when the page URL changes.
///
ULExport void ulViewSetChangeURLCallback(ULView view,
                                         ULChangeURLCallback callback,
                                         void* user_data);

typedef void
(*ULChangeTooltipCallback) (void* user_data, ULView caller, ULString tooltip);

///
/// Set callback for when the tooltip changes (usually result of a mouse hover).
///
ULExport void ulViewSetChangeTooltipCallback(ULView view,
                                             ULChangeTooltipCallback callback,
                                             void* user_data);

typedef void
(*ULChangeCursorCallback) (void* user_data, ULView caller, ULCursor cursor);

///
/// Set callback for when the mouse cursor changes.
///
ULExport void ulViewSetChangeCursorCallback(ULView view,
                                            ULChangeCursorCallback callback,
                                            void* user_data);

typedef void
(*ULAddConsoleMessageCallback) (void* user_data, ULView caller,
                                ULMessageSource source, ULMessageLevel level,
                                ULString message, unsigned int line_number,
                                unsigned int column_number,
                                ULString source_id);

///
/// Set callback for when a message is added to the console (useful for
/// JavaScript / network errors and debugging).
///
ULExport void ulViewSetAddConsoleMessageCallback(ULView view,
                                          ULAddConsoleMessageCallback callback,
                                          void* user_data);

typedef ULView
(*ULCreateChildViewCallback) (void* user_data, ULView caller,
  ULString opener_url, ULString target_url, bool is_popup,
  ULIntRect popup_rect);

///
/// Set callback for when the page wants to create a new View.
///
/// This is usually the result of a user clicking a link with target="_blank"
/// or by JavaScript calling window.open(url).
///
/// To allow creation of these new Views, you should create a new View in
/// this callback, resize it to your container,
/// and return it. You are responsible for displaying the returned View.
///
/// You should return NULL if you want to block the action.
///
ULExport void ulViewSetCreateChildViewCallback(ULView view,
                                            ULCreateChildViewCallback callback,
                                            void* user_data);

typedef void
(*ULBeginLoadingCallback) (void* user_data, ULView caller,
  unsigned long long frame_id, bool is_main_frame, ULString url);

///
/// Set callback for when the page begins loading a new URL into a frame.
///
ULExport void ulViewSetBeginLoadingCallback(ULView view,
                                            ULBeginLoadingCallback callback,
                                            void* user_data);

typedef void
(*ULFinishLoadingCallback) (void* user_data, ULView caller,
  unsigned long long frame_id, bool is_main_frame, ULString url);

///
/// Set callback for when the page finishes loading a URL into a frame.
///
ULExport void ulViewSetFinishLoadingCallback(ULView view,
                                             ULFinishLoadingCallback callback,
                                             void* user_data);

typedef void
(*ULFailLoadingCallback) (void* user_data, ULView caller,
  unsigned long long frame_id, bool is_main_frame, ULString url,
  ULString description, ULString error_domain, int error_code);

///
/// Set callback for when an error occurs while loading a URL into a frame.
///
ULExport void ulViewSetFailLoadingCallback(ULView view,
                                           ULFailLoadingCallback callback,
                                           void* user_data);

typedef void
(*ULWindowObjectReadyCallback) (void* user_data, ULView caller,
  unsigned long long frame_id, bool is_main_frame, ULString url);

///
/// Set callback for when the JavaScript window object is reset for a new
/// page load.
///
/// This is called before any scripts are executed on the page and is the
/// earliest time to setup any initial JavaScript state or bindings.
///
/// The document is not guaranteed to be loaded/parsed at this point. If
/// you need to make any JavaScript calls that are dependent on DOM elements
/// or scripts on the page, use DOMReady instead.
///
/// The window object is lazily initialized (this will not be called on pages
/// with no scripts).
///
ULExport void ulViewSetWindowObjectReadyCallback(ULView view,
                                          ULWindowObjectReadyCallback callback,
                                          void* user_data);

typedef void
(*ULDOMReadyCallback) (void* user_data, ULView caller,
  unsigned long long frame_id, bool is_main_frame, ULString url);

///
/// Set callback for when all JavaScript has been parsed and the document is
/// ready.
///
/// This is the best time to make any JavaScript calls that are dependent on
/// DOM elements or scripts on the page.
///
ULExport void ulViewSetDOMReadyCallback(ULView view,
                                        ULDOMReadyCallback callback,
                                        void* user_data);

typedef void
(*ULUpdateHistoryCallback) (void* user_data, ULView caller);

///
/// Set callback for when the history (back/forward state) is modified.
///
ULExport void ulViewSetUpdateHistoryCallback(ULView view,
                                             ULUpdateHistoryCallback callback,
                                             void* user_data);

///
/// Set whether or not a view should be repainted during the next call to
/// ulRender.
///
/// @note  This flag is automatically set whenever the page content changes
///        but you can set it directly in case you need to force a repaint.
///
ULExport void ulViewSetNeedsPaint(ULView view, bool needs_paint);

///
/// Whether or not a view should be painted during the next call to ulRender.
///
ULExport bool ulViewGetNeedsPaint(ULView view);

///
/// Create an inspector for this View, this is useful for debugging and
/// inspecting pages locally. This will only succeed if you have the
/// inspector assets in your filesystem-- the inspector will look for
/// file:///inspector/Main.html when it loads.
///
/// @note  The initial dimensions of the returned View are 10x10, you should
///        call ulViewResize on the returned View to resize it to your desired
///        dimensions.
///
/// @note  You will need to call ulDestroyView on the returned instance
///        when you're done using it.
///
ULExport ULView ulViewCreateInspectorView(ULView view);

/******************************************************************************
 * String
 *****************************************************************************/

///
/// Create string from null-terminated ASCII C-string.
///
ULExport ULString ulCreateString(const char* str);

///
/// Create string from UTF-8 buffer.
///
ULExport ULString ulCreateStringUTF8(const char* str, size_t len);

///
/// Create string from UTF-16 buffer.
///
ULExport ULString ulCreateStringUTF16(ULChar16* str, size_t len);

///
/// Create string from copy of existing string.
///
ULExport ULString ulCreateStringFromCopy(ULString str);

///
/// Destroy string (you should destroy any strings you explicitly Create).
///
ULExport void ulDestroyString(ULString str);

///
/// Get internal UTF-16 buffer data.
///
ULExport ULChar16* ulStringGetData(ULString str);

///
/// Get length in UTF-16 characters.
///
ULExport size_t ulStringGetLength(ULString str);

///
/// Whether this string is empty or not.
///
ULExport bool ulStringIsEmpty(ULString str);

///
/// Replaces the contents of 'str' with the contents of 'new_str'
///
ULExport void ulStringAssignString(ULString str, ULString new_str);

///
/// Replaces the contents of 'str' with the contents of a C-string.
///
ULExport void ulStringAssignCString(ULString str, const char* c_str);

/******************************************************************************
 * Bitmap
 *****************************************************************************/

///
/// Create empty bitmap.
///
ULExport ULBitmap ulCreateEmptyBitmap();

///
/// Create bitmap with certain dimensions and pixel format.
///
ULExport ULBitmap ulCreateBitmap(unsigned int width, unsigned int height,
                                 ULBitmapFormat format);

///
/// Create bitmap from existing pixel buffer. @see Bitmap for help using
/// this function.
///
ULExport ULBitmap ulCreateBitmapFromPixels(unsigned int width,
                                           unsigned int height,
                                           ULBitmapFormat format,
                                           unsigned int row_bytes,
                                           const void* pixels, size_t size,
                                           bool should_copy);

///
/// Create bitmap from copy.
///
ULExport ULBitmap ulCreateBitmapFromCopy(ULBitmap existing_bitmap);

///
/// Destroy a bitmap (you should only destroy Bitmaps you have explicitly
/// created via one of the creation functions above.
///
ULExport void ulDestroyBitmap(ULBitmap bitmap);

///
/// Get the width in pixels.
///
ULExport unsigned int ulBitmapGetWidth(ULBitmap bitmap);

///
/// Get the height in pixels.
///
ULExport unsigned int ulBitmapGetHeight(ULBitmap bitmap);

///
/// Get the pixel format.
///
ULExport ULBitmapFormat ulBitmapGetFormat(ULBitmap bitmap);

///
/// Get the bytes per pixel.
///
ULExport unsigned int ulBitmapGetBpp(ULBitmap bitmap);

///
/// Get the number of bytes per row.
///
ULExport unsigned int ulBitmapGetRowBytes(ULBitmap bitmap);

///
/// Get the size in bytes of the underlying pixel buffer.
///
ULExport size_t ulBitmapGetSize(ULBitmap bitmap);

///
/// Whether or not this bitmap owns its own pixel buffer.
///
ULExport bool ulBitmapOwnsPixels(ULBitmap bitmap);

///
/// Lock pixels for reading/writing, returns pointer to pixel buffer.
///
ULExport void* ulBitmapLockPixels(ULBitmap bitmap);

///
/// Unlock pixels after locking.
///
ULExport void ulBitmapUnlockPixels(ULBitmap bitmap);

///
/// Get raw pixel buffer-- you should only call this if Bitmap is already
/// locked.
///
ULExport void* ulBitmapRawPixels(ULBitmap bitmap);

///
/// Whether or not this bitmap is empty.
///
ULExport bool ulBitmapIsEmpty(ULBitmap bitmap);

///
/// Reset bitmap pixels to 0.
///
ULExport void ulBitmapErase(ULBitmap bitmap);

///
/// Write bitmap to a PNG on disk.
///
ULExport bool ulBitmapWritePNG(ULBitmap bitmap, const char* path);

///
/// This converts a BGRA bitmap to RGBA bitmap and vice-versa by swapping
/// the red and blue channels.
///
ULExport void ulBitmapSwapRedBlueChannels(ULBitmap bitmap);

/******************************************************************************
* Key Event
******************************************************************************/

///
/// Create a key event, @see KeyEvent for help with the following parameters.
///
ULExport ULKeyEvent ulCreateKeyEvent(ULKeyEventType type,
                                     unsigned int modifiers,
                                     int virtual_key_code, int native_key_code,
                                     ULString text, ULString unmodified_text,
                                     bool is_keypad, bool is_auto_repeat,
                                     bool is_system_key);

#ifdef _WIN32
///
/// Create a key event from native Windows event.
///
ULExport ULKeyEvent ulCreateKeyEventWindows(ULKeyEventType type,
                                            uintptr_t wparam, intptr_t lparam,
                                            bool is_system_key);
#endif

#ifdef __OBJC__
///
/// Create a key event from native macOS event.
///
ULExport ULKeyEvent ulCreateKeyEventMacOS(NSEvent* evt);
#endif

///
/// Destroy a key event.
///
ULExport void ulDestroyKeyEvent(ULKeyEvent evt);

/******************************************************************************
 * Mouse Event
 *****************************************************************************/

///
/// Create a mouse event, @see MouseEvent for help using this function.
///
ULExport ULMouseEvent ulCreateMouseEvent(ULMouseEventType type, int x, int y,
                                         ULMouseButton button);

///
/// Destroy a mouse event.
///
ULExport void ulDestroyMouseEvent(ULMouseEvent evt);

/******************************************************************************
 * Scroll Event
 *****************************************************************************/

///
/// Create a scroll event, @see ScrollEvent for help using this function.
///
ULExport ULScrollEvent ulCreateScrollEvent(ULScrollEventType type, int delta_x,
                                           int delta_y);

///
/// Destroy a scroll event.
///
ULExport void ulDestroyScrollEvent(ULScrollEvent evt);

/******************************************************************************
 * Rect
 *****************************************************************************/

///
/// Whether or not a ULRect is empty (all members equal to 0)
///
ULExport bool ulRectIsEmpty(ULRect rect);

///
/// Create an empty ULRect (all members equal to 0)
///
ULExport ULRect ulRectMakeEmpty();

/******************************************************************************
 * IntRect
 *****************************************************************************/

 ///
 /// Whether or not a ULIntRect is empty (all members equal to 0)
 ///
ULExport bool ulIntRectIsEmpty(ULIntRect rect);

///
/// Create an empty ULIntRect (all members equal to 0)
///
ULExport ULIntRect ulIntRectMakeEmpty();

/******************************************************************************
 * Surface
 *****************************************************************************/

///
/// Width (in pixels).
///
ULExport unsigned int ulSurfaceGetWidth(ULSurface surface);

///
/// Height (in pixels).
///
ULExport unsigned int ulSurfaceGetHeight(ULSurface surface);

///
/// Number of bytes between rows (usually width * 4)
///
ULExport unsigned int ulSurfaceGetRowBytes(ULSurface surface);

///
/// Size in bytes.
///
ULExport size_t ulSurfaceGetSize(ULSurface surface);

///
/// Lock the pixel buffer and get a pointer to the beginning of the data
/// for reading/writing.
///
/// Native pixel format is premultiplied BGRA 32-bit (8 bits per channel).
///
ULExport void* ulSurfaceLockPixels(ULSurface surface);

///
/// Unlock the pixel buffer.
///
ULExport void ulSurfaceUnlockPixels(ULSurface surface);

///
/// Resize the pixel buffer to a certain width and height (both in pixels).
///
/// This should never be called while pixels are locked.
///
ULExport void ulSurfaceResize(ULSurface surface, unsigned int width, unsigned int height);

///
/// Set the dirty bounds to a certain value.
///
/// This is called after the Renderer paints to an area of the pixel buffer.
/// (The new value will be joined with the existing dirty_bounds())
///
ULExport void ulSurfaceSetDirtyBounds(ULSurface surface, ULIntRect bounds);

///
/// Get the dirty bounds.
///
/// This value can be used to determine which portion of the pixel buffer has
/// been updated since the last call to ulSurfaceClearDirtyBounds().
///
/// The general algorithm to determine if a Surface needs display is:
/// <pre>
///   if (!ulIntRectIsEmpty(ulSurfaceGetDirtyBounds(surface))) {
///       // Surface pixels are dirty and needs display.
///       // Cast Surface to native Surface and use it here (pseudo code)
///       DisplaySurface(surface);
///
///       // Once you're done, clear the dirty bounds:
///       ulSurfaceClearDirtyBounds(surface);
///  }
///  </pre>
///
ULExport ULIntRect ulSurfaceGetDirtyBounds(ULSurface surface);

///
/// Clear the dirty bounds.
///
/// You should call this after you're done displaying the Surface.
///
ULExport void ulSurfaceClearDirtyBounds(ULSurface surface);

///
/// Get the underlying user data pointer (this is only valid if you have
/// set a custom surface implementation via ulPlatformSetSurfaceDefinition).
///
/// This will return nullptr if this surface is the default ULBitmapSurface.
///
ULExport void* ulSurfaceGetUserData(ULSurface surface);

/******************************************************************************
 * BitmapSurface
 *****************************************************************************/

///
/// Get the underlying Bitmap from the default Surface.
///
/// @note  Do not call ulDestroyBitmap() on the returned value, it is owned
///        by the surface.
///
ULExport ULBitmap ulBitmapSurfaceGetBitmap(ULBitmapSurface surface);

/******************************************************************************
 * Surface Definition
 *****************************************************************************/

///
/// The callback invoked when a Surface is created.
///
/// @param  width  The width in pixels.
/// @param  height  The height in pixels.
///
/// @return  This callback should return a pointer to user-defined data for the
///          instance. This user data pointer will be passed to all other
///          callbacks when operating on the instance.
///
typedef void*
(*ULSurfaceDefinitionCreateCallback) (unsigned int width, unsigned int height);

///
/// The callback invoked when a Surface is destroyed.
///
/// @param  user_data  User data pointer uniquely identifying the surface.
///
typedef void
(*ULSurfaceDefinitionDestroyCallback) (void* user_data);

///
/// The callback invoked when a Surface's width (in pixels) is requested.
///
/// @param  user_data  User data pointer uniquely identifying the surface.
///
typedef unsigned int
(*ULSurfaceDefinitionGetWidthCallback) (void* user_data);

///
/// The callback invoked when a Surface's height (in pixels) is requested.
///
/// @param  user_data  User data pointer uniquely identifying the surface.
///
typedef unsigned int
(*ULSurfaceDefinitionGetHeightCallback) (void* user_data);

///
/// The callback invoked when a Surface's row bytes is requested.
///
/// @note  This value is also known as "stride". Usually width * 4.
///
/// @param  user_data  User data pointer uniquely identifying the surface.
///
typedef unsigned int
(*ULSurfaceDefinitionGetRowBytesCallback) (void* user_data);

///
/// The callback invoked when a Surface's size (in bytes) is requested.
///
/// @param  user_data  User data pointer uniquely identifying the surface.
///
typedef size_t
(*ULSurfaceDefinitionGetSizeCallback) (void* user_data);

///
/// The callback invoked when a Surface's pixel buffer is requested to be
/// locked for reading/writing (should return a pointer to locked bytes).
///
/// @param  user_data  User data pointer uniquely identifying the surface.
///
typedef void*
(*ULSurfaceDefinitionLockPixelsCallback) (void* user_data);

///
/// The callback invoked when a Surface's pixel buffer is requested to be
/// unlocked after previously being locked.
///
/// @param  user_data  User data pointer uniquely identifying the surface.
///
typedef void
(*ULSurfaceDefinitionUnlockPixelsCallback) (void* user_data);

///
/// The callback invoked when a Surface is requested to be resized to a
/// certain width/height.
///
/// @param  user_data  User data pointer uniquely identifying the surface.
/// @param  width      Width in pixels.
/// @param  height     Height in pixels.
///
typedef void
(*ULSurfaceDefinitionResizeCallback) (void* user_data, unsigned int width, unsigned int height);

typedef struct {
  ULSurfaceDefinitionCreateCallback create;
  ULSurfaceDefinitionDestroyCallback destroy;
  ULSurfaceDefinitionGetWidthCallback get_width;
  ULSurfaceDefinitionGetHeightCallback get_height;
  ULSurfaceDefinitionGetRowBytesCallback get_row_bytes;
  ULSurfaceDefinitionGetSizeCallback get_size;
  ULSurfaceDefinitionLockPixelsCallback lock_pixels;
  ULSurfaceDefinitionUnlockPixelsCallback unlock_pixels;
  ULSurfaceDefinitionResizeCallback resize;
} ULSurfaceDefinition;

/******************************************************************************
 * File System
 *****************************************************************************/

///
/// File Handle type used as unique ID for opened files.
///
#if defined(__WIN32__) || defined(_WIN32)
typedef size_t ULFileHandle;
#else
typedef int ULFileHandle;
#endif

///
/// Handle used to denote an invalid file.
///
const ULFileHandle ULInvalidFileHandle = (ULFileHandle)-1;

///
/// The callback invoked when the FileSystem wants to check if a file path
/// exists, return true if it exists.
///
typedef bool
(*ULFileSystemFileExistsCallback) (ULString path);

///
/// The callback invoked when the FileSystem wants to get the file size of a
/// previously opened file, store result in 'result'. Return true on success.
///
typedef bool
(*ULFileSystemGetFileSizeCallback) (ULFileHandle handle, long long* result);

///
/// The callback invoked when the FileSystem wants to get the mime type of a
/// file (eg "text/html"), store result in 'result'. Return true on success.
///
typedef bool
(*ULFileSystemGetFileMimeTypeCallback) (ULString path, ULString result);

///
/// The callback invoked when the FileSystem wants to open a file path for
/// reading or writing. Return file handle on success, or ULInvalidFileHandle
/// on failure.
///
/// @NOTE:  As of this writing (v1.2), this function is only used for reading.
///
typedef ULFileHandle
(*ULFileSystemOpenFileCallback) (ULString path, bool open_for_writing);

///
/// The callback invoked when the FileSystem wants to close a previously-opened
/// file.
///
typedef void
(*ULFileSystemCloseFileCallback) (ULFileHandle handle);

///
/// The callback invoked when the FileSystem wants to read from a
/// currently-opened file, return number of bytes read or -1 on failure.
///
typedef long long
(*ULFileSystemReadFromFileCallback) (ULFileHandle handle, char* data, long long length);

typedef struct {
  ULFileSystemFileExistsCallback file_exists;
  ULFileSystemGetFileSizeCallback get_file_size;
  ULFileSystemGetFileMimeTypeCallback get_file_mime_type;
  ULFileSystemOpenFileCallback open_file;
  ULFileSystemCloseFileCallback close_file;
  ULFileSystemReadFromFileCallback read_from_file;
} ULFileSystem;

/******************************************************************************
 * Logger
 *****************************************************************************/

typedef enum {
  kLogLevel_Error = 0,
  kLogLevel_Warning,
  kLogLevel_Info
} ULLogLevel;

///
/// The callback invoked when the library wants to print a message to the log.
///
typedef void
(*ULLoggerLogMessageCallback) (ULLogLevel log_level, ULString message);

typedef struct {
  ULLoggerLogMessageCallback log_message;
} ULLogger;


/******************************************************************************
 * GPUDriver
 *****************************************************************************/

///
/// Render buffer description.
///
typedef struct {
  unsigned int texture_id;  // The backing texture for this RenderBuffer
  unsigned int width;       // The width of the RenderBuffer texture
  unsigned int height;      // The height of the RenderBuffer texture
  bool has_stencil_buffer;  // Currently unused, always false.
  bool has_depth_buffer;    // Currently unsued, always false.
} ULRenderBuffer;

///
/// @note  This pragma pack(push, 1) command is important! Vertex layouts
///	       should not be padded with any bytes.
///
#pragma pack(push, 1)

///
/// Vertex layout for path vertices.
///
/// (this struct's members aligned on single-byte boundaries)
///
typedef struct {
  float pos[2];
  unsigned char color[4];
  float obj[2];
} ULVertex_2f_4ub_2f;

///
/// Vertex layout for quad vertices.
///
/// (this struct's members aligned on single-byte boundaries)
///
typedef struct {
  float pos[2];
  unsigned char color[4];
  float tex[2];
  float obj[2];
  float data0[4];
  float data1[4];
  float data2[4];
  float data3[4];
  float data4[4];
  float data5[4];
  float data6[4];
} ULVertex_2f_4ub_2f_2f_28f;

///
/// End single-byte alignment.
///
#pragma pack(pop)

///
/// Vertex formats.
///
typedef enum {
  kVertexBufferFormat_2f_4ub_2f,
  kVertexBufferFormat_2f_4ub_2f_2f_28f,
} ULVertexBufferFormat;

///
/// Vertex buffer data.
///
typedef struct {
  ULVertexBufferFormat format;
  unsigned int size;
  unsigned char* data;
} ULVertexBuffer;

///
/// Vertex index type.
///
typedef unsigned int ULIndexType;

///
/// Vertex index buffer data.
///
typedef struct {
  unsigned int size;
  unsigned char* data;
} ULIndexBuffer;

///
/// Shader types, used with ULGPUState::shader_type
///
/// Each of these correspond to a vertex/pixel shader pair. You can find
/// stock shader code for these in the `shaders` folder of the AppCore repo.
///
typedef enum {
  kShaderType_Fill,      // Shader program for quad geometry
  kShaderType_FillPath,  // Shader program for path geometry
} ULShaderType;

///
/// Raw 4x4 matrix as an array of floats
///
typedef struct {
  float data[16];
} ULMatrix4x4;

///
/// 4-component float vector
///
typedef struct {
  float value[4];
} ULvec4;

///
/// GPU State description.
///
typedef struct {
  /// Viewport width in pixels
  unsigned int viewport_width;

  /// Viewport height in pixels
  unsigned int viewport_height;

  /// Transform matrix-- you should multiply this with the screen-space
  /// orthographic projection matrix then pass to the vertex shader.
  ULMatrix4x4 transform;

  /// Whether or not we should enable texturing for the current draw command.
  bool enable_texturing;

  /// Whether or not we should enable blending for the current draw command.
  /// If blending is disabled, any drawn pixels should overwrite existing.
  /// Mainly used so we can modify alpha values of the RenderBuffer during
  /// scissored clears.
  bool enable_blend;

  /// The vertex/pixel shader program pair to use for the current draw command.
  /// You should cast this to ShaderType to get the corresponding enum.
  unsigned char shader_type;

  /// The render buffer to use for the current draw command.
  unsigned int render_buffer_id;

  /// The texture id to bind to slot #1. (Will be 0 if none)
  unsigned int texture_1_id;

  /// The texture id to bind to slot #2. (Will be 0 if none)
  unsigned int texture_2_id;

  /// The texture id to bind to slot #3. (Will be 0 if none)
  unsigned int texture_3_id;

  /// The following four members are passed to the pixel shader via uniforms.
  float uniform_scalar[8];
  ULvec4 uniform_vector[8];
  unsigned char clip_size;
  ULMatrix4x4 clip[8];

  /// Whether or not scissor testing should be used for the current draw
  /// command.
  bool enable_scissor;

  /// The scissor rect to use for scissor testing (units in pixels)
  ULIntRect scissor_rect;
} ULGPUState;

///
/// Command types, used with ULCommand::command_type
///
typedef enum {
  kCommandType_ClearRenderBuffer,
  kCommandType_DrawGeometry,
} ULCommandType;

///
/// Command description.
///
typedef struct {
  unsigned char command_type;    // The type of command to dispatch.
  ULGPUState gpu_state;          // GPU state parameters for current command.

  /// The following members are only used with kCommandType_DrawGeometry
  unsigned int geometry_id;    // The geometry ID to bind
  unsigned int indices_count;  // The number of indices
  unsigned int indices_offset; // The index to start from
} ULCommand;

///
/// Command list, @see ULGPUDriverUpdateCommandList
typedef struct {
  unsigned int size;
  ULCommand* commands;
} ULCommandList;

///
/// The callback invoked when the GPUDriver will begin dispatching commands
/// (such as CreateTexture and UpdateCommandList) during the current call to
/// ulRender().
///
typedef void
(*ULGPUDriverBeginSynchronizeCallback) ();

///
/// The callback invoked when the GPUDriver has finished dispatching commands.
/// during the current call to ulRender().
///
typedef void
(*ULGPUDriverEndSynchronizeCallback) ();

///
/// The callback invoked when the GPUDriver wants to get the next available
/// texture ID.
///
typedef unsigned int
(*ULGPUDriverNextTextureIdCallback) ();

///
/// The callback invoked when the GPUDriver wants to create a texture with a
/// certain ID and optional bitmap.
///
/// **NOTE**: If the Bitmap is empty (ulBitmapIsEmpty), then a RTT Texture
///           should be created instead. This will be used as a backing
///           texture for a new RenderBuffer.
///
typedef void
(*ULGPUDriverCreateTextureCallback) (unsigned int texture_id,
                                     ULBitmap bitmap);

///
/// The callback invoked when the GPUDriver wants to update an existing non-RTT
/// texture with new bitmap data.
///
typedef void
(*ULGPUDriverUpdateTextureCallback) (unsigned int texture_id,
                                     ULBitmap bitmap);

///
/// The callback invoked when the GPUDriver wants to destroy a texture.
///
typedef void
(*ULGPUDriverDestroyTextureCallback) (unsigned int texture_id);

///
/// The callback invoked when the GPUDriver wants to generate the next
/// available render buffer ID.
///
typedef unsigned int
(*ULGPUDriverNextRenderBufferIdCallback) ();

///
/// The callback invoked when the GPUDriver wants to create a render buffer
/// with certain ID and buffer description.
///
typedef void
(*ULGPUDriverCreateRenderBufferCallback) (unsigned int render_buffer_id,
                                          ULRenderBuffer buffer);

///
/// The callback invoked when the GPUDriver wants to destroy a render buffer
///
typedef void
(*ULGPUDriverDestroyRenderBufferCallback) (unsigned int render_buffer_id);

///
/// The callback invoked when the GPUDriver wants to generate the next
/// available geometry ID.
///
typedef unsigned int
(*ULGPUDriverNextGeometryIdCallback) ();

///
/// The callback invoked when the GPUDriver wants to create geometry with
/// certain ID and vertex/index data.
///
typedef void
(*ULGPUDriverCreateGeometryCallback) (unsigned int geometry_id,
                                      ULVertexBuffer vertices,
                                      ULIndexBuffer indices);

///
/// The callback invoked when the GPUDriver wants to update existing geometry
/// with new vertex/index data.
///
typedef void
(*ULGPUDriverUpdateGeometryCallback) (unsigned int geometry_id,
                                      ULVertexBuffer vertices,
                                      ULIndexBuffer indices);

///
/// The callback invoked when the GPUDriver wants to destroy geometry.
///
typedef void
(*ULGPUDriverDestroyGeometryCallback) (unsigned int geometry_id);

///
/// The callback invoked when the GPUDriver wants to update the command list
/// (you should copy the commands to your own structure).
///
typedef void
(*ULGPUDriverUpdateCommandListCallback) (ULCommandList list);

typedef struct {
  ULGPUDriverBeginSynchronizeCallback begin_synchronize;
  ULGPUDriverEndSynchronizeCallback end_synchronize;
  ULGPUDriverNextTextureIdCallback next_texture_id;
  ULGPUDriverCreateTextureCallback create_texture;
  ULGPUDriverUpdateTextureCallback update_texture;
  ULGPUDriverDestroyTextureCallback destroy_texture;
  ULGPUDriverNextRenderBufferIdCallback next_render_buffer_id;
  ULGPUDriverCreateRenderBufferCallback create_render_buffer;
  ULGPUDriverDestroyRenderBufferCallback destroy_render_buffer;
  ULGPUDriverNextGeometryIdCallback next_geometry_id;
  ULGPUDriverCreateGeometryCallback create_geometry;
  ULGPUDriverUpdateGeometryCallback update_geometry;
  ULGPUDriverDestroyGeometryCallback destroy_geometry;
  ULGPUDriverUpdateCommandListCallback update_command_list;
} ULGPUDriver;

///
/// Sets up an orthographic projection matrix with a certain viewport width
/// and height, multiplies it by 'transform', and returns the result.
///
/// This should be used to calculate the model-view projection matrix for the
/// vertex shaders using the current ULGPUState.
///
/// The 'flip_y' can be optionally used to flip the Y coordinate-space.
/// (Usually flip_y == true for OpenGL)
///
ULExport ULMatrix4x4 ulApplyProjection(ULMatrix4x4 transform,
                                       float viewport_width,
                                       float viewport_height,
                                       bool flip_y);

/******************************************************************************
 * Clipboard
 *****************************************************************************/

///
/// The callback invoked when the library wants to clear the system's
/// clipboard.
///
typedef void
(*ULClipboardClearCallback) ();

///
/// The callback invoked when the library wants to read from the system's
/// clipboard.
///
/// You should store the result (if any) in 'result'.
///
typedef void
(*ULClipboardReadPlainTextCallback) (ULString result);

///
/// The callback invoked when the library wants to write to the system's
/// clipboard.
///
typedef void
(*ULClipboardWritePlainTextCallback) (ULString text);

typedef struct {
  ULClipboardClearCallback clear;
  ULClipboardReadPlainTextCallback read_plain_text;
  ULClipboardWritePlainTextCallback write_plain_text;
} ULClipboard;

/******************************************************************************
 * Platform
 *****************************************************************************/

///
/// Set a custom Logger implementation.
///
/// This is used to log debug messages to the console or to a log file.
///
/// You should call this before ulCreateRenderer() or ulCreateApp().
///
/// @note  ulCreateApp() will use the default logger if you never call this.
///
/// @note  If you're not using ulCreateApp(), (eg, using ulCreateRenderer())
///        you can still use the default logger by calling
///        ulEnableDefaultLogger() (@see <AppCore/CAPI.h>)
///
ULExport void ulPlatformSetLogger(ULLogger logger);

///
/// Set a custom FileSystem implementation.
///
/// This is used for loading File URLs (eg, <file:///page.html>). If you don't
/// call this, and are not using ulCreateApp() or ulEnablePlatformFileSystem(),
/// you will not be able to load any File URLs.
///
/// You should call this before ulCreateRenderer() or ulCreateApp().
///
/// @note  ulCreateApp() will use the default platform file system if you never
///        call this.
///
/// @note  If you're not using ulCreateApp(), (eg, using ulCreateRenderer())
///        you can still use the default platform file system by calling
///        ulEnablePlatformFileSystem() (@see <AppCore/CAPI.h>)
///
ULExport void ulPlatformSetFileSystem(ULFileSystem file_system);

///
/// Set a custom Surface implementation.
///
/// This can be used to wrap a platform-specific GPU texture, Windows DIB,
/// macOS CGImage, or any other pixel buffer target for display on screen.
///
/// By default, the library uses a bitmap surface for all surfaces but you can
/// override this by providing your own surface definition here.
///
/// You should call this before ulCreateRenderer() or ulCreateApp().
///
ULExport void ulPlatformSetSurfaceDefinition(ULSurfaceDefinition surface_definition);

///
/// Set a custom GPUDriver implementation.
///
/// This should be used if you have enabled the GPU renderer in the Config and
/// are using ulCreateRenderer() (which does not provide its own GPUDriver
/// implementation).
///
/// The GPUDriver interface is used by the library to dispatch GPU calls to
/// your native GPU context (eg, D3D11, Metal, OpenGL, Vulkan, etc.) There
/// are reference implementations for this interface in the AppCore repo.
///
/// You should call this before ulCreateRenderer().
///
ULExport void ulPlatformSetGPUDriver(ULGPUDriver gpu_driver);

///
/// Set a custom Clipboard implementation.
///
/// This should be used if you are using ulCreateRenderer() (which does not
/// provide its own clipboard implementation).
///
/// The Clipboard interface is used by the library to make calls to the
/// system's native clipboard (eg, cut, copy, paste).
///
/// You should call this before ulCreateRenderer().
///
ULExport void ulPlatformSetClipboard(ULClipboard clipboard);

#ifdef __cplusplus
}
#endif

#endif // ULTRALIGHT_CAPI_H