browser.c 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441
  1. /* browser: a small HTML/CSS browser built on ngui, the image library and the
  2. * shared uhttp client.
  3. *
  4. * No JavaScript and no forms; external CSS is loaded over uhttp, and images
  5. * are decoded with img.c and drawn inline. Large buffers (page body and the
  6. * image decode arena) live in the per-process SYS_MEM_ALLOC heap; the DOM and
  7. * the image/CSS I/O scratch use fixed static arenas.
  8. */
  9. #include "ucmd_lib.h"
  10. #include "ngui.h"
  11. #include "browser_html.h"
  12. #include "uhttp.h"
  13. #include "img.h"
  14. #include "inflate.h"
  15. #define BR_W 960
  16. #define BR_H 640
  17. /* CSS media queries are evaluated as a desktop browser. */
  18. #define BR_VIEWPORT_W 1000
  19. #define BR_TOOLBAR_H 30
  20. #define BR_STATUS_H 18
  21. #define BR_HEAP_INIT (6u * 1024u * 1024u)
  22. #define BR_HEAP_MAX (32u * 1024u * 1024u)
  23. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  24. #define BR_IMG_FILE_MAX (512u * 1024u)
  25. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  26. #define BR_MAX_IMAGES 16
  27. #define BR_IMG_ARENA (24u * 1024u * 1024u)
  28. #define BR_IMG_LAYOUT_W 1000
  29. #define BR_CSS_MAX (832u * 1024u)
  30. #define BR_CSS_COMP_MAX (192u * 1024u)
  31. #define BR_MAX_SHEETS 6
  32. #define BR_HISTORY 16
  33. #define BR_URL_MAX 512
  34. #define BR_STATUS_MAX 200
  35. #define BR_IMG_RGB565(r, g, b) \
  36. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  37. #define BR_GRAY 0x8410
  38. enum {
  39. ID_URL = 1,
  40. ID_GO,
  41. ID_BACK,
  42. ID_FORWARD,
  43. ID_RELOAD,
  44. ID_HOME
  45. };
  46. #define ACT_NAV (1u << 0)
  47. #define ACT_BACK (1u << 1)
  48. #define ACT_FORWARD (1u << 2)
  49. #define ACT_RELOAD (1u << 3)
  50. #define ACT_HOME (1u << 4)
  51. #define ACT_CLOSE (1u << 5)
  52. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  53. ACT_HOME | ACT_CLOSE)
  54. struct br_image {
  55. int state; /* 0 empty, 1 ready */
  56. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  57. int native_w, native_h;
  58. char err[32];
  59. };
  60. static struct ngui ui;
  61. static struct ngui_input url_in;
  62. static struct ngui_scroll page_scroll;
  63. static struct br_doc doc;
  64. static struct br_image images[BR_MAX_IMAGES];
  65. static int image_count;
  66. /* Images are loaded one per main-loop iteration so the parsed page stays
  67. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  68. static int preload_active;
  69. static int preload_pending;
  70. static int preload_wait;
  71. static unsigned int preload_node;
  72. static int preload_loaded;
  73. static int preload_scroll;
  74. static char post_status_text[BR_STATUS_MAX];
  75. static int post_status_error;
  76. static unsigned int post_status_ttl;
  77. /* Content-relative position/height of each <img>, recorded by the measure
  78. * pass so image loading can be deferred until it is near the viewport. */
  79. static unsigned short img_top[BR_MAX_NODES];
  80. static unsigned short img_h[BR_MAX_NODES];
  81. static unsigned char *heap;
  82. static unsigned int heap_size = 0;
  83. static unsigned int heap_used = 0;
  84. /* One reusable I/O buffer and one shared decode arena: decoded pixels are
  85. * scaled down to a display bitmap, then the arena is reused for the next
  86. * image. This keeps 4K screenshots inside the 32 MB heap. The two halves
  87. * double as the gzip input scratch for page/CSS fetches, where the heap has
  88. * no room for another multi-megabyte body. */
  89. static unsigned char *image_io_buf;
  90. #define image_file_buf (image_io_buf)
  91. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  92. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  93. static struct inflate image_inflate_ws;
  94. static unsigned char *image_arena;
  95. static unsigned int image_arena_size;
  96. static void *heap_alloc(unsigned int bytes, unsigned int align);
  97. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  98. #error "CSS scratch must fit in image_io_buf"
  99. #endif
  100. static char page_url[BR_URL_MAX];
  101. static char page_title[BR_TITLE_MAX];
  102. static char cwd[64];
  103. static int page_is_local;
  104. static int page_loading;
  105. static char status_text[BR_STATUS_MAX];
  106. static unsigned int status_until;
  107. static int status_error;
  108. static char history[BR_HISTORY][BR_URL_MAX];
  109. static int hist_len, hist_pos;
  110. static char click_url[BR_URL_MAX];
  111. static char pending_url[BR_URL_MAX];
  112. static unsigned int pending_action;
  113. static int cancel_fetch;
  114. static int quit;
  115. static struct ngui_rect page_rect;
  116. static unsigned short *page_backbuf;
  117. static int pagebuf_w, pagebuf_h;
  118. static int page_cache_valid;
  119. static int page_cache_scroll;
  120. static unsigned int page_cache_nnode;
  121. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  122. static int layout_valid, layout_left, layout_right;
  123. static unsigned int layout_nnode;
  124. static int layout_content_h;
  125. /* layout output */
  126. struct lay_run {
  127. unsigned short off, len;
  128. unsigned short gap;
  129. unsigned short color;
  130. unsigned short href;
  131. char lit[28];
  132. short img;
  133. unsigned short iw, ih;
  134. unsigned char scale, bold, underline;
  135. unsigned char has_lit;
  136. };
  137. struct lay {
  138. int draw;
  139. struct ngui *ui;
  140. int left, right;
  141. int y;
  142. int line_x, line_y, line_h;
  143. int run_x;
  144. int align;
  145. int depth;
  146. int space_pending;
  147. struct lay_run runs[96];
  148. int nruns;
  149. };
  150. struct hit {
  151. int x, y, w, h;
  152. unsigned short node;
  153. };
  154. #define HIT_MAX 96
  155. static struct hit hits[HIT_MAX];
  156. static int nhits;
  157. static unsigned short block_h[BR_MAX_NODES];
  158. static char li_marker[BR_MAX_NODES][6];
  159. /* one connection object; the browser fetches one resource at a time */
  160. /* ---- tiny strings ---- */
  161. static unsigned int s_len(const char *s)
  162. {
  163. unsigned int n = 0;
  164. while (s && s[n])
  165. n++;
  166. return n;
  167. }
  168. static void s_copy(char *d, const char *s, unsigned int cap)
  169. {
  170. unsigned int i = 0;
  171. if (!cap)
  172. return;
  173. while (s && s[i] && i + 1 < cap) {
  174. d[i] = s[i];
  175. i++;
  176. }
  177. d[i] = '\0';
  178. }
  179. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  180. {
  181. while (s && *s && *n + 1 < cap)
  182. d[(*n)++] = *s++;
  183. d[*n] = '\0';
  184. }
  185. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  186. unsigned int cap)
  187. {
  188. char tmp[12];
  189. unsigned int i = 0, j;
  190. do {
  191. tmp[i++] = (char)('0' + v % 10);
  192. v /= 10;
  193. } while (v && i < sizeof(tmp));
  194. for (j = 0; j < i && *n + 1 < cap; j++)
  195. d[(*n)++] = tmp[i - 1 - j];
  196. d[*n] = '\0';
  197. }
  198. static int s_eq(const char *a, const char *b)
  199. {
  200. while (*a && *b) {
  201. if (*a != *b)
  202. return 0;
  203. a++;
  204. b++;
  205. }
  206. return *a == *b;
  207. }
  208. static int starts_with(const char *s, const char *p)
  209. {
  210. unsigned int i = 0;
  211. while (p[i]) {
  212. if (s[i] != p[i])
  213. return 0;
  214. i++;
  215. }
  216. return 1;
  217. }
  218. static int contains_ci(const char *s, const char *p)
  219. {
  220. unsigned int i, j;
  221. for (i = 0; s[i]; i++) {
  222. for (j = 0; p[j]; j++) {
  223. char a = s[i + j];
  224. if (a >= 'A' && a <= 'Z')
  225. a = (char)(a - 'A' + 'a');
  226. if (a != p[j])
  227. break;
  228. }
  229. if (!p[j])
  230. return 1;
  231. }
  232. return 0;
  233. }
  234. static char *trim(char *s)
  235. {
  236. unsigned int n;
  237. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  238. s++;
  239. n = s_len(s);
  240. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  241. s[n - 1] == '\r' || s[n - 1] == '\n'))
  242. s[--n] = '\0';
  243. return s;
  244. }
  245. /* ---- per-process heap ---- */
  246. static int heap_start(void)
  247. {
  248. heap = (unsigned char *)u_mem_alloc(BR_HEAP_INIT);
  249. if (!heap) {
  250. heap_size = heap_used = 0;
  251. return -1;
  252. }
  253. heap_size = BR_HEAP_INIT;
  254. heap_used = 0;
  255. image_io_buf = (unsigned char *)heap_alloc(2u * BR_IMG_FILE_MAX, 16);
  256. if (!image_io_buf) {
  257. heap_size = heap_used = 0;
  258. return -1;
  259. }
  260. page_backbuf = (unsigned short *)heap_alloc(
  261. (unsigned int)ui.w * (unsigned int)ui.h * 2u, 16);
  262. pagebuf_w = page_backbuf ? ui.w : 0;
  263. pagebuf_h = page_backbuf ? ui.h : 0;
  264. page_cache_valid = 0;
  265. return 0;
  266. }
  267. static void heap_clear(void)
  268. {
  269. u_mem_free();
  270. heap = 0;
  271. heap_size = heap_used = 0;
  272. image_io_buf = 0;
  273. page_backbuf = 0;
  274. pagebuf_w = pagebuf_h = 0;
  275. page_cache_valid = 0;
  276. image_arena = 0;
  277. image_arena_size = 0;
  278. }
  279. static void *heap_alloc(unsigned int bytes, unsigned int align)
  280. {
  281. unsigned int start, want;
  282. if (!heap || bytes == 0)
  283. return 0;
  284. if (align < 1)
  285. align = 1;
  286. if (align & (align - 1))
  287. return 0;
  288. start = (heap_used + align - 1) & ~(align - 1);
  289. if (start > BR_HEAP_MAX || bytes > BR_HEAP_MAX - start)
  290. return 0;
  291. if (start + bytes > heap_size) {
  292. want = heap_size ? heap_size : BR_HEAP_INIT;
  293. while (want < start + bytes) {
  294. if (want > BR_HEAP_MAX / 2) {
  295. want = BR_HEAP_MAX;
  296. break;
  297. }
  298. want *= 2;
  299. }
  300. if (want < start + bytes || want > BR_HEAP_MAX)
  301. return 0;
  302. if (u_mem_grow(want) != 0)
  303. return 0;
  304. heap_size = want;
  305. }
  306. heap_used = start + bytes;
  307. return heap + start;
  308. }
  309. static void browser_rules_alloc(void)
  310. {
  311. struct br_rule *rules;
  312. rules = (struct br_rule *)heap_alloc(
  313. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)), 16);
  314. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  315. }
  316. /* ---- status ---- */
  317. static void set_status(const char *s, int err, unsigned int ttl_ms)
  318. {
  319. s_copy(status_text, s, sizeof(status_text));
  320. status_error = err;
  321. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  322. ngui_invalidate(&ui);
  323. }
  324. /* ---- images ---- */
  325. static void image_reset(void)
  326. {
  327. int i;
  328. for (i = 0; i < BR_MAX_IMAGES; i++) {
  329. images[i].state = 0;
  330. images[i].native_w = images[i].native_h = 0;
  331. images[i].err[0] = '\0';
  332. }
  333. image_count = 0;
  334. preload_active = 0;
  335. preload_pending = 0;
  336. preload_wait = 0;
  337. preload_node = 0;
  338. preload_loaded = 0;
  339. }
  340. /* Decode into the shared arena, then copy/scale the result into a display
  341. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  342. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  343. * pixels. Transparent edges are composited over white. */
  344. static int decode_image_data(const unsigned char *data, unsigned int len,
  345. struct br_image *bi)
  346. {
  347. struct img_info info;
  348. struct img_options opt;
  349. struct img_mem mem;
  350. struct img_image decoded;
  351. unsigned int est, bytes, i;
  352. unsigned short *px;
  353. int dw, dh, r;
  354. if (img_sniff(data, len, &info) != 0) {
  355. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  356. return -1;
  357. }
  358. est = img_estimate(&info);
  359. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA) {
  360. s_copy(bi->err, "image too large", sizeof(bi->err));
  361. return -1;
  362. }
  363. if (!image_arena) {
  364. image_arena = (unsigned char *)heap_alloc(BR_IMG_ARENA, 16);
  365. if (!image_arena) {
  366. s_copy(bi->err, "out of memory", sizeof(bi->err));
  367. return -1;
  368. }
  369. image_arena_size = BR_IMG_ARENA;
  370. }
  371. img_mem_init(&mem, image_arena, image_arena_size);
  372. opt.max_pixels = BR_IMG_PIX_MAX;
  373. r = img_decode(data, len, &opt, &mem, &decoded);
  374. if (r != 0) {
  375. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  376. return -1;
  377. }
  378. if (decoded.w == 0 || decoded.h == 0) {
  379. s_copy(bi->err, "empty image", sizeof(bi->err));
  380. return -1;
  381. }
  382. bi->native_w = (int)decoded.w;
  383. bi->native_h = (int)decoded.h;
  384. dw = (int)decoded.w;
  385. dh = (int)decoded.h;
  386. if (dw > BR_IMG_LAYOUT_W) {
  387. dh = (int)((unsigned int)decoded.h * BR_IMG_LAYOUT_W /
  388. decoded.w);
  389. dw = BR_IMG_LAYOUT_W;
  390. }
  391. if (dh < 1)
  392. dh = 1;
  393. if (dw < 1)
  394. dw = 1;
  395. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  396. px = (unsigned short *)heap_alloc(bytes, 16);
  397. if (!px) {
  398. s_copy(bi->err, "out of memory", sizeof(bi->err));
  399. return -1;
  400. }
  401. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  402. px[i] = ui.theme.bg;
  403. {
  404. struct img_blit b;
  405. b.dst = px;
  406. b.dst_w = dw;
  407. b.dst_h = dh;
  408. b.clip_x = 0;
  409. b.clip_y = 0;
  410. b.clip_w = dw;
  411. b.clip_h = dh;
  412. b.x = 0;
  413. b.y = 0;
  414. b.scale = ((unsigned int)dw << 16) / decoded.w;
  415. b.bg = ui.theme.bg;
  416. b.bg2 = ui.theme.bg;
  417. b.flags = IMG_BLIT_OVER_DST;
  418. img_draw(&decoded, &b);
  419. }
  420. bi->img.format = decoded.format;
  421. bi->img.w = (unsigned int)dw;
  422. bi->img.h = (unsigned int)dh;
  423. bi->img.px = px;
  424. bi->img.alpha = 0;
  425. bi->img.flags = 0;
  426. bi->state = 1;
  427. return 0;
  428. }
  429. /* ---- URL / local path handling ---- */
  430. static int is_http(const char *s)
  431. {
  432. return starts_with(s, "http://") || starts_with(s, "https://");
  433. }
  434. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  435. static int normalize_abs(const char *in, char *out, unsigned int cap)
  436. {
  437. char seg[64];
  438. unsigned int i = 0, o = 1;
  439. int depth = 0;
  440. int trailing;
  441. if (!in || in[0] != '/' || cap < 2)
  442. return -1;
  443. trailing = 0;
  444. {
  445. unsigned int n = s_len(in);
  446. if (n > 1 && in[n - 1] == '/')
  447. trailing = 1;
  448. }
  449. out[0] = '/';
  450. while (in[i]) {
  451. unsigned int n = 0;
  452. while (in[i] == '/')
  453. i++;
  454. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  455. if (n + 1 < sizeof(seg))
  456. seg[n++] = in[i];
  457. i++;
  458. }
  459. seg[n] = '\0';
  460. if (n == 0)
  461. break;
  462. if (s_eq(seg, "."))
  463. continue;
  464. if (s_eq(seg, "..")) {
  465. if (depth > 0) {
  466. while (o > 1 && out[o - 1] != '/')
  467. o--;
  468. if (o > 1)
  469. o--;
  470. depth--;
  471. }
  472. continue;
  473. }
  474. if (o > 1) {
  475. if (o + 1 >= cap)
  476. return -1;
  477. out[o++] = '/';
  478. }
  479. if (o + n + 1 >= cap)
  480. return -1;
  481. {
  482. unsigned int j;
  483. for (j = 0; j < n; j++)
  484. out[o++] = seg[j];
  485. }
  486. depth++;
  487. }
  488. if (trailing && o > 1) {
  489. if (o + 1 >= cap)
  490. return -1;
  491. out[o++] = '/';
  492. }
  493. out[o] = '\0';
  494. return 0;
  495. }
  496. static void make_abs_local(const char *in, char *out, unsigned int cap)
  497. {
  498. char joined[BR_URL_MAX];
  499. if (!in || !in[0]) {
  500. s_copy(out, cwd[0] ? cwd : "/", cap);
  501. return;
  502. }
  503. if (in[0] == '/') {
  504. if (normalize_abs(in, out, cap) != 0)
  505. s_copy(out, in, cap);
  506. return;
  507. }
  508. {
  509. unsigned int n = 0;
  510. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  511. s_append(joined, &n, "/", sizeof(joined));
  512. s_append(joined, &n, in, sizeof(joined));
  513. }
  514. if (normalize_abs(joined, out, cap) != 0)
  515. s_copy(out, joined, cap);
  516. }
  517. static int path_dir(const char *path, char *out, unsigned int cap)
  518. {
  519. unsigned int i, last = 0;
  520. for (i = 0; path[i]; i++)
  521. if (path[i] == '/')
  522. last = i;
  523. if (last == 0) {
  524. if (cap < 2)
  525. return -1;
  526. out[0] = '/';
  527. out[1] = '\0';
  528. return 0;
  529. }
  530. if (last + 1 >= cap)
  531. return -1;
  532. {
  533. unsigned int j;
  534. for (j = 0; j < last; j++)
  535. out[j] = path[j];
  536. out[last] = '\0';
  537. }
  538. return 0;
  539. }
  540. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  541. static int resolve_link(const char *base, const char *href, char *out,
  542. unsigned int cap)
  543. {
  544. char joined[BR_URL_MAX];
  545. if (!href || !href[0] || href[0] == '#')
  546. return -1;
  547. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  548. starts_with(href, "data:") || starts_with(href, "tel:"))
  549. return -1;
  550. if (starts_with(href, "about:")) {
  551. s_copy(out, href, cap);
  552. return 0;
  553. }
  554. if (is_http(href)) {
  555. s_copy(out, href, cap);
  556. return 0;
  557. }
  558. if (starts_with(href, "//")) {
  559. if (is_http(base)) {
  560. unsigned int n = 0;
  561. s_append(out, &n, starts_with(base, "https:") ?
  562. "https:" : "http:", cap);
  563. s_append(out, &n, href, cap);
  564. return 0;
  565. }
  566. return -1;
  567. }
  568. if (is_http(base)) {
  569. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  570. }
  571. /* local page */
  572. if (href[0] == '/') {
  573. if (normalize_abs(href, out, cap) != 0)
  574. return -1;
  575. return 0;
  576. }
  577. {
  578. char dir[BR_URL_MAX];
  579. unsigned int n = 0;
  580. if (s_eq(base, "about:home"))
  581. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  582. else if (path_dir(base, dir, sizeof(dir)) != 0)
  583. s_copy(dir, "/", sizeof(dir));
  584. s_append(joined, &n, dir, sizeof(joined));
  585. if (n == 0 || joined[n - 1] != '/')
  586. s_append(joined, &n, "/", sizeof(joined));
  587. s_append(joined, &n, href, sizeof(joined));
  588. }
  589. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  590. }
  591. /* Best-effort decompression: keep the first `cap` bytes and discard the
  592. * rest instead of failing when a page or stylesheet is larger than the
  593. * buffer. The stream is still walked to the end, so a normal page is
  594. * verified; a truncated compressed input still returns whatever was decoded
  595. * so far. */
  596. struct trunc_buf {
  597. unsigned char *dst;
  598. unsigned int cap, pos;
  599. int full;
  600. };
  601. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  602. {
  603. struct trunc_buf *m = (struct trunc_buf *)ctx;
  604. if (len > m->cap - m->pos) {
  605. unsigned int room = m->cap - m->pos;
  606. if (room) {
  607. unsigned int i;
  608. for (i = 0; i < room; i++)
  609. m->dst[m->pos + i] = data[i];
  610. m->pos += room;
  611. }
  612. m->full = 1;
  613. return 0;
  614. }
  615. {
  616. unsigned int i;
  617. for (i = 0; i < len; i++)
  618. m->dst[m->pos + i] = data[i];
  619. }
  620. m->pos += len;
  621. return 0;
  622. }
  623. static void worker_wait_ui(void);
  624. static void inflate_ui_pump(void *ctx)
  625. {
  626. static unsigned int last;
  627. unsigned int now = u_ticks_ms();
  628. (void)ctx;
  629. if ((int)(now - last) >= 50) {
  630. last = now;
  631. worker_wait_ui();
  632. }
  633. }
  634. static int inflate_trunc(const unsigned char *src, unsigned int len,
  635. unsigned char *dst, unsigned int cap,
  636. unsigned int *outlen, int gzip, int *truncated)
  637. {
  638. struct inflate_src in;
  639. struct inflate_sink sink;
  640. struct trunc_buf m;
  641. unsigned int got = 0;
  642. int r;
  643. in.p = src;
  644. in.len = len;
  645. in.more = 0;
  646. in.ctx = 0;
  647. m.dst = dst;
  648. m.cap = cap;
  649. m.pos = 0;
  650. m.full = 0;
  651. sink.write = trunc_write;
  652. sink.ctx = &m;
  653. inflate_init(&image_inflate_ws, &in, &sink);
  654. image_inflate_ws.progress = inflate_ui_pump;
  655. image_inflate_ws.progress_ctx = 0;
  656. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  657. inflate_zlib(&image_inflate_ws, &got);
  658. *outlen = m.pos;
  659. *truncated = m.full || r != 0;
  660. if (r != 0 && m.pos == 0)
  661. return -1;
  662. return 0;
  663. }
  664. /* ---- headless fetch helper ------------------------------------------- *
  665. *
  666. * Network I/O runs in a separate ring-3 process (`curl __fetch`): it writes
  667. * the raw response and a small metadata file under /share. While it works,
  668. * the browser keeps drawing and scrolling its own window, so a slow DNS/TLS
  669. * handshake or a multi-megabyte body never freezes the UI.
  670. */
  671. #define FETCH_REQ "/share/bfreq"
  672. #define FETCH_BODY "/share/bfbody"
  673. #define FETCH_META "/share/bfmeta"
  674. #define FETCH_DONE "/share/bfdone"
  675. #define FETCH_ABORT (-2)
  676. struct fetch_meta {
  677. int status;
  678. int error;
  679. int trunc;
  680. unsigned int len;
  681. char encoding[16];
  682. char ctype[64];
  683. char final[BR_URL_MAX];
  684. };
  685. static void draw(unsigned int *action);
  686. static void handle_keys(unsigned int *action);
  687. static void handle_page_click(unsigned int *action);
  688. static int fetch_helper_tty = -2;
  689. static int fetch_helper_pid = -1;
  690. static unsigned int fetch_seq;
  691. static struct fetch_meta fetch_meta;
  692. static unsigned int meta_uint(char **pp)
  693. {
  694. char *p = *pp;
  695. unsigned int v = 0;
  696. while (*p >= '0' && *p <= '9') {
  697. v = v * 10 + (unsigned int)(*p - '0');
  698. p++;
  699. }
  700. while (*p && *p != '\n')
  701. p++;
  702. if (*p == '\n')
  703. p++;
  704. *pp = p;
  705. return v;
  706. }
  707. static void meta_str(char **pp, char *out, unsigned int cap)
  708. {
  709. char *p = *pp;
  710. unsigned int n = 0;
  711. while (*p && *p != '\n' && n + 1 < cap)
  712. out[n++] = *p++;
  713. out[n] = '\0';
  714. while (*p && *p != '\n')
  715. p++;
  716. if (*p == '\n')
  717. p++;
  718. *pp = p;
  719. }
  720. static void worker_wait_ui(void)
  721. {
  722. unsigned int action = 0;
  723. if (!ngui_begin(&ui))
  724. return;
  725. draw(&action);
  726. handle_keys(&action);
  727. handle_page_click(&action);
  728. if (action & ACT_WAIT_NAV) {
  729. pending_action |= action & ACT_WAIT_NAV;
  730. if ((action & ACT_NAV) && click_url[0])
  731. s_copy(pending_url, click_url, sizeof(pending_url));
  732. click_url[0] = '\0';
  733. cancel_fetch = 1;
  734. }
  735. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  736. ngui_invalidate(&ui);
  737. ngui_end(&ui);
  738. }
  739. static void fetch_helper_stop(void)
  740. {
  741. int i;
  742. if (fetch_helper_pid > 0) {
  743. u_kill((unsigned int)fetch_helper_pid);
  744. for (i = 0; i < 40 && u_alive((unsigned int)fetch_helper_pid); i++)
  745. u_sleep_ms(5);
  746. /* Let the reaper release the NIC before the next request. */
  747. u_sleep_ms(10);
  748. }
  749. fetch_helper_pid = -1;
  750. }
  751. static int fetch_helper_start(char *err, unsigned int errcap)
  752. {
  753. if (fetch_helper_pid > 0 &&
  754. u_alive((unsigned int)fetch_helper_pid))
  755. return 0;
  756. fetch_helper_pid = -1;
  757. if (fetch_helper_tty == -2) {
  758. int t = u_tty_create();
  759. fetch_helper_tty = t > 0 ? t : 0;
  760. }
  761. fetch_helper_pid = u_spawn("/ramfs/bin/curl", "__serve",
  762. fetch_helper_tty, "/");
  763. if (fetch_helper_pid <= 0) {
  764. fetch_helper_pid = -1;
  765. s_copy(err, "cannot start network helper", errcap);
  766. return -1;
  767. }
  768. return 0;
  769. }
  770. static int worker_fetch(const char *url, unsigned int cap,
  771. struct fetch_meta *m, char *err, unsigned int errcap)
  772. {
  773. static char req[768], meta[1024], done[24];
  774. char *p;
  775. unsigned int n = 0, deadline;
  776. int rn, mseq, retried = 0;
  777. struct sys_stat st;
  778. if (cancel_fetch || pending_action)
  779. return FETCH_ABORT;
  780. if (u_stat("/share", &st) != 0 || !st.is_dir ||
  781. u_stat("/ramfs/bin/curl", &st) != 0) {
  782. s_copy(err, "network helper unavailable", errcap);
  783. return -1;
  784. }
  785. fetch_seq++;
  786. if (!fetch_seq)
  787. fetch_seq = 1;
  788. s_append_dec(req, &n, fetch_seq, sizeof(req));
  789. s_append(req, &n, " ", sizeof(req));
  790. s_append_dec(req, &n, cap, sizeof(req));
  791. s_append(req, &n, " ", sizeof(req));
  792. s_append(req, &n, url, sizeof(req));
  793. s_append(req, &n, "\n", sizeof(req));
  794. u_syscall1(SYS_UNLINK, (int)FETCH_DONE);
  795. u_syscall1(SYS_UNLINK, (int)FETCH_META);
  796. if (u_syscall3(SYS_WRITE_FILE, (int)FETCH_REQ, (int)req, (int)n) < 0) {
  797. s_copy(err, "cannot queue network request", errcap);
  798. return -1;
  799. }
  800. if (fetch_helper_start(err, errcap) != 0)
  801. return -1;
  802. deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  803. for (;;) {
  804. worker_wait_ui();
  805. if (cancel_fetch || pending_action) {
  806. fetch_helper_stop();
  807. return FETCH_ABORT;
  808. }
  809. rn = u_syscall3(SYS_READ_FILE, (int)FETCH_DONE, (int)done,
  810. (int)(sizeof(done) - 1));
  811. if (rn > 0) {
  812. done[rn] = '\0';
  813. p = done;
  814. mseq = (int)meta_uint(&p);
  815. if (mseq == (int)fetch_seq)
  816. break;
  817. }
  818. if (!u_alive((unsigned int)fetch_helper_pid)) {
  819. fetch_helper_pid = -1;
  820. if (!retried && fetch_helper_start(err, errcap) == 0) {
  821. retried = 1;
  822. continue;
  823. }
  824. s_copy(err, "network helper stopped", errcap);
  825. return -1;
  826. }
  827. if ((int)(u_ticks_ms() - deadline) >= 0) {
  828. fetch_helper_stop();
  829. s_copy(err, "network request timed out", errcap);
  830. return -1;
  831. }
  832. u_sleep_ms(20);
  833. }
  834. if (cancel_fetch || pending_action)
  835. return FETCH_ABORT;
  836. rn = u_syscall3(SYS_READ_FILE, (int)FETCH_META, (int)meta,
  837. (int)(sizeof(meta) - 1));
  838. if (rn <= 0) {
  839. s_copy(err, "network helper failed", errcap);
  840. return -1;
  841. }
  842. meta[rn] = '\0';
  843. p = meta;
  844. mseq = (int)meta_uint(&p);
  845. if (mseq != (int)fetch_seq) {
  846. s_copy(err, "stale network response", errcap);
  847. return -1;
  848. }
  849. m->status = (int)meta_uint(&p);
  850. m->error = (int)meta_uint(&p);
  851. m->trunc = (int)meta_uint(&p);
  852. meta_str(&p, m->encoding, sizeof(m->encoding));
  853. meta_str(&p, m->ctype, sizeof(m->ctype));
  854. meta_str(&p, m->final, sizeof(m->final));
  855. m->len = meta_uint(&p);
  856. if (m->error) {
  857. s_copy(err, uhttp_error_string(m->error), errcap);
  858. return -1;
  859. }
  860. return 0;
  861. }
  862. static int fetch_remote(const char *url, unsigned int cap,
  863. unsigned char *plain, unsigned int plaincap,
  864. unsigned char *comp, unsigned int compcap,
  865. struct fetch_meta *m, int *truncated,
  866. char *err, unsigned int errcap)
  867. {
  868. int rv, zr, was_trunc;
  869. rv = worker_fetch(url, cap, m, err, errcap);
  870. if (rv == FETCH_ABORT)
  871. return FETCH_ABORT;
  872. if (rv != 0)
  873. return -1;
  874. if (contains_ci(m->encoding, "gzip") ||
  875. contains_ci(m->encoding, "deflate")) {
  876. unsigned int comp_len = 0, plen = 0;
  877. rv = u_syscall3(SYS_READ_FILE, (int)FETCH_BODY, (int)comp,
  878. (int)compcap);
  879. if (rv < 0) {
  880. s_copy(err, "empty response", errcap);
  881. return -1;
  882. }
  883. comp_len = (unsigned int)rv;
  884. if (comp_len < m->len) {
  885. s_copy(err, "compressed response is too large", errcap);
  886. return -1;
  887. }
  888. if (contains_ci(m->encoding, "deflate"))
  889. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  890. &plen, 0, &was_trunc);
  891. else
  892. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  893. &plen, 1, &was_trunc);
  894. if (zr != 0) {
  895. s_copy(err, "compressed response is corrupt", errcap);
  896. return -1;
  897. }
  898. *truncated = m->trunc || was_trunc;
  899. return (cancel_fetch || pending_action) ? FETCH_ABORT :
  900. (int)plen;
  901. }
  902. rv = u_syscall3(SYS_READ_FILE, (int)FETCH_BODY, (int)plain,
  903. (int)plaincap);
  904. if (rv < 0) {
  905. s_copy(err, "empty response", errcap);
  906. return -1;
  907. }
  908. *truncated = m->trunc || ((unsigned int)rv < m->len);
  909. return (cancel_fetch || pending_action) ? FETCH_ABORT : rv;
  910. }
  911. /* ---- HTTP / file fetch ---- */
  912. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  913. unsigned int *outlen, int *is_local, char *ctype,
  914. unsigned int ctcap, char *final, unsigned int finalcap,
  915. char *err, unsigned int errcap, int *truncated)
  916. {
  917. unsigned char *buf;
  918. unsigned int len;
  919. int tr = 0;
  920. int rv;
  921. *out = 0;
  922. *outlen = 0;
  923. *truncated = 0;
  924. if (final && finalcap)
  925. final[0] = '\0';
  926. if (ctype && ctcap)
  927. ctype[0] = '\0';
  928. if (url[0] == '/') {
  929. buf = (unsigned char *)heap_alloc(cap, 16);
  930. if (!buf) {
  931. s_copy(err, "out of memory", errcap);
  932. return -1;
  933. }
  934. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf, (int)cap);
  935. if (rv < 0) {
  936. s_copy(err, "file not found", errcap);
  937. return -1;
  938. }
  939. *out = buf;
  940. *outlen = (unsigned int)rv;
  941. *is_local = 1;
  942. if (ctype)
  943. s_copy(ctype, "text/html", ctcap);
  944. if (final)
  945. s_copy(final, url, finalcap);
  946. if ((unsigned int)rv == cap)
  947. *truncated = 1;
  948. return 0;
  949. }
  950. buf = (unsigned char *)heap_alloc(cap, 16);
  951. if (!buf) {
  952. s_copy(err, "out of memory", errcap);
  953. return -1;
  954. }
  955. rv = fetch_remote(url, cap, buf, cap, image_io_buf, BR_PAGE_COMP_MAX,
  956. &fetch_meta, &tr, err, errcap);
  957. if (rv == FETCH_ABORT)
  958. return FETCH_ABORT;
  959. if (rv < 0)
  960. return -1;
  961. len = (unsigned int)rv;
  962. if (len == 0) {
  963. s_copy(err, "empty response", errcap);
  964. return -1;
  965. }
  966. if (ctype)
  967. s_copy(ctype, fetch_meta.ctype, ctcap);
  968. if (final && fetch_meta.final[0])
  969. s_copy(final, fetch_meta.final, finalcap);
  970. *is_local = 0;
  971. *out = buf;
  972. *outlen = len;
  973. *truncated = tr;
  974. return 0;
  975. }
  976. /* Fetch an image into the fixed scratch buffers. The page heap is already
  977. * carrying the 24 MB decode arena and every scaled bitmap, so images must not
  978. * allocate their file body from it as well. */
  979. static int fetch_image(const char *url, unsigned int cap,
  980. unsigned char **out, unsigned int *outlen,
  981. char *err, unsigned int errcap)
  982. {
  983. unsigned int len;
  984. int tr = 0;
  985. int rv;
  986. *out = 0;
  987. *outlen = 0;
  988. if (cap > BR_IMG_FILE_MAX)
  989. cap = BR_IMG_FILE_MAX;
  990. if (url[0] == '/') {
  991. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  992. (int)cap);
  993. if (rv < 0) {
  994. s_copy(err, "file not found", errcap);
  995. return -1;
  996. }
  997. *out = image_file_buf;
  998. *outlen = (unsigned int)rv;
  999. return 0;
  1000. }
  1001. rv = fetch_remote(url, cap, image_file_buf, cap, image_comp_buf,
  1002. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  1003. if (rv == FETCH_ABORT)
  1004. return FETCH_ABORT;
  1005. if (rv < 0)
  1006. return -1;
  1007. len = (unsigned int)rv;
  1008. if (len == 0) {
  1009. s_copy(err, "empty image", errcap);
  1010. return -1;
  1011. }
  1012. *out = image_file_buf;
  1013. *outlen = len;
  1014. return 0;
  1015. }
  1016. /* Read one stylesheet into the shared static buffer. CSS is parsed
  1017. * immediately, so it does not need the page heap; this leaves the heap for
  1018. * the 2 MB page body, the decode arena and the scaled image bitmaps. */
  1019. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  1020. char *err, unsigned int errcap)
  1021. {
  1022. unsigned int len;
  1023. int tr = 0;
  1024. int rv;
  1025. *out = 0;
  1026. *outlen = 0;
  1027. if (url[0] == '/') {
  1028. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  1029. (int)BR_CSS_MAX);
  1030. if (rv < 0) {
  1031. s_copy(err, "stylesheet not found", errcap);
  1032. return -1;
  1033. }
  1034. *out = image_io_buf;
  1035. *outlen = (unsigned int)rv;
  1036. return 0;
  1037. }
  1038. rv = fetch_remote(url, BR_CSS_MAX, image_io_buf, BR_CSS_MAX,
  1039. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  1040. &fetch_meta, &tr, err, errcap);
  1041. if (rv == FETCH_ABORT)
  1042. return FETCH_ABORT;
  1043. if (rv < 0)
  1044. return -1;
  1045. len = (unsigned int)rv;
  1046. if (len == 0) {
  1047. s_copy(err, "empty stylesheet", errcap);
  1048. return -1;
  1049. }
  1050. *out = image_io_buf;
  1051. *outlen = len;
  1052. return 0;
  1053. }
  1054. static void redraw_now(void);
  1055. static char error_page[1024];
  1056. static void show_error(const char *title, const char *detail)
  1057. {
  1058. char *page = error_page;
  1059. unsigned int n = 0;
  1060. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  1061. s_append(page, &n, title, sizeof(error_page));
  1062. s_append(page, &n, "</h2><p>", sizeof(error_page));
  1063. {
  1064. const char *p = detail;
  1065. while (*p && n + 1 < sizeof(error_page)) {
  1066. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  1067. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  1068. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  1069. else page[n++] = *p;
  1070. p++;
  1071. }
  1072. }
  1073. page[n] = '\0';
  1074. s_append(page, &n, "</p><p>", sizeof(error_page));
  1075. s_append(page, &n, page_url, sizeof(error_page));
  1076. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  1077. sizeof(error_page));
  1078. br_parse(&doc, page, n);
  1079. layout_valid = 0;
  1080. preload_active = 0;
  1081. preload_pending = 0;
  1082. preload_wait = 0;
  1083. s_copy(page_title, title, sizeof(page_title));
  1084. page_loading = 0;
  1085. set_status(title, 1, 0);
  1086. ngui_invalidate(&ui);
  1087. }
  1088. static int decode_direct_image(const unsigned char *data, unsigned int len,
  1089. unsigned int node)
  1090. {
  1091. if (image_count >= BR_MAX_IMAGES)
  1092. return -1;
  1093. if (decode_image_data(data, len, &images[0]) != 0)
  1094. return -1;
  1095. doc.nodes[node].img_index = 0;
  1096. image_count = 1;
  1097. return 0;
  1098. }
  1099. static int ancestor_is(unsigned int node, unsigned int tag)
  1100. {
  1101. unsigned int p = doc.nodes[node].parent;
  1102. while (p) {
  1103. if (doc.nodes[p].tag == tag)
  1104. return 1;
  1105. p = doc.nodes[p].parent;
  1106. }
  1107. return 0;
  1108. }
  1109. static int load_stylesheets(void)
  1110. {
  1111. static char seen[BR_MAX_SHEETS][BR_URL_MAX];
  1112. unsigned int i, sheets = 0, nseen = 0;
  1113. for (i = 0; i < doc.nnode && sheets < BR_MAX_SHEETS; i++) {
  1114. struct br_node *nd = &doc.nodes[i];
  1115. const char *rel, *href;
  1116. char url[BR_URL_MAX];
  1117. unsigned char *data;
  1118. unsigned int len;
  1119. char err[64];
  1120. int rv;
  1121. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1122. continue;
  1123. rel = br_rel(&doc, i);
  1124. if (!contains_ci(rel, "stylesheet"))
  1125. continue;
  1126. href = br_href(&doc, i);
  1127. if (!href[0])
  1128. continue;
  1129. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1130. continue;
  1131. {
  1132. unsigned int k;
  1133. int dup = 0;
  1134. for (k = 0; k < nseen; k++)
  1135. if (s_eq(seen[k], url)) {
  1136. dup = 1;
  1137. break;
  1138. }
  1139. if (dup)
  1140. continue;
  1141. if (nseen < BR_MAX_SHEETS) {
  1142. s_copy(seen[nseen], url, BR_URL_MAX);
  1143. nseen++;
  1144. }
  1145. }
  1146. rv = fetch_css(url, &data, &len, err, sizeof(err));
  1147. if (rv == FETCH_ABORT)
  1148. return FETCH_ABORT;
  1149. if (rv != 0)
  1150. continue;
  1151. if (len)
  1152. br_parse_css_text(&doc, (const char *)data, len);
  1153. sheets++;
  1154. }
  1155. br_parse_inline_css(&doc);
  1156. br_reset_styles(&doc);
  1157. layout_valid = 0;
  1158. return 0;
  1159. }
  1160. static void preload_begin(void)
  1161. {
  1162. preload_active = 1;
  1163. preload_pending = 0;
  1164. preload_wait = 1;
  1165. preload_node = 0;
  1166. preload_loaded = 0;
  1167. preload_scroll = 0;
  1168. }
  1169. /* Load at most one image per call. Images below the current viewport are
  1170. * left pending until the page is scrolled; this keeps a long article with
  1171. * many 4K screenshots from stalling on content the user cannot see yet. */
  1172. static void preload_step(void)
  1173. {
  1174. while (preload_active && preload_node < doc.nnode) {
  1175. unsigned int i = preload_node;
  1176. struct br_node *nd = &doc.nodes[i];
  1177. const char *src;
  1178. char url[BR_URL_MAX];
  1179. unsigned char *data;
  1180. unsigned int len;
  1181. char err[64];
  1182. char msg[64];
  1183. unsigned int n = 0;
  1184. int rv;
  1185. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_IMG ||
  1186. nd->img_index >= 0) {
  1187. preload_node++;
  1188. continue;
  1189. }
  1190. if (ancestor_is(i, BR_TAG_NOSCRIPT)) {
  1191. preload_node++;
  1192. continue;
  1193. }
  1194. src = br_src(&doc, i);
  1195. if (!src[0] || contains_ci(src, ".svg") ||
  1196. starts_with(src, "data:")) {
  1197. preload_node++;
  1198. continue;
  1199. }
  1200. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  1201. preload_node++;
  1202. continue;
  1203. }
  1204. if (image_count >= BR_MAX_IMAGES) {
  1205. preload_node = doc.nnode;
  1206. break;
  1207. }
  1208. if (img_top[i] >
  1209. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  1210. preload_active = 0;
  1211. preload_pending = 1;
  1212. preload_scroll = page_scroll.offset;
  1213. set_status(post_status_text, post_status_error,
  1214. post_status_ttl);
  1215. ngui_invalidate(&ui);
  1216. return;
  1217. }
  1218. preload_node = i + 1;
  1219. s_append(msg, &n, "Loading images ", sizeof(msg));
  1220. s_append_dec(msg, &n, (unsigned int)preload_loaded + 1,
  1221. sizeof(msg));
  1222. s_append(msg, &n, "...", sizeof(msg));
  1223. set_status(msg, 0, 0);
  1224. ngui_invalidate(&ui);
  1225. data = 0;
  1226. len = 0;
  1227. rv = fetch_image(url, BR_IMG_FILE_MAX, &data, &len, err,
  1228. sizeof(err));
  1229. if (rv == FETCH_ABORT) {
  1230. preload_active = 0;
  1231. preload_pending = 0;
  1232. return;
  1233. }
  1234. if (rv == 0 &&
  1235. decode_image_data(data, len, &images[image_count]) == 0) {
  1236. nd->img_index = (short)image_count;
  1237. image_count++;
  1238. preload_loaded++;
  1239. layout_valid = 0;
  1240. }
  1241. ngui_invalidate(&ui);
  1242. return;
  1243. }
  1244. preload_active = 0;
  1245. preload_pending = 0;
  1246. set_status(post_status_text, post_status_error, post_status_ttl);
  1247. ngui_invalidate(&ui);
  1248. }
  1249. static void history_push(const char *url)
  1250. {
  1251. if (!url || !url[0])
  1252. return;
  1253. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  1254. s_eq(history[hist_pos], url))
  1255. return;
  1256. if (hist_len > 0 && hist_pos + 1 < hist_len)
  1257. hist_len = hist_pos + 1;
  1258. if (hist_len < BR_HISTORY) {
  1259. s_copy(history[hist_len], url, BR_URL_MAX);
  1260. hist_pos = hist_len;
  1261. hist_len++;
  1262. } else {
  1263. int i;
  1264. for (i = 1; i < BR_HISTORY; i++)
  1265. s_copy(history[i - 1], history[i], BR_URL_MAX);
  1266. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  1267. hist_pos = BR_HISTORY - 1;
  1268. }
  1269. }
  1270. static void load_page(const char *url, int local, int push)
  1271. {
  1272. unsigned char *body = 0;
  1273. unsigned int len = 0;
  1274. int truncated = 0;
  1275. struct img_info image_info;
  1276. char ctype[64];
  1277. char final[BR_URL_MAX];
  1278. char err[80];
  1279. const char *detail = 0;
  1280. int rv;
  1281. final[0] = '\0';
  1282. cancel_fetch = 0;
  1283. preload_active = 0;
  1284. preload_pending = 0;
  1285. heap_clear();
  1286. image_reset();
  1287. layout_valid = 0;
  1288. page_scroll.offset = 0;
  1289. page_scroll.dragging = 0;
  1290. br_parse_plain(&doc, "", 0); /* blank while loading */
  1291. page_title[0] = '\0';
  1292. page_loading = 1;
  1293. page_is_local = local;
  1294. s_copy(page_url, url, sizeof(page_url));
  1295. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1296. url_in.len = s_len(url_in.text);
  1297. url_in.cursor = url_in.len;
  1298. url_in.scroll = 0;
  1299. ngui_set_focus(&ui, 0);
  1300. if (final[0])
  1301. final[0] = '\0';
  1302. if (push)
  1303. history_push(url);
  1304. set_status("Loading...", 0, 0);
  1305. ngui_invalidate(&ui);
  1306. redraw_now();
  1307. if (heap_start() != 0) {
  1308. show_error("Out of memory", "Cannot allocate the page buffer");
  1309. return;
  1310. }
  1311. browser_rules_alloc();
  1312. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  1313. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  1314. &truncated);
  1315. if (rv == FETCH_ABORT)
  1316. return;
  1317. if (rv != 0) {
  1318. detail = err;
  1319. show_error("Cannot load this page", detail);
  1320. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1321. url_in.len = s_len(url_in.text);
  1322. url_in.cursor = url_in.len;
  1323. url_in.scroll = 0;
  1324. return;
  1325. }
  1326. page_is_local = local;
  1327. if (final[0]) {
  1328. s_copy(page_url, final, sizeof(page_url));
  1329. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1330. url_in.len = s_len(url_in.text);
  1331. url_in.cursor = url_in.len;
  1332. url_in.scroll = 0;
  1333. }
  1334. if (contains_ci(ctype, "text/plain")) {
  1335. br_parse_plain(&doc, (const char *)body, len);
  1336. } else if (contains_ci(ctype, "image/") ||
  1337. (!contains_ci(ctype, "text/html") &&
  1338. img_sniff(body, len, &image_info) == 0)) {
  1339. unsigned int node = br_parse_image_doc(&doc, page_url);
  1340. if (node)
  1341. decode_direct_image(body, len, node);
  1342. s_copy(page_title, "Image", sizeof(page_title));
  1343. } else {
  1344. br_parse(&doc, (const char *)body, len);
  1345. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  1346. sizeof(page_title));
  1347. if (load_stylesheets() == FETCH_ABORT)
  1348. return;
  1349. if (pending_action)
  1350. return;
  1351. }
  1352. post_status_text[0] = '\0';
  1353. post_status_error = 0;
  1354. post_status_ttl = 0;
  1355. if (truncated) {
  1356. s_copy(post_status_text, "Page truncated at the buffer limit",
  1357. sizeof(post_status_text));
  1358. post_status_ttl = 6000;
  1359. } else if (doc.truncated) {
  1360. s_copy(post_status_text, "Page truncated by the parser",
  1361. sizeof(post_status_text));
  1362. post_status_ttl = 6000;
  1363. } else if (starts_with(page_url, "https://")) {
  1364. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  1365. sizeof(post_status_text));
  1366. post_status_ttl = 6000;
  1367. }
  1368. preload_begin();
  1369. page_loading = 0;
  1370. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1371. url_in.len = s_len(url_in.text);
  1372. url_in.cursor = url_in.len;
  1373. url_in.scroll = 0;
  1374. ngui_set_focus(&ui, 0);
  1375. ngui_invalidate(&ui);
  1376. }
  1377. static void load_home(int push)
  1378. {
  1379. cancel_fetch = 0;
  1380. preload_active = 0;
  1381. preload_pending = 0;
  1382. heap_clear();
  1383. image_reset();
  1384. layout_valid = 0;
  1385. page_scroll.offset = 0;
  1386. page_scroll.dragging = 0;
  1387. br_parse_plain(&doc, "", 0);
  1388. page_loading = 1;
  1389. page_is_local = 0;
  1390. s_copy(page_url, "about:home", sizeof(page_url));
  1391. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1392. url_in.len = s_len(url_in.text);
  1393. url_in.cursor = url_in.len;
  1394. url_in.scroll = 0;
  1395. ngui_set_focus(&ui, 0);
  1396. if (push)
  1397. history_push(page_url);
  1398. ngui_invalidate(&ui);
  1399. redraw_now();
  1400. if (heap_start() != 0) {
  1401. show_error("Out of memory", "Cannot allocate the browser heap");
  1402. return;
  1403. }
  1404. browser_rules_alloc();
  1405. {
  1406. static const char home[] =
  1407. "<html><head><title>Nebs Browser</title><style>"
  1408. "body { margin: 10px; color: #e4e6f0; }"
  1409. "h1 { color: #7fb0ff; }"
  1410. ".box { background-color: #262b3a; margin: 12px; "
  1411. "padding: 10px; }"
  1412. "a { color: #7fb0ff; }"
  1413. "pre { background-color: #32384a; }"
  1414. "</style></head><body>"
  1415. "<h1>Nebs Browser</h1>"
  1416. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  1417. "shared HTTP client and the image library.</p>"
  1418. "<div class=\"box\"><b>Try:</b>"
  1419. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  1420. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  1421. "<li><a href=\"http://10.0.2.2:8000/\">"
  1422. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  1423. "<li><a href=\"https://example.com/\">"
  1424. "https://example.com/</a> (TLS, not verified)</li>"
  1425. "</ul></div>"
  1426. "<p>Type a URL in the bar above. Esc closes the "
  1427. "window, Ctrl+L focuses the address bar.</p>"
  1428. "<pre>javascript: not supported\nforms: not supported"
  1429. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  1430. "</body></html>";
  1431. br_parse(&doc, home, sizeof(home) - 1);
  1432. br_parse_inline_css(&doc);
  1433. br_reset_styles(&doc);
  1434. s_copy(page_title, doc.title, sizeof(page_title));
  1435. }
  1436. post_status_text[0] = '\0';
  1437. post_status_error = 0;
  1438. post_status_ttl = 0;
  1439. page_loading = 0;
  1440. set_status("", 0, 0);
  1441. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1442. url_in.len = s_len(url_in.text);
  1443. url_in.cursor = url_in.len;
  1444. url_in.scroll = 0;
  1445. ngui_set_focus(&ui, 0);
  1446. ngui_invalidate(&ui);
  1447. }
  1448. static void navigate(const char *input, int push)
  1449. {
  1450. char target[BR_URL_MAX];
  1451. char *t;
  1452. if (!input)
  1453. return;
  1454. s_copy(target, input, sizeof(target));
  1455. t = trim(target);
  1456. if (!t[0])
  1457. return;
  1458. if (s_eq(t, "about:home")) {
  1459. load_home(push);
  1460. return;
  1461. }
  1462. if (starts_with(t, "file://")) {
  1463. make_abs_local(t + 7, target, sizeof(target));
  1464. load_page(target, 1, push);
  1465. return;
  1466. }
  1467. if (is_http(t)) {
  1468. load_page(t, 0, push);
  1469. return;
  1470. }
  1471. {
  1472. struct sys_stat st;
  1473. if (t[0] == '/' || (u_stat(t, &st) == 0 && !st.is_dir)) {
  1474. make_abs_local(t, target, sizeof(target));
  1475. load_page(target, 1, push);
  1476. return;
  1477. }
  1478. }
  1479. {
  1480. char with_scheme[BR_URL_MAX];
  1481. unsigned int n = 0;
  1482. s_append(with_scheme, &n, "http://", sizeof(with_scheme));
  1483. s_append(with_scheme, &n, t, sizeof(with_scheme));
  1484. load_page(with_scheme, 0, push);
  1485. }
  1486. }
  1487. /* ---- layout ---- */
  1488. static struct br_style base_style(void)
  1489. {
  1490. struct br_style s = { 0 };
  1491. s.color = ui.theme.text;
  1492. s.bg = ui.theme.bg;
  1493. s.has_bg = 0;
  1494. s.border_color = 0;
  1495. s.scale = 1;
  1496. s.bold = 0;
  1497. s.underline = 0;
  1498. s.align = BR_ALIGN_LEFT;
  1499. s.display = BR_DISPLAY_BLOCK;
  1500. s.no_bullet = 0;
  1501. s.uppercase = 0;
  1502. s.border_w = 0;
  1503. s.width_kind = s.max_width_kind = s.height_kind = 0;
  1504. s.width = s.max_width = s.height = 0;
  1505. s.line_h_pct = 0;
  1506. s.line_h_px = 0;
  1507. s.mt = s.mb = s.ml = s.mr = 0;
  1508. s.pt = s.pb = s.pl = s.pr = 0;
  1509. return s;
  1510. }
  1511. static int run_width(const struct lay_run *r)
  1512. {
  1513. if (r->img >= 0)
  1514. return r->iw;
  1515. if (r->img == -2)
  1516. return r->iw;
  1517. {
  1518. unsigned int n = r->has_lit ? s_len(r->lit) : r->len;
  1519. return (int)(n * (unsigned int)(8 * r->scale) +
  1520. (r->bold ? 1u : 0u));
  1521. }
  1522. }
  1523. static void flush_line(struct lay *l)
  1524. {
  1525. int total, x, i, vis;
  1526. if (!l->nruns && l->line_x == l->left) {
  1527. l->line_h = 0;
  1528. return;
  1529. }
  1530. total = l->line_x - l->left;
  1531. x = l->left;
  1532. vis = 1;
  1533. if (l->draw) {
  1534. int lh = l->line_h ? l->line_h : 16;
  1535. vis = l->line_y + lh >= page_rect.y &&
  1536. l->line_y <= page_rect.y + page_rect.h;
  1537. }
  1538. if (l->align == BR_ALIGN_CENTER)
  1539. x += (l->right - l->left - total) / 2;
  1540. else if (l->align == BR_ALIGN_RIGHT)
  1541. x = l->right - total;
  1542. if (x < l->left)
  1543. x = l->left;
  1544. for (i = 0; i < l->nruns; i++) {
  1545. struct lay_run *r = &l->runs[i];
  1546. int w = run_width(r);
  1547. x += r->gap;
  1548. if (l->draw && vis) {
  1549. if (r->img == -2) {
  1550. int hh = r->ih ? r->ih : 20;
  1551. ngui_fill_rect(l->ui,
  1552. (struct ngui_rect){x, l->line_y, w, hh},
  1553. l->ui->theme.panel_alt);
  1554. ngui_frame(l->ui,
  1555. (struct ngui_rect){x, l->line_y, w, hh},
  1556. l->ui->theme.border);
  1557. ngui_text_styled(l->ui, x + 6, l->line_y + 2,
  1558. r->lit, s_len(r->lit), r->color,
  1559. r->scale, r->bold);
  1560. } else if (r->img >= 0) {
  1561. struct br_image *bi = &images[r->img];
  1562. if (bi->state == 1) {
  1563. struct img_blit b;
  1564. b.dst = l->ui->px;
  1565. b.dst_w = l->ui->w;
  1566. b.dst_h = l->ui->h;
  1567. b.clip_x = page_rect.x;
  1568. b.clip_y = page_rect.y;
  1569. b.clip_w = page_rect.w - 12;
  1570. b.clip_h = page_rect.h;
  1571. b.x = x;
  1572. b.y = l->line_y;
  1573. b.scale = ((unsigned int)r->iw << 16) /
  1574. bi->img.w;
  1575. b.bg = ui.theme.bg;
  1576. b.bg2 = ui.theme.bg;
  1577. b.flags = IMG_BLIT_OVER_DST;
  1578. img_draw(&bi->img, &b);
  1579. }
  1580. } else {
  1581. const char *s = r->has_lit ? r->lit :
  1582. doc.text + r->off;
  1583. unsigned int n = r->has_lit ? s_len(r->lit) :
  1584. r->len;
  1585. ngui_text_styled(l->ui, x, l->line_y, s, n,
  1586. r->color, r->scale, r->bold);
  1587. if (r->underline)
  1588. ngui_fill_rect(l->ui,
  1589. (struct ngui_rect){x,
  1590. l->line_y + 16 * r->scale - 2,
  1591. w, 1}, r->color);
  1592. }
  1593. if (r->href) {
  1594. if (nhits < HIT_MAX) {
  1595. struct hit *h = &hits[nhits];
  1596. int hh = r->img >= 0 ? r->ih :
  1597. 16 * r->scale;
  1598. int merge = nhits > 0 &&
  1599. hits[nhits - 1].node == r->href &&
  1600. hits[nhits - 1].y == l->line_y &&
  1601. hits[nhits - 1].h == hh &&
  1602. x <= hits[nhits - 1].x +
  1603. hits[nhits - 1].w + 2;
  1604. if (merge) {
  1605. struct hit *p = &hits[nhits - 1];
  1606. int end = x + w;
  1607. if (end > p->x + p->w)
  1608. p->w = end - p->x;
  1609. } else {
  1610. h->x = x;
  1611. h->y = l->line_y;
  1612. h->w = w;
  1613. h->h = hh;
  1614. h->node = r->href;
  1615. nhits++;
  1616. }
  1617. }
  1618. }
  1619. }
  1620. x += w;
  1621. }
  1622. l->y += l->line_h + 2;
  1623. l->nruns = 0;
  1624. l->line_x = l->left;
  1625. l->run_x = l->left;
  1626. l->line_h = 0;
  1627. l->space_pending = 0;
  1628. }
  1629. static void add_run(struct lay *l, unsigned short off, unsigned short len,
  1630. const struct br_style *st, unsigned short href,
  1631. const char *lit)
  1632. {
  1633. unsigned int n = lit ? s_len(lit) : len;
  1634. int w = (int)(n * (unsigned int)(8 * st->scale) +
  1635. (st->bold ? 1u : 0u));
  1636. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  1637. flush_line(l);
  1638. if (l->nruns == 0) {
  1639. l->line_y = l->y;
  1640. l->line_h = 0;
  1641. }
  1642. {
  1643. struct lay_run *r = &l->runs[l->nruns++];
  1644. int gap = l->line_x - l->run_x;
  1645. if (gap < 0)
  1646. gap = 0;
  1647. r->gap = (unsigned short)gap;
  1648. r->off = off;
  1649. r->len = len;
  1650. r->color = st->color;
  1651. r->href = href;
  1652. r->has_lit = 0;
  1653. r->lit[0] = '\0';
  1654. if (lit && lit[0]) {
  1655. unsigned int i;
  1656. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  1657. r->lit[i] = lit[i];
  1658. r->lit[i] = '\0';
  1659. r->has_lit = 1;
  1660. }
  1661. r->img = -1;
  1662. r->iw = r->ih = 0;
  1663. r->scale = st->scale;
  1664. r->bold = st->bold;
  1665. r->underline = st->underline;
  1666. }
  1667. l->line_x += w;
  1668. l->run_x = l->line_x;
  1669. {
  1670. int lh = 16 * st->scale;
  1671. if (st->line_h_px)
  1672. lh = st->line_h_px;
  1673. else if (st->line_h_pct)
  1674. lh = (16 * st->scale) * st->line_h_pct / 100;
  1675. if (lh < 16 * st->scale)
  1676. lh = 16 * st->scale;
  1677. if (l->line_h < lh)
  1678. l->line_h = lh;
  1679. }
  1680. }
  1681. static void add_image_run(struct lay *l, unsigned int node,
  1682. const struct br_style *st, unsigned short href)
  1683. {
  1684. struct br_image *bi = 0;
  1685. int idx = doc.nodes[node].img_index;
  1686. int dw, dh, maxw;
  1687. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  1688. bi = &images[idx];
  1689. if (l->space_pending && (l->nruns > 0 || l->line_x > l->left)) {
  1690. if (l->line_x + 8 <= l->right)
  1691. l->line_x += 8;
  1692. }
  1693. l->space_pending = 0;
  1694. if (!bi) {
  1695. const char *alt = br_alt(&doc, node);
  1696. struct br_style gs = *st;
  1697. char tmp[96];
  1698. unsigned int n = 0;
  1699. int w;
  1700. gs.color = BR_GRAY;
  1701. gs.underline = 0;
  1702. s_append(tmp, &n, "[", sizeof(tmp));
  1703. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  1704. s_append(tmp, &n, "]", sizeof(tmp));
  1705. w = (int)(n * (unsigned int)(8 * gs.scale));
  1706. if (l->line_x + w > l->right &&
  1707. (l->nruns > 0 || l->line_x > l->left))
  1708. flush_line(l);
  1709. add_run(l, 0, 0, &gs, href, tmp);
  1710. if (!l->draw) {
  1711. int t = l->line_y < 0 ? 0 : l->line_y;
  1712. int hh = 16 * gs.scale;
  1713. if (t > 65535)
  1714. t = 65535;
  1715. if (hh > 65535)
  1716. hh = 65535;
  1717. img_top[node] = (unsigned short)t;
  1718. img_h[node] = (unsigned short)hh;
  1719. }
  1720. return;
  1721. }
  1722. maxw = l->right - l->left;
  1723. if (maxw < 8)
  1724. maxw = 8;
  1725. {
  1726. int iw = bi->native_w, ih = bi->native_h;
  1727. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  1728. if (iw <= 0 || ih <= 0) {
  1729. iw = (int)bi->img.w;
  1730. ih = (int)bi->img.h;
  1731. }
  1732. dw = iw;
  1733. dh = ih;
  1734. if (doc.nodes[node].width_attr) {
  1735. int want = doc.nodes[node].width_attr;
  1736. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  1737. have_w = 1;
  1738. }
  1739. if (doc.nodes[node].height_attr) {
  1740. int want = doc.nodes[node].height_attr;
  1741. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  1742. have_h = 1;
  1743. }
  1744. if (have_w && !have_h)
  1745. dh = ih ? ih * dw / iw : 0;
  1746. if (have_h && !have_w)
  1747. dw = iw ? iw * dh / ih : 0;
  1748. if (st->width_kind) {
  1749. css_w = 1;
  1750. dw = st->width_kind == 2 ? maxw * (int)st->width / 100 :
  1751. (int)st->width;
  1752. }
  1753. if (st->height_kind) {
  1754. css_h = 1;
  1755. dh = st->height_kind == 2 ? maxw * (int)st->height / 100 :
  1756. (int)st->height;
  1757. }
  1758. if (css_w && !css_h)
  1759. dh = ih ? ih * dw / iw : 0;
  1760. if (css_h && !css_w)
  1761. dw = iw ? iw * dh / ih : 0;
  1762. if (st->max_width_kind) {
  1763. int mw = st->max_width_kind == 2 ?
  1764. maxw * (int)st->max_width / 100 :
  1765. (int)st->max_width;
  1766. if (mw > 0 && dw > mw) {
  1767. dh = iw ? ih * mw / iw : 0;
  1768. dw = mw;
  1769. }
  1770. }
  1771. }
  1772. if (dw < 8)
  1773. dw = 8;
  1774. if (dh < 8)
  1775. dh = 8;
  1776. if (dw > maxw) {
  1777. dh = dw ? dh * maxw / dw : dh;
  1778. dw = maxw;
  1779. }
  1780. if (!l->draw) {
  1781. int t = l->line_y < 0 ? 0 : l->line_y;
  1782. if (t > 65535)
  1783. t = 65535;
  1784. if (dh > 65535)
  1785. dh = 65535;
  1786. img_top[node] = (unsigned short)t;
  1787. img_h[node] = (unsigned short)dh;
  1788. }
  1789. if (l->line_x + dw > l->right && (l->nruns > 0 ||
  1790. l->line_x > l->left))
  1791. flush_line(l);
  1792. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  1793. flush_line(l);
  1794. if (l->nruns == 0) {
  1795. l->line_y = l->y;
  1796. l->line_h = 0;
  1797. }
  1798. {
  1799. struct lay_run *r = &l->runs[l->nruns++];
  1800. int gap = l->line_x - l->run_x;
  1801. if (gap < 0)
  1802. gap = 0;
  1803. r->gap = (unsigned short)gap;
  1804. r->off = 0;
  1805. r->len = 0;
  1806. r->color = 0;
  1807. r->href = href;
  1808. r->has_lit = 0;
  1809. r->lit[0] = '\0';
  1810. r->img = (short)idx;
  1811. r->iw = (unsigned short)dw;
  1812. r->ih = (unsigned short)dh;
  1813. r->scale = 1;
  1814. r->bold = 0;
  1815. r->underline = 0;
  1816. }
  1817. l->line_x += dw;
  1818. l->run_x = l->line_x;
  1819. if (l->line_h < dh)
  1820. l->line_h = dh;
  1821. }
  1822. static void emit_text(struct lay *l, const char *s, unsigned int len,
  1823. const struct br_style *st, unsigned short href, int pre)
  1824. {
  1825. unsigned int i = 0;
  1826. unsigned int base;
  1827. int cw = 8 * st->scale;
  1828. int adv = cw + (st->bold ? 1 : 0);
  1829. if (!s || !len)
  1830. return;
  1831. base = (unsigned int)(s - doc.text);
  1832. if (st->uppercase) {
  1833. char *p = (char *)s;
  1834. unsigned int j;
  1835. for (j = 0; j < len; j++)
  1836. if (p[j] >= 'a' && p[j] <= 'z')
  1837. p[j] = (char)(p[j] - 'a' + 'A');
  1838. }
  1839. if (pre) {
  1840. while (i < len) {
  1841. unsigned int start;
  1842. if (s[i] == '\n') {
  1843. flush_line(l);
  1844. i++;
  1845. continue;
  1846. }
  1847. if (s[i] == ' ') {
  1848. if (l->line_x + cw > l->right &&
  1849. (l->nruns > 0 || l->line_x > l->left))
  1850. flush_line(l);
  1851. else
  1852. l->line_x += cw;
  1853. i++;
  1854. continue;
  1855. }
  1856. start = i;
  1857. while (i < len && s[i] != ' ' && s[i] != '\n')
  1858. i++;
  1859. {
  1860. unsigned int n = i - start;
  1861. int w = (int)(n * (unsigned int)adv);
  1862. if (l->line_x + w > l->right &&
  1863. (l->nruns > 0 || l->line_x > l->left))
  1864. flush_line(l);
  1865. if (w > l->right - l->left) {
  1866. int maxc = (l->right - l->left) / adv;
  1867. unsigned int off = start;
  1868. if (maxc < 1)
  1869. maxc = 1;
  1870. while (n > 0) {
  1871. unsigned int take = n >
  1872. (unsigned int)maxc ?
  1873. (unsigned int)maxc : n;
  1874. add_run(l, (unsigned short)(base + off),
  1875. (unsigned short)take,
  1876. st, href, 0);
  1877. off += take;
  1878. n -= take;
  1879. if (n)
  1880. flush_line(l);
  1881. }
  1882. } else {
  1883. add_run(l, (unsigned short)(base + start),
  1884. (unsigned short)n, st, href, 0);
  1885. }
  1886. }
  1887. }
  1888. return;
  1889. }
  1890. while (i < len) {
  1891. unsigned int start, n;
  1892. int w;
  1893. if (s[i] == ' ') {
  1894. l->space_pending = 1;
  1895. i++;
  1896. continue;
  1897. }
  1898. start = i;
  1899. while (i < len && s[i] != ' ')
  1900. i++;
  1901. n = i - start;
  1902. w = (int)(n * (unsigned int)adv);
  1903. if (l->space_pending &&
  1904. (l->nruns > 0 || l->line_x > l->left)) {
  1905. if (l->line_x + cw <= l->right)
  1906. l->line_x += cw;
  1907. }
  1908. l->space_pending = 0;
  1909. if (l->line_x + w > l->right &&
  1910. (l->nruns > 0 || l->line_x > l->left))
  1911. flush_line(l);
  1912. if (w > l->right - l->left) {
  1913. int maxc = (l->right - l->left) / adv;
  1914. unsigned int off = start;
  1915. if (maxc < 1)
  1916. maxc = 1;
  1917. while (n > 0) {
  1918. unsigned int take = n > (unsigned int)maxc ?
  1919. (unsigned int)maxc : n;
  1920. add_run(l, (unsigned short)(base + off),
  1921. (unsigned short)take, st, href, 0);
  1922. off += take;
  1923. n -= take;
  1924. if (n)
  1925. flush_line(l);
  1926. }
  1927. } else if (n) {
  1928. add_run(l, (unsigned short)(base + start),
  1929. (unsigned short)n, st, href, 0);
  1930. }
  1931. }
  1932. }
  1933. static int list_index(unsigned int parent, unsigned int node)
  1934. {
  1935. unsigned int n = 0, i;
  1936. for (i = doc.nodes[parent].first; i && i != node;
  1937. i = doc.nodes[i].next)
  1938. if (doc.nodes[i].tag == BR_TAG_LI)
  1939. n++;
  1940. return (int)n + 1;
  1941. }
  1942. static const char *form_text(unsigned int node)
  1943. {
  1944. const char *v = br_value(&doc, node);
  1945. const char *p = br_placeholder(&doc, node);
  1946. const char *t = br_type(&doc, node);
  1947. if (s_eq(t, "hidden"))
  1948. return 0;
  1949. if (s_eq(t, "submit") || s_eq(t, "button") || s_eq(t, "reset"))
  1950. return v[0] ? v : "Button";
  1951. if (v[0])
  1952. return v;
  1953. if (p[0])
  1954. return p;
  1955. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  1956. return "Text";
  1957. if (doc.nodes[node].tag == BR_TAG_SELECT)
  1958. return "Select";
  1959. return "Search";
  1960. }
  1961. static void add_form_run(struct lay *l, unsigned int node,
  1962. const struct br_style *st, unsigned short href)
  1963. {
  1964. const char *text = form_text(node);
  1965. struct lay_run *r;
  1966. int tw, w, h = 20, i;
  1967. if (!text)
  1968. return;
  1969. tw = (int)s_len(text) * 8 * st->scale;
  1970. if (st->width_kind == 1)
  1971. w = st->width;
  1972. else if (st->width_kind == 2)
  1973. w = (l->right - l->left) * (int)st->width / 100;
  1974. else
  1975. w = tw + 18;
  1976. if (w < 64)
  1977. w = 64;
  1978. if (w > l->right - l->left)
  1979. w = l->right - l->left;
  1980. if (w < 8)
  1981. w = 8;
  1982. if (l->line_x + w > l->right &&
  1983. (l->nruns > 0 || l->line_x > l->left))
  1984. flush_line(l);
  1985. if (l->nruns >= 96)
  1986. return;
  1987. r = &l->runs[l->nruns++];
  1988. r->gap = (unsigned short)(l->line_x - l->run_x);
  1989. r->off = r->len = 0;
  1990. r->color = st->color;
  1991. r->href = href;
  1992. r->has_lit = 1;
  1993. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  1994. r->lit[i] = text[i];
  1995. r->lit[i] = '\0';
  1996. r->img = -2;
  1997. r->iw = (unsigned short)w;
  1998. r->ih = (unsigned short)h;
  1999. r->scale = st->scale;
  2000. r->bold = st->bold;
  2001. r->underline = 0;
  2002. l->line_x += w;
  2003. l->run_x = l->line_x;
  2004. if (l->line_h < h)
  2005. l->line_h = h;
  2006. }
  2007. static void layout_children(struct lay *l, unsigned int parent,
  2008. const struct br_style *pst, int depth,
  2009. unsigned short link);
  2010. static void layout_flex_children(struct lay *l, unsigned int parent,
  2011. const struct br_style *pst, int depth,
  2012. unsigned short link);
  2013. static void layout_grid_children(struct lay *l, unsigned int parent,
  2014. const struct br_style *pst, int depth,
  2015. unsigned short link);
  2016. /* A flex container whose items are only inline spans is usually just a
  2017. * heading/icon pair. Our flex row positions such items without emitting
  2018. * their inline text in some deep page contexts; normal inline flow renders
  2019. * the same content correctly. */
  2020. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  2021. {
  2022. unsigned int c;
  2023. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  2024. struct br_node *nd = &doc.nodes[c];
  2025. struct br_style cs;
  2026. if (nd->type == BR_NODE_TEXT)
  2027. continue;
  2028. br_style_for(&doc, c, pst, &cs);
  2029. if (cs.display == BR_DISPLAY_NONE)
  2030. continue;
  2031. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  2032. cs.width_kind || nd->tag == BR_TAG_IMG)
  2033. return 1;
  2034. }
  2035. return 0;
  2036. }
  2037. static void layout_block(struct lay *l, unsigned int node,
  2038. const struct br_style *st, int depth,
  2039. unsigned short link)
  2040. {
  2041. int old_left = l->left, old_right = l->right, old_align = l->align;
  2042. int top, l0, r0;
  2043. int flow_y, flow_left, flow_right, positioned;
  2044. if (depth > 24 || st->display == BR_DISPLAY_NONE)
  2045. return;
  2046. flow_y = l->y;
  2047. flow_left = l->left;
  2048. flow_right = l->right;
  2049. positioned = st->pos;
  2050. if (positioned) {
  2051. if (st->pos == 2) {
  2052. l->y = page_rect.y + (st->top_set ? st->top : 0);
  2053. l->left = page_rect.x;
  2054. l->right = page_rect.x + page_rect.w - 12;
  2055. } else {
  2056. l->y = flow_y + (st->top_set ? st->top : 0);
  2057. l->left = flow_left + (st->left_set ? st->left : 0);
  2058. l->right = flow_right + (st->left_set ? st->left : 0);
  2059. }
  2060. old_left = l->left;
  2061. old_right = l->right;
  2062. }
  2063. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  2064. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  2065. doc.nodes[node].tag == BR_TAG_SELECT) {
  2066. if (!(doc.nodes[node].tag == BR_TAG_INPUT &&
  2067. s_eq(br_type(&doc, node), "hidden")))
  2068. add_form_run(l, node, st, link);
  2069. l->y += 20;
  2070. return;
  2071. }
  2072. flush_line(l);
  2073. l->y += st->mt;
  2074. top = l->y;
  2075. l0 = old_left + st->ml;
  2076. r0 = old_right - st->mr;
  2077. if (r0 < l0 + 16)
  2078. r0 = l0 + 16;
  2079. if (l->draw && block_h[node] &&
  2080. top < page_rect.y + page_rect.h &&
  2081. top + block_h[node] > page_rect.y) {
  2082. if (st->has_bg)
  2083. ngui_fill_rect(l->ui, (struct ngui_rect){l0, top,
  2084. r0 - l0, block_h[node]},
  2085. st->bg);
  2086. if (st->border_w)
  2087. ngui_frame(l->ui, (struct ngui_rect){l0, top,
  2088. r0 - l0, block_h[node]},
  2089. st->border_color);
  2090. }
  2091. l->left = l0 + st->pl;
  2092. l->right = r0 - st->pr;
  2093. if (l->right < l->left + 8)
  2094. l->right = l->left + 8;
  2095. l->align = st->align;
  2096. l->y += st->pt;
  2097. if (doc.nodes[node].tag == BR_TAG_HR) {
  2098. if (l->draw)
  2099. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  2100. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  2101. l->y += 8;
  2102. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  2103. int vw = l->right - l->left;
  2104. int vh;
  2105. if (doc.nodes[node].width_pct)
  2106. vw = vw * doc.nodes[node].width_attr / 100;
  2107. else if (doc.nodes[node].width_attr)
  2108. vw = doc.nodes[node].width_attr;
  2109. if (vw > l->right - l->left)
  2110. vw = l->right - l->left;
  2111. if (vw < 8)
  2112. vw = 8;
  2113. vh = vw * 9 / 16;
  2114. if (vh > 240)
  2115. vh = 240;
  2116. if (vh < 80)
  2117. vh = 80;
  2118. if (l->draw) {
  2119. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  2120. vw, vh}, 0xD69A);
  2121. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  2122. vw, vh}, 0x8410);
  2123. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  2124. 0x4208);
  2125. }
  2126. l->y += vh + 4;
  2127. } else {
  2128. if (doc.nodes[node].tag == BR_TAG_LI && !st->no_bullet) {
  2129. char *m = li_marker[node];
  2130. if (!m[0]) {
  2131. unsigned int parent = doc.nodes[node].parent;
  2132. if (parent &&
  2133. doc.nodes[parent].tag == BR_TAG_OL) {
  2134. int idx = list_index(parent, node);
  2135. unsigned int n = 0;
  2136. s_append_dec(m, &n, (unsigned int)idx, 6);
  2137. s_append(m, &n, ".", 6);
  2138. } else {
  2139. s_copy(m, "-", 6);
  2140. }
  2141. }
  2142. if (l->draw) {
  2143. int mw = (int)s_len(m) * 8;
  2144. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  2145. st->color);
  2146. }
  2147. }
  2148. if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  2149. st->grid_gap > 0)
  2150. layout_grid_children(l, node, st, depth + 1, link);
  2151. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  2152. flex_wants_row(node, st))
  2153. layout_flex_children(l, node, st, depth + 1, link);
  2154. else
  2155. layout_children(l, node, st, depth + 1, link);
  2156. }
  2157. flush_line(l);
  2158. l->y += st->pb;
  2159. /* Honour an explicit CSS height. Fixed-height header/icon boxes often
  2160. * contain only absolutely positioned children, so their flow height
  2161. * would otherwise collapse to zero. */
  2162. if (st->height_kind == 1 && st->height > 0 &&
  2163. l->y < top + st->height)
  2164. l->y = top + st->height;
  2165. l->left = old_left;
  2166. l->right = old_right;
  2167. l->align = old_align;
  2168. l->y += st->mb;
  2169. if (!l->draw) {
  2170. int h = l->y - top;
  2171. if (h < 0)
  2172. h = 0;
  2173. if (h > 65535)
  2174. h = 65535;
  2175. block_h[node] = (unsigned short)h;
  2176. }
  2177. if (positioned) {
  2178. l->y = flow_y;
  2179. l->left = flow_left;
  2180. l->right = flow_right;
  2181. }
  2182. }
  2183. static int text_node_blank(const struct br_node *nd)
  2184. {
  2185. const char *t = doc.text + nd->text_off;
  2186. unsigned int i;
  2187. for (i = 0; i < nd->text_len; i++)
  2188. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  2189. t[i] != '\r')
  2190. return 0;
  2191. return 1;
  2192. }
  2193. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  2194. * text/image widths in the subtree, plus padding and margins. This keeps
  2195. * Bootstrap's floated nav items on one line instead of giving each the whole
  2196. * row. */
  2197. static int intrinsic_width(unsigned int node, const struct br_style *pst,
  2198. int depth)
  2199. {
  2200. unsigned int c;
  2201. int w = 0;
  2202. if (depth > 12)
  2203. return 0;
  2204. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  2205. struct br_node *nd = &doc.nodes[c];
  2206. struct br_style cs;
  2207. if (nd->type == BR_NODE_TEXT) {
  2208. w += (int)nd->text_len * (8 * pst->scale) +
  2209. (pst->bold ? 1 : 0);
  2210. continue;
  2211. }
  2212. br_style_for(&doc, c, pst, &cs);
  2213. if (cs.display == BR_DISPLAY_NONE)
  2214. continue;
  2215. if (cs.float_left)
  2216. w += 8;
  2217. if (nd->tag == BR_TAG_BR) {
  2218. w += 8;
  2219. continue;
  2220. }
  2221. if (nd->tag == BR_TAG_IMG) {
  2222. int idx = nd->img_index;
  2223. if (idx >= 0 && idx < image_count &&
  2224. images[idx].state == 1)
  2225. w += (int)images[idx].img.w;
  2226. else if (nd->width_attr)
  2227. w += nd->width_attr;
  2228. else
  2229. w += 64;
  2230. continue;
  2231. }
  2232. w += cs.pl + cs.pr + cs.ml + cs.mr;
  2233. w += intrinsic_width(c, &cs, depth + 1);
  2234. if (w > 4096)
  2235. break;
  2236. }
  2237. return w;
  2238. }
  2239. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  2240. * the main user: .row > .col-md-* with float:left and a percentage width.
  2241. * Each column is laid out with its own left/right edge and the row advances
  2242. * to the tallest column. Returns the first child not consumed. */
  2243. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  2244. const struct br_style *pst, int depth,
  2245. unsigned short link)
  2246. {
  2247. unsigned int n = first;
  2248. int row_left = l->left, row_right = l->right;
  2249. int row_top, row_bottom, x, any = 0;
  2250. flush_line(l);
  2251. row_top = l->y;
  2252. row_bottom = l->y;
  2253. x = row_left;
  2254. while (n) {
  2255. struct br_node *nd = &doc.nodes[n];
  2256. struct br_style cs;
  2257. int colw;
  2258. if (nd->type == BR_NODE_TEXT) {
  2259. if (text_node_blank(nd)) {
  2260. n = nd->next;
  2261. continue;
  2262. }
  2263. break;
  2264. }
  2265. br_style_for(&doc, n, pst, &cs);
  2266. if (cs.display == BR_DISPLAY_NONE) {
  2267. n = nd->next;
  2268. continue;
  2269. }
  2270. if (!cs.float_left || cs.display != BR_DISPLAY_BLOCK)
  2271. break;
  2272. if (cs.width_kind == 2)
  2273. colw = (row_right - row_left) * (int)cs.width / 100;
  2274. else if (cs.width_kind == 1)
  2275. colw = (int)cs.width;
  2276. else {
  2277. colw = intrinsic_width(n, &cs, 0) +
  2278. cs.pl + cs.pr + cs.ml + cs.mr + 8;
  2279. if (colw < 8)
  2280. colw = 8;
  2281. }
  2282. if (colw < 8)
  2283. colw = 8;
  2284. if (colw > row_right - row_left)
  2285. colw = row_right - row_left;
  2286. if (any && x + colw > row_right) {
  2287. row_top = row_bottom;
  2288. row_bottom = row_top;
  2289. x = row_left;
  2290. }
  2291. l->left = x;
  2292. l->right = x + colw;
  2293. if (l->right < l->left + 8)
  2294. l->right = l->left + 8;
  2295. l->y = row_top;
  2296. l->line_x = l->left;
  2297. l->run_x = l->left;
  2298. l->line_y = l->y;
  2299. l->line_h = 0;
  2300. l->nruns = 0;
  2301. l->space_pending = 0;
  2302. l->align = cs.align;
  2303. layout_block(l, n, &cs, depth + 1, link);
  2304. if (l->y > row_bottom)
  2305. row_bottom = l->y;
  2306. x += colw;
  2307. any++;
  2308. n = nd->next;
  2309. }
  2310. l->left = row_left;
  2311. l->right = row_right;
  2312. l->y = row_bottom;
  2313. l->line_x = l->left;
  2314. l->run_x = l->left;
  2315. l->line_y = l->y;
  2316. l->line_h = 0;
  2317. l->nruns = 0;
  2318. l->space_pending = 0;
  2319. return n;
  2320. }
  2321. /* A deliberately simple flex row: items are placed left to right, grow
  2322. * items share the leftover width, and a row wraps when the next item does not
  2323. * fit. It is enough for site headers, cards and Wikipedia's main-page boxes;
  2324. * flex-direction: column uses the normal block path. */
  2325. static int flex_item_width(struct lay *l, unsigned int n,
  2326. const struct br_style *cs, int avail)
  2327. {
  2328. struct br_node *nd = &doc.nodes[n];
  2329. (void)l;
  2330. int w;
  2331. if (cs->width_kind == 2)
  2332. w = avail * (int)cs->width / 100;
  2333. else if (cs->width_kind == 1)
  2334. w = (int)cs->width;
  2335. else if (nd->tag == BR_TAG_IMG) {
  2336. int idx = nd->img_index;
  2337. if (idx >= 0 && idx < image_count &&
  2338. images[idx].state == 1)
  2339. w = (int)images[idx].img.w;
  2340. else if (nd->width_attr)
  2341. w = (int)nd->width_attr;
  2342. else
  2343. w = 64;
  2344. } else {
  2345. w = intrinsic_width(n, cs, 0);
  2346. w += cs->pl + cs->pr + cs->ml + cs->mr;
  2347. }
  2348. if (w < 24)
  2349. w = 24;
  2350. if (w > avail)
  2351. w = avail;
  2352. return w;
  2353. }
  2354. static void layout_flex_children(struct lay *l, unsigned int parent,
  2355. const struct br_style *pst, int depth,
  2356. unsigned short link)
  2357. {
  2358. unsigned int n, c;
  2359. int row_left = l->left, row_right = l->right;
  2360. int avail = row_right - row_left;
  2361. int grow_count = 0, fixed = 0, grow_w;
  2362. int x = row_left, row_top = l->y, row_bottom = l->y, any = 0;
  2363. if (avail < 160 || depth > 24) {
  2364. layout_children(l, parent, pst, depth, link);
  2365. return;
  2366. }
  2367. /* If direct text is not just whitespace, normal block flow handles it
  2368. * better than pretending it is a flex item. */
  2369. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  2370. struct br_node *nd = &doc.nodes[c];
  2371. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  2372. layout_children(l, parent, pst, depth, link);
  2373. return;
  2374. }
  2375. }
  2376. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  2377. struct br_node *nd = &doc.nodes[c];
  2378. struct br_style cs;
  2379. if (nd->type == BR_NODE_TEXT)
  2380. continue;
  2381. br_style_for(&doc, c, pst, &cs);
  2382. if (cs.display == BR_DISPLAY_NONE)
  2383. continue;
  2384. if (cs.flex_grow && !cs.width_kind)
  2385. grow_count++;
  2386. else
  2387. fixed += flex_item_width(l, c, &cs, avail);
  2388. }
  2389. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  2390. if (grow_w < 96)
  2391. grow_w = 96;
  2392. n = doc.nodes[parent].first;
  2393. while (n) {
  2394. struct br_node *nd = &doc.nodes[n];
  2395. struct br_style cs;
  2396. unsigned short lk = link;
  2397. int colw;
  2398. if (nd->type == BR_NODE_TEXT) {
  2399. n = nd->next;
  2400. continue;
  2401. }
  2402. br_style_for(&doc, n, pst, &cs);
  2403. if (cs.display == BR_DISPLAY_NONE) {
  2404. n = nd->next;
  2405. continue;
  2406. }
  2407. if (nd->tag == BR_TAG_A && nd->href_off)
  2408. lk = (unsigned short)n;
  2409. if (cs.flex_grow && !cs.width_kind)
  2410. colw = grow_w;
  2411. else
  2412. colw = flex_item_width(l, n, &cs, avail);
  2413. if (colw > row_right - row_left)
  2414. colw = row_right - row_left;
  2415. if (pst->flex_wrap != 2 && any && x + colw > row_right) {
  2416. row_top = row_bottom;
  2417. row_bottom = row_top;
  2418. x = row_left;
  2419. }
  2420. l->left = x;
  2421. l->right = x + colw;
  2422. if (l->right < l->left + 8)
  2423. l->right = l->left + 8;
  2424. l->y = row_top;
  2425. l->line_x = l->left;
  2426. l->run_x = l->left;
  2427. l->line_y = l->y;
  2428. l->line_h = 0;
  2429. l->nruns = 0;
  2430. l->space_pending = 0;
  2431. l->align = cs.align;
  2432. layout_block(l, n, &cs, depth + 1, lk);
  2433. if (l->y > row_bottom)
  2434. row_bottom = l->y;
  2435. x += colw;
  2436. any++;
  2437. n = nd->next;
  2438. }
  2439. l->left = row_left;
  2440. l->right = row_right;
  2441. l->y = row_bottom;
  2442. l->line_x = l->left;
  2443. l->run_x = l->left;
  2444. l->line_y = l->y;
  2445. l->line_h = 0;
  2446. l->nruns = 0;
  2447. l->space_pending = 0;
  2448. }
  2449. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  2450. * plus the grid-area hints used by site shells (site notice/footer full
  2451. * width, column-start left, page-content right). Anything more elaborate
  2452. * falls back to normal block flow. */
  2453. static int grid_track_width(unsigned char kind, unsigned short val,
  2454. int avail, int other)
  2455. {
  2456. if (kind == 2)
  2457. return avail * (int)val / 100;
  2458. if (kind == 1)
  2459. return val;
  2460. return other;
  2461. }
  2462. static void layout_grid_children(struct lay *l, unsigned int parent,
  2463. const struct br_style *pst, int depth,
  2464. unsigned short link)
  2465. {
  2466. unsigned int n;
  2467. int row_left = l->left, row_right = l->right;
  2468. int avail = row_right - row_left;
  2469. int gap = pst->grid_gap;
  2470. int track_total = avail - gap;
  2471. int col0, col1, x0, x1;
  2472. int row_y, row_bottom, have_left = 0, have_right = 0;
  2473. unsigned int c;
  2474. if (avail < 32 || depth > 24)
  2475. return;
  2476. if (track_total < 16)
  2477. track_total = 16;
  2478. col0 = grid_track_width((unsigned char)(pst->width_kind),
  2479. pst->width, track_total, 0);
  2480. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  2481. pst->max_width, track_total, 0);
  2482. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  2483. int w0 = pst->width ? pst->width : 1;
  2484. int w1 = pst->max_width ? pst->max_width : 1;
  2485. col0 = track_total * w0 / (w0 + w1);
  2486. col1 = track_total - col0;
  2487. } else if (pst->width_kind == 3) {
  2488. col0 = track_total - col1;
  2489. if (col0 < 24)
  2490. col0 = 24;
  2491. } else if (pst->max_width_kind == 3) {
  2492. col1 = track_total - col0;
  2493. if (col1 < 24)
  2494. col1 = 24;
  2495. }
  2496. if (col0 < 24)
  2497. col0 = 24;
  2498. if (col1 < 24)
  2499. col1 = 24;
  2500. if (col0 + col1 > track_total) {
  2501. col1 = track_total - col0;
  2502. if (col1 < 24)
  2503. col1 = 24;
  2504. }
  2505. x0 = row_left;
  2506. x1 = row_left + col0 + gap;
  2507. /* Direct text makes a grid ambiguous; use block flow instead. */
  2508. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  2509. struct br_node *nd = &doc.nodes[c];
  2510. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  2511. layout_children(l, parent, pst, depth, link);
  2512. return;
  2513. }
  2514. }
  2515. row_y = row_bottom = l->y;
  2516. n = doc.nodes[parent].first;
  2517. while (n) {
  2518. struct br_node *nd = &doc.nodes[n];
  2519. struct br_style cs;
  2520. unsigned short lk = link;
  2521. int slot, x, w;
  2522. if (nd->type == BR_NODE_TEXT) {
  2523. n = nd->next;
  2524. continue;
  2525. }
  2526. br_style_for(&doc, n, pst, &cs);
  2527. if (cs.display == BR_DISPLAY_NONE) {
  2528. n = nd->next;
  2529. continue;
  2530. }
  2531. if (nd->tag == BR_TAG_A && nd->href_off)
  2532. lk = (unsigned short)n;
  2533. slot = cs.grid_slot;
  2534. if (!slot) {
  2535. if (!have_left)
  2536. slot = 2;
  2537. else if (!have_right)
  2538. slot = 3;
  2539. else
  2540. slot = 2;
  2541. }
  2542. if (slot == 1) {
  2543. if (have_left || have_right) {
  2544. row_y = row_bottom;
  2545. have_left = have_right = 0;
  2546. }
  2547. x = row_left;
  2548. w = avail;
  2549. } else if (slot == 2) {
  2550. if (have_left) {
  2551. row_y = row_bottom;
  2552. have_left = have_right = 0;
  2553. }
  2554. x = x0;
  2555. w = col0;
  2556. have_left = 1;
  2557. } else {
  2558. if (have_right) {
  2559. row_y = row_bottom;
  2560. have_left = have_right = 0;
  2561. }
  2562. x = x1;
  2563. w = col1;
  2564. have_right = 1;
  2565. }
  2566. l->left = x;
  2567. l->right = x + w;
  2568. if (l->right < l->left + 8)
  2569. l->right = l->left + 8;
  2570. l->y = row_y;
  2571. l->line_x = l->left;
  2572. l->run_x = l->left;
  2573. l->line_y = l->y;
  2574. l->line_h = 0;
  2575. l->nruns = 0;
  2576. l->space_pending = 0;
  2577. l->align = cs.align;
  2578. layout_block(l, n, &cs, depth + 1, lk);
  2579. if (l->y > row_bottom)
  2580. row_bottom = l->y;
  2581. n = nd->next;
  2582. }
  2583. l->left = row_left;
  2584. l->right = row_right;
  2585. l->y = row_bottom;
  2586. l->line_x = l->left;
  2587. l->run_x = l->left;
  2588. l->line_y = l->y;
  2589. l->line_h = 0;
  2590. l->nruns = 0;
  2591. l->space_pending = 0;
  2592. }
  2593. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  2594. * flow so they sit above it, like CSS painting order. Their flow origin is
  2595. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  2596. struct br_deferred {
  2597. unsigned int node;
  2598. int flow_y, flow_left, flow_right;
  2599. unsigned short link;
  2600. };
  2601. static struct br_deferred deferred[16];
  2602. static int ndeferred;
  2603. static void layout_children(struct lay *l, unsigned int parent,
  2604. const struct br_style *pst, int depth,
  2605. unsigned short link)
  2606. {
  2607. unsigned int n;
  2608. if (depth > 24)
  2609. return;
  2610. n = doc.nodes[parent].first;
  2611. while (n) {
  2612. struct br_node *nd = &doc.nodes[n];
  2613. struct br_style cs;
  2614. unsigned short lk = link;
  2615. if (nd->type == BR_NODE_TEXT) {
  2616. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  2617. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  2618. n = nd->next;
  2619. continue;
  2620. }
  2621. br_style_for(&doc, n, pst, &cs);
  2622. if (cs.display == BR_DISPLAY_NONE) {
  2623. n = nd->next;
  2624. continue;
  2625. }
  2626. if (nd->tag == BR_TAG_A && nd->href_off)
  2627. lk = (unsigned short)n;
  2628. if (cs.pos) {
  2629. if (l->draw && ndeferred < 16) {
  2630. deferred[ndeferred].node = n;
  2631. deferred[ndeferred].flow_y = l->y;
  2632. deferred[ndeferred].flow_left = l->left;
  2633. deferred[ndeferred].flow_right = l->right;
  2634. deferred[ndeferred].link = lk;
  2635. ndeferred++;
  2636. } else {
  2637. layout_block(l, n, &cs, depth + 1, lk);
  2638. }
  2639. if (cs.pos == 1 && block_h[n] &&
  2640. doc.nodes[n].class_off) {
  2641. const char *cl = doc.attrs +
  2642. doc.nodes[n].class_off;
  2643. if (contains_ci(cl, "poster-wrapper") ||
  2644. contains_ci(cl, "ts-picture"))
  2645. l->y += block_h[n];
  2646. }
  2647. n = nd->next;
  2648. continue;
  2649. }
  2650. if (nd->tag == BR_TAG_BR) {
  2651. flush_line(l);
  2652. n = nd->next;
  2653. continue;
  2654. }
  2655. if (nd->tag == BR_TAG_HR) {
  2656. flush_line(l);
  2657. if (l->draw)
  2658. ngui_fill_rect(l->ui,
  2659. (struct ngui_rect){l->left, l->y + 2,
  2660. l->right - l->left, 1}, BR_GRAY);
  2661. l->y += 8;
  2662. n = nd->next;
  2663. continue;
  2664. }
  2665. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  2666. nd->tag == BR_TAG_SELECT) {
  2667. if (!(nd->tag == BR_TAG_INPUT &&
  2668. s_eq(br_type(&doc, n), "hidden")))
  2669. add_form_run(l, n, &cs, lk);
  2670. n = nd->next;
  2671. continue;
  2672. }
  2673. if (nd->tag == BR_TAG_IMG) {
  2674. add_image_run(l, n, &cs, lk);
  2675. n = nd->next;
  2676. continue;
  2677. }
  2678. if (nd->tag == BR_TAG_VIDEO) {
  2679. layout_block(l, n, &cs, depth + 1, lk);
  2680. n = nd->next;
  2681. continue;
  2682. }
  2683. if (cs.float_left && cs.display == BR_DISPLAY_BLOCK) {
  2684. n = layout_float_group(l, n, pst, depth, link);
  2685. continue;
  2686. }
  2687. if (cs.display == BR_DISPLAY_BLOCK || br_tag_is_block(nd->tag))
  2688. layout_block(l, n, &cs, depth + 1, lk);
  2689. else {
  2690. layout_children(l, n, &cs, depth + 1, lk);
  2691. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  2692. l->space_pending = 1;
  2693. }
  2694. n = nd->next;
  2695. }
  2696. }
  2697. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  2698. * runs and a recursive page can otherwise overflow the stack. */
  2699. static struct lay layout_state;
  2700. static int measure_page(int left, int right)
  2701. {
  2702. struct lay *l = &layout_state;
  2703. struct br_style base = base_style();
  2704. unsigned int i;
  2705. for (i = 0; i < BR_MAX_NODES; i++) {
  2706. block_h[i] = 0;
  2707. img_top[i] = 0;
  2708. img_h[i] = 0;
  2709. }
  2710. l->draw = 0;
  2711. l->ui = 0;
  2712. l->left = left;
  2713. l->right = right;
  2714. l->y = 0;
  2715. l->line_x = left;
  2716. l->run_x = left;
  2717. l->line_y = 0;
  2718. l->line_h = 0;
  2719. l->align = BR_ALIGN_LEFT;
  2720. l->depth = 0;
  2721. l->nruns = 0;
  2722. l->space_pending = 0;
  2723. layout_children(l, doc.root, &base, 0, 0);
  2724. return l->y + 8;
  2725. }
  2726. static void render_page(int left, int right, int y0)
  2727. {
  2728. struct lay *l = &layout_state;
  2729. struct br_style base = base_style();
  2730. l->draw = 1;
  2731. l->ui = &ui;
  2732. l->left = left;
  2733. l->right = right;
  2734. l->y = y0;
  2735. l->line_x = left;
  2736. l->run_x = left;
  2737. l->line_y = y0;
  2738. l->line_h = 0;
  2739. l->align = BR_ALIGN_LEFT;
  2740. l->depth = 0;
  2741. l->nruns = 0;
  2742. l->space_pending = 0;
  2743. nhits = 0;
  2744. ndeferred = 0;
  2745. layout_children(l, doc.root, &base, 0, 0);
  2746. {
  2747. int i;
  2748. for (i = 0; i < ndeferred; i++) {
  2749. struct br_style st;
  2750. br_style_for(&doc, deferred[i].node, &base, &st);
  2751. if (st.display == BR_DISPLAY_NONE)
  2752. continue;
  2753. l->draw = 1;
  2754. l->left = deferred[i].flow_left;
  2755. l->right = deferred[i].flow_right;
  2756. l->y = deferred[i].flow_y;
  2757. l->line_x = l->left;
  2758. l->run_x = l->left;
  2759. l->line_y = l->y;
  2760. l->line_h = 0;
  2761. l->nruns = 0;
  2762. l->space_pending = 0;
  2763. l->align = st.align;
  2764. if (st.pos == 2 && block_h[deferred[i].node]) {
  2765. struct ngui_rect clip;
  2766. int ch = block_h[deferred[i].node] + 24;
  2767. clip.x = page_rect.x;
  2768. clip.y = page_rect.y;
  2769. clip.w = page_rect.w - 12;
  2770. if (ch > page_rect.h)
  2771. ch = page_rect.h;
  2772. clip.h = ch;
  2773. ngui_push_clip(&ui, clip);
  2774. if (st.has_bg)
  2775. ngui_fill_rect(&ui, clip, st.bg);
  2776. layout_block(l, deferred[i].node, &st, 0,
  2777. deferred[i].link);
  2778. ngui_pop_clip(&ui);
  2779. } else {
  2780. layout_block(l, deferred[i].node, &st, 0,
  2781. deferred[i].link);
  2782. }
  2783. }
  2784. }
  2785. }
  2786. /* ---- UI ---- */
  2787. static int find_hit(int x, int y)
  2788. {
  2789. int i;
  2790. for (i = nhits - 1; i >= 0; i--) {
  2791. struct hit *h = &hits[i];
  2792. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  2793. y < h->y + h->h)
  2794. return (int)h->node;
  2795. }
  2796. return 0;
  2797. }
  2798. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  2799. {
  2800. int x = r.x + 4, y = r.y + 4, h = 22;
  2801. int compact = r.w < 560;
  2802. int go_w = r.w < 420 ? 32 : 42;
  2803. int in_x, in_w, res;
  2804. ngui_fill_rect(&ui, r, ui.theme.panel);
  2805. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  2806. ui.theme.border);
  2807. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  2808. NGUI_ICON_CHEVRON_LEFT))
  2809. *action |= ACT_BACK;
  2810. x += 32;
  2811. if (!compact) {
  2812. if (ngui_icon_button(&ui, ID_FORWARD,
  2813. (struct ngui_rect){x, y, 28, h},
  2814. NGUI_ICON_CHEVRON_RIGHT))
  2815. *action |= ACT_FORWARD;
  2816. x += 32;
  2817. }
  2818. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  2819. NGUI_ICON_REFRESH))
  2820. *action |= ACT_RELOAD;
  2821. x += 32;
  2822. if (!compact) {
  2823. if (ngui_icon_button(&ui, ID_HOME,
  2824. (struct ngui_rect){x, y, 28, h},
  2825. NGUI_ICON_HOME))
  2826. *action |= ACT_HOME;
  2827. x += 32;
  2828. }
  2829. in_x = x + 2;
  2830. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  2831. if (in_w < 60)
  2832. in_w = 60;
  2833. res = ngui_text_input(&ui, ID_URL,
  2834. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  2835. if (res & NGUI_INPUT_SUBMIT)
  2836. *action |= ACT_NAV;
  2837. if (res & NGUI_INPUT_CANCEL)
  2838. ngui_set_focus(&ui, 0);
  2839. if (ngui_button(&ui, ID_GO,
  2840. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  2841. "Go"))
  2842. *action |= ACT_NAV;
  2843. }
  2844. static int page_hover_node(void)
  2845. {
  2846. if (!ui.inside)
  2847. return 0;
  2848. if (ui.mouse_x < page_rect.x ||
  2849. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  2850. ui.mouse_y < page_rect.y ||
  2851. ui.mouse_y >= page_rect.y + page_rect.h)
  2852. return 0;
  2853. return find_hit(ui.mouse_x, ui.mouse_y);
  2854. }
  2855. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  2856. {
  2857. int x, y, w = page.w, h = page.h;
  2858. if (!src || w <= 0 || h <= 0)
  2859. return;
  2860. for (y = 0; y < h; y++) {
  2861. unsigned short *s = src + (page.y + y) * sw + page.x;
  2862. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  2863. for (x = 0; x + 1 < w; x += 2) {
  2864. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  2865. }
  2866. if (x < w)
  2867. d[x] = s[x];
  2868. }
  2869. }
  2870. static void draw_page(struct ngui_rect page)
  2871. {
  2872. int left, right, ch;
  2873. int old_panel, old_dim;
  2874. unsigned short *saved_px;
  2875. int saved_w, saved_h, use_buf;
  2876. page_rect = page;
  2877. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  2878. page_cache_valid && layout_valid &&
  2879. page_scroll.offset == page_cache_scroll &&
  2880. page_cache_nnode == doc.nnode &&
  2881. page_cache_x == page.x && page_cache_y == page.y &&
  2882. page_cache_w == page.w && page_cache_h == page.h) {
  2883. blit_page(page, page_backbuf, pagebuf_w);
  2884. return;
  2885. }
  2886. ngui_fill_rect(&ui, page, ui.theme.bg);
  2887. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  2888. const char *s = page_loading ? "Loading..." : "No page";
  2889. int w = (int)ngui_text_width(s);
  2890. ngui_text(&ui, page.x + (page.w - w) / 2,
  2891. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  2892. page_scroll.content_h = 0;
  2893. page_scroll.view_h = page.h;
  2894. page_cache_valid = 0;
  2895. return;
  2896. }
  2897. if (page.w < 40 || page.h < 40) {
  2898. page_cache_valid = 0;
  2899. return;
  2900. }
  2901. saved_px = ui.px;
  2902. saved_w = ui.w;
  2903. saved_h = ui.h;
  2904. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  2905. if (use_buf) {
  2906. ui.px = page_backbuf;
  2907. ui.w = pagebuf_w;
  2908. ui.h = pagebuf_h;
  2909. ngui_fill_rect(&ui, page, ui.theme.bg);
  2910. }
  2911. left = page.x + 8;
  2912. right = page.x + page.w - 16;
  2913. if (!layout_valid || left != layout_left || right != layout_right ||
  2914. layout_nnode != doc.nnode) {
  2915. layout_content_h = measure_page(left, right);
  2916. layout_valid = 1;
  2917. layout_left = left;
  2918. layout_right = right;
  2919. layout_nnode = doc.nnode;
  2920. }
  2921. ch = layout_content_h;
  2922. page_scroll.content_h = ch;
  2923. page_scroll.view_h = page.h;
  2924. ngui_scroll_begin(&ui, page, &page_scroll);
  2925. render_page(left, right, page.y + 4 - page_scroll.offset);
  2926. old_panel = ui.theme.panel_alt;
  2927. old_dim = ui.theme.text_dim;
  2928. ui.theme.panel_alt = 0xC618;
  2929. ui.theme.text_dim = 0x8410;
  2930. ngui_scroll_end(&ui, page, &page_scroll);
  2931. ui.theme.panel_alt = old_panel;
  2932. ui.theme.text_dim = old_dim;
  2933. if (use_buf) {
  2934. ui.px = saved_px;
  2935. ui.w = saved_w;
  2936. ui.h = saved_h;
  2937. blit_page(page, page_backbuf, pagebuf_w);
  2938. page_cache_valid = 1;
  2939. page_cache_scroll = page_scroll.offset;
  2940. page_cache_nnode = doc.nnode;
  2941. page_cache_x = page.x;
  2942. page_cache_y = page.y;
  2943. page_cache_w = page.w;
  2944. page_cache_h = page.h;
  2945. } else {
  2946. page_cache_valid = 0;
  2947. }
  2948. }
  2949. static void draw_status(struct ngui_rect r)
  2950. {
  2951. char msg[BR_URL_MAX + 32];
  2952. unsigned int n = 0;
  2953. int hover = page_hover_node();
  2954. unsigned short color;
  2955. const char *kind;
  2956. ngui_fill_rect(&ui, r, ui.theme.panel);
  2957. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  2958. ui.theme.border);
  2959. if (hover) {
  2960. const char *href = br_href(&doc, (unsigned int)hover);
  2961. char url[BR_URL_MAX];
  2962. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  2963. s_append(msg, &n, "Link: ", sizeof(msg));
  2964. s_append(msg, &n, url, sizeof(msg));
  2965. } else {
  2966. s_copy(msg, "Link", sizeof(msg));
  2967. }
  2968. color = ui.theme.accent;
  2969. } else if (status_text[0]) {
  2970. s_copy(msg, status_text, sizeof(msg));
  2971. color = status_error ? ui.theme.error : ui.theme.text;
  2972. } else if (page_title[0]) {
  2973. s_copy(msg, page_title, sizeof(msg));
  2974. color = ui.theme.text;
  2975. } else {
  2976. s_copy(msg, "Ready", sizeof(msg));
  2977. color = ui.theme.text_dim;
  2978. }
  2979. kind = s_eq(page_url, "about:home") ? "HOME" :
  2980. page_is_local ? "FILE" :
  2981. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  2982. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  2983. {
  2984. int kw = (int)ngui_text_width(kind);
  2985. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  2986. ui.theme.text_dim);
  2987. }
  2988. }
  2989. static void draw(unsigned int *action)
  2990. {
  2991. struct ngui_rect r = {0, 0, ui.w, ui.h};
  2992. struct ngui_rect toolbar, status, page;
  2993. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  2994. status = ngui_cut_bottom(&r, BR_STATUS_H);
  2995. page = r;
  2996. draw_toolbar(toolbar, action);
  2997. draw_page(page);
  2998. draw_status(status);
  2999. }
  3000. static void redraw_now(void)
  3001. {
  3002. unsigned int action = 0;
  3003. ngui_begin(&ui);
  3004. draw(&action);
  3005. ngui_end(&ui);
  3006. }
  3007. static void handle_keys(unsigned int *action)
  3008. {
  3009. int k, scrolled = 0;
  3010. /* Batch queued page keys: a slow full-page render must not make a
  3011. * held Page Down advance only once every few frames. */
  3012. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  3013. scrolled++;
  3014. if (scrolled)
  3015. ngui_invalidate(&ui);
  3016. if (ngui_focus(&ui))
  3017. return;
  3018. while ((k = ngui_key(&ui)) != 0) {
  3019. switch (k) {
  3020. case NGUI_KEY_ESC:
  3021. *action |= ACT_CLOSE;
  3022. break;
  3023. case NGUI_KEY_TAB:
  3024. case 0x0C: /* Ctrl+L */
  3025. ngui_set_focus(&ui, ID_URL);
  3026. break;
  3027. case 0x12: /* Ctrl+R */
  3028. *action |= ACT_RELOAD;
  3029. break;
  3030. case NGUI_KEY_BACKSPACE:
  3031. *action |= ACT_BACK;
  3032. break;
  3033. case NGUI_KEY_UP:
  3034. ngui_scroll_to(&page_scroll,
  3035. page_scroll.offset - 24);
  3036. ngui_invalidate(&ui);
  3037. break;
  3038. case NGUI_KEY_DOWN:
  3039. ngui_scroll_to(&page_scroll,
  3040. page_scroll.offset + 24);
  3041. ngui_invalidate(&ui);
  3042. break;
  3043. case NGUI_KEY_HOME:
  3044. ngui_scroll_to(&page_scroll, 0);
  3045. ngui_invalidate(&ui);
  3046. break;
  3047. case NGUI_KEY_END:
  3048. ngui_scroll_to(&page_scroll,
  3049. page_scroll.content_h -
  3050. page_scroll.view_h);
  3051. ngui_invalidate(&ui);
  3052. break;
  3053. default:
  3054. break;
  3055. }
  3056. }
  3057. }
  3058. static void handle_page_click(unsigned int *action)
  3059. {
  3060. int node;
  3061. char url[BR_URL_MAX];
  3062. if (!ui.pressed)
  3063. return;
  3064. if (ui.press_x < page_rect.x ||
  3065. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  3066. ui.press_y < page_rect.y ||
  3067. ui.press_y >= page_rect.y + page_rect.h)
  3068. return;
  3069. node = find_hit(ui.press_x, ui.press_y);
  3070. if (!node)
  3071. return;
  3072. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  3073. sizeof(url)) != 0)
  3074. return;
  3075. s_copy(click_url, url, sizeof(click_url));
  3076. *action |= ACT_NAV;
  3077. }
  3078. void _start(const char *arg)
  3079. {
  3080. struct win_info wi;
  3081. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0) {
  3082. u_puts("browser: no graphics window\n");
  3083. u_exit(1);
  3084. }
  3085. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  3086. url_in.placeholder = "http://...";
  3087. br_doc_init(&doc);
  3088. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  3089. ui.theme.accent);
  3090. br_set_viewport(BR_VIEWPORT_W);
  3091. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  3092. s_copy(cwd, "/", sizeof(cwd));
  3093. heap_clear();
  3094. page_scroll.offset = 0;
  3095. page_scroll.content_h = 0;
  3096. if (arg && arg[0])
  3097. navigate(arg, 1);
  3098. else
  3099. load_home(1);
  3100. for (;;) {
  3101. unsigned int action = 0;
  3102. unsigned int now;
  3103. click_url[0] = '\0';
  3104. if (pending_action) {
  3105. action |= pending_action & ACT_WAIT_NAV;
  3106. if (pending_url[0])
  3107. s_copy(click_url, pending_url, sizeof(click_url));
  3108. pending_action = 0;
  3109. pending_url[0] = '\0';
  3110. cancel_fetch = 0;
  3111. } else if (preload_active) {
  3112. if (preload_wait)
  3113. preload_wait = 0;
  3114. else
  3115. preload_step();
  3116. } else if (preload_pending &&
  3117. page_scroll.offset != preload_scroll) {
  3118. preload_scroll = page_scroll.offset;
  3119. preload_pending = 0;
  3120. preload_active = 1;
  3121. }
  3122. now = u_ticks_ms();
  3123. if (status_until && (int)(now - status_until) >= 0) {
  3124. status_text[0] = '\0';
  3125. status_until = 0;
  3126. status_error = 0;
  3127. ngui_invalidate(&ui);
  3128. }
  3129. if (!ngui_begin(&ui)) {
  3130. /* A queued navigation (e.g. Enter in the URL bar during
  3131. * a slow fetch) must be handled even when this frame
  3132. * needs no redraw. */
  3133. if (!action) {
  3134. u_sleep_ms(10);
  3135. continue;
  3136. }
  3137. } else {
  3138. draw(&action);
  3139. handle_keys(&action);
  3140. handle_page_click(&action);
  3141. ngui_end(&ui);
  3142. }
  3143. if (action & ACT_NAV) {
  3144. if (click_url[0]) {
  3145. navigate(click_url, 1);
  3146. click_url[0] = '\0';
  3147. } else {
  3148. navigate(url_in.text, 1);
  3149. }
  3150. }
  3151. if (action & ACT_BACK) {
  3152. if (hist_pos > 0) {
  3153. hist_pos--;
  3154. navigate(history[hist_pos], 0);
  3155. }
  3156. }
  3157. if (action & ACT_FORWARD) {
  3158. if (hist_pos + 1 < hist_len) {
  3159. hist_pos++;
  3160. navigate(history[hist_pos], 0);
  3161. }
  3162. }
  3163. if (action & ACT_RELOAD) {
  3164. if (s_eq(page_url, "about:home"))
  3165. load_home(0);
  3166. else
  3167. navigate(page_url, 0);
  3168. }
  3169. if (action & ACT_HOME)
  3170. load_home(1);
  3171. if (action & ACT_CLOSE)
  3172. quit = 1;
  3173. if (quit)
  3174. break;
  3175. if (pending_action)
  3176. continue;
  3177. u_sleep_ms(10);
  3178. }
  3179. fetch_helper_stop();
  3180. u_win_close();
  3181. u_exit(0);
  3182. }