browser.c 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783
  1. /* browser: a small HTML/CSS browser built on ngui, the image library and the
  2. * shared uhttp client.
  3. *
  4. * Inline JavaScript runs through the vendored MuJS engine (console.log,
  5. * alert, document.getElementById(...).textContent and location.href); forms
  6. * are not supported. External CSS is loaded over uhttp, and images are
  7. * decoded with img.c and drawn inline. Page-scoped buffers (page body,
  8. * rules and image bitmaps) come from the ring-3 libc heap; each image gets an
  9. * exact-size decode arena that is freed as soon as the scaled bitmap exists.
  10. * The DOM and the image/CSS I/O scratch use fixed static arenas.
  11. */
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <ucmd_heap.h>
  15. #include "ucmd_lib.h"
  16. #include "ngui.h"
  17. #include "browser_html.h"
  18. #include "js_browser.h"
  19. #include "uhttp.h"
  20. #include "img.h"
  21. #include "inflate.h"
  22. /* Start wide enough for the desktop nav; smaller screens fall back to
  23. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  24. #define BR_W 1100
  25. #define BR_H 700
  26. #define BR_TOOLBAR_H 30
  27. #define BR_STATUS_H 18
  28. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  29. #define BR_IMG_FILE_MAX (512u * 1024u)
  30. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  31. #define BR_MAX_IMAGES 16
  32. #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
  33. #define BR_IMG_LAYOUT_W 1000
  34. #define BR_CSS_MAX (832u * 1024u)
  35. #define BR_CSS_COMP_MAX (192u * 1024u)
  36. #define BR_SCRIPT_MAX (512u * 1024u)
  37. #define FETCH_ABORT (-2)
  38. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  39. #define CSS_CACHE_MAX 16
  40. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  41. #define CSS_CACHE_PREFIX "bcss-"
  42. #define BR_MAX_SHEETS 6
  43. #define BR_HISTORY 16
  44. #define BR_URL_MAX 512
  45. #define BR_STATUS_MAX 200
  46. #define BR_IMG_RGB565(r, g, b) \
  47. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  48. #define BR_GRAY 0x8410
  49. enum {
  50. ID_URL = 1,
  51. ID_GO,
  52. ID_BACK,
  53. ID_FORWARD,
  54. ID_RELOAD,
  55. ID_HOME
  56. };
  57. #define ACT_NAV (1u << 0)
  58. #define ACT_BACK (1u << 1)
  59. #define ACT_FORWARD (1u << 2)
  60. #define ACT_RELOAD (1u << 3)
  61. #define ACT_HOME (1u << 4)
  62. #define ACT_CLOSE (1u << 5)
  63. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  64. ACT_HOME | ACT_CLOSE)
  65. struct br_image {
  66. int state; /* 0 empty, 1 ready */
  67. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  68. int native_w, native_h;
  69. char err[32];
  70. };
  71. static struct ngui ui;
  72. static struct ngui_input url_in;
  73. static struct ngui_scroll page_scroll;
  74. static struct br_doc doc;
  75. static struct br_image images[BR_MAX_IMAGES];
  76. static int image_count;
  77. /* Images are loaded one per main-loop iteration so the parsed page stays
  78. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  79. static int preload_active;
  80. static int preload_pending;
  81. static int preload_wait;
  82. static unsigned int preload_node;
  83. static int preload_loaded;
  84. static int preload_scroll;
  85. static char post_status_text[BR_STATUS_MAX];
  86. static int post_status_error;
  87. static unsigned int post_status_ttl;
  88. /* Content-relative position/height of each <img>, recorded by the measure
  89. * pass so image loading can be deferred until it is near the viewport. */
  90. static unsigned short img_top[BR_MAX_NODES];
  91. static unsigned short img_h[BR_MAX_NODES];
  92. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  93. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  94. * body. Decode arenas are allocated per image instead of living here. */
  95. static unsigned char *image_io_buf;
  96. #define image_file_buf (image_io_buf)
  97. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  98. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  99. static struct inflate image_inflate_ws;
  100. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  101. #error "CSS scratch must fit in image_io_buf"
  102. #endif
  103. static char page_url[BR_URL_MAX];
  104. static char page_title[BR_TITLE_MAX];
  105. static char cwd[64];
  106. static int page_is_local;
  107. static int page_loading;
  108. static char status_text[BR_STATUS_MAX];
  109. static unsigned int status_until;
  110. static int status_error;
  111. static char history[BR_HISTORY][BR_URL_MAX];
  112. static int hist_len, hist_pos;
  113. static char click_url[BR_URL_MAX];
  114. static char pending_url[BR_URL_MAX];
  115. static unsigned int pending_action;
  116. static int cancel_fetch;
  117. static int quit;
  118. static struct ngui_rect page_rect;
  119. static unsigned short *page_backbuf;
  120. static int pagebuf_w, pagebuf_h;
  121. static int page_cache_valid;
  122. static int page_cache_scroll;
  123. static unsigned int page_cache_nnode;
  124. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  125. static int layout_valid, layout_left, layout_right;
  126. static unsigned int layout_nnode;
  127. static int layout_content_h;
  128. /* layout output */
  129. struct lay_run {
  130. unsigned short off, len;
  131. unsigned short gap;
  132. unsigned short color;
  133. unsigned short href;
  134. char lit[28];
  135. short img;
  136. signed short dy; /* inline image vertical offset */
  137. unsigned short iw, ih;
  138. unsigned short w;
  139. unsigned char font_px, bold, italic, mono, underline;
  140. unsigned char has_lit;
  141. };
  142. struct lay {
  143. int draw;
  144. struct ngui *ui;
  145. int left, right;
  146. int y;
  147. int line_x, line_y, line_h;
  148. int run_x;
  149. int align;
  150. int depth;
  151. int space_pending;
  152. struct lay_run runs[96];
  153. int nruns;
  154. };
  155. struct hit {
  156. int x, y, w, h;
  157. unsigned short node;
  158. };
  159. #define HIT_MAX 96
  160. static struct hit hits[HIT_MAX];
  161. static int nhits;
  162. static unsigned short block_h[BR_MAX_NODES];
  163. static char li_marker[BR_MAX_NODES][6];
  164. /* one connection object; the browser fetches one resource at a time */
  165. /* ---- tiny strings ---- */
  166. static unsigned int s_len(const char *s)
  167. {
  168. unsigned int n = 0;
  169. while (s && s[n])
  170. n++;
  171. return n;
  172. }
  173. static void s_copy(char *d, const char *s, unsigned int cap)
  174. {
  175. unsigned int i = 0;
  176. if (!cap)
  177. return;
  178. while (s && s[i] && i + 1 < cap) {
  179. d[i] = s[i];
  180. i++;
  181. }
  182. d[i] = '\0';
  183. }
  184. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  185. {
  186. while (s && *s && *n + 1 < cap)
  187. d[(*n)++] = *s++;
  188. d[*n] = '\0';
  189. }
  190. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  191. unsigned int cap)
  192. {
  193. char tmp[12];
  194. unsigned int i = 0, j;
  195. do {
  196. tmp[i++] = (char)('0' + v % 10);
  197. v /= 10;
  198. } while (v && i < sizeof(tmp));
  199. for (j = 0; j < i && *n + 1 < cap; j++)
  200. d[(*n)++] = tmp[i - 1 - j];
  201. d[*n] = '\0';
  202. }
  203. static int s_eq(const char *a, const char *b)
  204. {
  205. while (*a && *b) {
  206. if (*a != *b)
  207. return 0;
  208. a++;
  209. b++;
  210. }
  211. return *a == *b;
  212. }
  213. static int starts_with(const char *s, const char *p)
  214. {
  215. unsigned int i = 0;
  216. while (p[i]) {
  217. if (s[i] != p[i])
  218. return 0;
  219. i++;
  220. }
  221. return 1;
  222. }
  223. static int contains_ci(const char *s, const char *p)
  224. {
  225. unsigned int i, j;
  226. for (i = 0; s[i]; i++) {
  227. for (j = 0; p[j]; j++) {
  228. char a = s[i + j];
  229. if (a >= 'A' && a <= 'Z')
  230. a = (char)(a - 'A' + 'a');
  231. if (a != p[j])
  232. break;
  233. }
  234. if (!p[j])
  235. return 1;
  236. }
  237. return 0;
  238. }
  239. static char *trim(char *s)
  240. {
  241. unsigned int n;
  242. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  243. s++;
  244. n = s_len(s);
  245. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  246. s[n - 1] == '\r' || s[n - 1] == '\n'))
  247. s[--n] = '\0';
  248. return s;
  249. }
  250. /* ---- per-process heap ---- */
  251. static int heap_start(void)
  252. {
  253. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  254. if (!image_io_buf)
  255. return -1;
  256. page_backbuf = (unsigned short *)malloc(
  257. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  258. pagebuf_w = page_backbuf ? ui.w : 0;
  259. pagebuf_h = page_backbuf ? ui.h : 0;
  260. page_cache_valid = 0;
  261. return 0;
  262. }
  263. static void heap_clear(void)
  264. {
  265. ngui_font_detach(&ui);
  266. heap_reset();
  267. image_io_buf = 0;
  268. page_backbuf = 0;
  269. pagebuf_w = pagebuf_h = 0;
  270. page_cache_valid = 0;
  271. }
  272. static void browser_rules_alloc(void)
  273. {
  274. struct br_rule *rules;
  275. rules = (struct br_rule *)malloc(
  276. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  277. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  278. }
  279. /* ---- status ---- */
  280. static void set_status(const char *s, int err, unsigned int ttl_ms)
  281. {
  282. s_copy(status_text, s, sizeof(status_text));
  283. status_error = err;
  284. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  285. ngui_invalidate(&ui);
  286. }
  287. /* ---- JavaScript ---- */
  288. static int resolve_link(const char *base, const char *href, char *out,
  289. unsigned int cap);
  290. static char js_last_status[BR_STATUS_MAX];
  291. static int js_last_error;
  292. static void js_host_status(const char *msg, int error)
  293. {
  294. s_copy(js_last_status, msg, sizeof(js_last_status));
  295. js_last_error = error;
  296. set_status(msg, error, 6000);
  297. }
  298. static void js_host_report(const char *msg)
  299. {
  300. u_puts("[js] ");
  301. u_puts(msg);
  302. u_putc('\n');
  303. s_copy(js_last_status, msg, sizeof(js_last_status));
  304. js_last_error = 1;
  305. set_status(msg, 1, 8000);
  306. }
  307. static void js_host_navigate(const char *url)
  308. {
  309. char resolved[BR_URL_MAX];
  310. if (!url || !url[0])
  311. return;
  312. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  313. return;
  314. s_copy(pending_url, resolved, sizeof(pending_url));
  315. pending_action |= ACT_NAV;
  316. cancel_fetch = 1;
  317. }
  318. static void js_host_changed(void)
  319. {
  320. /* textContent only replaces text nodes; computed styles are unchanged.
  321. * A future class/style binding must call br_reset_styles() itself. */
  322. layout_valid = 0;
  323. ngui_invalidate(&ui);
  324. }
  325. static int fetch_script_text(const char *url, unsigned char **out,
  326. unsigned int *outlen, char *err,
  327. unsigned int errcap);
  328. static void script_error(const char *what, const char *url, const char *why)
  329. {
  330. char msg[192];
  331. unsigned int n = 0;
  332. s_append(msg, &n, what, sizeof(msg));
  333. if (url && url[0]) {
  334. s_append(msg, &n, " ", sizeof(msg));
  335. s_append(msg, &n, url, sizeof(msg));
  336. }
  337. if (why && why[0]) {
  338. s_append(msg, &n, ": ", sizeof(msg));
  339. s_append(msg, &n, why, sizeof(msg));
  340. }
  341. js_host_report(msg);
  342. }
  343. /* Run the page's scripts in document order: external <script src> bodies are
  344. * fetched, inline bodies are copied because MuJS needs NUL-terminated text. */
  345. static void run_page_scripts(void)
  346. {
  347. struct js_browser_host host;
  348. unsigned int i;
  349. if (!doc.nscripts)
  350. return;
  351. host.status = js_host_status;
  352. host.report = js_host_report;
  353. host.navigate = js_host_navigate;
  354. host.changed = js_host_changed;
  355. host.page_url = page_url;
  356. if (js_browser_start(&doc, &host) != 0) {
  357. js_host_status("JavaScript: out of memory", 1);
  358. return;
  359. }
  360. for (i = 0; i < doc.nscripts; i++) {
  361. struct br_script *script = &doc.scripts[i];
  362. if (script->src_off) {
  363. const char *src_attr = doc.attrs + script->src_off;
  364. char url[BR_URL_MAX];
  365. unsigned char *data;
  366. unsigned int len;
  367. char err[64];
  368. int rv;
  369. if (!src_attr[0])
  370. continue;
  371. if (resolve_link(page_url, src_attr, url,
  372. sizeof(url)) != 0) {
  373. script_error("Cannot load script", src_attr,
  374. "unsupported URL");
  375. continue;
  376. }
  377. set_status("Loading script...", 0, 0);
  378. rv = fetch_script_text(url, &data, &len, err,
  379. sizeof(err));
  380. if (rv == FETCH_ABORT)
  381. break;
  382. if (rv != 0) {
  383. script_error("Cannot load script", url, err);
  384. continue;
  385. }
  386. js_browser_run((const char *)data, url);
  387. free(data);
  388. } else {
  389. unsigned int off = script->off;
  390. unsigned int len = script->len;
  391. unsigned int k;
  392. char *src = (char *)malloc(len + 1);
  393. if (!src) {
  394. js_host_status("JavaScript: out of memory", 1);
  395. break;
  396. }
  397. for (k = 0; k < len; k++)
  398. src[k] = doc.script_src[off + k];
  399. src[len] = '\0';
  400. js_browser_run(src, page_url);
  401. free(src);
  402. }
  403. if (pending_action)
  404. break;
  405. }
  406. js_browser_stop();
  407. if (doc.scripts_truncated && !js_last_error)
  408. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  409. 1);
  410. }
  411. /* ---- images ---- */
  412. static void image_reset(void)
  413. {
  414. int i;
  415. for (i = 0; i < BR_MAX_IMAGES; i++) {
  416. images[i].state = 0;
  417. images[i].native_w = images[i].native_h = 0;
  418. images[i].err[0] = '\0';
  419. }
  420. image_count = 0;
  421. preload_active = 0;
  422. preload_pending = 0;
  423. preload_wait = 0;
  424. preload_node = 0;
  425. preload_loaded = 0;
  426. }
  427. /* Decode into the shared arena, then copy/scale the result into a display
  428. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  429. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  430. * pixels. Transparent edges are composited over white. */
  431. static int decode_image_data(const unsigned char *data, unsigned int len,
  432. struct br_image *bi)
  433. {
  434. struct img_info info;
  435. struct img_options opt;
  436. struct img_mem mem;
  437. struct img_image decoded;
  438. unsigned char *arena;
  439. unsigned int est, bytes, i;
  440. unsigned short *px;
  441. unsigned char *alpha = 0;
  442. int dw, dh, r;
  443. if (img_sniff(data, len, &info) != 0) {
  444. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  445. return -1;
  446. }
  447. est = img_estimate(&info);
  448. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  449. s_copy(bi->err, "image too large", sizeof(bi->err));
  450. return -1;
  451. }
  452. arena = (unsigned char *)malloc(est);
  453. if (!arena) {
  454. s_copy(bi->err, "out of memory", sizeof(bi->err));
  455. return -1;
  456. }
  457. img_mem_init(&mem, arena, est);
  458. opt.max_pixels = BR_IMG_PIX_MAX;
  459. r = img_decode(data, len, &opt, &mem, &decoded);
  460. if (r != 0) {
  461. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  462. goto fail;
  463. }
  464. if (decoded.w == 0 || decoded.h == 0) {
  465. s_copy(bi->err, "empty image", sizeof(bi->err));
  466. goto fail;
  467. }
  468. bi->native_w = (int)decoded.w;
  469. bi->native_h = (int)decoded.h;
  470. dw = (int)decoded.w;
  471. dh = (int)decoded.h;
  472. if (dw > BR_IMG_LAYOUT_W) {
  473. dh = (int)((unsigned int)decoded.h * BR_IMG_LAYOUT_W /
  474. decoded.w);
  475. dw = BR_IMG_LAYOUT_W;
  476. }
  477. if (dh < 1)
  478. dh = 1;
  479. if (dw < 1)
  480. dw = 1;
  481. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  482. px = (unsigned short *)malloc(bytes);
  483. if (!px) {
  484. s_copy(bi->err, "out of memory", sizeof(bi->err));
  485. goto fail;
  486. }
  487. /* Keep the alpha plane for the scaled image so transparent logos and
  488. * icons composite over the page instead of the browser's dark theme
  489. * background. Very large alpha images stay flattened to bound the
  490. * heap use. */
  491. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  492. alpha = (unsigned char *)malloc((unsigned int)dw *
  493. (unsigned int)dh);
  494. if (alpha) {
  495. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  496. alpha[i] = 255;
  497. }
  498. }
  499. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  500. px[i] = ui.theme.bg;
  501. {
  502. struct img_blit b;
  503. b.dst = px;
  504. b.dst_w = dw;
  505. b.dst_h = dh;
  506. b.clip_x = 0;
  507. b.clip_y = 0;
  508. b.clip_w = dw;
  509. b.clip_h = dh;
  510. b.x = 0;
  511. b.y = 0;
  512. b.scale = ((unsigned int)dw << 16) / decoded.w;
  513. b.bg = ui.theme.bg;
  514. b.bg2 = ui.theme.bg;
  515. b.dst_a = alpha;
  516. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  517. img_draw(&decoded, &b);
  518. }
  519. bi->img.format = decoded.format;
  520. bi->img.w = (unsigned int)dw;
  521. bi->img.h = (unsigned int)dh;
  522. bi->img.px = px;
  523. bi->img.alpha = alpha;
  524. bi->img.flags = 0;
  525. bi->state = 1;
  526. free(arena);
  527. return 0;
  528. fail:
  529. free(arena);
  530. return -1;
  531. }
  532. /* ---- URL / local path handling ---- */
  533. static int is_http(const char *s)
  534. {
  535. return starts_with(s, "http://") || starts_with(s, "https://");
  536. }
  537. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  538. static int normalize_abs(const char *in, char *out, unsigned int cap)
  539. {
  540. char seg[64];
  541. unsigned int i = 0, o = 1;
  542. int depth = 0;
  543. int trailing;
  544. if (!in || in[0] != '/' || cap < 2)
  545. return -1;
  546. trailing = 0;
  547. {
  548. unsigned int n = s_len(in);
  549. if (n > 1 && in[n - 1] == '/')
  550. trailing = 1;
  551. }
  552. out[0] = '/';
  553. while (in[i]) {
  554. unsigned int n = 0;
  555. while (in[i] == '/')
  556. i++;
  557. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  558. if (n + 1 < sizeof(seg))
  559. seg[n++] = in[i];
  560. i++;
  561. }
  562. seg[n] = '\0';
  563. if (n == 0)
  564. break;
  565. if (s_eq(seg, "."))
  566. continue;
  567. if (s_eq(seg, "..")) {
  568. if (depth > 0) {
  569. while (o > 1 && out[o - 1] != '/')
  570. o--;
  571. if (o > 1)
  572. o--;
  573. depth--;
  574. }
  575. continue;
  576. }
  577. if (o > 1) {
  578. if (o + 1 >= cap)
  579. return -1;
  580. out[o++] = '/';
  581. }
  582. if (o + n + 1 >= cap)
  583. return -1;
  584. {
  585. unsigned int j;
  586. for (j = 0; j < n; j++)
  587. out[o++] = seg[j];
  588. }
  589. depth++;
  590. }
  591. if (trailing && o > 1) {
  592. if (o + 1 >= cap)
  593. return -1;
  594. out[o++] = '/';
  595. }
  596. out[o] = '\0';
  597. return 0;
  598. }
  599. static void make_abs_local(const char *in, char *out, unsigned int cap)
  600. {
  601. char joined[BR_URL_MAX];
  602. if (!in || !in[0]) {
  603. s_copy(out, cwd[0] ? cwd : "/", cap);
  604. return;
  605. }
  606. if (in[0] == '/') {
  607. if (normalize_abs(in, out, cap) != 0)
  608. s_copy(out, in, cap);
  609. return;
  610. }
  611. {
  612. unsigned int n = 0;
  613. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  614. s_append(joined, &n, "/", sizeof(joined));
  615. s_append(joined, &n, in, sizeof(joined));
  616. }
  617. if (normalize_abs(joined, out, cap) != 0)
  618. s_copy(out, joined, cap);
  619. }
  620. /* ---- canonical origin cache ---- *
  621. *
  622. * Sites commonly redirect http://host to https://host and then to
  623. * https://www.host. Remember the final scheme/host of the last navigation so
  624. * a bare domain typed again goes straight there instead of paying for two
  625. * more connections and TLS handshakes. Only default-port requests are
  626. * rewritten; explicit ports are left alone. */
  627. #define ORIGIN_CACHE_MAX 8
  628. #define ORIGIN_FILE "/share/borigins"
  629. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  630. UHTTP_HOST_MAX + 2))
  631. struct origin_cache_entry {
  632. char host[UHTTP_HOST_MAX];
  633. char origin[UHTTP_HOST_MAX + 16];
  634. };
  635. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  636. static int origin_count;
  637. static char origin_buf[ORIGIN_BUF_SIZE];
  638. static int default_port(const struct uhttp_url *u)
  639. {
  640. return u->secure ? u->port == 443 : u->port == 80;
  641. }
  642. static void url_origin(const struct uhttp_url *u, char *out,
  643. unsigned int cap)
  644. {
  645. unsigned int n = 0;
  646. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  647. s_append(out, &n, u->host, cap);
  648. if (!default_port(u)) {
  649. s_append(out, &n, ":", cap);
  650. s_append_dec(out, &n, u->port, cap);
  651. }
  652. }
  653. static void origin_cache_apply(char *url, unsigned int cap)
  654. {
  655. struct uhttp_url u;
  656. char out[BR_URL_MAX];
  657. unsigned int n = 0;
  658. int i;
  659. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  660. return;
  661. for (i = 0; i < origin_count; i++) {
  662. if (!s_eq(u.host, origins[i].host))
  663. continue;
  664. s_append(out, &n, origins[i].origin, sizeof(out));
  665. s_append(out, &n, u.path, sizeof(out));
  666. s_copy(url, out, cap);
  667. return;
  668. }
  669. }
  670. static void origin_cache_save(void)
  671. {
  672. unsigned int n = 0;
  673. int i;
  674. for (i = 0; i < origin_count; i++) {
  675. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  676. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  677. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  678. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  679. }
  680. if (n)
  681. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  682. (int)origin_buf, (int)n);
  683. }
  684. static void origin_cache_load(void)
  685. {
  686. char *p;
  687. int rn;
  688. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  689. (int)(sizeof(origin_buf) - 1));
  690. if (rn <= 0)
  691. return;
  692. origin_buf[rn] = '\0';
  693. p = origin_buf;
  694. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  695. char *line = p, *origin;
  696. while (*p && *p != '\n')
  697. p++;
  698. if (*p)
  699. *p++ = '\0';
  700. if (!line[0])
  701. continue;
  702. origin = line;
  703. while (*origin && *origin != ' ')
  704. origin++;
  705. if (!*origin)
  706. continue;
  707. *origin++ = '\0';
  708. if (!line[0] || !is_http(origin))
  709. continue;
  710. {
  711. struct uhttp_url uo;
  712. if (uhttp_parse_url(origin, &uo) != 0 ||
  713. !s_eq(uo.path, "/"))
  714. continue;
  715. }
  716. s_copy(origins[origin_count].host, line,
  717. sizeof(origins[origin_count].host));
  718. s_copy(origins[origin_count].origin, origin,
  719. sizeof(origins[origin_count].origin));
  720. origin_count++;
  721. }
  722. }
  723. static int host_is_www_of(const char *host, const char *base)
  724. {
  725. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  726. host[3] == '.' && s_eq(host + 4, base);
  727. }
  728. static void origin_cache_learn(const char *requested, const char *final)
  729. {
  730. struct uhttp_url from, to;
  731. char origin[UHTTP_HOST_MAX + 16];
  732. int i;
  733. if (!is_http(requested) || !is_http(final))
  734. return;
  735. if (uhttp_parse_url(requested, &from) != 0 ||
  736. uhttp_parse_url(final, &to) != 0)
  737. return;
  738. if (!default_port(&from))
  739. return;
  740. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  741. from.port == to.port)
  742. return;
  743. /* Only remember origin-level canonicalisation: the same path, and
  744. * either the same host or its www./apex sibling. A path- or
  745. * host-specific redirect (a shortener, a login page) must not poison
  746. * every request to the typed host. */
  747. if (!s_eq(from.path, to.path))
  748. return;
  749. if (!s_eq(from.host, to.host) &&
  750. !host_is_www_of(to.host, from.host) &&
  751. !host_is_www_of(from.host, to.host))
  752. return;
  753. url_origin(&to, origin, sizeof(origin));
  754. for (i = 0; i < origin_count; i++) {
  755. if (s_eq(origins[i].host, from.host)) {
  756. if (!s_eq(origins[i].origin, origin)) {
  757. s_copy(origins[i].origin, origin,
  758. sizeof(origins[i].origin));
  759. origin_cache_save();
  760. }
  761. return;
  762. }
  763. }
  764. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  765. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  766. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  767. origin_cache_save();
  768. }
  769. static int path_dir(const char *path, char *out, unsigned int cap)
  770. {
  771. unsigned int i, last = 0;
  772. for (i = 0; path[i]; i++)
  773. if (path[i] == '/')
  774. last = i;
  775. if (last == 0) {
  776. if (cap < 2)
  777. return -1;
  778. out[0] = '/';
  779. out[1] = '\0';
  780. return 0;
  781. }
  782. if (last + 1 >= cap)
  783. return -1;
  784. {
  785. unsigned int j;
  786. for (j = 0; j < last; j++)
  787. out[j] = path[j];
  788. out[last] = '\0';
  789. }
  790. return 0;
  791. }
  792. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  793. static int resolve_link(const char *base, const char *href, char *out,
  794. unsigned int cap)
  795. {
  796. char joined[BR_URL_MAX];
  797. if (!href || !href[0] || href[0] == '#')
  798. return -1;
  799. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  800. starts_with(href, "data:") || starts_with(href, "tel:"))
  801. return -1;
  802. if (starts_with(href, "about:")) {
  803. s_copy(out, href, cap);
  804. return 0;
  805. }
  806. if (is_http(href)) {
  807. s_copy(out, href, cap);
  808. return 0;
  809. }
  810. if (starts_with(href, "//")) {
  811. if (is_http(base)) {
  812. unsigned int n = 0;
  813. s_append(out, &n, starts_with(base, "https:") ?
  814. "https:" : "http:", cap);
  815. s_append(out, &n, href, cap);
  816. return 0;
  817. }
  818. return -1;
  819. }
  820. if (is_http(base)) {
  821. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  822. }
  823. /* local page */
  824. if (href[0] == '/') {
  825. if (normalize_abs(href, out, cap) != 0)
  826. return -1;
  827. return 0;
  828. }
  829. {
  830. char dir[BR_URL_MAX];
  831. unsigned int n = 0;
  832. if (s_eq(base, "about:home"))
  833. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  834. else if (path_dir(base, dir, sizeof(dir)) != 0)
  835. s_copy(dir, "/", sizeof(dir));
  836. s_append(joined, &n, dir, sizeof(joined));
  837. if (n == 0 || joined[n - 1] != '/')
  838. s_append(joined, &n, "/", sizeof(joined));
  839. s_append(joined, &n, href, sizeof(joined));
  840. }
  841. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  842. }
  843. /* Best-effort decompression: keep the first `cap` bytes and discard the
  844. * rest instead of failing when a page or stylesheet is larger than the
  845. * buffer. The stream is still walked to the end, so a normal page is
  846. * verified; a truncated compressed input still returns whatever was decoded
  847. * so far. */
  848. struct trunc_buf {
  849. unsigned char *dst;
  850. unsigned int cap, pos;
  851. int full;
  852. };
  853. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  854. {
  855. struct trunc_buf *m = (struct trunc_buf *)ctx;
  856. if (len > m->cap - m->pos) {
  857. unsigned int room = m->cap - m->pos;
  858. if (room) {
  859. unsigned int i;
  860. for (i = 0; i < room; i++)
  861. m->dst[m->pos + i] = data[i];
  862. m->pos += room;
  863. }
  864. m->full = 1;
  865. return 0;
  866. }
  867. {
  868. unsigned int i;
  869. for (i = 0; i < len; i++)
  870. m->dst[m->pos + i] = data[i];
  871. }
  872. m->pos += len;
  873. return 0;
  874. }
  875. static void worker_wait_ui(void);
  876. static void inflate_ui_pump(void *ctx)
  877. {
  878. static unsigned int last;
  879. unsigned int now = u_ticks_ms();
  880. (void)ctx;
  881. if ((int)(now - last) >= 50) {
  882. last = now;
  883. worker_wait_ui();
  884. }
  885. }
  886. static int inflate_trunc(const unsigned char *src, unsigned int len,
  887. unsigned char *dst, unsigned int cap,
  888. unsigned int *outlen, int gzip, int *truncated)
  889. {
  890. struct inflate_src in;
  891. struct inflate_sink sink;
  892. struct trunc_buf m;
  893. unsigned int got = 0;
  894. int r;
  895. in.p = src;
  896. in.len = len;
  897. in.more = 0;
  898. in.ctx = 0;
  899. m.dst = dst;
  900. m.cap = cap;
  901. m.pos = 0;
  902. m.full = 0;
  903. sink.write = trunc_write;
  904. sink.ctx = &m;
  905. inflate_init(&image_inflate_ws, &in, &sink);
  906. image_inflate_ws.progress = inflate_ui_pump;
  907. image_inflate_ws.progress_ctx = 0;
  908. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  909. inflate_zlib(&image_inflate_ws, &got);
  910. *outlen = m.pos;
  911. *truncated = m.full || r != 0;
  912. if (r != 0 && m.pos == 0)
  913. return -1;
  914. return 0;
  915. }
  916. /* ---- headless fetch helper ------------------------------------------- *
  917. *
  918. * Network I/O runs in a separate ring-3 process (`curl __fetch`): it writes
  919. * the raw response and a small metadata file under /share. While it works,
  920. * the browser keeps drawing and scrolling its own window, so a slow DNS/TLS
  921. * handshake or a multi-megabyte body never freezes the UI.
  922. */
  923. #define FETCH_REQ "/share/bfreq"
  924. #define FETCH_BODY "/share/bfbody"
  925. #define FETCH_META "/share/bfmeta"
  926. #define FETCH_DONE "/share/bfdone"
  927. struct fetch_meta {
  928. int status;
  929. int error;
  930. int trunc;
  931. unsigned int len;
  932. char encoding[16];
  933. char ctype[64];
  934. char final[BR_URL_MAX];
  935. };
  936. static void draw(unsigned int *action);
  937. static void handle_keys(unsigned int *action);
  938. static void handle_page_click(unsigned int *action);
  939. static int fetch_helper_tty = -2;
  940. static int fetch_helper_pid = -1;
  941. static unsigned int fetch_seq;
  942. static struct fetch_meta fetch_meta;
  943. static unsigned int meta_uint(char **pp)
  944. {
  945. char *p = *pp;
  946. unsigned int v = 0;
  947. while (*p >= '0' && *p <= '9') {
  948. v = v * 10 + (unsigned int)(*p - '0');
  949. p++;
  950. }
  951. while (*p && *p != '\n')
  952. p++;
  953. if (*p == '\n')
  954. p++;
  955. *pp = p;
  956. return v;
  957. }
  958. static void meta_str(char **pp, char *out, unsigned int cap)
  959. {
  960. char *p = *pp;
  961. unsigned int n = 0;
  962. while (*p && *p != '\n' && n + 1 < cap)
  963. out[n++] = *p++;
  964. out[n] = '\0';
  965. while (*p && *p != '\n')
  966. p++;
  967. if (*p == '\n')
  968. p++;
  969. *pp = p;
  970. }
  971. static void worker_wait_ui(void)
  972. {
  973. unsigned int action = 0;
  974. if (!ngui_begin(&ui))
  975. return;
  976. draw(&action);
  977. handle_keys(&action);
  978. handle_page_click(&action);
  979. if (action & ACT_WAIT_NAV) {
  980. pending_action |= action & ACT_WAIT_NAV;
  981. if ((action & ACT_NAV) && click_url[0])
  982. s_copy(pending_url, click_url, sizeof(pending_url));
  983. click_url[0] = '\0';
  984. cancel_fetch = 1;
  985. }
  986. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  987. ngui_invalidate(&ui);
  988. ngui_end(&ui);
  989. }
  990. static void fetch_helper_stop(void)
  991. {
  992. int i;
  993. if (fetch_helper_pid > 0) {
  994. u_kill((unsigned int)fetch_helper_pid);
  995. for (i = 0; i < 40 && u_alive((unsigned int)fetch_helper_pid); i++)
  996. u_sleep_ms(5);
  997. /* Let the reaper release the NIC before the next request. */
  998. u_sleep_ms(10);
  999. }
  1000. fetch_helper_pid = -1;
  1001. }
  1002. static int fetch_helper_start(char *err, unsigned int errcap)
  1003. {
  1004. if (fetch_helper_pid > 0 &&
  1005. u_alive((unsigned int)fetch_helper_pid))
  1006. return 0;
  1007. fetch_helper_pid = -1;
  1008. if (fetch_helper_tty == -2) {
  1009. int t = u_tty_create();
  1010. fetch_helper_tty = t > 0 ? t : 0;
  1011. }
  1012. fetch_helper_pid = u_spawn("/ramfs/bin/curl", "__serve",
  1013. fetch_helper_tty, "/");
  1014. if (fetch_helper_pid <= 0) {
  1015. fetch_helper_pid = -1;
  1016. s_copy(err, "cannot start network helper", errcap);
  1017. return -1;
  1018. }
  1019. return 0;
  1020. }
  1021. static int worker_fetch(const char *url, unsigned int cap,
  1022. struct fetch_meta *m, char *err, unsigned int errcap)
  1023. {
  1024. static char req[768], meta[1024], done[24];
  1025. char *p;
  1026. unsigned int n = 0, deadline;
  1027. int rn, mseq, retried = 0;
  1028. struct sys_stat st;
  1029. if (cancel_fetch || pending_action)
  1030. return FETCH_ABORT;
  1031. if (u_stat("/share", &st) != 0 || !st.is_dir ||
  1032. u_stat("/ramfs/bin/curl", &st) != 0) {
  1033. s_copy(err, "network helper unavailable", errcap);
  1034. return -1;
  1035. }
  1036. fetch_seq++;
  1037. if (!fetch_seq)
  1038. fetch_seq = 1;
  1039. s_append_dec(req, &n, fetch_seq, sizeof(req));
  1040. s_append(req, &n, " ", sizeof(req));
  1041. s_append_dec(req, &n, cap, sizeof(req));
  1042. s_append(req, &n, " ", sizeof(req));
  1043. s_append(req, &n, url, sizeof(req));
  1044. s_append(req, &n, "\n", sizeof(req));
  1045. u_syscall1(SYS_UNLINK, (int)FETCH_DONE);
  1046. u_syscall1(SYS_UNLINK, (int)FETCH_META);
  1047. if (u_syscall3(SYS_WRITE_FILE, (int)FETCH_REQ, (int)req, (int)n) < 0) {
  1048. s_copy(err, "cannot queue network request", errcap);
  1049. return -1;
  1050. }
  1051. if (fetch_helper_start(err, errcap) != 0)
  1052. return -1;
  1053. deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  1054. for (;;) {
  1055. worker_wait_ui();
  1056. if (cancel_fetch || pending_action) {
  1057. fetch_helper_stop();
  1058. return FETCH_ABORT;
  1059. }
  1060. rn = u_syscall3(SYS_READ_FILE, (int)FETCH_DONE, (int)done,
  1061. (int)(sizeof(done) - 1));
  1062. if (rn > 0) {
  1063. done[rn] = '\0';
  1064. p = done;
  1065. mseq = (int)meta_uint(&p);
  1066. if (mseq == (int)fetch_seq)
  1067. break;
  1068. }
  1069. if (!u_alive((unsigned int)fetch_helper_pid)) {
  1070. fetch_helper_pid = -1;
  1071. if (!retried && fetch_helper_start(err, errcap) == 0) {
  1072. retried = 1;
  1073. continue;
  1074. }
  1075. s_copy(err, "network helper stopped", errcap);
  1076. return -1;
  1077. }
  1078. if ((int)(u_ticks_ms() - deadline) >= 0) {
  1079. fetch_helper_stop();
  1080. s_copy(err, "network request timed out", errcap);
  1081. return -1;
  1082. }
  1083. u_sleep_ms(20);
  1084. }
  1085. if (cancel_fetch || pending_action)
  1086. return FETCH_ABORT;
  1087. rn = u_syscall3(SYS_READ_FILE, (int)FETCH_META, (int)meta,
  1088. (int)(sizeof(meta) - 1));
  1089. if (rn <= 0) {
  1090. s_copy(err, "network helper failed", errcap);
  1091. return -1;
  1092. }
  1093. meta[rn] = '\0';
  1094. p = meta;
  1095. mseq = (int)meta_uint(&p);
  1096. if (mseq != (int)fetch_seq) {
  1097. s_copy(err, "stale network response", errcap);
  1098. return -1;
  1099. }
  1100. m->status = (int)meta_uint(&p);
  1101. m->error = (int)meta_uint(&p);
  1102. m->trunc = (int)meta_uint(&p);
  1103. meta_str(&p, m->encoding, sizeof(m->encoding));
  1104. meta_str(&p, m->ctype, sizeof(m->ctype));
  1105. meta_str(&p, m->final, sizeof(m->final));
  1106. m->len = meta_uint(&p);
  1107. if (m->error) {
  1108. s_copy(err, uhttp_error_string(m->error), errcap);
  1109. return -1;
  1110. }
  1111. return 0;
  1112. }
  1113. static int fetch_remote(const char *url, unsigned int cap,
  1114. unsigned char *plain, unsigned int plaincap,
  1115. unsigned char *comp, unsigned int compcap,
  1116. struct fetch_meta *m, int *truncated,
  1117. char *err, unsigned int errcap)
  1118. {
  1119. int rv, zr, was_trunc;
  1120. rv = worker_fetch(url, cap, m, err, errcap);
  1121. if (rv == FETCH_ABORT)
  1122. return FETCH_ABORT;
  1123. if (rv != 0)
  1124. return -1;
  1125. if (contains_ci(m->encoding, "gzip") ||
  1126. contains_ci(m->encoding, "deflate")) {
  1127. unsigned int comp_len = 0, plen = 0;
  1128. rv = u_syscall3(SYS_READ_FILE, (int)FETCH_BODY, (int)comp,
  1129. (int)compcap);
  1130. if (rv < 0) {
  1131. s_copy(err, "empty response", errcap);
  1132. return -1;
  1133. }
  1134. comp_len = (unsigned int)rv;
  1135. if (comp_len < m->len) {
  1136. s_copy(err, "compressed response is too large", errcap);
  1137. return -1;
  1138. }
  1139. if (contains_ci(m->encoding, "deflate"))
  1140. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  1141. &plen, 0, &was_trunc);
  1142. else
  1143. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  1144. &plen, 1, &was_trunc);
  1145. if (zr != 0) {
  1146. s_copy(err, "compressed response is corrupt", errcap);
  1147. return -1;
  1148. }
  1149. *truncated = m->trunc || was_trunc;
  1150. return (cancel_fetch || pending_action) ? FETCH_ABORT :
  1151. (int)plen;
  1152. }
  1153. rv = u_syscall3(SYS_READ_FILE, (int)FETCH_BODY, (int)plain,
  1154. (int)plaincap);
  1155. if (rv < 0) {
  1156. s_copy(err, "empty response", errcap);
  1157. return -1;
  1158. }
  1159. *truncated = m->trunc || ((unsigned int)rv < m->len);
  1160. return (cancel_fetch || pending_action) ? FETCH_ABORT : rv;
  1161. }
  1162. /* ---- HTTP / file fetch ---- */
  1163. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  1164. unsigned int *outlen, int *is_local, char *ctype,
  1165. unsigned int ctcap, char *final, unsigned int finalcap,
  1166. char *err, unsigned int errcap, int *truncated)
  1167. {
  1168. unsigned char *buf;
  1169. unsigned int len;
  1170. int tr = 0;
  1171. int rv;
  1172. *out = 0;
  1173. *outlen = 0;
  1174. *truncated = 0;
  1175. if (final && finalcap)
  1176. final[0] = '\0';
  1177. if (ctype && ctcap)
  1178. ctype[0] = '\0';
  1179. if (url[0] == '/') {
  1180. buf = (unsigned char *)malloc(cap);
  1181. if (!buf) {
  1182. s_copy(err, "out of memory", errcap);
  1183. return -1;
  1184. }
  1185. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf, (int)cap);
  1186. if (rv < 0) {
  1187. free(buf);
  1188. s_copy(err, "file not found", errcap);
  1189. return -1;
  1190. }
  1191. *out = buf;
  1192. *outlen = (unsigned int)rv;
  1193. *is_local = 1;
  1194. if (ctype)
  1195. s_copy(ctype, "text/html", ctcap);
  1196. if (final)
  1197. s_copy(final, url, finalcap);
  1198. if ((unsigned int)rv == cap)
  1199. *truncated = 1;
  1200. return 0;
  1201. }
  1202. buf = (unsigned char *)malloc(cap);
  1203. if (!buf) {
  1204. s_copy(err, "out of memory", errcap);
  1205. return -1;
  1206. }
  1207. rv = fetch_remote(url, cap, buf, cap, image_io_buf, BR_PAGE_COMP_MAX,
  1208. &fetch_meta, &tr, err, errcap);
  1209. if (rv == FETCH_ABORT) {
  1210. free(buf);
  1211. return FETCH_ABORT;
  1212. }
  1213. if (rv < 0) {
  1214. free(buf);
  1215. return -1;
  1216. }
  1217. len = (unsigned int)rv;
  1218. if (len == 0) {
  1219. free(buf);
  1220. s_copy(err, "empty response", errcap);
  1221. return -1;
  1222. }
  1223. if (ctype)
  1224. s_copy(ctype, fetch_meta.ctype, ctcap);
  1225. if (final && fetch_meta.final[0])
  1226. s_copy(final, fetch_meta.final, finalcap);
  1227. *is_local = 0;
  1228. *out = buf;
  1229. *outlen = len;
  1230. *truncated = tr;
  1231. return 0;
  1232. }
  1233. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  1234. static int fetch_script_text(const char *url, unsigned char **out,
  1235. unsigned int *outlen, char *err,
  1236. unsigned int errcap)
  1237. {
  1238. unsigned char *buf;
  1239. unsigned int len;
  1240. int local, truncated = 0;
  1241. char ctype[64], final[BR_URL_MAX];
  1242. int rv;
  1243. *out = 0;
  1244. *outlen = 0;
  1245. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  1246. sizeof(ctype), final, sizeof(final), err, errcap,
  1247. &truncated);
  1248. if (rv != 0)
  1249. return rv;
  1250. if (truncated || len >= BR_SCRIPT_MAX) {
  1251. free(buf);
  1252. s_copy(err, "script is too large", errcap);
  1253. return -1;
  1254. }
  1255. buf[len] = '\0';
  1256. *out = buf;
  1257. *outlen = len;
  1258. return 0;
  1259. }
  1260. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  1261. * the heap, so images must not allocate their file body from it as well. */
  1262. static int fetch_image(const char *url, unsigned int cap,
  1263. unsigned char **out, unsigned int *outlen,
  1264. char *err, unsigned int errcap)
  1265. {
  1266. unsigned int len;
  1267. int tr = 0;
  1268. int rv;
  1269. *out = 0;
  1270. *outlen = 0;
  1271. if (cap > BR_IMG_FILE_MAX)
  1272. cap = BR_IMG_FILE_MAX;
  1273. if (url[0] == '/') {
  1274. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  1275. (int)cap);
  1276. if (rv < 0) {
  1277. s_copy(err, "file not found", errcap);
  1278. return -1;
  1279. }
  1280. *out = image_file_buf;
  1281. *outlen = (unsigned int)rv;
  1282. return 0;
  1283. }
  1284. rv = fetch_remote(url, cap, image_file_buf, cap, image_comp_buf,
  1285. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  1286. if (rv == FETCH_ABORT)
  1287. return FETCH_ABORT;
  1288. if (rv < 0)
  1289. return -1;
  1290. len = (unsigned int)rv;
  1291. if (len == 0) {
  1292. s_copy(err, "empty image", errcap);
  1293. return -1;
  1294. }
  1295. *out = image_file_buf;
  1296. *outlen = len;
  1297. return 0;
  1298. }
  1299. /* Remote stylesheets are immutable enough for the current boot: keep
  1300. * successful responses under /share so a reload, a second visit or a fresh
  1301. * browser launch does not fetch the same five sheets over the network again.
  1302. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  1303. static int css_cache_count;
  1304. static unsigned int css_cache_hash(const char *s)
  1305. {
  1306. unsigned int h = 2166136261u;
  1307. while (*s) {
  1308. h ^= (unsigned char)*s++;
  1309. h *= 16777619u;
  1310. }
  1311. return h;
  1312. }
  1313. static void css_cache_path(const char *url, char *out, unsigned int cap)
  1314. {
  1315. unsigned int n = 0;
  1316. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  1317. s_append_dec(out, &n, css_cache_hash(url), cap);
  1318. }
  1319. static void css_cache_clear(void)
  1320. {
  1321. struct sys_dirent d;
  1322. char path[96];
  1323. for (;;) {
  1324. int i, found = 0;
  1325. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  1326. (int)&d) == 1; i++) {
  1327. unsigned int n = 0;
  1328. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  1329. continue;
  1330. s_append(path, &n, "/share/", sizeof(path));
  1331. s_append(path, &n, d.name, sizeof(path));
  1332. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  1333. return;
  1334. found = 1;
  1335. break;
  1336. }
  1337. if (!found)
  1338. break;
  1339. }
  1340. css_cache_count = 0;
  1341. }
  1342. static void css_cache_init(void)
  1343. {
  1344. struct sys_dirent d;
  1345. int i, count = 0;
  1346. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  1347. (int)&d) == 1; i++)
  1348. if (starts_with(d.name, CSS_CACHE_PREFIX))
  1349. count++;
  1350. if (count >= CSS_CACHE_MAX) {
  1351. css_cache_clear();
  1352. return;
  1353. }
  1354. css_cache_count = count;
  1355. }
  1356. static int css_cache_get(const char *url, unsigned char **out,
  1357. unsigned int *outlen)
  1358. {
  1359. char path[96];
  1360. int rn;
  1361. css_cache_path(url, path, sizeof(path));
  1362. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  1363. (int)CSS_CACHE_FILE_MAX);
  1364. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  1365. return 0;
  1366. *out = image_io_buf;
  1367. *outlen = (unsigned int)rn;
  1368. return 1;
  1369. }
  1370. static void css_cache_put(const char *url, const unsigned char *data,
  1371. unsigned int len)
  1372. {
  1373. char path[96];
  1374. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  1375. len >= CSS_CACHE_FILE_MAX)
  1376. return;
  1377. css_cache_path(url, path, sizeof(path));
  1378. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  1379. (int)len) >= 0)
  1380. css_cache_count++;
  1381. }
  1382. /* Read one stylesheet into the shared static buffer. CSS is parsed
  1383. * immediately, so it does not need the page heap; this leaves the heap for
  1384. * the 2 MB page body, the rules and the scaled image bitmaps. */
  1385. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  1386. char *err, unsigned int errcap)
  1387. {
  1388. unsigned int len;
  1389. int tr = 0;
  1390. int rv;
  1391. *out = 0;
  1392. *outlen = 0;
  1393. if (url[0] == '/') {
  1394. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  1395. (int)BR_CSS_MAX);
  1396. if (rv < 0) {
  1397. s_copy(err, "stylesheet not found", errcap);
  1398. return -1;
  1399. }
  1400. *out = image_io_buf;
  1401. *outlen = (unsigned int)rv;
  1402. return 0;
  1403. }
  1404. if (css_cache_get(url, out, outlen))
  1405. return 0;
  1406. rv = fetch_remote(url, BR_CSS_MAX, image_io_buf, BR_CSS_MAX,
  1407. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  1408. &fetch_meta, &tr, err, errcap);
  1409. if (rv == FETCH_ABORT)
  1410. return FETCH_ABORT;
  1411. if (rv < 0)
  1412. return -1;
  1413. len = (unsigned int)rv;
  1414. if (len == 0) {
  1415. s_copy(err, "empty stylesheet", errcap);
  1416. return -1;
  1417. }
  1418. *out = image_io_buf;
  1419. *outlen = len;
  1420. css_cache_put(url, image_io_buf, len);
  1421. return 0;
  1422. }
  1423. static void redraw_now(void);
  1424. static char error_page[1024];
  1425. static void show_error(const char *title, const char *detail)
  1426. {
  1427. char *page = error_page;
  1428. unsigned int n = 0;
  1429. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  1430. s_append(page, &n, title, sizeof(error_page));
  1431. s_append(page, &n, "</h2><p>", sizeof(error_page));
  1432. {
  1433. const char *p = detail;
  1434. while (*p && n + 1 < sizeof(error_page)) {
  1435. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  1436. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  1437. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  1438. else page[n++] = *p;
  1439. p++;
  1440. }
  1441. }
  1442. page[n] = '\0';
  1443. s_append(page, &n, "</p><p>", sizeof(error_page));
  1444. s_append(page, &n, page_url, sizeof(error_page));
  1445. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  1446. sizeof(error_page));
  1447. br_parse(&doc, page, n);
  1448. layout_valid = 0;
  1449. preload_active = 0;
  1450. preload_pending = 0;
  1451. preload_wait = 0;
  1452. s_copy(page_title, title, sizeof(page_title));
  1453. page_loading = 0;
  1454. set_status(title, 1, 0);
  1455. ngui_invalidate(&ui);
  1456. }
  1457. static int decode_direct_image(const unsigned char *data, unsigned int len,
  1458. unsigned int node)
  1459. {
  1460. if (image_count >= BR_MAX_IMAGES)
  1461. return -1;
  1462. if (decode_image_data(data, len, &images[0]) != 0)
  1463. return -1;
  1464. doc.nodes[node].img_index = 0;
  1465. image_count = 1;
  1466. return 0;
  1467. }
  1468. static int ancestor_is(unsigned int node, unsigned int tag)
  1469. {
  1470. unsigned int p = doc.nodes[node].parent;
  1471. while (p) {
  1472. if (doc.nodes[p].tag == tag)
  1473. return 1;
  1474. p = doc.nodes[p].parent;
  1475. }
  1476. return 0;
  1477. }
  1478. static int load_stylesheets(void)
  1479. {
  1480. static char seen[BR_MAX_SHEETS][BR_URL_MAX];
  1481. unsigned int i, sheets = 0, nseen = 0;
  1482. for (i = 0; i < doc.nnode && sheets < BR_MAX_SHEETS; i++) {
  1483. struct br_node *nd = &doc.nodes[i];
  1484. const char *rel, *href;
  1485. char url[BR_URL_MAX];
  1486. unsigned char *data;
  1487. unsigned int len;
  1488. char err[64];
  1489. int rv;
  1490. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1491. continue;
  1492. rel = br_rel(&doc, i);
  1493. if (!contains_ci(rel, "stylesheet"))
  1494. continue;
  1495. href = br_href(&doc, i);
  1496. if (!href[0])
  1497. continue;
  1498. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1499. continue;
  1500. {
  1501. unsigned int k;
  1502. int dup = 0;
  1503. for (k = 0; k < nseen; k++)
  1504. if (s_eq(seen[k], url)) {
  1505. dup = 1;
  1506. break;
  1507. }
  1508. if (dup)
  1509. continue;
  1510. if (nseen < BR_MAX_SHEETS) {
  1511. s_copy(seen[nseen], url, BR_URL_MAX);
  1512. nseen++;
  1513. }
  1514. }
  1515. rv = fetch_css(url, &data, &len, err, sizeof(err));
  1516. if (rv == FETCH_ABORT)
  1517. return FETCH_ABORT;
  1518. if (rv != 0)
  1519. continue;
  1520. if (len)
  1521. br_parse_css_text(&doc, (const char *)data, len);
  1522. sheets++;
  1523. }
  1524. br_parse_inline_css(&doc);
  1525. br_reset_styles(&doc);
  1526. layout_valid = 0;
  1527. return 0;
  1528. }
  1529. static void preload_begin(void)
  1530. {
  1531. preload_active = 1;
  1532. preload_pending = 0;
  1533. preload_wait = 1;
  1534. preload_node = 0;
  1535. preload_loaded = 0;
  1536. preload_scroll = 0;
  1537. }
  1538. /* Styles are computed top-down during layout, but images inside a hidden
  1539. * menu/carousel are never visited and keep img_top == 0. Without this check
  1540. * the preloader walks the DOM in node order and spends the whole image
  1541. * budget on logos and off-canvas thumbnails the reader cannot see. */
  1542. static int node_hidden(unsigned int node)
  1543. {
  1544. unsigned int path[32], n = 0, p = node, i;
  1545. struct br_style st, parent;
  1546. while (p && n < sizeof(path) / sizeof(path[0])) {
  1547. path[n++] = p;
  1548. p = doc.nodes[p].parent;
  1549. }
  1550. parent = (struct br_style){0};
  1551. parent.font_px = 16;
  1552. parent.display = BR_DISPLAY_BLOCK;
  1553. for (i = n; i > 0; i--) {
  1554. br_style_for(&doc, path[i - 1], &parent, &st);
  1555. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  1556. st.opacity_hidden)
  1557. return 1;
  1558. parent = st;
  1559. }
  1560. return 0;
  1561. }
  1562. /* Load at most one image per call. Images below the current viewport are
  1563. * left pending until the page is scrolled; this keeps a long article with
  1564. * many 4K screenshots from stalling on content the user cannot see yet. */
  1565. static void preload_step(void)
  1566. {
  1567. unsigned int batch = 0;
  1568. while (preload_active && preload_node < doc.nnode) {
  1569. unsigned int i = preload_node;
  1570. struct br_node *nd = &doc.nodes[i];
  1571. const char *src;
  1572. char url[BR_URL_MAX];
  1573. unsigned char *data;
  1574. unsigned int len;
  1575. char err[64];
  1576. char msg[64];
  1577. unsigned int n = 0;
  1578. int rv;
  1579. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_IMG ||
  1580. nd->img_index != -1) {
  1581. preload_node++;
  1582. continue;
  1583. }
  1584. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  1585. preload_node++;
  1586. continue;
  1587. }
  1588. src = br_src(&doc, i);
  1589. if (!src[0] || contains_ci(src, ".svg") ||
  1590. starts_with(src, "data:")) {
  1591. preload_node++;
  1592. continue;
  1593. }
  1594. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  1595. preload_node++;
  1596. continue;
  1597. }
  1598. if (image_count >= BR_MAX_IMAGES) {
  1599. preload_node = doc.nnode;
  1600. break;
  1601. }
  1602. /* Do not stop at the first below-fold image: DOM order is
  1603. * not visual order, and a footer/ad image early in the DOM
  1604. * used to hide every later article image from the loader. */
  1605. if (img_top[i] >
  1606. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  1607. preload_pending = 1;
  1608. preload_node++;
  1609. continue;
  1610. }
  1611. preload_node = i + 1;
  1612. s_append(msg, &n, "Loading images ", sizeof(msg));
  1613. s_append_dec(msg, &n, (unsigned int)preload_loaded + 1,
  1614. sizeof(msg));
  1615. s_append(msg, &n, "...", sizeof(msg));
  1616. set_status(msg, 0, 0);
  1617. ngui_invalidate(&ui);
  1618. data = 0;
  1619. len = 0;
  1620. rv = fetch_image(url, BR_IMG_FILE_MAX, &data, &len, err,
  1621. sizeof(err));
  1622. if (rv == FETCH_ABORT) {
  1623. preload_active = 0;
  1624. preload_pending = 0;
  1625. return;
  1626. }
  1627. if (rv == 0 &&
  1628. decode_image_data(data, len, &images[image_count]) == 0) {
  1629. nd->img_index = (short)image_count;
  1630. image_count++;
  1631. preload_loaded++;
  1632. layout_valid = 0;
  1633. } else {
  1634. /* Remember failures so a scroll does not retry an
  1635. * unreachable tracking/ad image with the full network
  1636. * timeout on every pass. */
  1637. nd->img_index = -2;
  1638. }
  1639. ngui_invalidate(&ui);
  1640. /* A full page layout after every image dominates loading on a
  1641. * long page. Decode a small batch, then let the main loop draw
  1642. * once for the whole batch. */
  1643. if (++batch >= 4)
  1644. return;
  1645. }
  1646. preload_active = 0;
  1647. if (preload_pending)
  1648. preload_scroll = page_scroll.offset;
  1649. else
  1650. preload_pending = 0;
  1651. set_status(post_status_text, post_status_error, post_status_ttl);
  1652. ngui_invalidate(&ui);
  1653. }
  1654. static void history_push(const char *url)
  1655. {
  1656. if (!url || !url[0])
  1657. return;
  1658. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  1659. s_eq(history[hist_pos], url))
  1660. return;
  1661. if (hist_len > 0 && hist_pos + 1 < hist_len)
  1662. hist_len = hist_pos + 1;
  1663. if (hist_len < BR_HISTORY) {
  1664. s_copy(history[hist_len], url, BR_URL_MAX);
  1665. hist_pos = hist_len;
  1666. hist_len++;
  1667. } else {
  1668. int i;
  1669. for (i = 1; i < BR_HISTORY; i++)
  1670. s_copy(history[i - 1], history[i], BR_URL_MAX);
  1671. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  1672. hist_pos = BR_HISTORY - 1;
  1673. }
  1674. }
  1675. static void load_page(const char *url, int local, int push)
  1676. {
  1677. unsigned char *body = 0;
  1678. unsigned int len = 0;
  1679. int truncated = 0;
  1680. struct img_info image_info;
  1681. char ctype[64];
  1682. char final[BR_URL_MAX];
  1683. char err[80];
  1684. const char *detail = 0;
  1685. int rv;
  1686. final[0] = '\0';
  1687. cancel_fetch = 0;
  1688. preload_active = 0;
  1689. preload_pending = 0;
  1690. js_browser_stop();
  1691. js_last_status[0] = '\0';
  1692. js_last_error = 0;
  1693. heap_clear();
  1694. image_reset();
  1695. layout_valid = 0;
  1696. page_scroll.offset = 0;
  1697. page_scroll.dragging = 0;
  1698. br_parse_plain(&doc, "", 0); /* blank while loading */
  1699. page_title[0] = '\0';
  1700. page_loading = 1;
  1701. page_is_local = local;
  1702. s_copy(page_url, url, sizeof(page_url));
  1703. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1704. url_in.len = s_len(url_in.text);
  1705. url_in.cursor = url_in.len;
  1706. url_in.scroll = 0;
  1707. ngui_set_focus(&ui, 0);
  1708. if (final[0])
  1709. final[0] = '\0';
  1710. if (push)
  1711. history_push(url);
  1712. set_status("Loading...", 0, 0);
  1713. ngui_invalidate(&ui);
  1714. /* heap_clear() detaches the fonts, so attach them again before the
  1715. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  1716. if (heap_start() != 0) {
  1717. show_error("Out of memory", "Cannot allocate the page buffer");
  1718. return;
  1719. }
  1720. ngui_font_attach(&ui);
  1721. redraw_now();
  1722. browser_rules_alloc();
  1723. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  1724. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  1725. &truncated);
  1726. if (rv == FETCH_ABORT)
  1727. return;
  1728. if (rv != 0) {
  1729. detail = err;
  1730. show_error("Cannot load this page", detail);
  1731. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1732. url_in.len = s_len(url_in.text);
  1733. url_in.cursor = url_in.len;
  1734. url_in.scroll = 0;
  1735. return;
  1736. }
  1737. if (!local)
  1738. origin_cache_learn(url, final[0] ? final : url);
  1739. page_is_local = local;
  1740. if (final[0]) {
  1741. s_copy(page_url, final, sizeof(page_url));
  1742. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1743. url_in.len = s_len(url_in.text);
  1744. url_in.cursor = url_in.len;
  1745. url_in.scroll = 0;
  1746. }
  1747. if (contains_ci(ctype, "text/plain")) {
  1748. br_parse_plain(&doc, (const char *)body, len);
  1749. } else if (contains_ci(ctype, "image/") ||
  1750. (!contains_ci(ctype, "text/html") &&
  1751. img_sniff(body, len, &image_info) == 0)) {
  1752. unsigned int node = br_parse_image_doc(&doc, page_url);
  1753. if (node)
  1754. decode_direct_image(body, len, node);
  1755. s_copy(page_title, "Image", sizeof(page_title));
  1756. } else {
  1757. br_set_viewport(ui.w);
  1758. br_parse(&doc, (const char *)body, len);
  1759. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  1760. sizeof(page_title));
  1761. if (load_stylesheets() == FETCH_ABORT)
  1762. return;
  1763. if (pending_action)
  1764. return;
  1765. run_page_scripts();
  1766. if (pending_action)
  1767. return;
  1768. }
  1769. post_status_text[0] = '\0';
  1770. post_status_error = 0;
  1771. post_status_ttl = 0;
  1772. if (js_last_status[0]) {
  1773. s_copy(post_status_text, js_last_status,
  1774. sizeof(post_status_text));
  1775. post_status_error = js_last_error;
  1776. post_status_ttl = 8000;
  1777. } else if (truncated) {
  1778. s_copy(post_status_text, "Page truncated at the buffer limit",
  1779. sizeof(post_status_text));
  1780. post_status_ttl = 6000;
  1781. } else if (doc.truncated) {
  1782. s_copy(post_status_text, "Page truncated by the parser",
  1783. sizeof(post_status_text));
  1784. post_status_ttl = 6000;
  1785. } else if (starts_with(page_url, "https://")) {
  1786. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  1787. sizeof(post_status_text));
  1788. post_status_ttl = 6000;
  1789. }
  1790. preload_begin();
  1791. page_loading = 0;
  1792. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1793. url_in.len = s_len(url_in.text);
  1794. url_in.cursor = url_in.len;
  1795. url_in.scroll = 0;
  1796. ngui_set_focus(&ui, 0);
  1797. ngui_invalidate(&ui);
  1798. }
  1799. static void load_home(int push)
  1800. {
  1801. cancel_fetch = 0;
  1802. preload_active = 0;
  1803. preload_pending = 0;
  1804. js_browser_stop();
  1805. js_last_status[0] = '\0';
  1806. js_last_error = 0;
  1807. heap_clear();
  1808. image_reset();
  1809. layout_valid = 0;
  1810. page_scroll.offset = 0;
  1811. page_scroll.dragging = 0;
  1812. br_parse_plain(&doc, "", 0);
  1813. page_loading = 1;
  1814. page_is_local = 0;
  1815. s_copy(page_url, "about:home", sizeof(page_url));
  1816. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1817. url_in.len = s_len(url_in.text);
  1818. url_in.cursor = url_in.len;
  1819. url_in.scroll = 0;
  1820. ngui_set_focus(&ui, 0);
  1821. if (push)
  1822. history_push(page_url);
  1823. ngui_invalidate(&ui);
  1824. /* See load_page(): reattach the fonts before the first redraw. */
  1825. if (heap_start() != 0) {
  1826. show_error("Out of memory", "Cannot allocate the browser heap");
  1827. return;
  1828. }
  1829. ngui_font_attach(&ui);
  1830. redraw_now();
  1831. browser_rules_alloc();
  1832. {
  1833. static const char home[] =
  1834. "<html><head><title>NebOS Browser</title><style>"
  1835. "body { margin: 10px; color: #e4e6f0; }"
  1836. "h1 { color: #7fb0ff; }"
  1837. ".box { background-color: #262b3a; margin: 12px; "
  1838. "padding: 10px; }"
  1839. "a { color: #7fb0ff; }"
  1840. "pre { background-color: #32384a; }"
  1841. "</style></head><body>"
  1842. "<h1>NebOS Browser</h1>"
  1843. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  1844. "shared HTTP client and the image library.</p>"
  1845. "<div class=\"box\"><b>Try:</b>"
  1846. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  1847. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  1848. "<li><a href=\"/floppy1/JS.HTM\">/"
  1849. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  1850. "<li><a href=\"http://10.0.2.2:8000/\">"
  1851. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  1852. "<li><a href=\"https://example.com/\">"
  1853. "https://example.com/</a> (TLS, not verified)</li>"
  1854. "</ul></div>"
  1855. "<p>Type a URL in the bar above. Esc closes the "
  1856. "window, Ctrl+L focuses the address bar.</p>"
  1857. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  1858. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  1859. "</body></html>";
  1860. br_set_viewport(ui.w);
  1861. br_parse(&doc, home, sizeof(home) - 1);
  1862. br_parse_inline_css(&doc);
  1863. br_reset_styles(&doc);
  1864. s_copy(page_title, doc.title, sizeof(page_title));
  1865. }
  1866. post_status_text[0] = '\0';
  1867. post_status_error = 0;
  1868. post_status_ttl = 0;
  1869. page_loading = 0;
  1870. set_status("", 0, 0);
  1871. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1872. url_in.len = s_len(url_in.text);
  1873. url_in.cursor = url_in.len;
  1874. url_in.scroll = 0;
  1875. ngui_set_focus(&ui, 0);
  1876. ngui_invalidate(&ui);
  1877. }
  1878. /* Extensions the browser opens from the local filesystem. A dotted input
  1879. * with one of these still resolves relative to the cwd. */
  1880. static int local_file_ext(const char *s)
  1881. {
  1882. static const char *const exts[] = {
  1883. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  1884. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  1885. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  1886. "cfg", "conf", 0
  1887. };
  1888. unsigned int i = 0, start = 0, len = 0, e;
  1889. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  1890. s[i] != '#') {
  1891. if (s[i] == '.') {
  1892. start = i + 1;
  1893. len = 0;
  1894. } else if (start) {
  1895. len++;
  1896. }
  1897. i++;
  1898. }
  1899. if (!len)
  1900. return 0;
  1901. for (e = 0; exts[e]; e++) {
  1902. const char *x = exts[e];
  1903. unsigned int xn = s_len(x), k;
  1904. if (xn != len)
  1905. continue;
  1906. for (k = 0; k < len; k++) {
  1907. char a = s[start + k];
  1908. if (a >= 'A' && a <= 'Z')
  1909. a = (char)(a - 'A' + 'a');
  1910. if (a != x[k])
  1911. break;
  1912. }
  1913. if (k == len)
  1914. return 1;
  1915. }
  1916. return 0;
  1917. }
  1918. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  1919. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  1920. * Enter to the first network request. */
  1921. static int looks_like_host(const char *s)
  1922. {
  1923. unsigned int i = 0;
  1924. int dot = 0;
  1925. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  1926. s[i] != ':') {
  1927. char c = s[i];
  1928. if (c == '.') {
  1929. dot = 1;
  1930. } else if (!((c >= 'a' && c <= 'z') ||
  1931. (c >= 'A' && c <= 'Z') ||
  1932. (c >= '0' && c <= '9') ||
  1933. c == '-' || c == '_')) {
  1934. return 0;
  1935. }
  1936. i++;
  1937. }
  1938. return dot && i > 0 && !local_file_ext(s);
  1939. }
  1940. static void load_remote(const char *url, int push)
  1941. {
  1942. char canon[BR_URL_MAX];
  1943. s_copy(canon, url, sizeof(canon));
  1944. origin_cache_apply(canon, sizeof(canon));
  1945. load_page(canon, 0, push);
  1946. }
  1947. static void navigate(const char *input, int push)
  1948. {
  1949. char target[BR_URL_MAX];
  1950. char *t;
  1951. if (!input)
  1952. return;
  1953. s_copy(target, input, sizeof(target));
  1954. t = trim(target);
  1955. if (!t[0])
  1956. return;
  1957. if (s_eq(t, "about:home")) {
  1958. load_home(push);
  1959. return;
  1960. }
  1961. if (starts_with(t, "file://")) {
  1962. make_abs_local(t + 7, target, sizeof(target));
  1963. load_page(target, 1, push);
  1964. return;
  1965. }
  1966. if (is_http(t)) {
  1967. load_remote(t, push);
  1968. return;
  1969. }
  1970. if (t[0] == '/') {
  1971. make_abs_local(t, target, sizeof(target));
  1972. load_page(target, 1, push);
  1973. return;
  1974. }
  1975. if (!looks_like_host(t)) {
  1976. struct sys_stat st;
  1977. if (u_stat(t, &st) == 0 && !st.is_dir) {
  1978. make_abs_local(t, target, sizeof(target));
  1979. load_page(target, 1, push);
  1980. return;
  1981. }
  1982. }
  1983. {
  1984. char with_scheme[BR_URL_MAX];
  1985. unsigned int n = 0;
  1986. s_append(with_scheme, &n, "http://", sizeof(with_scheme));
  1987. s_append(with_scheme, &n, t, sizeof(with_scheme));
  1988. load_remote(with_scheme, push);
  1989. }
  1990. }
  1991. /* ---- layout ---- */
  1992. static struct br_style base_style(void)
  1993. {
  1994. struct br_style s = { 0 };
  1995. s.color = ui.theme.text;
  1996. s.bg = ui.theme.bg;
  1997. s.has_bg = 0;
  1998. s.border_color = 0;
  1999. s.font_px = 16;
  2000. s.bold = 0;
  2001. s.italic = 0;
  2002. s.mono = 0;
  2003. s.underline = 0;
  2004. s.align = BR_ALIGN_LEFT;
  2005. s.display = BR_DISPLAY_BLOCK;
  2006. s.no_bullet = 0;
  2007. s.uppercase = 0;
  2008. s.border_w = 0;
  2009. s.width_kind = s.max_width_kind = s.height_kind = 0;
  2010. s.width = s.max_width = s.height = 0;
  2011. s.line_h_pct = 0;
  2012. s.line_h_px = 0;
  2013. s.mt = s.mb = s.ml = s.mr = 0;
  2014. s.pt = s.pb = s.pl = s.pr = 0;
  2015. return s;
  2016. }
  2017. static int run_width(const struct lay_run *r)
  2018. {
  2019. if (r->img >= 0)
  2020. return r->iw;
  2021. if (r->img == -2)
  2022. return r->iw;
  2023. return (int)r->w;
  2024. }
  2025. static void flush_line(struct lay *l)
  2026. {
  2027. int total, x, i, vis;
  2028. if (!l->nruns && l->line_x == l->left) {
  2029. l->line_h = 0;
  2030. return;
  2031. }
  2032. total = l->line_x - l->left;
  2033. x = l->left;
  2034. vis = 1;
  2035. if (l->draw) {
  2036. int lh = l->line_h ? l->line_h : 16;
  2037. vis = l->line_y + lh >= page_rect.y &&
  2038. l->line_y <= page_rect.y + page_rect.h;
  2039. }
  2040. if (l->align == BR_ALIGN_CENTER)
  2041. x += (l->right - l->left - total) / 2;
  2042. else if (l->align == BR_ALIGN_RIGHT)
  2043. x = l->right - total;
  2044. if (x < l->left)
  2045. x = l->left;
  2046. for (i = 0; i < l->nruns; i++) {
  2047. struct lay_run *r = &l->runs[i];
  2048. int w = run_width(r);
  2049. int ry = l->line_y + r->dy;
  2050. x += r->gap;
  2051. if (l->draw && vis) {
  2052. if (r->img == -2) {
  2053. int hh = r->ih ? r->ih : 20;
  2054. ngui_fill_rect(l->ui,
  2055. (struct ngui_rect){x, ry, w, hh},
  2056. l->ui->theme.panel_alt);
  2057. ngui_frame(l->ui,
  2058. (struct ngui_rect){x, ry, w, hh},
  2059. l->ui->theme.border);
  2060. ngui_text_px(l->ui, x + 6, ry + 2,
  2061. r->lit, s_len(r->lit), r->color,
  2062. r->font_px, r->bold, r->italic,
  2063. r->mono);
  2064. } else if (r->img >= 0) {
  2065. struct br_image *bi = &images[r->img];
  2066. if (bi->state == 1) {
  2067. struct img_blit b;
  2068. b.dst = l->ui->px;
  2069. b.dst_w = l->ui->w;
  2070. b.dst_h = l->ui->h;
  2071. b.clip_x = page_rect.x;
  2072. b.clip_y = page_rect.y;
  2073. b.clip_w = page_rect.w - 12;
  2074. b.clip_h = page_rect.h;
  2075. b.x = x;
  2076. b.y = ry;
  2077. b.scale = ((unsigned int)r->iw << 16) /
  2078. bi->img.w;
  2079. b.bg = ui.theme.bg;
  2080. b.bg2 = ui.theme.bg;
  2081. b.flags = IMG_BLIT_OVER_DST;
  2082. img_draw(&bi->img, &b);
  2083. }
  2084. } else {
  2085. const char *s = r->has_lit ? r->lit :
  2086. doc.text + r->off;
  2087. unsigned int n = r->has_lit ? s_len(r->lit) :
  2088. r->len;
  2089. ngui_text_px(l->ui, x, ry, s, n,
  2090. r->color, r->font_px, r->bold,
  2091. r->italic, r->mono);
  2092. if (r->underline)
  2093. ngui_fill_rect(l->ui,
  2094. (struct ngui_rect){x,
  2095. ry +
  2096. ngui_text_ascent(l->ui,
  2097. r->font_px,
  2098. r->mono) + 2,
  2099. w, 1}, r->color);
  2100. }
  2101. if (r->href) {
  2102. if (nhits < HIT_MAX) {
  2103. struct hit *h = &hits[nhits];
  2104. int hh = r->img >= 0 ? r->ih :
  2105. ngui_text_line_height(l->ui,
  2106. r->font_px, r->mono);
  2107. int merge = nhits > 0 &&
  2108. hits[nhits - 1].node == r->href &&
  2109. hits[nhits - 1].y == ry &&
  2110. hits[nhits - 1].h == hh &&
  2111. x <= hits[nhits - 1].x +
  2112. hits[nhits - 1].w + 2;
  2113. if (merge) {
  2114. struct hit *p = &hits[nhits - 1];
  2115. int end = x + w;
  2116. if (end > p->x + p->w)
  2117. p->w = end - p->x;
  2118. } else {
  2119. h->x = x;
  2120. h->y = ry;
  2121. h->w = w;
  2122. h->h = hh;
  2123. h->node = r->href;
  2124. nhits++;
  2125. }
  2126. }
  2127. }
  2128. }
  2129. x += w;
  2130. }
  2131. l->y += l->line_h + 2;
  2132. l->nruns = 0;
  2133. l->line_x = l->left;
  2134. l->run_x = l->left;
  2135. l->line_h = 0;
  2136. l->space_pending = 0;
  2137. }
  2138. static void add_run(struct lay *l, unsigned short off, unsigned short len,
  2139. const struct br_style *st, unsigned short href,
  2140. const char *lit)
  2141. {
  2142. unsigned int n = lit ? s_len(lit) : len;
  2143. const char *tp = lit ? lit : doc.text + off;
  2144. int w = (int)ngui_text_width_px(l->ui, tp, n, st->font_px,
  2145. st->bold, st->italic, st->mono);
  2146. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  2147. flush_line(l);
  2148. if (l->nruns == 0) {
  2149. l->line_y = l->y;
  2150. l->line_h = 0;
  2151. }
  2152. {
  2153. struct lay_run *r = &l->runs[l->nruns++];
  2154. int gap = l->line_x - l->run_x;
  2155. if (gap < 0)
  2156. gap = 0;
  2157. r->gap = (unsigned short)gap;
  2158. r->off = off;
  2159. r->len = len;
  2160. r->color = st->color;
  2161. r->href = href;
  2162. r->dy = 0;
  2163. r->has_lit = 0;
  2164. r->lit[0] = '\0';
  2165. if (lit && lit[0]) {
  2166. unsigned int i;
  2167. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  2168. r->lit[i] = lit[i];
  2169. r->lit[i] = '\0';
  2170. r->has_lit = 1;
  2171. }
  2172. r->img = -1;
  2173. r->iw = r->ih = 0;
  2174. r->font_px = st->font_px;
  2175. r->bold = st->bold;
  2176. r->italic = st->italic;
  2177. r->mono = st->mono;
  2178. /* A control with its own background is a button, not body copy;
  2179. * an inherited link underline would strike through the fill. */
  2180. r->underline = st->underline && !st->has_bg;
  2181. r->w = (unsigned short)w;
  2182. if (r->has_lit)
  2183. r->w = (unsigned short)ngui_text_width_px(
  2184. l->ui, r->lit, s_len(r->lit), r->font_px,
  2185. r->bold, r->italic, r->mono);
  2186. w = r->w;
  2187. }
  2188. l->line_x += w;
  2189. l->run_x = l->line_x;
  2190. {
  2191. int lh = ngui_text_line_height(l->ui, st->font_px, st->mono);
  2192. if (st->line_h_px)
  2193. lh = st->line_h_px;
  2194. else if (st->line_h_pct)
  2195. lh = st->font_px * st->line_h_pct / 100;
  2196. if (lh < ngui_text_line_height(l->ui, st->font_px, st->mono))
  2197. lh = ngui_text_line_height(l->ui, st->font_px,
  2198. st->mono);
  2199. if (l->line_h < lh)
  2200. l->line_h = lh;
  2201. }
  2202. }
  2203. static void add_image_run(struct lay *l, unsigned int node,
  2204. const struct br_style *st, unsigned short href)
  2205. {
  2206. struct br_image *bi = 0;
  2207. int idx = doc.nodes[node].img_index;
  2208. int dw, dh, maxw;
  2209. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  2210. bi = &images[idx];
  2211. if (l->space_pending && (l->nruns > 0 || l->line_x > l->left)) {
  2212. int sp = (int)ngui_text_width_px(l->ui, " ", 1, st->font_px,
  2213. st->bold, st->italic,
  2214. st->mono);
  2215. if (l->line_x + sp <= l->right)
  2216. l->line_x += sp;
  2217. }
  2218. l->space_pending = 0;
  2219. if (!bi) {
  2220. const char *alt = br_alt(&doc, node);
  2221. struct br_style gs = *st;
  2222. char tmp[96];
  2223. unsigned int n = 0;
  2224. int w;
  2225. gs.color = BR_GRAY;
  2226. gs.underline = 0;
  2227. s_append(tmp, &n, "[", sizeof(tmp));
  2228. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  2229. s_append(tmp, &n, "]", sizeof(tmp));
  2230. w = (int)ngui_text_width_px(l->ui, tmp, n, gs.font_px,
  2231. gs.bold, gs.italic, gs.mono);
  2232. if (l->line_x + w > l->right &&
  2233. (l->nruns > 0 || l->line_x > l->left))
  2234. flush_line(l);
  2235. add_run(l, 0, 0, &gs, href, tmp);
  2236. if (!l->draw) {
  2237. int t = l->line_y < 0 ? 0 : l->line_y;
  2238. int hh = ngui_text_line_height(l->ui, gs.font_px,
  2239. gs.mono);
  2240. if (t > 65535)
  2241. t = 65535;
  2242. if (hh > 65535)
  2243. hh = 65535;
  2244. img_top[node] = (unsigned short)t;
  2245. img_h[node] = (unsigned short)hh;
  2246. }
  2247. return;
  2248. }
  2249. maxw = l->right - l->left;
  2250. if (maxw < 8)
  2251. maxw = 8;
  2252. {
  2253. int iw = bi->native_w, ih = bi->native_h;
  2254. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  2255. if (iw <= 0 || ih <= 0) {
  2256. iw = (int)bi->img.w;
  2257. ih = (int)bi->img.h;
  2258. }
  2259. dw = iw;
  2260. dh = ih;
  2261. if (doc.nodes[node].width_attr) {
  2262. int want = doc.nodes[node].width_attr;
  2263. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  2264. have_w = 1;
  2265. }
  2266. if (doc.nodes[node].height_attr) {
  2267. int want = doc.nodes[node].height_attr;
  2268. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  2269. have_h = 1;
  2270. }
  2271. if (have_w && !have_h)
  2272. dh = ih ? ih * dw / iw : 0;
  2273. if (have_h && !have_w)
  2274. dw = iw ? iw * dh / ih : 0;
  2275. if (st->width_kind) {
  2276. css_w = 1;
  2277. dw = st->width_kind == 2 ? maxw * (int)st->width / 100 :
  2278. (int)st->width;
  2279. }
  2280. if (st->height_kind) {
  2281. css_h = 1;
  2282. dh = st->height_kind == 2 ? maxw * (int)st->height / 100 :
  2283. (int)st->height;
  2284. }
  2285. if (css_w && !css_h)
  2286. dh = ih ? ih * dw / iw : 0;
  2287. if (css_h && !css_w)
  2288. dw = iw ? iw * dh / ih : 0;
  2289. if (st->max_width_kind) {
  2290. int mw = st->max_width_kind == 2 ?
  2291. maxw * (int)st->max_width / 100 :
  2292. (int)st->max_width;
  2293. if (mw > 0 && dw > mw) {
  2294. dh = iw ? ih * mw / iw : 0;
  2295. dw = mw;
  2296. }
  2297. }
  2298. }
  2299. if (dw < 8)
  2300. dw = 8;
  2301. if (dh < 8)
  2302. dh = 8;
  2303. if (dw > maxw) {
  2304. dh = dw ? dh * maxw / dw : dh;
  2305. dw = maxw;
  2306. }
  2307. if (!l->draw) {
  2308. int t = l->line_y < 0 ? 0 : l->line_y;
  2309. if (t > 65535)
  2310. t = 65535;
  2311. if (dh > 65535)
  2312. dh = 65535;
  2313. img_top[node] = (unsigned short)t;
  2314. img_h[node] = (unsigned short)dh;
  2315. }
  2316. if (l->line_x + dw > l->right && (l->nruns > 0 ||
  2317. l->line_x > l->left))
  2318. flush_line(l);
  2319. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  2320. flush_line(l);
  2321. if (l->nruns == 0) {
  2322. l->line_y = l->y;
  2323. l->line_h = 0;
  2324. }
  2325. {
  2326. struct lay_run *r = &l->runs[l->nruns++];
  2327. int gap = l->line_x - l->run_x;
  2328. if (gap < 0)
  2329. gap = 0;
  2330. r->gap = (unsigned short)gap;
  2331. r->off = 0;
  2332. r->len = 0;
  2333. r->color = 0;
  2334. r->href = href;
  2335. /* Inline replaced elements honour their vertical margins; this
  2336. * is how Bootstrap's negative logo margins centre the wordmark. */
  2337. r->dy = st->mt;
  2338. r->has_lit = 0;
  2339. r->lit[0] = '\0';
  2340. r->img = (short)idx;
  2341. r->iw = (unsigned short)dw;
  2342. r->ih = (unsigned short)dh;
  2343. r->w = (unsigned short)dw;
  2344. r->font_px = st->font_px;
  2345. r->bold = st->bold;
  2346. r->italic = st->italic;
  2347. r->mono = st->mono;
  2348. r->underline = 0;
  2349. }
  2350. l->line_x += dw;
  2351. l->run_x = l->line_x;
  2352. if (l->line_h < dh)
  2353. l->line_h = dh;
  2354. }
  2355. static int text_width(struct lay *l, const char *s, unsigned int n,
  2356. const struct br_style *st)
  2357. {
  2358. return (int)ngui_text_width_px(l->ui, s, n, st->font_px,
  2359. st->bold, st->italic, st->mono);
  2360. }
  2361. /* Longest prefix that fits in maxw, at least one byte. */
  2362. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  2363. const struct br_style *st, int maxw)
  2364. {
  2365. unsigned int take = 0;
  2366. while (take < n) {
  2367. if (text_width(l, s, take + 1, st) > maxw)
  2368. break;
  2369. take++;
  2370. }
  2371. return take ? take : 1;
  2372. }
  2373. static void emit_word(struct lay *l, const char *s, unsigned int start,
  2374. unsigned int n, unsigned int base,
  2375. const struct br_style *st, unsigned short href)
  2376. {
  2377. int avail = l->right - l->left;
  2378. int w = text_width(l, s + start, n, st);
  2379. unsigned int off = start;
  2380. if (l->line_x + w > l->right &&
  2381. (l->nruns > 0 || l->line_x > l->left))
  2382. flush_line(l);
  2383. if (w <= avail) {
  2384. if (n)
  2385. add_run(l, (unsigned short)(base + start),
  2386. (unsigned short)n, st, href, 0);
  2387. return;
  2388. }
  2389. while (n > 0) {
  2390. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  2391. add_run(l, (unsigned short)(base + off),
  2392. (unsigned short)take, st, href, 0);
  2393. off += take;
  2394. n -= take;
  2395. if (n)
  2396. flush_line(l);
  2397. }
  2398. }
  2399. static void emit_text(struct lay *l, const char *s, unsigned int len,
  2400. const struct br_style *st, unsigned short href, int pre)
  2401. {
  2402. unsigned int i = 0;
  2403. unsigned int base;
  2404. int space_w = (int)ngui_text_width_px(l->ui, " ", 1, st->font_px,
  2405. st->bold, st->italic, st->mono);
  2406. if (!s || !len)
  2407. return;
  2408. if (space_w <= 0)
  2409. space_w = 8;
  2410. base = (unsigned int)(s - doc.text);
  2411. if (st->uppercase) {
  2412. char *p = (char *)s;
  2413. unsigned int j;
  2414. for (j = 0; j < len; j++)
  2415. if (p[j] >= 'a' && p[j] <= 'z')
  2416. p[j] = (char)(p[j] - 'a' + 'A');
  2417. }
  2418. if (pre) {
  2419. while (i < len) {
  2420. unsigned int start;
  2421. if (s[i] == '\n') {
  2422. flush_line(l);
  2423. i++;
  2424. continue;
  2425. }
  2426. if (s[i] == ' ') {
  2427. if (l->line_x + space_w > l->right &&
  2428. (l->nruns > 0 || l->line_x > l->left))
  2429. flush_line(l);
  2430. else
  2431. l->line_x += space_w;
  2432. i++;
  2433. continue;
  2434. }
  2435. start = i;
  2436. while (i < len && s[i] != ' ' && s[i] != '\n')
  2437. i++;
  2438. emit_word(l, s, start, i - start, base, st, href);
  2439. }
  2440. return;
  2441. }
  2442. while (i < len) {
  2443. unsigned int start, n;
  2444. if (s[i] == ' ') {
  2445. l->space_pending = 1;
  2446. i++;
  2447. continue;
  2448. }
  2449. start = i;
  2450. while (i < len && s[i] != ' ')
  2451. i++;
  2452. n = i - start;
  2453. if (l->space_pending &&
  2454. (l->nruns > 0 || l->line_x > l->left)) {
  2455. if (l->line_x + space_w <= l->right)
  2456. l->line_x += space_w;
  2457. }
  2458. l->space_pending = 0;
  2459. emit_word(l, s, start, n, base, st, href);
  2460. }
  2461. }
  2462. static int list_index(unsigned int parent, unsigned int node)
  2463. {
  2464. unsigned int n = 0, i;
  2465. for (i = doc.nodes[parent].first; i && i != node;
  2466. i = doc.nodes[i].next)
  2467. if (doc.nodes[i].tag == BR_TAG_LI)
  2468. n++;
  2469. return (int)n + 1;
  2470. }
  2471. static const char *form_text(unsigned int node)
  2472. {
  2473. const char *v = br_value(&doc, node);
  2474. const char *p = br_placeholder(&doc, node);
  2475. const char *t = br_type(&doc, node);
  2476. if (s_eq(t, "hidden"))
  2477. return 0;
  2478. if (s_eq(t, "submit") || s_eq(t, "button") || s_eq(t, "reset"))
  2479. return v[0] ? v : "Button";
  2480. if (v[0])
  2481. return v;
  2482. if (p[0])
  2483. return p;
  2484. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  2485. return "Text";
  2486. if (doc.nodes[node].tag == BR_TAG_SELECT)
  2487. return "Select";
  2488. return "Search";
  2489. }
  2490. static void add_form_run(struct lay *l, unsigned int node,
  2491. const struct br_style *st, unsigned short href)
  2492. {
  2493. const char *text = form_text(node);
  2494. struct lay_run *r;
  2495. int tw, w, h, i;
  2496. if (!text)
  2497. return;
  2498. tw = (int)ngui_text_width_px(l->ui, text, s_len(text), st->font_px,
  2499. st->bold, st->italic, st->mono);
  2500. h = ngui_text_line_height(l->ui, st->font_px, st->mono) + 4;
  2501. if (h < 20)
  2502. h = 20;
  2503. if (st->width_kind == 1)
  2504. w = st->width;
  2505. else if (st->width_kind == 2)
  2506. w = (l->right - l->left) * (int)st->width / 100;
  2507. else
  2508. w = tw + 18;
  2509. if (w < 64)
  2510. w = 64;
  2511. if (w > l->right - l->left)
  2512. w = l->right - l->left;
  2513. if (w < 8)
  2514. w = 8;
  2515. if (l->line_x + w > l->right &&
  2516. (l->nruns > 0 || l->line_x > l->left))
  2517. flush_line(l);
  2518. if (l->nruns >= 96)
  2519. return;
  2520. r = &l->runs[l->nruns++];
  2521. r->gap = (unsigned short)(l->line_x - l->run_x);
  2522. r->off = r->len = 0;
  2523. r->color = st->color;
  2524. r->href = href;
  2525. r->dy = 0;
  2526. r->has_lit = 1;
  2527. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  2528. r->lit[i] = text[i];
  2529. r->lit[i] = '\0';
  2530. r->img = -2;
  2531. r->iw = (unsigned short)w;
  2532. r->ih = (unsigned short)h;
  2533. r->w = (unsigned short)w;
  2534. r->font_px = st->font_px;
  2535. r->bold = st->bold;
  2536. r->italic = st->italic;
  2537. r->mono = st->mono;
  2538. r->underline = 0;
  2539. l->line_x += w;
  2540. l->run_x = l->line_x;
  2541. if (l->line_h < h)
  2542. l->line_h = h;
  2543. }
  2544. /* A poster wrapper is absolutely positioned over the media slot; the
  2545. * measured height of its picture is normally added back to the flow. When a
  2546. * loading-skeleton sibling already reserves that slot, adding both doubles
  2547. * the media height and pushes the article text a full screen down. */
  2548. static int has_skeleton_sibling(unsigned int node)
  2549. {
  2550. unsigned int p = doc.nodes[node].parent, c;
  2551. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  2552. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  2553. continue;
  2554. if (doc.nodes[c].class_off &&
  2555. contains_ci(doc.attrs + doc.nodes[c].class_off,
  2556. "skeleton"))
  2557. return 1;
  2558. }
  2559. return 0;
  2560. }
  2561. static void layout_children(struct lay *l, unsigned int parent,
  2562. const struct br_style *pst, int depth,
  2563. unsigned short link);
  2564. static void layout_flex_children(struct lay *l, unsigned int parent,
  2565. const struct br_style *pst, int depth,
  2566. unsigned short link);
  2567. static void layout_grid_children(struct lay *l, unsigned int parent,
  2568. const struct br_style *pst, int depth,
  2569. unsigned short link);
  2570. static void layout_grid_auto(struct lay *l, unsigned int parent,
  2571. const struct br_style *pst, int depth,
  2572. unsigned short link);
  2573. static int flex_item_width(struct lay *l, unsigned int n,
  2574. const struct br_style *cs, int avail);
  2575. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  2576. const struct br_style *pst, int depth,
  2577. unsigned short link);
  2578. static void layout_table_row(struct lay *l, unsigned int row,
  2579. const struct br_style *pst, int depth,
  2580. unsigned short link);
  2581. /* A flex container whose items are only inline spans is usually just a
  2582. * heading/icon pair. Our flex row positions such items without emitting
  2583. * their inline text in some deep page contexts; normal inline flow renders
  2584. * the same content correctly. */
  2585. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  2586. {
  2587. unsigned int c;
  2588. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  2589. struct br_node *nd = &doc.nodes[c];
  2590. struct br_style cs;
  2591. if (nd->type == BR_NODE_TEXT)
  2592. continue;
  2593. br_style_for(&doc, c, pst, &cs);
  2594. if (cs.display == BR_DISPLAY_NONE)
  2595. continue;
  2596. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  2597. cs.width_kind || cs.has_bg || cs.border_w ||
  2598. nd->tag == BR_TAG_IMG)
  2599. return 1;
  2600. }
  2601. return 0;
  2602. }
  2603. static int css_radius(const struct br_style *st, int corner,
  2604. int w, int h)
  2605. {
  2606. int r = st->radius[corner];
  2607. if (r <= 0)
  2608. return 0;
  2609. if (r > w / 2)
  2610. r = w / 2;
  2611. if (r > h / 2)
  2612. r = h / 2;
  2613. return r;
  2614. }
  2615. static void svg_viewbox(unsigned node, int *vw, int *vh)
  2616. {
  2617. struct br_node *nd = &doc.nodes[node];
  2618. if (nd->width_attr && nd->height_attr) {
  2619. *vw = nd->width_attr;
  2620. *vh = nd->height_attr;
  2621. } else {
  2622. *vw = 300;
  2623. *vh = 150;
  2624. }
  2625. if (*vw < 1)
  2626. *vw = 1;
  2627. if (*vh < 1)
  2628. *vh = 1;
  2629. }
  2630. static int svg_num(const char **pp)
  2631. {
  2632. const char *p = *pp;
  2633. int neg = 0, v = 0, frac = 0, scale = 1;
  2634. while (*p == ' ' || *p == ',' || *p == '\t' ||
  2635. *p == '\n' || *p == '\r')
  2636. p++;
  2637. if (*p == '-') {
  2638. neg = 1;
  2639. p++;
  2640. } else if (*p == '+') {
  2641. p++;
  2642. }
  2643. while (*p >= '0' && *p <= '9') {
  2644. v = v * 10 + (*p - '0');
  2645. p++;
  2646. }
  2647. if (*p == '.') {
  2648. p++;
  2649. while (*p >= '0' && *p <= '9' && scale < 1000) {
  2650. frac = frac * 10 + (*p - '0');
  2651. scale *= 10;
  2652. p++;
  2653. }
  2654. }
  2655. v += frac / scale;
  2656. *pp = p;
  2657. return neg ? -v : v;
  2658. }
  2659. static void svg_path(struct ngui *ui, const char *d,
  2660. int ox, int oy, int dw, int dh, int vw, int vh,
  2661. unsigned short color)
  2662. {
  2663. int cx = 0, cy = 0, sx = 0, sy = 0;
  2664. char cmd = 0;
  2665. const char *p = d;
  2666. while (p && *p) {
  2667. int rel, nx, ny;
  2668. char c;
  2669. while (*p == ' ' || *p == ',' || *p == '\t' ||
  2670. *p == '\n' || *p == '\r')
  2671. p++;
  2672. if (!*p)
  2673. break;
  2674. if ((*p >= 'A' && *p <= 'Z') ||
  2675. (*p >= 'a' && *p <= 'z'))
  2676. cmd = *p++;
  2677. else if (!cmd) {
  2678. p++;
  2679. continue;
  2680. }
  2681. rel = cmd >= 'a' && cmd <= 'z';
  2682. c = rel ? (char)(cmd - 'a' + 'A') : cmd;
  2683. if (c == 'Z') {
  2684. ngui_line(ui, ox + cx * dw / vw, oy + cy * dh / vh,
  2685. ox + sx * dw / vw, oy + sy * dh / vh,
  2686. color);
  2687. cx = sx;
  2688. cy = sy;
  2689. cmd = 0;
  2690. continue;
  2691. }
  2692. if (c == 'H' || c == 'V') {
  2693. const char *save = p;
  2694. int a = svg_num(&p);
  2695. if (p == save) {
  2696. p++;
  2697. continue;
  2698. }
  2699. nx = cx;
  2700. ny = cy;
  2701. if (c == 'H')
  2702. nx = rel ? cx + a : a;
  2703. else
  2704. ny = rel ? cy + a : a;
  2705. } else {
  2706. const char *save = p;
  2707. int a = svg_num(&p);
  2708. int b = svg_num(&p);
  2709. if (p == save) {
  2710. p++;
  2711. continue;
  2712. }
  2713. if (c == 'M') {
  2714. nx = rel ? cx + a : a;
  2715. ny = rel ? cy + b : b;
  2716. cx = sx = nx;
  2717. cy = sy = ny;
  2718. cmd = rel ? 'l' : 'L';
  2719. continue;
  2720. }
  2721. if (c != 'L')
  2722. break;
  2723. nx = rel ? cx + a : a;
  2724. ny = rel ? cy + b : b;
  2725. }
  2726. ngui_line(ui, ox + cx * dw / vw, oy + cy * dh / vh,
  2727. ox + nx * dw / vw, oy + ny * dh / vh, color);
  2728. cx = nx;
  2729. cy = ny;
  2730. }
  2731. }
  2732. static void draw_svg(struct ngui *ui, unsigned node,
  2733. int ox, int oy, int dw, int dh, int vw, int vh,
  2734. const struct br_style *pst)
  2735. {
  2736. unsigned int c;
  2737. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  2738. struct br_node *nd = &doc.nodes[c];
  2739. struct br_style st;
  2740. const char *nm;
  2741. if (nd->type != BR_NODE_ELEM || !nd->name_off)
  2742. continue;
  2743. nm = doc.attrs + nd->name_off;
  2744. br_style_for(&doc, c, pst, &st);
  2745. if (s_eq(nm, "rect")) {
  2746. struct ngui_rect r;
  2747. int rx = (int)nd->svg_rx * dw / vw;
  2748. r.x = ox + (int)nd->svg_x * dw / vw;
  2749. r.y = oy + (int)nd->svg_y * dh / vh;
  2750. r.w = (int)nd->width_attr * dw / vw;
  2751. r.h = (int)nd->height_attr * dh / vh;
  2752. if (r.w < 1)
  2753. r.w = 1;
  2754. if (r.h < 1)
  2755. r.h = 1;
  2756. if (rx > r.w / 2)
  2757. rx = r.w / 2;
  2758. if (rx > r.h / 2)
  2759. rx = r.h / 2;
  2760. if (st.has_bg) {
  2761. if (rx)
  2762. ngui_fill_round_rect(ui, r, rx, rx,
  2763. rx, rx, st.bg);
  2764. else
  2765. ngui_fill_rect(ui, r, st.bg);
  2766. }
  2767. if (st.border_w) {
  2768. if (rx)
  2769. ngui_frame_round(ui, r, rx, rx, rx, rx,
  2770. st.border_w,
  2771. st.border_color);
  2772. else
  2773. ngui_frame(ui, r, st.border_color);
  2774. }
  2775. } else if (s_eq(nm, "line")) {
  2776. if (st.border_w)
  2777. ngui_line(ui,
  2778. ox + (int)nd->svg_x * dw / vw,
  2779. oy + (int)nd->svg_y * dh / vh,
  2780. ox + (int)nd->width_attr * dw / vw,
  2781. oy + (int)nd->height_attr * dh / vh,
  2782. st.border_color);
  2783. } else if (s_eq(nm, "path")) {
  2784. if (st.border_w && nd->src_off)
  2785. svg_path(ui, doc.attrs + nd->src_off,
  2786. ox, oy, dw, dh, vw, vh,
  2787. st.border_color);
  2788. } else if (s_eq(nm, "text")) {
  2789. unsigned int t = nd->first;
  2790. const char *s;
  2791. unsigned int n, tw;
  2792. int px = st.font_px ? st.font_px : 16;
  2793. int tx, ty, anchor;
  2794. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  2795. continue;
  2796. s = doc.text + doc.nodes[t].text_off;
  2797. n = doc.nodes[t].text_len;
  2798. tw = ngui_text_width_px(ui, s, n, px, st.bold,
  2799. st.italic, st.mono);
  2800. tx = ox + (int)nd->svg_x * dw / vw;
  2801. ty = oy + (int)nd->svg_y * dh / vh -
  2802. ngui_text_ascent(ui, px, st.mono);
  2803. anchor = st.align;
  2804. if (nd->attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  2805. anchor = BR_ALIGN_CENTER;
  2806. else if (nd->attr_flags & BR_ATTR_ANCHOR_END)
  2807. anchor = BR_ALIGN_RIGHT;
  2808. if (anchor == BR_ALIGN_CENTER)
  2809. tx -= (int)tw / 2;
  2810. else if (anchor == BR_ALIGN_RIGHT)
  2811. tx -= (int)tw;
  2812. ngui_text_px(ui, tx, ty, s, n, st.color, px,
  2813. st.bold, st.italic, st.mono);
  2814. }
  2815. }
  2816. }
  2817. static void layout_block(struct lay *l, unsigned int node,
  2818. const struct br_style *st, int depth,
  2819. unsigned short link)
  2820. {
  2821. int old_left = l->left, old_right = l->right, old_align = l->align;
  2822. int top, l0, r0;
  2823. int flow_y, flow_left, flow_right, positioned;
  2824. if (depth > 24 || st->display == BR_DISPLAY_NONE)
  2825. return;
  2826. flow_y = l->y;
  2827. flow_left = l->left;
  2828. flow_right = l->right;
  2829. positioned = st->pos;
  2830. if (positioned) {
  2831. if (st->pos == 2) {
  2832. l->y = page_rect.y + (st->top_set ? st->top : 0);
  2833. l->left = page_rect.x;
  2834. l->right = page_rect.x + page_rect.w - 12;
  2835. } else {
  2836. l->y = flow_y + (st->top_set ? st->top : 0);
  2837. l->left = flow_left + (st->left_set ? st->left : 0);
  2838. l->right = flow_right + (st->left_set ? st->left : 0);
  2839. }
  2840. old_left = l->left;
  2841. old_right = l->right;
  2842. }
  2843. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  2844. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  2845. doc.nodes[node].tag == BR_TAG_SELECT) {
  2846. if (!(doc.nodes[node].tag == BR_TAG_INPUT &&
  2847. s_eq(br_type(&doc, node), "hidden")))
  2848. add_form_run(l, node, st, link);
  2849. l->y += 20;
  2850. return;
  2851. }
  2852. flush_line(l);
  2853. l->y += st->mt;
  2854. top = l->y;
  2855. l0 = old_left + st->ml;
  2856. r0 = old_right - st->mr;
  2857. if (r0 < l0 + 16)
  2858. r0 = l0 + 16;
  2859. if (l->draw && block_h[node] &&
  2860. top < page_rect.y + page_rect.h &&
  2861. top + block_h[node] > page_rect.y) {
  2862. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  2863. int rtl = css_radius(st, 0, box.w, box.h);
  2864. int rtr = css_radius(st, 1, box.w, box.h);
  2865. int rbr = css_radius(st, 2, box.w, box.h);
  2866. int rbl = css_radius(st, 3, box.w, box.h);
  2867. if (rtl || rtr || rbr || rbl) {
  2868. if (st->has_bg) {
  2869. int bw = st->border_w;
  2870. if (bw > 0 && st->border_color != st->bg &&
  2871. box.w > bw * 2 && box.h > bw * 2) {
  2872. struct ngui_rect inner = {
  2873. box.x + bw, box.y + bw,
  2874. box.w - bw * 2, box.h - bw * 2
  2875. };
  2876. int itl = rtl > bw ? rtl - bw : 0;
  2877. int itr = rtr > bw ? rtr - bw : 0;
  2878. int ibr = rbr > bw ? rbr - bw : 0;
  2879. int ibl = rbl > bw ? rbl - bw : 0;
  2880. ngui_fill_round_rect(l->ui, box, rtl,
  2881. rtr, rbr, rbl,
  2882. st->border_color);
  2883. ngui_fill_round_rect(l->ui, inner,
  2884. itl, itr, ibr,
  2885. ibl, st->bg);
  2886. } else {
  2887. ngui_fill_round_rect(l->ui, box, rtl,
  2888. rtr, rbr, rbl,
  2889. st->bg);
  2890. }
  2891. } else if (st->border_w) {
  2892. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  2893. rbl, st->border_w,
  2894. st->border_color);
  2895. }
  2896. } else {
  2897. if (st->has_bg)
  2898. ngui_fill_rect(l->ui, box, st->bg);
  2899. if (st->border_w)
  2900. ngui_frame(l->ui, box, st->border_color);
  2901. }
  2902. }
  2903. l->left = l0 + st->pl;
  2904. l->right = r0 - st->pr;
  2905. if (l->right < l->left + 8)
  2906. l->right = l->left + 8;
  2907. l->align = st->align;
  2908. l->y += st->pt;
  2909. if (doc.nodes[node].tag == BR_TAG_HR) {
  2910. if (l->draw)
  2911. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  2912. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  2913. l->y += 8;
  2914. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  2915. int vw = l->right - l->left;
  2916. int vh;
  2917. if (doc.nodes[node].width_pct)
  2918. vw = vw * doc.nodes[node].width_attr / 100;
  2919. else if (doc.nodes[node].width_attr)
  2920. vw = doc.nodes[node].width_attr;
  2921. if (vw > l->right - l->left)
  2922. vw = l->right - l->left;
  2923. if (vw < 8)
  2924. vw = 8;
  2925. vh = vw * 9 / 16;
  2926. if (vh > 240)
  2927. vh = 240;
  2928. if (vh < 80)
  2929. vh = 80;
  2930. if (l->draw) {
  2931. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  2932. vw, vh}, 0xD69A);
  2933. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  2934. vw, vh}, 0x8410);
  2935. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  2936. 0x4208);
  2937. }
  2938. l->y += vh + 4;
  2939. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  2940. int vw, vh, dw = l->right - l->left;
  2941. int dh;
  2942. svg_viewbox(node, &vw, &vh);
  2943. if (dw < 8)
  2944. dw = 8;
  2945. dh = dw * vh / vw;
  2946. if (dh < 8)
  2947. dh = 8;
  2948. if (dh > 1400)
  2949. dh = 1400;
  2950. if (l->draw) {
  2951. struct ngui_rect clip = {l->left, l->y, dw, dh};
  2952. ngui_push_clip(l->ui, clip);
  2953. draw_svg(l->ui, node, l->left, l->y, dw, dh,
  2954. vw, vh, st);
  2955. ngui_pop_clip(l->ui);
  2956. }
  2957. l->y += dh;
  2958. } else {
  2959. if (doc.nodes[node].tag == BR_TAG_LI && !st->no_bullet) {
  2960. char *m = li_marker[node];
  2961. if (!m[0]) {
  2962. unsigned int parent = doc.nodes[node].parent;
  2963. if (parent &&
  2964. doc.nodes[parent].tag == BR_TAG_OL) {
  2965. int idx = list_index(parent, node);
  2966. unsigned int n = 0;
  2967. s_append_dec(m, &n, (unsigned int)idx, 6);
  2968. s_append(m, &n, ".", 6);
  2969. } else {
  2970. s_copy(m, "-", 6);
  2971. }
  2972. }
  2973. if (l->draw) {
  2974. int mw = (int)ngui_text_width_ui(l->ui, m);
  2975. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  2976. st->color);
  2977. }
  2978. }
  2979. if (doc.nodes[node].tag == BR_TAG_TR)
  2980. layout_table_row(l, node, st, depth + 1, link);
  2981. else if (st->grid_auto)
  2982. layout_grid_auto(l, node, st, depth + 1, link);
  2983. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  2984. st->grid_gap > 0)
  2985. layout_grid_children(l, node, st, depth + 1, link);
  2986. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  2987. flex_wants_row(node, st))
  2988. layout_flex_children(l, node, st, depth + 1, link);
  2989. else
  2990. layout_children(l, node, st, depth + 1, link);
  2991. }
  2992. flush_line(l);
  2993. l->y += st->pb;
  2994. /* Honour an explicit CSS height. Fixed-height header/icon boxes often
  2995. * contain only absolutely positioned children, so their flow height
  2996. * would otherwise collapse to zero. */
  2997. if (st->height_kind == 1 && st->height > 0 &&
  2998. l->y < top + st->height)
  2999. l->y = top + st->height;
  3000. l->left = old_left;
  3001. l->right = old_right;
  3002. l->align = old_align;
  3003. l->y += st->mb;
  3004. if (!l->draw) {
  3005. /* block_h is the element box, not the flow advance: the bottom
  3006. * margin must not be painted as part of the background. */
  3007. int h = l->y - st->mb - top;
  3008. if (h < 0)
  3009. h = 0;
  3010. if (h > 65535)
  3011. h = 65535;
  3012. block_h[node] = (unsigned short)h;
  3013. }
  3014. if (positioned) {
  3015. l->y = flow_y;
  3016. l->left = flow_left;
  3017. l->right = flow_right;
  3018. }
  3019. }
  3020. static int text_node_blank(const struct br_node *nd)
  3021. {
  3022. const char *t = doc.text + nd->text_off;
  3023. unsigned int i;
  3024. for (i = 0; i < nd->text_len; i++)
  3025. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  3026. t[i] != '\r')
  3027. return 0;
  3028. return 1;
  3029. }
  3030. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  3031. * text/image widths in the subtree, plus padding and margins. This keeps
  3032. * Bootstrap's floated nav items on one line instead of giving each the whole
  3033. * row. */
  3034. static int text_space(char c)
  3035. {
  3036. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  3037. }
  3038. static int intrinsic_width(struct ngui *ui, unsigned int node,
  3039. const struct br_style *pst, int depth)
  3040. {
  3041. unsigned int c;
  3042. int w = 0;
  3043. if (depth > 12)
  3044. return 0;
  3045. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  3046. struct br_node *nd = &doc.nodes[c];
  3047. struct br_style cs;
  3048. if (nd->type == BR_NODE_TEXT) {
  3049. const char *t = doc.text + nd->text_off;
  3050. unsigned int tn = nd->text_len;
  3051. if (doc.nodes[node].tag == BR_TAG_PRE) {
  3052. w += (int)ngui_text_width_px(ui, t, tn,
  3053. pst->font_px, pst->bold, pst->italic,
  3054. pst->mono);
  3055. } else {
  3056. unsigned int ti = 0;
  3057. int first = 1;
  3058. int lead = w > 0 && tn > 0 && text_space(t[0]);
  3059. int sp = (int)ngui_text_width_px(ui, " ", 1,
  3060. pst->font_px, pst->bold, pst->italic,
  3061. pst->mono);
  3062. while (ti < tn) {
  3063. unsigned int ts;
  3064. while (ti < tn && text_space(t[ti]))
  3065. ti++;
  3066. ts = ti;
  3067. while (ti < tn && !text_space(t[ti]))
  3068. ti++;
  3069. if (ti == ts)
  3070. break;
  3071. if (!first || lead)
  3072. w += sp;
  3073. lead = 0;
  3074. w += (int)ngui_text_width_px(ui,
  3075. t + ts, ti - ts,
  3076. pst->font_px, pst->bold,
  3077. pst->italic, pst->mono);
  3078. first = 0;
  3079. }
  3080. }
  3081. continue;
  3082. }
  3083. br_style_for(&doc, c, pst, &cs);
  3084. if (cs.display == BR_DISPLAY_NONE)
  3085. continue;
  3086. if (nd->tag == BR_TAG_BR) {
  3087. w += 8;
  3088. continue;
  3089. }
  3090. if (nd->tag == BR_TAG_IMG) {
  3091. /* Measure the image as layout will draw it: a CSS or
  3092. * attribute height keeps the intrinsic aspect ratio, and
  3093. * a CSS width overrides the native pixel width. Bootstrap
  3094. * sizes the Cloudron logo with height:40px only. */
  3095. int idx = nd->img_index;
  3096. int iw = 0, ih = 0;
  3097. if (idx >= 0 && idx < image_count &&
  3098. images[idx].state == 1) {
  3099. iw = (int)images[idx].native_w;
  3100. ih = (int)images[idx].native_h;
  3101. if (iw <= 0 || ih <= 0) {
  3102. iw = (int)images[idx].img.w;
  3103. ih = (int)images[idx].img.h;
  3104. }
  3105. }
  3106. if (cs.width_kind == 1) {
  3107. w += cs.width;
  3108. } else if (cs.width_kind == 2) {
  3109. w += 64;
  3110. } else if (nd->width_attr) {
  3111. w += nd->width_attr;
  3112. } else if (nd->height_attr && iw && ih) {
  3113. w += iw * (int)nd->height_attr / ih;
  3114. } else if (cs.height_kind == 1 && iw && ih) {
  3115. w += iw * (int)cs.height / ih;
  3116. } else if (iw) {
  3117. w += iw;
  3118. } else {
  3119. w += 64;
  3120. }
  3121. continue;
  3122. }
  3123. w += cs.pl + cs.pr + cs.ml + cs.mr;
  3124. w += intrinsic_width(ui, c, &cs, depth + 1);
  3125. if (w > 4096)
  3126. break;
  3127. }
  3128. return w;
  3129. }
  3130. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  3131. * the main user: .row > .col-md-* with float:left and a percentage width.
  3132. * Each column is laid out with its own left/right edge and the row advances
  3133. * to the tallest column. Returns the first child not consumed. */
  3134. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  3135. const struct br_style *pst, int depth,
  3136. unsigned short link)
  3137. {
  3138. unsigned int n = first;
  3139. int row_left = l->left, row_right = l->right;
  3140. int row_top, row_bottom, xl, xr, any = 0;
  3141. flush_line(l);
  3142. row_top = l->y;
  3143. row_bottom = l->y;
  3144. xl = row_left;
  3145. xr = row_right;
  3146. while (n) {
  3147. struct br_node *nd = &doc.nodes[n];
  3148. struct br_style cs;
  3149. unsigned short lk = link;
  3150. int colw, right;
  3151. if (nd->type == BR_NODE_TEXT) {
  3152. if (text_node_blank(nd)) {
  3153. n = nd->next;
  3154. continue;
  3155. }
  3156. break;
  3157. }
  3158. br_style_for(&doc, n, pst, &cs);
  3159. if (cs.display == BR_DISPLAY_NONE) {
  3160. n = nd->next;
  3161. continue;
  3162. }
  3163. /* A float blockifies its box: Bootstrap floats inline
  3164. * anchors too (the navbar brand and its text links), and
  3165. * their padding must be honoured. */
  3166. if (!cs.float_left)
  3167. break;
  3168. if (nd->tag == BR_TAG_A && nd->href_off)
  3169. lk = (unsigned short)n;
  3170. right = cs.float_left == 2;
  3171. if (cs.width_kind == 2)
  3172. colw = (row_right - row_left) * (int)cs.width / 100;
  3173. else if (cs.width_kind == 1)
  3174. colw = (int)cs.width;
  3175. else {
  3176. colw = intrinsic_width(l->ui, n, &cs, 0) +
  3177. cs.pl + cs.pr + cs.ml + cs.mr;
  3178. if (colw < 8)
  3179. colw = 8;
  3180. }
  3181. if (colw < 8)
  3182. colw = 8;
  3183. if (colw > row_right - row_left)
  3184. colw = row_right - row_left;
  3185. if (right) {
  3186. if (any && xr - colw < xl) {
  3187. row_top = row_bottom;
  3188. row_bottom = row_top;
  3189. xl = row_left;
  3190. xr = row_right;
  3191. }
  3192. if (xr - colw < xl)
  3193. colw = xr - xl;
  3194. if (colw < 8)
  3195. colw = 8;
  3196. l->left = xr - colw;
  3197. if (l->left < row_left)
  3198. l->left = row_left;
  3199. l->right = xr;
  3200. xr = l->left;
  3201. } else {
  3202. if (any && xl + colw > xr) {
  3203. row_top = row_bottom;
  3204. row_bottom = row_top;
  3205. xl = row_left;
  3206. xr = row_right;
  3207. }
  3208. l->left = xl;
  3209. l->right = xl + colw;
  3210. xl += colw;
  3211. }
  3212. if (l->right < l->left + 8)
  3213. l->right = l->left + 8;
  3214. l->y = row_top;
  3215. l->line_x = l->left;
  3216. l->run_x = l->left;
  3217. l->line_y = l->y;
  3218. l->line_h = 0;
  3219. l->nruns = 0;
  3220. l->space_pending = 0;
  3221. l->align = cs.align;
  3222. layout_block(l, n, &cs, depth + 1, lk);
  3223. if (l->y > row_bottom)
  3224. row_bottom = l->y;
  3225. any = 1;
  3226. n = nd->next;
  3227. }
  3228. l->left = row_left;
  3229. l->right = row_right;
  3230. l->y = row_bottom;
  3231. l->line_x = l->left;
  3232. l->run_x = l->left;
  3233. l->line_y = l->y;
  3234. l->line_h = 0;
  3235. l->nruns = 0;
  3236. l->space_pending = 0;
  3237. return n;
  3238. }
  3239. static int flex_item_width(struct lay *l, unsigned int n,
  3240. const struct br_style *cs, int avail)
  3241. {
  3242. struct br_node *nd = &doc.nodes[n];
  3243. (void)l;
  3244. int w;
  3245. if (cs->width_kind == 2)
  3246. w = avail * (int)cs->width / 100;
  3247. else if (cs->width_kind == 1)
  3248. w = (int)cs->width;
  3249. else if (nd->tag == BR_TAG_IMG) {
  3250. int idx = nd->img_index;
  3251. if (idx >= 0 && idx < image_count &&
  3252. images[idx].state == 1)
  3253. w = (int)images[idx].img.w;
  3254. else if (nd->width_attr)
  3255. w = (int)nd->width_attr;
  3256. else
  3257. w = 64;
  3258. } else {
  3259. w = intrinsic_width(l->ui, n, cs, 0);
  3260. w += cs->pl + cs->pr + cs->ml + cs->mr;
  3261. }
  3262. if (w < 24)
  3263. w = 24;
  3264. if (w > avail)
  3265. w = avail;
  3266. return w;
  3267. }
  3268. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  3269. * on one line, not one full-width block each. Place intrinsic widths from
  3270. * left to right and wrap when the row is full. */
  3271. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  3272. const struct br_style *pst, int depth,
  3273. unsigned short link)
  3274. {
  3275. unsigned int n = first;
  3276. int row_left = l->left, row_right = l->right;
  3277. int avail = row_right - row_left;
  3278. int x = row_left, y = l->y, row_h = 0, any = 0;
  3279. flush_line(l);
  3280. y = l->y;
  3281. while (n) {
  3282. struct br_node *nd = &doc.nodes[n];
  3283. struct br_style cs;
  3284. unsigned short lk = link;
  3285. int colw, h;
  3286. if (nd->type == BR_NODE_TEXT) {
  3287. if (!text_node_blank(nd))
  3288. break;
  3289. if (any)
  3290. x += 4;
  3291. n = nd->next;
  3292. continue;
  3293. }
  3294. br_style_for(&doc, n, pst, &cs);
  3295. if (cs.display == BR_DISPLAY_NONE) {
  3296. n = nd->next;
  3297. continue;
  3298. }
  3299. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  3300. break;
  3301. if (nd->tag == BR_TAG_A && nd->href_off)
  3302. lk = (unsigned short)n;
  3303. colw = flex_item_width(l, n, &cs, avail);
  3304. /* A few pixels of slack keep a single long token (boot.S)
  3305. * from wrapping at the exact content width. */
  3306. colw += 8;
  3307. if (colw > avail)
  3308. colw = avail;
  3309. if (any && x + colw > row_right) {
  3310. y += row_h + 2;
  3311. x = row_left;
  3312. row_h = 0;
  3313. any = 0;
  3314. }
  3315. if (any && x > row_left)
  3316. x += 4;
  3317. l->left = x;
  3318. l->right = x + colw;
  3319. if (l->right < l->left + 8)
  3320. l->right = l->left + 8;
  3321. l->y = y;
  3322. l->line_x = l->left;
  3323. l->run_x = l->left;
  3324. l->line_y = l->y;
  3325. l->line_h = 0;
  3326. l->nruns = 0;
  3327. l->space_pending = 0;
  3328. l->align = cs.align;
  3329. layout_block(l, n, &cs, depth + 1, lk);
  3330. h = l->y - y;
  3331. if (h > row_h)
  3332. row_h = h;
  3333. x += colw;
  3334. any = 1;
  3335. n = nd->next;
  3336. }
  3337. if (any)
  3338. y += row_h;
  3339. l->left = row_left;
  3340. l->right = row_right;
  3341. l->y = y;
  3342. l->line_x = l->left;
  3343. l->run_x = l->left;
  3344. l->line_y = l->y;
  3345. l->line_h = 0;
  3346. l->nruns = 0;
  3347. l->space_pending = 0;
  3348. return n;
  3349. }
  3350. static void layout_flex_children(struct lay *l, unsigned int parent,
  3351. const struct br_style *pst, int depth,
  3352. unsigned short link)
  3353. {
  3354. unsigned int n, c;
  3355. int row_left = l->left, row_right = l->right;
  3356. int avail = row_right - row_left;
  3357. int grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  3358. int x = row_left, row_top = l->y, row_bottom = l->y, any = 0;
  3359. if (avail < 160 || depth > 24) {
  3360. layout_children(l, parent, pst, depth, link);
  3361. return;
  3362. }
  3363. /* If direct text is not just whitespace, normal block flow handles it
  3364. * better than pretending it is a flex item. */
  3365. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  3366. struct br_node *nd = &doc.nodes[c];
  3367. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  3368. layout_children(l, parent, pst, depth, link);
  3369. return;
  3370. }
  3371. }
  3372. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  3373. struct br_node *nd = &doc.nodes[c];
  3374. struct br_style cs;
  3375. if (nd->type == BR_NODE_TEXT)
  3376. continue;
  3377. br_style_for(&doc, c, pst, &cs);
  3378. if (cs.display == BR_DISPLAY_NONE)
  3379. continue;
  3380. if (cs.flex_grow && !cs.width_kind)
  3381. grow_count++;
  3382. else
  3383. fixed += flex_item_width(l, c, &cs, avail);
  3384. }
  3385. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  3386. if (grow_w < 96)
  3387. grow_w = 96;
  3388. n = doc.nodes[parent].first;
  3389. while (n) {
  3390. struct br_node *nd = &doc.nodes[n];
  3391. struct br_style cs;
  3392. unsigned short lk = link;
  3393. int colw;
  3394. if (nd->type == BR_NODE_TEXT) {
  3395. n = nd->next;
  3396. continue;
  3397. }
  3398. br_style_for(&doc, n, pst, &cs);
  3399. if (cs.display == BR_DISPLAY_NONE) {
  3400. n = nd->next;
  3401. continue;
  3402. }
  3403. if (nd->tag == BR_TAG_A && nd->href_off)
  3404. lk = (unsigned short)n;
  3405. if (cs.flex_grow && !cs.width_kind)
  3406. colw = grow_w;
  3407. else
  3408. colw = flex_item_width(l, n, &cs, avail);
  3409. if (colw > row_right - row_left)
  3410. colw = row_right - row_left;
  3411. if (any && x + colw > row_right) {
  3412. if (pst->flex_wrap == 2) {
  3413. if (colw > row_right - x)
  3414. colw = row_right - x;
  3415. } else {
  3416. row_top = row_bottom;
  3417. row_bottom = row_top;
  3418. x = row_left;
  3419. }
  3420. }
  3421. if (any && gap && x > row_left)
  3422. x += gap;
  3423. l->left = x;
  3424. l->right = x + colw;
  3425. if (l->right < l->left + 8)
  3426. l->right = l->left + 8;
  3427. l->y = row_top;
  3428. l->line_x = l->left;
  3429. l->run_x = l->left;
  3430. l->line_y = l->y;
  3431. l->line_h = 0;
  3432. l->nruns = 0;
  3433. l->space_pending = 0;
  3434. l->align = cs.align;
  3435. layout_block(l, n, &cs, depth + 1, lk);
  3436. if (l->y > row_bottom)
  3437. row_bottom = l->y;
  3438. x += colw;
  3439. any++;
  3440. n = nd->next;
  3441. }
  3442. l->left = row_left;
  3443. l->right = row_right;
  3444. l->y = row_bottom;
  3445. l->line_x = l->left;
  3446. l->run_x = l->left;
  3447. l->line_y = l->y;
  3448. l->line_h = 0;
  3449. l->nruns = 0;
  3450. l->space_pending = 0;
  3451. }
  3452. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  3453. * plus the grid-area hints used by site shells (site notice/footer full
  3454. * width, column-start left, page-content right). Anything more elaborate
  3455. * falls back to normal block flow. */
  3456. static int grid_track_width(unsigned char kind, unsigned short val,
  3457. int avail, int other)
  3458. {
  3459. if (kind == 2)
  3460. return avail * (int)val / 100;
  3461. if (kind == 1)
  3462. return val;
  3463. return other;
  3464. }
  3465. static void layout_grid_children(struct lay *l, unsigned int parent,
  3466. const struct br_style *pst, int depth,
  3467. unsigned short link)
  3468. {
  3469. unsigned int n;
  3470. int row_left = l->left, row_right = l->right;
  3471. int avail = row_right - row_left;
  3472. int gap = pst->grid_gap;
  3473. int track_total = avail - gap;
  3474. int col0, col1, x0, x1;
  3475. int row_y, row_bottom, have_left = 0, have_right = 0;
  3476. unsigned int c;
  3477. if (avail < 32 || depth > 24)
  3478. return;
  3479. if (track_total < 16)
  3480. track_total = 16;
  3481. col0 = grid_track_width((unsigned char)(pst->width_kind),
  3482. pst->width, track_total, 0);
  3483. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  3484. pst->max_width, track_total, 0);
  3485. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  3486. int w0 = pst->width ? pst->width : 1;
  3487. int w1 = pst->max_width ? pst->max_width : 1;
  3488. col0 = track_total * w0 / (w0 + w1);
  3489. col1 = track_total - col0;
  3490. } else if (pst->width_kind == 3) {
  3491. col0 = track_total - col1;
  3492. if (col0 < 24)
  3493. col0 = 24;
  3494. } else if (pst->max_width_kind == 3) {
  3495. col1 = track_total - col0;
  3496. if (col1 < 24)
  3497. col1 = 24;
  3498. }
  3499. if (col0 < 24)
  3500. col0 = 24;
  3501. if (col1 < 24)
  3502. col1 = 24;
  3503. if (col0 + col1 > track_total) {
  3504. col1 = track_total - col0;
  3505. if (col1 < 24)
  3506. col1 = 24;
  3507. }
  3508. x0 = row_left;
  3509. x1 = row_left + col0 + gap;
  3510. /* Direct text makes a grid ambiguous; use block flow instead. */
  3511. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  3512. struct br_node *nd = &doc.nodes[c];
  3513. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  3514. layout_children(l, parent, pst, depth, link);
  3515. return;
  3516. }
  3517. }
  3518. row_y = row_bottom = l->y;
  3519. n = doc.nodes[parent].first;
  3520. while (n) {
  3521. struct br_node *nd = &doc.nodes[n];
  3522. struct br_style cs;
  3523. unsigned short lk = link;
  3524. int slot, x, w;
  3525. if (nd->type == BR_NODE_TEXT) {
  3526. n = nd->next;
  3527. continue;
  3528. }
  3529. br_style_for(&doc, n, pst, &cs);
  3530. if (cs.display == BR_DISPLAY_NONE) {
  3531. n = nd->next;
  3532. continue;
  3533. }
  3534. if (nd->tag == BR_TAG_A && nd->href_off)
  3535. lk = (unsigned short)n;
  3536. slot = cs.grid_slot;
  3537. if (!slot) {
  3538. if (!have_left)
  3539. slot = 2;
  3540. else if (!have_right)
  3541. slot = 3;
  3542. else
  3543. slot = 2;
  3544. }
  3545. if (slot == 1) {
  3546. if (have_left || have_right) {
  3547. row_y = row_bottom;
  3548. have_left = have_right = 0;
  3549. }
  3550. x = row_left;
  3551. w = avail;
  3552. } else if (slot == 2) {
  3553. if (have_left) {
  3554. row_y = row_bottom;
  3555. have_left = have_right = 0;
  3556. }
  3557. x = x0;
  3558. w = col0;
  3559. have_left = 1;
  3560. } else {
  3561. if (have_right) {
  3562. row_y = row_bottom;
  3563. have_left = have_right = 0;
  3564. }
  3565. x = x1;
  3566. w = col1;
  3567. have_right = 1;
  3568. }
  3569. l->left = x;
  3570. l->right = x + w;
  3571. if (l->right < l->left + 8)
  3572. l->right = l->left + 8;
  3573. l->y = row_y;
  3574. l->line_x = l->left;
  3575. l->run_x = l->left;
  3576. l->line_y = l->y;
  3577. l->line_h = 0;
  3578. l->nruns = 0;
  3579. l->space_pending = 0;
  3580. l->align = cs.align;
  3581. layout_block(l, n, &cs, depth + 1, lk);
  3582. if (l->y > row_bottom)
  3583. row_bottom = l->y;
  3584. n = nd->next;
  3585. }
  3586. l->left = row_left;
  3587. l->right = row_right;
  3588. l->y = row_bottom;
  3589. l->line_x = l->left;
  3590. l->run_x = l->left;
  3591. l->line_y = l->y;
  3592. l->line_h = 0;
  3593. l->nruns = 0;
  3594. l->space_pending = 0;
  3595. }
  3596. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  3597. * capped at four. Used by the project docs' card grids. */
  3598. static void layout_grid_auto(struct lay *l, unsigned int parent,
  3599. const struct br_style *pst, int depth,
  3600. unsigned short link)
  3601. {
  3602. unsigned int n, c;
  3603. int row_left = l->left, row_right = l->right;
  3604. int avail = row_right - row_left;
  3605. int gap = pst->grid_gap;
  3606. int minw = pst->width_kind == 1 ? pst->width : 200;
  3607. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  3608. if (avail < 32 || depth > 24) {
  3609. layout_children(l, parent, pst, depth, link);
  3610. return;
  3611. }
  3612. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  3613. struct br_node *nd = &doc.nodes[c];
  3614. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  3615. layout_children(l, parent, pst, depth, link);
  3616. return;
  3617. }
  3618. }
  3619. if (minw < 80)
  3620. minw = 80;
  3621. ncols = (avail + gap) / (minw + gap);
  3622. if (ncols < 1)
  3623. ncols = 1;
  3624. if (ncols > 4)
  3625. ncols = 4;
  3626. colw = (avail - gap * (ncols - 1)) / ncols;
  3627. if (colw < 24)
  3628. colw = 24;
  3629. x = row_left;
  3630. n = doc.nodes[parent].first;
  3631. while (n) {
  3632. struct br_node *nd = &doc.nodes[n];
  3633. struct br_style cs;
  3634. unsigned short lk = link;
  3635. int h;
  3636. if (nd->type == BR_NODE_TEXT) {
  3637. n = nd->next;
  3638. continue;
  3639. }
  3640. br_style_for(&doc, n, pst, &cs);
  3641. if (cs.display == BR_DISPLAY_NONE) {
  3642. n = nd->next;
  3643. continue;
  3644. }
  3645. if (nd->tag == BR_TAG_A && nd->href_off)
  3646. lk = (unsigned short)n;
  3647. l->left = x;
  3648. l->right = x + colw;
  3649. if (l->right < l->left + 8)
  3650. l->right = l->left + 8;
  3651. l->y = y;
  3652. l->line_x = l->left;
  3653. l->run_x = l->left;
  3654. l->line_y = l->y;
  3655. l->line_h = 0;
  3656. l->nruns = 0;
  3657. l->space_pending = 0;
  3658. l->align = cs.align;
  3659. layout_block(l, n, &cs, depth + 1, lk);
  3660. h = l->y - y;
  3661. if (h > row_h)
  3662. row_h = h;
  3663. col++;
  3664. n = nd->next;
  3665. if (col == ncols) {
  3666. y += row_h + gap;
  3667. x = row_left;
  3668. row_h = 0;
  3669. col = 0;
  3670. } else {
  3671. x += colw + gap;
  3672. }
  3673. }
  3674. if (col)
  3675. y += row_h;
  3676. else if (y > start_y)
  3677. y -= gap;
  3678. l->left = row_left;
  3679. l->right = row_right;
  3680. l->y = y;
  3681. l->line_x = l->left;
  3682. l->run_x = l->left;
  3683. l->line_y = l->y;
  3684. l->line_h = 0;
  3685. l->nruns = 0;
  3686. l->space_pending = 0;
  3687. }
  3688. /* Column widths are the widest cell in each column across every row, so all
  3689. * rows line up. The table model is still deliberately basic: no colspan,
  3690. * border-collapse or percentage columns. */
  3691. static void table_columns(struct lay *l, unsigned int table,
  3692. const struct br_style *pst, int *raw, int maxcols,
  3693. int *out_cols, int *out_total)
  3694. {
  3695. unsigned int r, c;
  3696. int cols = 0, total = 0;
  3697. for (c = 0; c < (unsigned int)maxcols; c++)
  3698. raw[c] = 0;
  3699. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  3700. struct br_node *rn = &doc.nodes[r];
  3701. int col = 0;
  3702. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  3703. continue;
  3704. for (c = rn->first; c; c = doc.nodes[c].next) {
  3705. struct br_node *cn = &doc.nodes[c];
  3706. struct br_style cs;
  3707. int w;
  3708. if (cn->type != BR_NODE_ELEM ||
  3709. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  3710. continue;
  3711. if (col >= maxcols)
  3712. break;
  3713. br_style_for(&doc, c, pst, &cs);
  3714. if (cs.display == BR_DISPLAY_NONE)
  3715. continue;
  3716. w = intrinsic_width(l->ui, c, &cs, 0) + cs.pl + cs.pr +
  3717. cs.ml + cs.mr;
  3718. if (w < 24)
  3719. w = 24;
  3720. if (w > raw[col])
  3721. raw[col] = w;
  3722. if (col + 1 > cols)
  3723. cols = col + 1;
  3724. col++;
  3725. }
  3726. }
  3727. for (c = 0; c < (unsigned int)cols; c++)
  3728. total += raw[c];
  3729. *out_cols = cols;
  3730. *out_total = total;
  3731. }
  3732. static void layout_table_row(struct lay *l, unsigned int row,
  3733. const struct br_style *pst, int depth,
  3734. unsigned short link)
  3735. {
  3736. unsigned int n, cell[12];
  3737. int raw[12], ncell = 0, total = 0, cols = 0;
  3738. int row_left = l->left, row_right = l->right;
  3739. int avail = row_right - row_left;
  3740. int x = row_left, y = l->y, bottom = l->y;
  3741. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  3742. struct br_node *nd = &doc.nodes[n];
  3743. struct br_style cs;
  3744. if (nd->type == BR_NODE_TEXT) {
  3745. if (text_node_blank(nd))
  3746. continue;
  3747. layout_children(l, row, pst, depth, link);
  3748. return;
  3749. }
  3750. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  3751. layout_children(l, row, pst, depth, link);
  3752. return;
  3753. }
  3754. br_style_for(&doc, n, pst, &cs);
  3755. if (cs.display == BR_DISPLAY_NONE)
  3756. continue;
  3757. if (ncell >= 12) {
  3758. layout_children(l, row, pst, depth, link);
  3759. return;
  3760. }
  3761. cell[ncell] = n;
  3762. ncell++;
  3763. }
  3764. if (ncell < 2 || avail < 32) {
  3765. layout_children(l, row, pst, depth, link);
  3766. return;
  3767. }
  3768. table_columns(l, doc.nodes[row].parent, pst, raw, 12, &cols, &total);
  3769. if (cols < 2 || total <= 0) {
  3770. int c;
  3771. for (c = 0; c < ncell; c++) {
  3772. struct br_style cs;
  3773. br_style_for(&doc, cell[c], pst, &cs);
  3774. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0) +
  3775. cs.pl + cs.pr + cs.ml + cs.mr;
  3776. if (raw[c] < 24)
  3777. raw[c] = 24;
  3778. total += raw[c];
  3779. }
  3780. }
  3781. for (n = 0; n < (unsigned int)ncell; n++) {
  3782. struct br_style cs;
  3783. int w = (int)((long)raw[n] * avail / total);
  3784. br_style_for(&doc, cell[n], pst, &cs);
  3785. if (w < 24)
  3786. w = 24;
  3787. if (w < 8)
  3788. w = 8;
  3789. l->left = x;
  3790. l->right = x + w;
  3791. l->y = y;
  3792. l->line_x = l->left;
  3793. l->run_x = l->left;
  3794. l->line_y = l->y;
  3795. l->line_h = 0;
  3796. l->nruns = 0;
  3797. l->space_pending = 0;
  3798. l->align = cs.align;
  3799. layout_block(l, cell[n], &cs, depth + 1, link);
  3800. if (l->y > bottom)
  3801. bottom = l->y;
  3802. x += w;
  3803. }
  3804. l->left = row_left;
  3805. l->right = row_right;
  3806. l->y = bottom;
  3807. l->line_x = l->left;
  3808. l->run_x = l->left;
  3809. l->line_y = l->y;
  3810. l->line_h = 0;
  3811. l->nruns = 0;
  3812. l->space_pending = 0;
  3813. }
  3814. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  3815. * flow so they sit above it, like CSS painting order. Their flow origin is
  3816. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  3817. struct br_deferred {
  3818. unsigned int node;
  3819. int flow_y, flow_left, flow_right;
  3820. unsigned short link;
  3821. };
  3822. static struct br_deferred deferred[16];
  3823. static int ndeferred;
  3824. static void layout_children(struct lay *l, unsigned int parent,
  3825. const struct br_style *pst, int depth,
  3826. unsigned short link)
  3827. {
  3828. unsigned int n;
  3829. if (depth > 24)
  3830. return;
  3831. n = doc.nodes[parent].first;
  3832. while (n) {
  3833. struct br_node *nd = &doc.nodes[n];
  3834. struct br_style cs;
  3835. unsigned short lk = link;
  3836. if (nd->type == BR_NODE_TEXT) {
  3837. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  3838. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  3839. n = nd->next;
  3840. continue;
  3841. }
  3842. br_style_for(&doc, n, pst, &cs);
  3843. if (cs.display == BR_DISPLAY_NONE) {
  3844. n = nd->next;
  3845. continue;
  3846. }
  3847. if (nd->tag == BR_TAG_A && nd->href_off)
  3848. lk = (unsigned short)n;
  3849. if (cs.pos) {
  3850. if (l->draw && ndeferred < 16) {
  3851. deferred[ndeferred].node = n;
  3852. deferred[ndeferred].flow_y = l->y;
  3853. deferred[ndeferred].flow_left = l->left;
  3854. deferred[ndeferred].flow_right = l->right;
  3855. deferred[ndeferred].link = lk;
  3856. ndeferred++;
  3857. } else {
  3858. layout_block(l, n, &cs, depth + 1, lk);
  3859. }
  3860. if (cs.pos == 1 && block_h[n] &&
  3861. doc.nodes[n].class_off) {
  3862. const char *cl = doc.attrs +
  3863. doc.nodes[n].class_off;
  3864. if ((contains_ci(cl, "poster-wrapper") ||
  3865. contains_ci(cl, "ts-picture")) &&
  3866. !has_skeleton_sibling(n))
  3867. l->y += block_h[n];
  3868. }
  3869. n = nd->next;
  3870. continue;
  3871. }
  3872. if (nd->tag == BR_TAG_BR) {
  3873. flush_line(l);
  3874. n = nd->next;
  3875. continue;
  3876. }
  3877. if (nd->tag == BR_TAG_HR) {
  3878. flush_line(l);
  3879. if (l->draw)
  3880. ngui_fill_rect(l->ui,
  3881. (struct ngui_rect){l->left, l->y + 2,
  3882. l->right - l->left, 1}, BR_GRAY);
  3883. l->y += 8;
  3884. n = nd->next;
  3885. continue;
  3886. }
  3887. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  3888. nd->tag == BR_TAG_SELECT) {
  3889. if (!(nd->tag == BR_TAG_INPUT &&
  3890. s_eq(br_type(&doc, n), "hidden")))
  3891. add_form_run(l, n, &cs, lk);
  3892. n = nd->next;
  3893. continue;
  3894. }
  3895. if (nd->tag == BR_TAG_IMG) {
  3896. add_image_run(l, n, &cs, lk);
  3897. n = nd->next;
  3898. continue;
  3899. }
  3900. if (nd->tag == BR_TAG_VIDEO) {
  3901. layout_block(l, n, &cs, depth + 1, lk);
  3902. n = nd->next;
  3903. continue;
  3904. }
  3905. if (cs.float_left) {
  3906. n = layout_float_group(l, n, pst, depth, lk);
  3907. continue;
  3908. }
  3909. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  3910. n = layout_inline_blocks(l, n, pst, depth, link);
  3911. continue;
  3912. }
  3913. if (cs.display == BR_DISPLAY_BLOCK || br_tag_is_block(nd->tag))
  3914. layout_block(l, n, &cs, depth + 1, lk);
  3915. else {
  3916. layout_children(l, n, &cs, depth + 1, lk);
  3917. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  3918. l->space_pending = 1;
  3919. }
  3920. n = nd->next;
  3921. }
  3922. }
  3923. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  3924. * runs and a recursive page can otherwise overflow the stack. */
  3925. static struct lay layout_state;
  3926. static int measure_page(int left, int right)
  3927. {
  3928. struct lay *l = &layout_state;
  3929. struct br_style base = base_style();
  3930. unsigned int i;
  3931. for (i = 0; i < BR_MAX_NODES; i++) {
  3932. block_h[i] = 0;
  3933. img_top[i] = 0;
  3934. img_h[i] = 0;
  3935. }
  3936. l->draw = 0;
  3937. l->ui = 0;
  3938. l->left = left;
  3939. l->right = right;
  3940. l->y = 0;
  3941. l->line_x = left;
  3942. l->run_x = left;
  3943. l->line_y = 0;
  3944. l->line_h = 0;
  3945. l->align = BR_ALIGN_LEFT;
  3946. l->depth = 0;
  3947. l->nruns = 0;
  3948. l->space_pending = 0;
  3949. layout_children(l, doc.root, &base, 0, 0);
  3950. return l->y + 8;
  3951. }
  3952. static void render_page(int left, int right, int y0)
  3953. {
  3954. struct lay *l = &layout_state;
  3955. struct br_style base = base_style();
  3956. l->draw = 1;
  3957. l->ui = &ui;
  3958. l->left = left;
  3959. l->right = right;
  3960. l->y = y0;
  3961. l->line_x = left;
  3962. l->run_x = left;
  3963. l->line_y = y0;
  3964. l->line_h = 0;
  3965. l->align = BR_ALIGN_LEFT;
  3966. l->depth = 0;
  3967. l->nruns = 0;
  3968. l->space_pending = 0;
  3969. nhits = 0;
  3970. ndeferred = 0;
  3971. layout_children(l, doc.root, &base, 0, 0);
  3972. {
  3973. int i;
  3974. for (i = 0; i < ndeferred; i++) {
  3975. struct br_style st;
  3976. br_style_for(&doc, deferred[i].node, &base, &st);
  3977. if (st.display == BR_DISPLAY_NONE)
  3978. continue;
  3979. l->draw = 1;
  3980. l->left = deferred[i].flow_left;
  3981. l->right = deferred[i].flow_right;
  3982. l->y = deferred[i].flow_y;
  3983. l->line_x = l->left;
  3984. l->run_x = l->left;
  3985. l->line_y = l->y;
  3986. l->line_h = 0;
  3987. l->nruns = 0;
  3988. l->space_pending = 0;
  3989. l->align = st.align;
  3990. if (st.pos == 2 && block_h[deferred[i].node]) {
  3991. struct ngui_rect clip;
  3992. int ch = block_h[deferred[i].node] + 24;
  3993. clip.x = page_rect.x;
  3994. clip.y = page_rect.y;
  3995. clip.w = page_rect.w - 12;
  3996. if (ch > page_rect.h)
  3997. ch = page_rect.h;
  3998. clip.h = ch;
  3999. ngui_push_clip(&ui, clip);
  4000. if (st.has_bg)
  4001. ngui_fill_rect(&ui, clip, st.bg);
  4002. layout_block(l, deferred[i].node, &st, 0,
  4003. deferred[i].link);
  4004. ngui_pop_clip(&ui);
  4005. } else {
  4006. layout_block(l, deferred[i].node, &st, 0,
  4007. deferred[i].link);
  4008. }
  4009. }
  4010. }
  4011. }
  4012. /* ---- UI ---- */
  4013. static int find_hit(int x, int y)
  4014. {
  4015. int i;
  4016. for (i = nhits - 1; i >= 0; i--) {
  4017. struct hit *h = &hits[i];
  4018. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  4019. y < h->y + h->h)
  4020. return (int)h->node;
  4021. }
  4022. return 0;
  4023. }
  4024. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  4025. {
  4026. int x = r.x + 4, y = r.y + 4, h = 22;
  4027. int compact = r.w < 560;
  4028. int go_w = r.w < 420 ? 32 : 42;
  4029. int in_x, in_w, res;
  4030. ngui_fill_rect(&ui, r, ui.theme.panel);
  4031. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  4032. ui.theme.border);
  4033. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  4034. NGUI_ICON_CHEVRON_LEFT))
  4035. *action |= ACT_BACK;
  4036. x += 32;
  4037. if (!compact) {
  4038. if (ngui_icon_button(&ui, ID_FORWARD,
  4039. (struct ngui_rect){x, y, 28, h},
  4040. NGUI_ICON_CHEVRON_RIGHT))
  4041. *action |= ACT_FORWARD;
  4042. x += 32;
  4043. }
  4044. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  4045. NGUI_ICON_REFRESH))
  4046. *action |= ACT_RELOAD;
  4047. x += 32;
  4048. if (!compact) {
  4049. if (ngui_icon_button(&ui, ID_HOME,
  4050. (struct ngui_rect){x, y, 28, h},
  4051. NGUI_ICON_HOME))
  4052. *action |= ACT_HOME;
  4053. x += 32;
  4054. }
  4055. in_x = x + 2;
  4056. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  4057. if (in_w < 60)
  4058. in_w = 60;
  4059. res = ngui_text_input(&ui, ID_URL,
  4060. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  4061. if (res & NGUI_INPUT_SUBMIT)
  4062. *action |= ACT_NAV;
  4063. if (res & NGUI_INPUT_CANCEL)
  4064. ngui_set_focus(&ui, 0);
  4065. if (ngui_button(&ui, ID_GO,
  4066. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  4067. "Go"))
  4068. *action |= ACT_NAV;
  4069. }
  4070. static int page_hover_node(void)
  4071. {
  4072. if (!ui.inside)
  4073. return 0;
  4074. if (ui.mouse_x < page_rect.x ||
  4075. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  4076. ui.mouse_y < page_rect.y ||
  4077. ui.mouse_y >= page_rect.y + page_rect.h)
  4078. return 0;
  4079. return find_hit(ui.mouse_x, ui.mouse_y);
  4080. }
  4081. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  4082. {
  4083. int x, y, w = page.w, h = page.h;
  4084. if (!src || w <= 0 || h <= 0)
  4085. return;
  4086. for (y = 0; y < h; y++) {
  4087. unsigned short *s = src + (page.y + y) * sw + page.x;
  4088. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  4089. for (x = 0; x + 1 < w; x += 2) {
  4090. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  4091. }
  4092. if (x < w)
  4093. d[x] = s[x];
  4094. }
  4095. }
  4096. static void draw_page(struct ngui_rect page)
  4097. {
  4098. int left, right, ch;
  4099. int old_panel, old_dim;
  4100. unsigned short *saved_px;
  4101. int saved_w, saved_h, use_buf;
  4102. page_rect = page;
  4103. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  4104. page_cache_valid && layout_valid &&
  4105. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  4106. page_scroll.offset == page_cache_scroll &&
  4107. page_cache_nnode == doc.nnode &&
  4108. page_cache_x == page.x && page_cache_y == page.y &&
  4109. page_cache_w == page.w && page_cache_h == page.h) {
  4110. blit_page(page, page_backbuf, pagebuf_w);
  4111. return;
  4112. }
  4113. ngui_fill_rect(&ui, page, ui.theme.bg);
  4114. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  4115. const char *s = page_loading ? "Loading..." : "No page";
  4116. int w = (int)ngui_text_width_ui(&ui, s);
  4117. ngui_text(&ui, page.x + (page.w - w) / 2,
  4118. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  4119. page_scroll.content_h = 0;
  4120. page_scroll.view_h = page.h;
  4121. page_cache_valid = 0;
  4122. return;
  4123. }
  4124. if (page.w < 40 || page.h < 40) {
  4125. page_cache_valid = 0;
  4126. return;
  4127. }
  4128. saved_px = ui.px;
  4129. saved_w = ui.w;
  4130. saved_h = ui.h;
  4131. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  4132. if (use_buf) {
  4133. ui.px = page_backbuf;
  4134. ui.w = pagebuf_w;
  4135. ui.h = pagebuf_h;
  4136. ngui_fill_rect(&ui, page, ui.theme.bg);
  4137. }
  4138. left = page.x + 8;
  4139. right = page.x + page.w - 16;
  4140. if (!layout_valid || left != layout_left || right != layout_right ||
  4141. layout_nnode != doc.nnode) {
  4142. layout_content_h = measure_page(left, right);
  4143. layout_valid = 1;
  4144. layout_left = left;
  4145. layout_right = right;
  4146. layout_nnode = doc.nnode;
  4147. }
  4148. ch = layout_content_h;
  4149. page_scroll.content_h = ch;
  4150. page_scroll.view_h = page.h;
  4151. ngui_scroll_begin(&ui, page, &page_scroll);
  4152. render_page(left, right, page.y + 4 - page_scroll.offset);
  4153. old_panel = ui.theme.panel_alt;
  4154. old_dim = ui.theme.text_dim;
  4155. ui.theme.panel_alt = 0xC618;
  4156. ui.theme.text_dim = 0x8410;
  4157. ngui_scroll_end(&ui, page, &page_scroll);
  4158. ui.theme.panel_alt = old_panel;
  4159. ui.theme.text_dim = old_dim;
  4160. if (use_buf) {
  4161. ui.px = saved_px;
  4162. ui.w = saved_w;
  4163. ui.h = saved_h;
  4164. blit_page(page, page_backbuf, pagebuf_w);
  4165. page_cache_valid = 1;
  4166. page_cache_scroll = page_scroll.offset;
  4167. page_cache_nnode = doc.nnode;
  4168. page_cache_x = page.x;
  4169. page_cache_y = page.y;
  4170. page_cache_w = page.w;
  4171. page_cache_h = page.h;
  4172. } else {
  4173. page_cache_valid = 0;
  4174. }
  4175. }
  4176. static void draw_status(struct ngui_rect r)
  4177. {
  4178. char msg[BR_URL_MAX + 32];
  4179. unsigned int n = 0;
  4180. int hover = page_hover_node();
  4181. unsigned short color;
  4182. const char *kind;
  4183. ngui_fill_rect(&ui, r, ui.theme.panel);
  4184. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  4185. ui.theme.border);
  4186. if (hover) {
  4187. const char *href = br_href(&doc, (unsigned int)hover);
  4188. char url[BR_URL_MAX];
  4189. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  4190. s_append(msg, &n, "Link: ", sizeof(msg));
  4191. s_append(msg, &n, url, sizeof(msg));
  4192. } else {
  4193. s_copy(msg, "Link", sizeof(msg));
  4194. }
  4195. color = ui.theme.accent;
  4196. } else if (status_text[0]) {
  4197. s_copy(msg, status_text, sizeof(msg));
  4198. color = status_error ? ui.theme.error : ui.theme.text;
  4199. } else if (page_title[0]) {
  4200. s_copy(msg, page_title, sizeof(msg));
  4201. color = ui.theme.text;
  4202. } else {
  4203. s_copy(msg, "Ready", sizeof(msg));
  4204. color = ui.theme.text_dim;
  4205. }
  4206. kind = s_eq(page_url, "about:home") ? "HOME" :
  4207. page_is_local ? "FILE" :
  4208. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  4209. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  4210. {
  4211. int kw = (int)ngui_text_width_ui(&ui, kind);
  4212. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  4213. ui.theme.text_dim);
  4214. }
  4215. }
  4216. static void draw(unsigned int *action)
  4217. {
  4218. struct ngui_rect r = {0, 0, ui.w, ui.h};
  4219. struct ngui_rect toolbar, status, page;
  4220. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  4221. status = ngui_cut_bottom(&r, BR_STATUS_H);
  4222. page = r;
  4223. draw_toolbar(toolbar, action);
  4224. draw_page(page);
  4225. draw_status(status);
  4226. }
  4227. static void redraw_now(void)
  4228. {
  4229. unsigned int action = 0;
  4230. ngui_begin(&ui);
  4231. draw(&action);
  4232. ngui_end(&ui);
  4233. }
  4234. static void handle_keys(unsigned int *action)
  4235. {
  4236. int k, scrolled = 0;
  4237. /* Batch queued page keys: a slow full-page render must not make a
  4238. * held Page Down advance only once every few frames. */
  4239. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  4240. scrolled++;
  4241. if (scrolled)
  4242. ngui_invalidate(&ui);
  4243. if (ngui_focus(&ui))
  4244. return;
  4245. while ((k = ngui_key(&ui)) != 0) {
  4246. switch (k) {
  4247. case NGUI_KEY_ESC:
  4248. *action |= ACT_CLOSE;
  4249. break;
  4250. case NGUI_KEY_TAB:
  4251. case 0x0C: /* Ctrl+L */
  4252. ngui_set_focus(&ui, ID_URL);
  4253. break;
  4254. case 0x12: /* Ctrl+R */
  4255. *action |= ACT_RELOAD;
  4256. break;
  4257. case NGUI_KEY_BACKSPACE:
  4258. *action |= ACT_BACK;
  4259. break;
  4260. case NGUI_KEY_UP:
  4261. ngui_scroll_to(&page_scroll,
  4262. page_scroll.offset - 24);
  4263. ngui_invalidate(&ui);
  4264. break;
  4265. case NGUI_KEY_DOWN:
  4266. ngui_scroll_to(&page_scroll,
  4267. page_scroll.offset + 24);
  4268. ngui_invalidate(&ui);
  4269. break;
  4270. case NGUI_KEY_HOME:
  4271. ngui_scroll_to(&page_scroll, 0);
  4272. ngui_invalidate(&ui);
  4273. break;
  4274. case NGUI_KEY_END:
  4275. ngui_scroll_to(&page_scroll,
  4276. page_scroll.content_h -
  4277. page_scroll.view_h);
  4278. ngui_invalidate(&ui);
  4279. break;
  4280. default:
  4281. break;
  4282. }
  4283. }
  4284. }
  4285. static void handle_page_click(unsigned int *action)
  4286. {
  4287. int node;
  4288. char url[BR_URL_MAX];
  4289. if (!ui.pressed)
  4290. return;
  4291. if (ui.press_x < page_rect.x ||
  4292. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  4293. ui.press_y < page_rect.y ||
  4294. ui.press_y >= page_rect.y + page_rect.h)
  4295. return;
  4296. node = find_hit(ui.press_x, ui.press_y);
  4297. if (!node)
  4298. return;
  4299. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  4300. sizeof(url)) != 0)
  4301. return;
  4302. s_copy(click_url, url, sizeof(click_url));
  4303. *action |= ACT_NAV;
  4304. }
  4305. void _start(const char *arg)
  4306. {
  4307. struct win_info wi;
  4308. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  4309. u_win_create(960, 640, "Browser", &wi) != 0 &&
  4310. u_win_create(780, 540, "Browser", &wi) != 0) {
  4311. u_puts("browser: no graphics window\n");
  4312. u_exit(1);
  4313. }
  4314. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  4315. url_in.placeholder = "http://...";
  4316. br_doc_init(&doc);
  4317. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  4318. ui.theme.accent);
  4319. br_set_viewport(wi.width);
  4320. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  4321. s_copy(cwd, "/", sizeof(cwd));
  4322. heap_clear();
  4323. origin_cache_load();
  4324. css_cache_init();
  4325. page_scroll.offset = 0;
  4326. page_scroll.content_h = 0;
  4327. if (arg && arg[0]) {
  4328. navigate(arg, 1);
  4329. } else {
  4330. load_home(1);
  4331. /* Start ready to type: keep the home page, but leave the address
  4332. * bar empty instead of showing "about:home". */
  4333. ngui_input_set(&url_in, "");
  4334. ngui_set_focus(&ui, ID_URL);
  4335. }
  4336. for (;;) {
  4337. unsigned int action = 0;
  4338. unsigned int now;
  4339. click_url[0] = '\0';
  4340. if (pending_action) {
  4341. action |= pending_action & ACT_WAIT_NAV;
  4342. if (pending_url[0])
  4343. s_copy(click_url, pending_url, sizeof(click_url));
  4344. pending_action = 0;
  4345. pending_url[0] = '\0';
  4346. cancel_fetch = 0;
  4347. } else if (preload_active) {
  4348. if (preload_wait)
  4349. preload_wait = 0;
  4350. else
  4351. preload_step();
  4352. } else if (preload_pending &&
  4353. page_scroll.offset != preload_scroll) {
  4354. preload_scroll = page_scroll.offset;
  4355. preload_pending = 0;
  4356. preload_node = 0;
  4357. preload_active = 1;
  4358. }
  4359. now = u_ticks_ms();
  4360. if (status_until && (int)(now - status_until) >= 0) {
  4361. status_text[0] = '\0';
  4362. status_until = 0;
  4363. status_error = 0;
  4364. ngui_invalidate(&ui);
  4365. }
  4366. if (!ngui_begin(&ui)) {
  4367. /* A queued navigation (e.g. Enter in the URL bar during
  4368. * a slow fetch) must be handled even when this frame
  4369. * needs no redraw. */
  4370. if (!action) {
  4371. u_sleep_ms(10);
  4372. continue;
  4373. }
  4374. } else {
  4375. draw(&action);
  4376. handle_keys(&action);
  4377. handle_page_click(&action);
  4378. ngui_end(&ui);
  4379. }
  4380. if (action & ACT_NAV) {
  4381. if (click_url[0]) {
  4382. navigate(click_url, 1);
  4383. click_url[0] = '\0';
  4384. } else {
  4385. navigate(url_in.text, 1);
  4386. }
  4387. }
  4388. if (action & ACT_BACK) {
  4389. if (hist_pos > 0) {
  4390. hist_pos--;
  4391. navigate(history[hist_pos], 0);
  4392. }
  4393. }
  4394. if (action & ACT_FORWARD) {
  4395. if (hist_pos + 1 < hist_len) {
  4396. hist_pos++;
  4397. navigate(history[hist_pos], 0);
  4398. }
  4399. }
  4400. if (action & ACT_RELOAD) {
  4401. if (s_eq(page_url, "about:home"))
  4402. load_home(0);
  4403. else
  4404. navigate(page_url, 0);
  4405. }
  4406. if (action & ACT_HOME)
  4407. load_home(1);
  4408. if (action & ACT_CLOSE)
  4409. quit = 1;
  4410. if (quit)
  4411. break;
  4412. if (pending_action)
  4413. continue;
  4414. u_sleep_ms(10);
  4415. }
  4416. fetch_helper_stop();
  4417. u_win_close();
  4418. u_exit(0);
  4419. }