browser.c 118 KB

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