browser.c 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462
  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. static struct br_style base_style(void);
  1665. static void style_for_node(unsigned int node, struct br_style *out)
  1666. {
  1667. unsigned int p = doc.nodes[node].parent;
  1668. struct br_style parent;
  1669. if (p) {
  1670. style_for_node(p, &parent);
  1671. br_style_for(&doc, node, &parent, out);
  1672. } else {
  1673. parent = base_style();
  1674. br_style_for(&doc, node, &parent, out);
  1675. }
  1676. }
  1677. /* Load at most one image per call. Images below the current viewport are
  1678. * left pending until the page is scrolled; this keeps a long article with
  1679. * many 4K screenshots from stalling on content the user cannot see yet. */
  1680. static void preload_step(void)
  1681. {
  1682. unsigned int batch = 0;
  1683. while (preload_active && preload_node < doc.nnode) {
  1684. unsigned int i = preload_node;
  1685. struct br_node *nd = &doc.nodes[i];
  1686. const char *src;
  1687. char url[BR_URL_MAX];
  1688. unsigned char *data;
  1689. unsigned int len;
  1690. char err[64];
  1691. char msg[64];
  1692. unsigned int n = 0;
  1693. int rv;
  1694. if (nd->type != BR_NODE_ELEM) {
  1695. preload_node++;
  1696. continue;
  1697. }
  1698. if (nd->tag != BR_TAG_IMG) {
  1699. if (nd->bg_img_index == -1) {
  1700. struct br_style bs;
  1701. style_for_node(i, &bs);
  1702. if (bs.display != BR_DISPLAY_NONE &&
  1703. !bs.vis_hidden && bs.bg_image) {
  1704. const char *bsrc =
  1705. br_bg_image_url(bs.bg_image - 1);
  1706. if (bsrc[0] &&
  1707. !contains_ci(bsrc, ".svg") &&
  1708. !starts_with(bsrc, "data:") &&
  1709. resolve_link(page_url, bsrc, url,
  1710. sizeof(url)) == 0) {
  1711. if (image_count >=
  1712. BR_MAX_IMAGES) {
  1713. preload_node =
  1714. doc.nnode;
  1715. break;
  1716. }
  1717. preload_node = i + 1;
  1718. data = 0;
  1719. len = 0;
  1720. rv = fetch_image(url,
  1721. BR_IMG_FILE_MAX,
  1722. &data, &len,
  1723. err, 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(
  1731. data, len,
  1732. &images[image_count]) == 0) {
  1733. nd->bg_img_index =
  1734. (short)image_count;
  1735. image_count++;
  1736. preload_loaded++;
  1737. layout_valid = 0;
  1738. } else {
  1739. nd->bg_img_index = -2;
  1740. }
  1741. ngui_invalidate(&ui);
  1742. if (++batch >= 4)
  1743. return;
  1744. continue;
  1745. }
  1746. }
  1747. nd->bg_img_index = -2;
  1748. }
  1749. preload_node++;
  1750. continue;
  1751. }
  1752. if (nd->img_index != -1) {
  1753. preload_node++;
  1754. continue;
  1755. }
  1756. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  1757. preload_node++;
  1758. continue;
  1759. }
  1760. src = br_src(&doc, i);
  1761. if (!src[0] || contains_ci(src, ".svg") ||
  1762. starts_with(src, "data:")) {
  1763. preload_node++;
  1764. continue;
  1765. }
  1766. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  1767. preload_node++;
  1768. continue;
  1769. }
  1770. if (image_count >= BR_MAX_IMAGES) {
  1771. preload_node = doc.nnode;
  1772. break;
  1773. }
  1774. /* Do not stop at the first below-fold image: DOM order is
  1775. * not visual order, and a footer/ad image early in the DOM
  1776. * used to hide every later article image from the loader. */
  1777. if (img_top[i] >
  1778. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  1779. preload_pending = 1;
  1780. preload_node++;
  1781. continue;
  1782. }
  1783. preload_node = i + 1;
  1784. s_append(msg, &n, "Loading images ", sizeof(msg));
  1785. s_append_dec(msg, &n, (unsigned int)preload_loaded + 1,
  1786. sizeof(msg));
  1787. s_append(msg, &n, "...", sizeof(msg));
  1788. set_status(msg, 0, 0);
  1789. ngui_invalidate(&ui);
  1790. data = 0;
  1791. len = 0;
  1792. rv = fetch_image(url, BR_IMG_FILE_MAX, &data, &len, err,
  1793. sizeof(err));
  1794. if (rv == FETCH_ABORT) {
  1795. preload_active = 0;
  1796. preload_pending = 0;
  1797. return;
  1798. }
  1799. if (rv == 0 &&
  1800. decode_image_data(data, len, &images[image_count]) == 0) {
  1801. nd->img_index = (short)image_count;
  1802. image_count++;
  1803. preload_loaded++;
  1804. layout_valid = 0;
  1805. } else {
  1806. /* Remember failures so a scroll does not retry an
  1807. * unreachable tracking/ad image with the full network
  1808. * timeout on every pass. */
  1809. nd->img_index = -2;
  1810. }
  1811. ngui_invalidate(&ui);
  1812. /* A full page layout after every image dominates loading on a
  1813. * long page. Decode a small batch, then let the main loop draw
  1814. * once for the whole batch. */
  1815. if (++batch >= 4)
  1816. return;
  1817. }
  1818. preload_active = 0;
  1819. if (preload_pending)
  1820. preload_scroll = page_scroll.offset;
  1821. else
  1822. preload_pending = 0;
  1823. set_status(post_status_text, post_status_error, post_status_ttl);
  1824. ngui_invalidate(&ui);
  1825. }
  1826. static void history_push(const char *url)
  1827. {
  1828. if (!url || !url[0])
  1829. return;
  1830. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  1831. s_eq(history[hist_pos], url))
  1832. return;
  1833. if (hist_len > 0 && hist_pos + 1 < hist_len)
  1834. hist_len = hist_pos + 1;
  1835. if (hist_len < BR_HISTORY) {
  1836. s_copy(history[hist_len], url, BR_URL_MAX);
  1837. hist_pos = hist_len;
  1838. hist_len++;
  1839. } else {
  1840. int i;
  1841. for (i = 1; i < BR_HISTORY; i++)
  1842. s_copy(history[i - 1], history[i], BR_URL_MAX);
  1843. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  1844. hist_pos = BR_HISTORY - 1;
  1845. }
  1846. }
  1847. static void load_page(const char *url, int local, int push)
  1848. {
  1849. unsigned char *body = 0;
  1850. unsigned int len = 0;
  1851. int truncated = 0;
  1852. struct img_info image_info;
  1853. char ctype[64];
  1854. char final[BR_URL_MAX];
  1855. char err[80];
  1856. const char *detail = 0;
  1857. int rv;
  1858. final[0] = '\0';
  1859. cancel_fetch = 0;
  1860. preload_active = 0;
  1861. preload_pending = 0;
  1862. js_browser_stop();
  1863. js_last_status[0] = '\0';
  1864. js_last_error = 0;
  1865. heap_clear();
  1866. image_reset();
  1867. layout_valid = 0;
  1868. page_scroll.offset = 0;
  1869. page_scroll.dragging = 0;
  1870. br_parse_plain(&doc, "", 0); /* blank while loading */
  1871. page_title[0] = '\0';
  1872. page_loading = 1;
  1873. page_is_local = local;
  1874. s_copy(page_url, url, sizeof(page_url));
  1875. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1876. url_in.len = s_len(url_in.text);
  1877. url_in.cursor = url_in.len;
  1878. url_in.scroll = 0;
  1879. ngui_set_focus(&ui, 0);
  1880. if (final[0])
  1881. final[0] = '\0';
  1882. if (push)
  1883. history_push(url);
  1884. set_status("Loading...", 0, 0);
  1885. ngui_invalidate(&ui);
  1886. /* heap_clear() detaches the fonts, so attach them again before the
  1887. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  1888. if (heap_start() != 0) {
  1889. show_error("Out of memory", "Cannot allocate the page buffer");
  1890. return;
  1891. }
  1892. ngui_font_attach(&ui);
  1893. redraw_now();
  1894. browser_rules_alloc();
  1895. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  1896. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  1897. &truncated);
  1898. if (rv == FETCH_ABORT)
  1899. return;
  1900. if (rv != 0) {
  1901. detail = err;
  1902. show_error("Cannot load this page", detail);
  1903. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1904. url_in.len = s_len(url_in.text);
  1905. url_in.cursor = url_in.len;
  1906. url_in.scroll = 0;
  1907. return;
  1908. }
  1909. if (!local)
  1910. origin_cache_learn(url, final[0] ? final : url);
  1911. page_is_local = local;
  1912. if (final[0]) {
  1913. s_copy(page_url, final, sizeof(page_url));
  1914. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1915. url_in.len = s_len(url_in.text);
  1916. url_in.cursor = url_in.len;
  1917. url_in.scroll = 0;
  1918. }
  1919. if (contains_ci(ctype, "text/plain")) {
  1920. br_parse_plain(&doc, (const char *)body, len);
  1921. } else if (contains_ci(ctype, "image/") ||
  1922. (!contains_ci(ctype, "text/html") &&
  1923. img_sniff(body, len, &image_info) == 0)) {
  1924. unsigned int node = br_parse_image_doc(&doc, page_url);
  1925. if (node)
  1926. decode_direct_image(body, len, node);
  1927. s_copy(page_title, "Image", sizeof(page_title));
  1928. } else {
  1929. br_set_viewport(ui.w);
  1930. br_parse(&doc, (const char *)body, len);
  1931. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  1932. sizeof(page_title));
  1933. if (load_stylesheets() == FETCH_ABORT)
  1934. return;
  1935. if (pending_action)
  1936. return;
  1937. }
  1938. preload_begin();
  1939. page_loading = 0;
  1940. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1941. url_in.len = s_len(url_in.text);
  1942. url_in.cursor = url_in.len;
  1943. url_in.scroll = 0;
  1944. ngui_set_focus(&ui, 0);
  1945. /* Paint the parsed page before fetching/running scripts. A slow
  1946. * remote <script src> then does not hide the page behind the loading
  1947. * screen; the fetch helper pumps this UI while it waits. */
  1948. set_status("Loading scripts...", 0, 0);
  1949. redraw_now();
  1950. run_page_scripts();
  1951. if (pending_action)
  1952. return;
  1953. post_status_text[0] = '\0';
  1954. post_status_error = 0;
  1955. post_status_ttl = 0;
  1956. if (js_last_status[0]) {
  1957. s_copy(post_status_text, js_last_status,
  1958. sizeof(post_status_text));
  1959. post_status_error = js_last_error;
  1960. post_status_ttl = 8000;
  1961. } else if (truncated) {
  1962. s_copy(post_status_text, "Page truncated at the buffer limit",
  1963. sizeof(post_status_text));
  1964. post_status_ttl = 6000;
  1965. } else if (doc.truncated) {
  1966. s_copy(post_status_text, "Page truncated by the parser",
  1967. sizeof(post_status_text));
  1968. post_status_ttl = 6000;
  1969. } else if (starts_with(page_url, "https://")) {
  1970. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  1971. sizeof(post_status_text));
  1972. post_status_ttl = 6000;
  1973. }
  1974. set_status(post_status_text, post_status_error, post_status_ttl);
  1975. ngui_invalidate(&ui);
  1976. }
  1977. static void load_home(int push)
  1978. {
  1979. cancel_fetch = 0;
  1980. preload_active = 0;
  1981. preload_pending = 0;
  1982. js_browser_stop();
  1983. js_last_status[0] = '\0';
  1984. js_last_error = 0;
  1985. heap_clear();
  1986. image_reset();
  1987. layout_valid = 0;
  1988. page_scroll.offset = 0;
  1989. page_scroll.dragging = 0;
  1990. br_parse_plain(&doc, "", 0);
  1991. page_loading = 1;
  1992. page_is_local = 0;
  1993. s_copy(page_url, "about:home", sizeof(page_url));
  1994. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1995. url_in.len = s_len(url_in.text);
  1996. url_in.cursor = url_in.len;
  1997. url_in.scroll = 0;
  1998. ngui_set_focus(&ui, 0);
  1999. if (push)
  2000. history_push(page_url);
  2001. ngui_invalidate(&ui);
  2002. /* See load_page(): reattach the fonts before the first redraw. */
  2003. if (heap_start() != 0) {
  2004. show_error("Out of memory", "Cannot allocate the browser heap");
  2005. return;
  2006. }
  2007. ngui_font_attach(&ui);
  2008. redraw_now();
  2009. browser_rules_alloc();
  2010. {
  2011. static const char home[] =
  2012. "<html><head><title>NebOS Browser</title><style>"
  2013. "body { margin: 10px; color: #e4e6f0; }"
  2014. "h1 { color: #7fb0ff; }"
  2015. ".box { background-color: #262b3a; margin: 12px; "
  2016. "padding: 10px; }"
  2017. "a { color: #7fb0ff; }"
  2018. "pre { background-color: #32384a; }"
  2019. "</style></head><body>"
  2020. "<h1>NebOS Browser</h1>"
  2021. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  2022. "shared HTTP client and the image library.</p>"
  2023. "<div class=\"box\"><b>Try:</b>"
  2024. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  2025. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  2026. "<li><a href=\"/floppy1/JS.HTM\">/"
  2027. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  2028. "<li><a href=\"http://10.0.2.2:8000/\">"
  2029. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  2030. "<li><a href=\"https://example.com/\">"
  2031. "https://example.com/</a> (TLS, not verified)</li>"
  2032. "</ul></div>"
  2033. "<p>Type a URL in the bar above. Esc closes the "
  2034. "window, Ctrl+L focuses the address bar.</p>"
  2035. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  2036. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  2037. "</body></html>";
  2038. br_set_viewport(ui.w);
  2039. br_parse(&doc, home, sizeof(home) - 1);
  2040. br_parse_inline_css(&doc);
  2041. br_reset_styles(&doc);
  2042. s_copy(page_title, doc.title, sizeof(page_title));
  2043. }
  2044. post_status_text[0] = '\0';
  2045. post_status_error = 0;
  2046. post_status_ttl = 0;
  2047. page_loading = 0;
  2048. set_status("", 0, 0);
  2049. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  2050. url_in.len = s_len(url_in.text);
  2051. url_in.cursor = url_in.len;
  2052. url_in.scroll = 0;
  2053. ngui_set_focus(&ui, 0);
  2054. ngui_invalidate(&ui);
  2055. }
  2056. /* Extensions the browser opens from the local filesystem. A dotted input
  2057. * with one of these still resolves relative to the cwd. */
  2058. static int local_file_ext(const char *s)
  2059. {
  2060. static const char *const exts[] = {
  2061. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  2062. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  2063. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  2064. "cfg", "conf", 0
  2065. };
  2066. unsigned int i = 0, start = 0, len = 0, e;
  2067. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  2068. s[i] != '#') {
  2069. if (s[i] == '.') {
  2070. start = i + 1;
  2071. len = 0;
  2072. } else if (start) {
  2073. len++;
  2074. }
  2075. i++;
  2076. }
  2077. if (!len)
  2078. return 0;
  2079. for (e = 0; exts[e]; e++) {
  2080. const char *x = exts[e];
  2081. unsigned int xn = s_len(x), k;
  2082. if (xn != len)
  2083. continue;
  2084. for (k = 0; k < len; k++) {
  2085. char a = s[start + k];
  2086. if (a >= 'A' && a <= 'Z')
  2087. a = (char)(a - 'A' + 'a');
  2088. if (a != x[k])
  2089. break;
  2090. }
  2091. if (k == len)
  2092. return 1;
  2093. }
  2094. return 0;
  2095. }
  2096. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  2097. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  2098. * Enter to the first network request. */
  2099. static int looks_like_host(const char *s)
  2100. {
  2101. unsigned int i = 0;
  2102. int dot = 0;
  2103. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  2104. s[i] != ':') {
  2105. char c = s[i];
  2106. if (c == '.') {
  2107. dot = 1;
  2108. } else if (!((c >= 'a' && c <= 'z') ||
  2109. (c >= 'A' && c <= 'Z') ||
  2110. (c >= '0' && c <= '9') ||
  2111. c == '-' || c == '_')) {
  2112. return 0;
  2113. }
  2114. i++;
  2115. }
  2116. return dot && i > 0 && !local_file_ext(s);
  2117. }
  2118. static void load_remote(const char *url, int push)
  2119. {
  2120. char canon[BR_URL_MAX];
  2121. s_copy(canon, url, sizeof(canon));
  2122. origin_cache_apply(canon, sizeof(canon));
  2123. load_page(canon, 0, push);
  2124. }
  2125. static void navigate(const char *input, int push)
  2126. {
  2127. char target[BR_URL_MAX];
  2128. char *t;
  2129. if (!input)
  2130. return;
  2131. s_copy(target, input, sizeof(target));
  2132. t = trim(target);
  2133. if (!t[0])
  2134. return;
  2135. if (s_eq(t, "about:home")) {
  2136. load_home(push);
  2137. return;
  2138. }
  2139. if (starts_with(t, "file://")) {
  2140. make_abs_local(t + 7, target, sizeof(target));
  2141. load_page(target, 1, push);
  2142. return;
  2143. }
  2144. if (is_http(t)) {
  2145. load_remote(t, push);
  2146. return;
  2147. }
  2148. if (t[0] == '/') {
  2149. make_abs_local(t, target, sizeof(target));
  2150. load_page(target, 1, push);
  2151. return;
  2152. }
  2153. if (!looks_like_host(t)) {
  2154. struct sys_stat st;
  2155. if (u_stat(t, &st) == 0 && !st.is_dir) {
  2156. make_abs_local(t, target, sizeof(target));
  2157. load_page(target, 1, push);
  2158. return;
  2159. }
  2160. }
  2161. {
  2162. char with_scheme[BR_URL_MAX];
  2163. unsigned int n = 0;
  2164. s_append(with_scheme, &n, "http://", sizeof(with_scheme));
  2165. s_append(with_scheme, &n, t, sizeof(with_scheme));
  2166. load_remote(with_scheme, push);
  2167. }
  2168. }
  2169. /* ---- layout ---- */
  2170. static struct br_style base_style(void)
  2171. {
  2172. struct br_style s = { 0 };
  2173. s.color = ui.theme.text;
  2174. s.bg = ui.theme.bg;
  2175. s.has_bg = 0;
  2176. for (int i = 0; i < 4; i++) {
  2177. s.border_c[i] = 0;
  2178. s.border_w[i] = 0;
  2179. }
  2180. s.font_px = 16;
  2181. s.bold = 0;
  2182. s.italic = 0;
  2183. s.mono = 0;
  2184. s.underline = 0;
  2185. s.align = BR_ALIGN_LEFT;
  2186. s.display = BR_DISPLAY_BLOCK;
  2187. s.no_bullet = 0;
  2188. s.uppercase = 0;
  2189. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  2190. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  2191. s.width = s.max_width = s.min_width = 0;
  2192. s.height = s.min_height = s.max_height = 0;
  2193. s.box_sizing = 0;
  2194. s.ml_auto = s.mr_auto = 0;
  2195. s.line_h_pct = 0;
  2196. s.line_h_px = 0;
  2197. s.mt = s.mb = s.ml = s.mr = 0;
  2198. s.pt = s.pb = s.pl = s.pr = 0;
  2199. return s;
  2200. }
  2201. static int css_size(unsigned char kind, int val, int base)
  2202. {
  2203. if (kind == 1)
  2204. return val;
  2205. if (kind == 2)
  2206. return base * val / 100;
  2207. return -1;
  2208. }
  2209. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  2210. const struct br_style *st)
  2211. {
  2212. int top = st->border_w[0], right = st->border_w[1];
  2213. int bottom = st->border_w[2], left = st->border_w[3];
  2214. if (r.w <= 0 || r.h <= 0)
  2215. return;
  2216. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  2217. int i;
  2218. for (i = 0; i < 4; i++)
  2219. if (st->border_w[i]) {
  2220. ngui_fill_rect(ui, r, st->border_c[i]);
  2221. break;
  2222. }
  2223. return;
  2224. }
  2225. if (top)
  2226. ngui_fill_rect(ui, (struct ngui_rect){r.x, r.y, r.w, top},
  2227. st->border_c[0]);
  2228. if (bottom)
  2229. ngui_fill_rect(ui, (struct ngui_rect){r.x,
  2230. r.y + r.h - bottom,
  2231. r.w, bottom},
  2232. st->border_c[2]);
  2233. if (left)
  2234. ngui_fill_rect(ui, (struct ngui_rect){r.x, r.y + top, left,
  2235. r.h - top - bottom},
  2236. st->border_c[3]);
  2237. if (right)
  2238. ngui_fill_rect(ui, (struct ngui_rect){r.x + r.w - right,
  2239. r.y + top, right,
  2240. r.h - top - bottom},
  2241. st->border_c[1]);
  2242. }
  2243. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  2244. unsigned int node, const struct br_style *st)
  2245. {
  2246. struct br_image *bi;
  2247. struct img_blit b;
  2248. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  2249. return;
  2250. if (doc.nodes[node].bg_img_index < 0 ||
  2251. doc.nodes[node].bg_img_index >= image_count)
  2252. return;
  2253. bi = &images[doc.nodes[node].bg_img_index];
  2254. if (bi->state != 1 || bi->img.w <= 0)
  2255. return;
  2256. b.dst = l->ui->px;
  2257. b.dst_w = l->ui->w;
  2258. b.dst_h = l->ui->h;
  2259. b.clip_x = page_rect.x;
  2260. b.clip_y = page_rect.y;
  2261. b.clip_w = page_rect.w - 12;
  2262. b.clip_h = page_rect.h;
  2263. b.x = box.x;
  2264. b.y = box.y;
  2265. b.scale = ((unsigned int)box.w << 16) / bi->img.w;
  2266. b.bg = ui.theme.bg;
  2267. b.bg2 = ui.theme.bg;
  2268. b.flags = IMG_BLIT_OVER_DST;
  2269. img_draw(&bi->img, &b);
  2270. }
  2271. static int run_width(const struct lay_run *r)
  2272. {
  2273. if (r->img >= 0)
  2274. return r->iw;
  2275. if (r->img == -2)
  2276. return r->iw;
  2277. return (int)r->w;
  2278. }
  2279. static void flush_line(struct lay *l)
  2280. {
  2281. int total, x, i, vis;
  2282. if (!l->nruns && l->line_x == l->left) {
  2283. l->line_h = 0;
  2284. return;
  2285. }
  2286. total = l->line_x - l->left;
  2287. x = l->left;
  2288. vis = 1;
  2289. if (l->draw) {
  2290. int lh = l->line_h ? l->line_h : 16;
  2291. vis = l->line_y + lh >= page_rect.y &&
  2292. l->line_y <= page_rect.y + page_rect.h;
  2293. }
  2294. if (l->align == BR_ALIGN_CENTER)
  2295. x += (l->right - l->left - total) / 2;
  2296. else if (l->align == BR_ALIGN_RIGHT)
  2297. x = l->right - total;
  2298. if (x < l->left)
  2299. x = l->left;
  2300. for (i = 0; i < l->nruns; i++) {
  2301. struct lay_run *r = &l->runs[i];
  2302. int w = run_width(r);
  2303. int ry = l->line_y + r->dy;
  2304. x += r->gap;
  2305. if (l->draw && vis) {
  2306. if (r->img == -2) {
  2307. int hh = r->ih ? r->ih : 20;
  2308. ngui_fill_rect(l->ui,
  2309. (struct ngui_rect){x, ry, w, hh},
  2310. l->ui->theme.panel_alt);
  2311. ngui_frame(l->ui,
  2312. (struct ngui_rect){x, ry, w, hh},
  2313. l->ui->theme.border);
  2314. ngui_text_px(l->ui, x + 6, ry + 2,
  2315. r->lit, s_len(r->lit), r->color,
  2316. r->font_px, r->bold, r->italic,
  2317. r->mono);
  2318. } else if (r->img >= 0) {
  2319. struct br_image *bi = &images[r->img];
  2320. if (bi->state == 1) {
  2321. struct img_blit b;
  2322. b.dst = l->ui->px;
  2323. b.dst_w = l->ui->w;
  2324. b.dst_h = l->ui->h;
  2325. b.clip_x = page_rect.x;
  2326. b.clip_y = page_rect.y;
  2327. b.clip_w = page_rect.w - 12;
  2328. b.clip_h = page_rect.h;
  2329. b.x = x;
  2330. b.y = ry;
  2331. b.scale = ((unsigned int)r->iw << 16) /
  2332. bi->img.w;
  2333. b.bg = ui.theme.bg;
  2334. b.bg2 = ui.theme.bg;
  2335. b.flags = IMG_BLIT_OVER_DST;
  2336. img_draw(&bi->img, &b);
  2337. }
  2338. } else {
  2339. const char *s = r->has_lit ? r->lit :
  2340. doc.text + r->off;
  2341. unsigned int n = r->has_lit ? s_len(r->lit) :
  2342. r->len;
  2343. ngui_text_px(l->ui, x, ry, s, n,
  2344. r->color, r->font_px, r->bold,
  2345. r->italic, r->mono);
  2346. if (r->underline)
  2347. ngui_fill_rect(l->ui,
  2348. (struct ngui_rect){x,
  2349. ry +
  2350. ngui_text_ascent(l->ui,
  2351. r->font_px,
  2352. r->mono) + 2,
  2353. w, 1}, r->color);
  2354. }
  2355. if (r->href) {
  2356. if (nhits < HIT_MAX) {
  2357. struct hit *h = &hits[nhits];
  2358. int hh = r->img >= 0 ? r->ih :
  2359. ngui_text_line_height(l->ui,
  2360. r->font_px, r->mono);
  2361. int merge = nhits > 0 &&
  2362. hits[nhits - 1].node == r->href &&
  2363. hits[nhits - 1].y == ry &&
  2364. hits[nhits - 1].h == hh &&
  2365. x <= hits[nhits - 1].x +
  2366. hits[nhits - 1].w + 2;
  2367. if (merge) {
  2368. struct hit *p = &hits[nhits - 1];
  2369. int end = x + w;
  2370. if (end > p->x + p->w)
  2371. p->w = end - p->x;
  2372. } else {
  2373. h->x = x;
  2374. h->y = ry;
  2375. h->w = w;
  2376. h->h = hh;
  2377. h->node = r->href;
  2378. nhits++;
  2379. }
  2380. }
  2381. }
  2382. }
  2383. x += w;
  2384. }
  2385. l->y += l->line_h + 2;
  2386. l->nruns = 0;
  2387. l->line_x = l->left;
  2388. l->run_x = l->left;
  2389. l->line_h = 0;
  2390. l->space_pending = 0;
  2391. }
  2392. static void add_run(struct lay *l, unsigned short off, unsigned short len,
  2393. const struct br_style *st, unsigned short href,
  2394. const char *lit)
  2395. {
  2396. unsigned int n = lit ? s_len(lit) : len;
  2397. const char *tp = lit ? lit : doc.text + off;
  2398. int w = (int)ngui_text_width_px(l->ui, tp, n, st->font_px,
  2399. st->bold, st->italic, st->mono);
  2400. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  2401. flush_line(l);
  2402. if (l->nruns == 0) {
  2403. l->line_y = l->y;
  2404. l->line_h = 0;
  2405. }
  2406. {
  2407. struct lay_run *r = &l->runs[l->nruns++];
  2408. int gap = l->line_x - l->run_x;
  2409. if (gap < 0)
  2410. gap = 0;
  2411. r->gap = (unsigned short)gap;
  2412. r->off = off;
  2413. r->len = len;
  2414. r->color = st->color;
  2415. r->href = href;
  2416. r->dy = 0;
  2417. r->has_lit = 0;
  2418. r->lit[0] = '\0';
  2419. if (lit && lit[0]) {
  2420. unsigned int i;
  2421. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  2422. r->lit[i] = lit[i];
  2423. r->lit[i] = '\0';
  2424. r->has_lit = 1;
  2425. }
  2426. r->img = -1;
  2427. r->iw = r->ih = 0;
  2428. r->font_px = st->font_px;
  2429. r->bold = st->bold;
  2430. r->italic = st->italic;
  2431. r->mono = st->mono;
  2432. /* A control with its own background is a button, not body copy;
  2433. * an inherited link underline would strike through the fill. */
  2434. r->underline = st->underline && !st->has_bg;
  2435. r->w = (unsigned short)w;
  2436. if (r->has_lit)
  2437. r->w = (unsigned short)ngui_text_width_px(
  2438. l->ui, r->lit, s_len(r->lit), r->font_px,
  2439. r->bold, r->italic, r->mono);
  2440. w = r->w;
  2441. }
  2442. l->line_x += w;
  2443. l->run_x = l->line_x;
  2444. {
  2445. int lh = ngui_text_line_height(l->ui, st->font_px, st->mono);
  2446. if (st->line_h_px)
  2447. lh = st->line_h_px;
  2448. else if (st->line_h_pct)
  2449. lh = st->font_px * st->line_h_pct / 100;
  2450. if (lh < ngui_text_line_height(l->ui, st->font_px, st->mono))
  2451. lh = ngui_text_line_height(l->ui, st->font_px,
  2452. st->mono);
  2453. if (l->line_h < lh)
  2454. l->line_h = lh;
  2455. }
  2456. }
  2457. static void add_image_run(struct lay *l, unsigned int node,
  2458. const struct br_style *st, unsigned short href)
  2459. {
  2460. struct br_image *bi = 0;
  2461. int idx = doc.nodes[node].img_index;
  2462. int dw, dh, maxw;
  2463. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  2464. bi = &images[idx];
  2465. if (l->space_pending && (l->nruns > 0 || l->line_x > l->left)) {
  2466. int sp = (int)ngui_text_width_px(l->ui, " ", 1, st->font_px,
  2467. st->bold, st->italic,
  2468. st->mono);
  2469. if (l->line_x + sp <= l->right)
  2470. l->line_x += sp;
  2471. }
  2472. l->space_pending = 0;
  2473. if (!bi) {
  2474. const char *alt = br_alt(&doc, node);
  2475. struct br_style gs = *st;
  2476. char tmp[96];
  2477. unsigned int n = 0;
  2478. int w;
  2479. gs.color = BR_GRAY;
  2480. gs.underline = 0;
  2481. s_append(tmp, &n, "[", sizeof(tmp));
  2482. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  2483. s_append(tmp, &n, "]", sizeof(tmp));
  2484. w = (int)ngui_text_width_px(l->ui, tmp, n, gs.font_px,
  2485. gs.bold, gs.italic, gs.mono);
  2486. if (l->line_x + w > l->right &&
  2487. (l->nruns > 0 || l->line_x > l->left))
  2488. flush_line(l);
  2489. add_run(l, 0, 0, &gs, href, tmp);
  2490. if (!l->draw) {
  2491. int t = l->line_y < 0 ? 0 : l->line_y;
  2492. int hh = ngui_text_line_height(l->ui, gs.font_px,
  2493. gs.mono);
  2494. if (t > 65535)
  2495. t = 65535;
  2496. if (hh > 65535)
  2497. hh = 65535;
  2498. img_top[node] = (unsigned short)t;
  2499. img_h[node] = (unsigned short)hh;
  2500. }
  2501. return;
  2502. }
  2503. maxw = l->right - l->left;
  2504. if (maxw < 8)
  2505. maxw = 8;
  2506. {
  2507. int iw = bi->native_w, ih = bi->native_h;
  2508. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  2509. if (iw <= 0 || ih <= 0) {
  2510. iw = (int)bi->img.w;
  2511. ih = (int)bi->img.h;
  2512. }
  2513. dw = iw;
  2514. dh = ih;
  2515. if (doc.nodes[node].width_attr) {
  2516. int want = doc.nodes[node].width_attr;
  2517. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  2518. have_w = 1;
  2519. }
  2520. if (doc.nodes[node].height_attr) {
  2521. int want = doc.nodes[node].height_attr;
  2522. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  2523. have_h = 1;
  2524. }
  2525. if (have_w && !have_h)
  2526. dh = ih ? ih * dw / iw : 0;
  2527. if (have_h && !have_w)
  2528. dw = iw ? iw * dh / ih : 0;
  2529. if (st->width_kind) {
  2530. css_w = 1;
  2531. dw = st->width_kind == 2 ? maxw * (int)st->width / 100 :
  2532. (int)st->width;
  2533. }
  2534. if (st->height_kind) {
  2535. css_h = 1;
  2536. dh = st->height_kind == 2 ? maxw * (int)st->height / 100 :
  2537. (int)st->height;
  2538. }
  2539. if (css_w && !css_h)
  2540. dh = ih ? ih * dw / iw : 0;
  2541. if (css_h && !css_w)
  2542. dw = iw ? iw * dh / ih : 0;
  2543. if (st->max_width_kind) {
  2544. int mw = st->max_width_kind == 2 ?
  2545. maxw * (int)st->max_width / 100 :
  2546. (int)st->max_width;
  2547. if (mw > 0 && dw > mw) {
  2548. dh = iw ? ih * mw / iw : 0;
  2549. dw = mw;
  2550. }
  2551. }
  2552. }
  2553. if (dw < 8)
  2554. dw = 8;
  2555. if (dh < 8)
  2556. dh = 8;
  2557. if (dw > maxw) {
  2558. dh = dw ? dh * maxw / dw : dh;
  2559. dw = maxw;
  2560. }
  2561. if (!l->draw) {
  2562. int t = l->line_y < 0 ? 0 : l->line_y;
  2563. if (t > 65535)
  2564. t = 65535;
  2565. if (dh > 65535)
  2566. dh = 65535;
  2567. img_top[node] = (unsigned short)t;
  2568. img_h[node] = (unsigned short)dh;
  2569. }
  2570. if (l->line_x + dw > l->right && (l->nruns > 0 ||
  2571. l->line_x > l->left))
  2572. flush_line(l);
  2573. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  2574. flush_line(l);
  2575. if (l->nruns == 0) {
  2576. l->line_y = l->y;
  2577. l->line_h = 0;
  2578. }
  2579. {
  2580. struct lay_run *r = &l->runs[l->nruns++];
  2581. int gap = l->line_x - l->run_x;
  2582. if (gap < 0)
  2583. gap = 0;
  2584. r->gap = (unsigned short)gap;
  2585. r->off = 0;
  2586. r->len = 0;
  2587. r->color = 0;
  2588. r->href = href;
  2589. /* Inline replaced elements honour their vertical margins; this
  2590. * is how Bootstrap's negative logo margins centre the wordmark. */
  2591. r->dy = st->mt;
  2592. r->has_lit = 0;
  2593. r->lit[0] = '\0';
  2594. r->img = (short)idx;
  2595. r->iw = (unsigned short)dw;
  2596. r->ih = (unsigned short)dh;
  2597. r->w = (unsigned short)dw;
  2598. r->font_px = st->font_px;
  2599. r->bold = st->bold;
  2600. r->italic = st->italic;
  2601. r->mono = st->mono;
  2602. r->underline = 0;
  2603. }
  2604. l->line_x += dw;
  2605. l->run_x = l->line_x;
  2606. if (l->line_h < dh)
  2607. l->line_h = dh;
  2608. }
  2609. static int text_width(struct lay *l, const char *s, unsigned int n,
  2610. const struct br_style *st)
  2611. {
  2612. return (int)ngui_text_width_px(l->ui, s, n, st->font_px,
  2613. st->bold, st->italic, st->mono);
  2614. }
  2615. /* Longest prefix that fits in maxw, at least one byte. */
  2616. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  2617. const struct br_style *st, int maxw)
  2618. {
  2619. unsigned int take = 0;
  2620. while (take < n) {
  2621. if (text_width(l, s, take + 1, st) > maxw)
  2622. break;
  2623. take++;
  2624. }
  2625. return take ? take : 1;
  2626. }
  2627. static void emit_word(struct lay *l, const char *s, unsigned int start,
  2628. unsigned int n, unsigned int base,
  2629. const struct br_style *st, unsigned short href)
  2630. {
  2631. int avail = l->right - l->left;
  2632. int w = text_width(l, s + start, n, st);
  2633. unsigned int off = start;
  2634. if (st->nowrap) {
  2635. if (n)
  2636. add_run(l, (unsigned short)(base + start),
  2637. (unsigned short)n, st, href, 0);
  2638. return;
  2639. }
  2640. if (l->line_x + w > l->right &&
  2641. (l->nruns > 0 || l->line_x > l->left))
  2642. flush_line(l);
  2643. if (w <= avail) {
  2644. if (n)
  2645. add_run(l, (unsigned short)(base + start),
  2646. (unsigned short)n, st, href, 0);
  2647. return;
  2648. }
  2649. while (n > 0) {
  2650. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  2651. add_run(l, (unsigned short)(base + off),
  2652. (unsigned short)take, st, href, 0);
  2653. off += take;
  2654. n -= take;
  2655. if (n)
  2656. flush_line(l);
  2657. }
  2658. }
  2659. static void emit_text(struct lay *l, const char *s, unsigned int len,
  2660. const struct br_style *st, unsigned short href, int pre)
  2661. {
  2662. unsigned int i = 0;
  2663. unsigned int base;
  2664. int space_w = (int)ngui_text_width_px(l->ui, " ", 1, st->font_px,
  2665. st->bold, st->italic, st->mono);
  2666. if (!s || !len)
  2667. return;
  2668. if (space_w <= 0)
  2669. space_w = 8;
  2670. base = (unsigned int)(s - doc.text);
  2671. if (st->uppercase) {
  2672. char *p = (char *)s;
  2673. unsigned int j;
  2674. for (j = 0; j < len; j++)
  2675. if (p[j] >= 'a' && p[j] <= 'z')
  2676. p[j] = (char)(p[j] - 'a' + 'A');
  2677. }
  2678. if (pre) {
  2679. while (i < len) {
  2680. unsigned int start;
  2681. if (s[i] == '\n') {
  2682. flush_line(l);
  2683. i++;
  2684. continue;
  2685. }
  2686. if (s[i] == ' ') {
  2687. if (l->line_x + space_w > l->right &&
  2688. (l->nruns > 0 || l->line_x > l->left))
  2689. flush_line(l);
  2690. else
  2691. l->line_x += space_w;
  2692. i++;
  2693. continue;
  2694. }
  2695. start = i;
  2696. while (i < len && s[i] != ' ' && s[i] != '\n')
  2697. i++;
  2698. emit_word(l, s, start, i - start, base, st, href);
  2699. }
  2700. return;
  2701. }
  2702. while (i < len) {
  2703. unsigned int start, n;
  2704. if (s[i] == ' ') {
  2705. l->space_pending = 1;
  2706. i++;
  2707. continue;
  2708. }
  2709. start = i;
  2710. while (i < len && s[i] != ' ')
  2711. i++;
  2712. n = i - start;
  2713. if (l->space_pending &&
  2714. (l->nruns > 0 || l->line_x > l->left)) {
  2715. if (st->nowrap || l->line_x + space_w <= l->right)
  2716. l->line_x += space_w;
  2717. }
  2718. l->space_pending = 0;
  2719. emit_word(l, s, start, n, base, st, href);
  2720. }
  2721. }
  2722. static int list_index(unsigned int parent, unsigned int node)
  2723. {
  2724. unsigned int n = 0, i;
  2725. for (i = doc.nodes[parent].first; i && i != node;
  2726. i = doc.nodes[i].next)
  2727. if (doc.nodes[i].tag == BR_TAG_LI)
  2728. n++;
  2729. return (int)n + 1;
  2730. }
  2731. static const char *form_text(unsigned int node)
  2732. {
  2733. const char *v = br_value(&doc, node);
  2734. const char *p = br_placeholder(&doc, node);
  2735. const char *t = br_type(&doc, node);
  2736. if (s_eq(t, "hidden"))
  2737. return 0;
  2738. if (s_eq(t, "submit") || s_eq(t, "button") || s_eq(t, "reset"))
  2739. return v[0] ? v : "Button";
  2740. if (v[0])
  2741. return v;
  2742. if (p[0])
  2743. return p;
  2744. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  2745. return "Text";
  2746. if (doc.nodes[node].tag == BR_TAG_SELECT)
  2747. return "Select";
  2748. return "Search";
  2749. }
  2750. static void add_form_run(struct lay *l, unsigned int node,
  2751. const struct br_style *st, unsigned short href)
  2752. {
  2753. const char *text = form_text(node);
  2754. struct lay_run *r;
  2755. int tw, w, h, i;
  2756. if (!text)
  2757. return;
  2758. tw = (int)ngui_text_width_px(l->ui, text, s_len(text), st->font_px,
  2759. st->bold, st->italic, st->mono);
  2760. h = ngui_text_line_height(l->ui, st->font_px, st->mono) + 4;
  2761. if (h < 20)
  2762. h = 20;
  2763. if (st->width_kind == 1)
  2764. w = st->width;
  2765. else if (st->width_kind == 2)
  2766. w = (l->right - l->left) * (int)st->width / 100;
  2767. else
  2768. w = tw + 18;
  2769. if (w < 64)
  2770. w = 64;
  2771. if (w > l->right - l->left)
  2772. w = l->right - l->left;
  2773. if (w < 8)
  2774. w = 8;
  2775. if (l->line_x + w > l->right &&
  2776. (l->nruns > 0 || l->line_x > l->left))
  2777. flush_line(l);
  2778. if (l->nruns >= 96)
  2779. return;
  2780. r = &l->runs[l->nruns++];
  2781. r->gap = (unsigned short)(l->line_x - l->run_x);
  2782. r->off = r->len = 0;
  2783. r->color = st->color;
  2784. r->href = href;
  2785. r->dy = 0;
  2786. r->has_lit = 1;
  2787. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  2788. r->lit[i] = text[i];
  2789. r->lit[i] = '\0';
  2790. r->img = -2;
  2791. r->iw = (unsigned short)w;
  2792. r->ih = (unsigned short)h;
  2793. r->w = (unsigned short)w;
  2794. r->font_px = st->font_px;
  2795. r->bold = st->bold;
  2796. r->italic = st->italic;
  2797. r->mono = st->mono;
  2798. r->underline = 0;
  2799. l->line_x += w;
  2800. l->run_x = l->line_x;
  2801. if (l->line_h < h)
  2802. l->line_h = h;
  2803. }
  2804. /* A poster wrapper is absolutely positioned over the media slot; the
  2805. * measured height of its picture is normally added back to the flow. When a
  2806. * loading-skeleton sibling already reserves that slot, adding both doubles
  2807. * the media height and pushes the article text a full screen down. */
  2808. static int has_skeleton_sibling(unsigned int node)
  2809. {
  2810. unsigned int p = doc.nodes[node].parent, c;
  2811. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  2812. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  2813. continue;
  2814. if (doc.nodes[c].class_off &&
  2815. contains_ci(doc.attrs + doc.nodes[c].class_off,
  2816. "skeleton"))
  2817. return 1;
  2818. }
  2819. return 0;
  2820. }
  2821. static void layout_children(struct lay *l, unsigned int parent,
  2822. const struct br_style *pst, int depth,
  2823. unsigned short link);
  2824. static void layout_flex_children(struct lay *l, unsigned int parent,
  2825. const struct br_style *pst, int depth,
  2826. unsigned short link);
  2827. static void layout_grid_children(struct lay *l, unsigned int parent,
  2828. const struct br_style *pst, int depth,
  2829. unsigned short link);
  2830. static void layout_grid_auto(struct lay *l, unsigned int parent,
  2831. const struct br_style *pst, int depth,
  2832. unsigned short link);
  2833. static int flex_item_width(struct lay *l, unsigned int n,
  2834. const struct br_style *cs, int avail);
  2835. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  2836. const struct br_style *pst, int depth,
  2837. unsigned short link);
  2838. static void layout_table_row(struct lay *l, unsigned int row,
  2839. const struct br_style *pst, int depth,
  2840. unsigned short link);
  2841. /* A flex container whose items are only inline spans is usually just a
  2842. * heading/icon pair. Our flex row positions such items without emitting
  2843. * their inline text in some deep page contexts; normal inline flow renders
  2844. * the same content correctly. */
  2845. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  2846. {
  2847. unsigned int c;
  2848. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  2849. struct br_node *nd = &doc.nodes[c];
  2850. struct br_style cs;
  2851. if (nd->type == BR_NODE_TEXT)
  2852. continue;
  2853. br_style_for(&doc, c, pst, &cs);
  2854. if (cs.display == BR_DISPLAY_NONE)
  2855. continue;
  2856. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  2857. cs.width_kind || cs.has_bg ||
  2858. cs.border_w[0] || cs.border_w[1] ||
  2859. cs.border_w[2] || cs.border_w[3] ||
  2860. nd->tag == BR_TAG_IMG)
  2861. return 1;
  2862. }
  2863. return 0;
  2864. }
  2865. static int css_radius(const struct br_style *st, int corner,
  2866. int w, int h)
  2867. {
  2868. int r = st->radius[corner];
  2869. if (r <= 0)
  2870. return 0;
  2871. if (r > w / 2)
  2872. r = w / 2;
  2873. if (r > h / 2)
  2874. r = h / 2;
  2875. return r;
  2876. }
  2877. static void svg_viewbox(unsigned node, int *vw, int *vh)
  2878. {
  2879. struct br_node *nd = &doc.nodes[node];
  2880. if (nd->width_attr && nd->height_attr) {
  2881. *vw = nd->width_attr;
  2882. *vh = nd->height_attr;
  2883. } else {
  2884. *vw = 300;
  2885. *vh = 150;
  2886. }
  2887. if (*vw < 1)
  2888. *vw = 1;
  2889. if (*vh < 1)
  2890. *vh = 1;
  2891. }
  2892. static int svg_num(const char **pp)
  2893. {
  2894. const char *p = *pp;
  2895. int neg = 0, v = 0, frac = 0, scale = 1;
  2896. while (*p == ' ' || *p == ',' || *p == '\t' ||
  2897. *p == '\n' || *p == '\r')
  2898. p++;
  2899. if (*p == '-') {
  2900. neg = 1;
  2901. p++;
  2902. } else if (*p == '+') {
  2903. p++;
  2904. }
  2905. while (*p >= '0' && *p <= '9') {
  2906. v = v * 10 + (*p - '0');
  2907. p++;
  2908. }
  2909. if (*p == '.') {
  2910. p++;
  2911. while (*p >= '0' && *p <= '9' && scale < 1000) {
  2912. frac = frac * 10 + (*p - '0');
  2913. scale *= 10;
  2914. p++;
  2915. }
  2916. }
  2917. v += frac / scale;
  2918. *pp = p;
  2919. return neg ? -v : v;
  2920. }
  2921. static void svg_path(struct ngui *ui, const char *d,
  2922. int ox, int oy, int dw, int dh, int vw, int vh,
  2923. unsigned short color)
  2924. {
  2925. int cx = 0, cy = 0, sx = 0, sy = 0;
  2926. char cmd = 0;
  2927. const char *p = d;
  2928. while (p && *p) {
  2929. int rel, nx, ny;
  2930. char c;
  2931. while (*p == ' ' || *p == ',' || *p == '\t' ||
  2932. *p == '\n' || *p == '\r')
  2933. p++;
  2934. if (!*p)
  2935. break;
  2936. if ((*p >= 'A' && *p <= 'Z') ||
  2937. (*p >= 'a' && *p <= 'z'))
  2938. cmd = *p++;
  2939. else if (!cmd) {
  2940. p++;
  2941. continue;
  2942. }
  2943. rel = cmd >= 'a' && cmd <= 'z';
  2944. c = rel ? (char)(cmd - 'a' + 'A') : cmd;
  2945. if (c == 'Z') {
  2946. ngui_line(ui, ox + cx * dw / vw, oy + cy * dh / vh,
  2947. ox + sx * dw / vw, oy + sy * dh / vh,
  2948. color);
  2949. cx = sx;
  2950. cy = sy;
  2951. cmd = 0;
  2952. continue;
  2953. }
  2954. if (c == 'H' || c == 'V') {
  2955. const char *save = p;
  2956. int a = svg_num(&p);
  2957. if (p == save) {
  2958. p++;
  2959. continue;
  2960. }
  2961. nx = cx;
  2962. ny = cy;
  2963. if (c == 'H')
  2964. nx = rel ? cx + a : a;
  2965. else
  2966. ny = rel ? cy + a : a;
  2967. } else {
  2968. const char *save = p;
  2969. int a = svg_num(&p);
  2970. int b = svg_num(&p);
  2971. if (p == save) {
  2972. p++;
  2973. continue;
  2974. }
  2975. if (c == 'M') {
  2976. nx = rel ? cx + a : a;
  2977. ny = rel ? cy + b : b;
  2978. cx = sx = nx;
  2979. cy = sy = ny;
  2980. cmd = rel ? 'l' : 'L';
  2981. continue;
  2982. }
  2983. if (c != 'L')
  2984. break;
  2985. nx = rel ? cx + a : a;
  2986. ny = rel ? cy + b : b;
  2987. }
  2988. ngui_line(ui, ox + cx * dw / vw, oy + cy * dh / vh,
  2989. ox + nx * dw / vw, oy + ny * dh / vh, color);
  2990. cx = nx;
  2991. cy = ny;
  2992. }
  2993. }
  2994. static void draw_svg(struct ngui *ui, unsigned node,
  2995. int ox, int oy, int dw, int dh, int vw, int vh,
  2996. const struct br_style *pst)
  2997. {
  2998. unsigned int c;
  2999. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  3000. struct br_node *nd = &doc.nodes[c];
  3001. struct br_style st;
  3002. const char *nm;
  3003. if (nd->type != BR_NODE_ELEM || !nd->name_off)
  3004. continue;
  3005. nm = doc.attrs + nd->name_off;
  3006. br_style_for(&doc, c, pst, &st);
  3007. if (s_eq(nm, "rect")) {
  3008. struct ngui_rect r;
  3009. int rx = (int)nd->svg_rx * dw / vw;
  3010. r.x = ox + (int)nd->svg_x * dw / vw;
  3011. r.y = oy + (int)nd->svg_y * dh / vh;
  3012. r.w = (int)nd->width_attr * dw / vw;
  3013. r.h = (int)nd->height_attr * dh / vh;
  3014. if (r.w < 1)
  3015. r.w = 1;
  3016. if (r.h < 1)
  3017. r.h = 1;
  3018. if (rx > r.w / 2)
  3019. rx = r.w / 2;
  3020. if (rx > r.h / 2)
  3021. rx = r.h / 2;
  3022. if (st.has_bg) {
  3023. if (rx)
  3024. ngui_fill_round_rect(ui, r, rx, rx,
  3025. rx, rx, st.bg);
  3026. else
  3027. ngui_fill_rect(ui, r, st.bg);
  3028. }
  3029. if (st.border_w[0]) {
  3030. if (rx)
  3031. ngui_frame_round(ui, r, rx, rx, rx, rx,
  3032. st.border_w[0],
  3033. st.border_c[0]);
  3034. else
  3035. draw_border_box(ui, r, &st);
  3036. }
  3037. } else if (s_eq(nm, "line")) {
  3038. if (st.border_w[0])
  3039. ngui_line(ui,
  3040. ox + (int)nd->svg_x * dw / vw,
  3041. oy + (int)nd->svg_y * dh / vh,
  3042. ox + (int)nd->width_attr * dw / vw,
  3043. oy + (int)nd->height_attr * dh / vh,
  3044. st.border_c[0]);
  3045. } else if (s_eq(nm, "path")) {
  3046. if (st.border_w[0] && nd->src_off)
  3047. svg_path(ui, doc.attrs + nd->src_off,
  3048. ox, oy, dw, dh, vw, vh,
  3049. st.border_c[0]);
  3050. } else if (s_eq(nm, "text")) {
  3051. unsigned int t = nd->first;
  3052. const char *s;
  3053. unsigned int n, tw;
  3054. int px = st.font_px ? st.font_px : 16;
  3055. int tx, ty, anchor;
  3056. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  3057. continue;
  3058. s = doc.text + doc.nodes[t].text_off;
  3059. n = doc.nodes[t].text_len;
  3060. tw = ngui_text_width_px(ui, s, n, px, st.bold,
  3061. st.italic, st.mono);
  3062. tx = ox + (int)nd->svg_x * dw / vw;
  3063. ty = oy + (int)nd->svg_y * dh / vh -
  3064. ngui_text_ascent(ui, px, st.mono);
  3065. anchor = st.align;
  3066. if (nd->attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  3067. anchor = BR_ALIGN_CENTER;
  3068. else if (nd->attr_flags & BR_ATTR_ANCHOR_END)
  3069. anchor = BR_ALIGN_RIGHT;
  3070. if (anchor == BR_ALIGN_CENTER)
  3071. tx -= (int)tw / 2;
  3072. else if (anchor == BR_ALIGN_RIGHT)
  3073. tx -= (int)tw;
  3074. ngui_text_px(ui, tx, ty, s, n, st.color, px,
  3075. st.bold, st.italic, st.mono);
  3076. }
  3077. }
  3078. }
  3079. static void layout_block(struct lay *l, unsigned int node,
  3080. const struct br_style *st, int depth,
  3081. unsigned short link)
  3082. {
  3083. int old_left = l->left, old_right = l->right, old_align = l->align;
  3084. int top, l0, r0;
  3085. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  3086. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  3087. int deco_w, deco_h, content_w, content_h, box_h;
  3088. int definite_w = 0;
  3089. int normal_top = 0;
  3090. int rel_dx = 0, rel_dy = 0;
  3091. if (depth > 24 || st->display == BR_DISPLAY_NONE)
  3092. return;
  3093. flow_y = l->y;
  3094. flow_left = l->left;
  3095. flow_right = l->right;
  3096. positioned = st->pos == 1 || st->pos == 2;
  3097. relative = st->pos == 3;
  3098. sticky = st->pos == 4;
  3099. shifted = relative || sticky || st->transform_set;
  3100. if (positioned) {
  3101. int def_w = st->width_kind == 1 ? st->width : -1;
  3102. if (st->pos == 2) {
  3103. int avail_w = page_rect.w - 12;
  3104. if (st->right_set && def_w >= 0)
  3105. l->left = page_rect.x + avail_w - st->right -
  3106. def_w;
  3107. else
  3108. l->left = page_rect.x +
  3109. (st->left_set ? st->left : 0);
  3110. l->right = def_w >= 0 ? l->left + def_w :
  3111. page_rect.x + avail_w;
  3112. if (st->bottom_set && st->height_kind == 1)
  3113. l->y = page_rect.y + page_rect.h -
  3114. st->bottom - st->height;
  3115. else
  3116. l->y = page_rect.y +
  3117. (st->top_set ? st->top : 0);
  3118. } else {
  3119. int left = flow_left + (st->left_set ? st->left : 0);
  3120. unsigned int parent = doc.nodes[node].parent;
  3121. if (st->right_set && def_w >= 0)
  3122. left = flow_right - st->right - def_w;
  3123. l->left = left;
  3124. l->right = def_w >= 0 ? left + def_w :
  3125. flow_right +
  3126. (st->left_set ? st->left : 0);
  3127. l->y = flow_y + (st->top_set ? st->top : 0);
  3128. if (st->bottom_set && st->height_kind == 1 &&
  3129. parent < BR_MAX_NODES && block_h[parent] > 0)
  3130. l->y = flow_y + block_h[parent] - st->bottom -
  3131. st->height;
  3132. }
  3133. old_left = l->left;
  3134. old_right = l->right;
  3135. } else if (relative) {
  3136. rel_dx = st->left_set ? st->left :
  3137. (st->right_set ? -st->right : 0);
  3138. rel_dy = st->top_set ? st->top :
  3139. (st->bottom_set ? -st->bottom : 0);
  3140. }
  3141. if (st->transform_set) {
  3142. rel_dx += st->tx;
  3143. rel_dy += st->ty;
  3144. }
  3145. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  3146. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  3147. doc.nodes[node].tag == BR_TAG_SELECT) {
  3148. if (!(doc.nodes[node].tag == BR_TAG_INPUT &&
  3149. s_eq(br_type(&doc, node), "hidden")))
  3150. add_form_run(l, node, st, link);
  3151. l->y += 20;
  3152. return;
  3153. }
  3154. flush_line(l);
  3155. l->y += st->mt;
  3156. top = l->y;
  3157. cbw = old_right - old_left;
  3158. if (cbw < 8)
  3159. cbw = 8;
  3160. ml = st->ml;
  3161. mr = st->mr;
  3162. bl = st->border_w[3];
  3163. br = st->border_w[1];
  3164. pl = st->pl;
  3165. pr = st->pr;
  3166. bt = st->border_w[0];
  3167. bb = st->border_w[2];
  3168. pt = st->pt;
  3169. pb = st->pb;
  3170. deco_w = bl + br + pl + pr;
  3171. deco_h = bt + bb + pt + pb;
  3172. if (st->width_kind) {
  3173. int w;
  3174. if (st->width_kind == 3)
  3175. w = cbw * st->width_calc_pct / 100 +
  3176. st->width_calc_px;
  3177. else
  3178. w = css_size(st->width_kind, st->width, cbw);
  3179. if (w < 0)
  3180. w = 0;
  3181. content_w = st->box_sizing ? w - deco_w : w;
  3182. definite_w = 1;
  3183. } else {
  3184. content_w = cbw - ml - mr - deco_w;
  3185. }
  3186. if (content_w < 0)
  3187. content_w = 0;
  3188. if (st->max_width_kind) {
  3189. int mw = css_size(st->max_width_kind, st->max_width, cbw);
  3190. int max_box = st->box_sizing ? mw : mw + deco_w;
  3191. if (content_w + deco_w > max_box)
  3192. content_w = max_box - deco_w;
  3193. }
  3194. if (st->min_width_kind) {
  3195. int mw = css_size(st->min_width_kind, st->min_width, cbw);
  3196. int min_box = st->box_sizing ? mw : mw + deco_w;
  3197. if (content_w + deco_w < min_box) {
  3198. content_w = min_box - deco_w;
  3199. definite_w = 1;
  3200. }
  3201. }
  3202. if (content_w < 8)
  3203. content_w = 8;
  3204. if (definite_w) {
  3205. int free_w = cbw - ml - mr - deco_w - content_w;
  3206. if (free_w < 0)
  3207. free_w = 0;
  3208. if (st->ml_auto && st->mr_auto) {
  3209. ml = free_w / 2;
  3210. mr = free_w - ml;
  3211. } else if (st->ml_auto) {
  3212. ml = free_w;
  3213. } else if (st->mr_auto) {
  3214. mr = free_w;
  3215. }
  3216. }
  3217. l0 = old_left + ml;
  3218. r0 = l0 + deco_w + content_w;
  3219. if (r0 < l0 + 8)
  3220. r0 = l0 + 8;
  3221. normal_top = top;
  3222. if (sticky) {
  3223. int stick = page_rect.y + 4 + (st->top_set ? st->top : 0);
  3224. if (normal_top < stick)
  3225. rel_dy += stick - normal_top;
  3226. }
  3227. if (shifted && l->draw) {
  3228. top += rel_dy;
  3229. l0 += rel_dx;
  3230. r0 += rel_dx;
  3231. }
  3232. if (l->draw && block_h[node] &&
  3233. top < page_rect.y + page_rect.h &&
  3234. top + block_h[node] > page_rect.y) {
  3235. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  3236. int rtl = css_radius(st, 0, box.w, box.h);
  3237. int rtr = css_radius(st, 1, box.w, box.h);
  3238. int rbr = css_radius(st, 2, box.w, box.h);
  3239. int rbl = css_radius(st, 3, box.w, box.h);
  3240. if (rtl || rtr || rbr || rbl) {
  3241. if (st->has_bg) {
  3242. int bw = st->border_w[0];
  3243. if (bw > 0 && st->border_c[0] != st->bg &&
  3244. box.w > bw * 2 && box.h > bw * 2) {
  3245. struct ngui_rect inner = {
  3246. box.x + bw, box.y + bw,
  3247. box.w - bw * 2, box.h - bw * 2
  3248. };
  3249. int itl = rtl > bw ? rtl - bw : 0;
  3250. int itr = rtr > bw ? rtr - bw : 0;
  3251. int ibr = rbr > bw ? rbr - bw : 0;
  3252. int ibl = rbl > bw ? rbl - bw : 0;
  3253. ngui_fill_round_rect(l->ui, box, rtl,
  3254. rtr, rbr, rbl,
  3255. st->border_c[0]);
  3256. ngui_fill_round_rect(l->ui, inner,
  3257. itl, itr, ibr,
  3258. ibl, st->bg);
  3259. } else {
  3260. ngui_fill_round_rect(l->ui, box, rtl,
  3261. rtr, rbr, rbl,
  3262. st->bg);
  3263. }
  3264. } else if (st->border_w[0]) {
  3265. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  3266. rbl, st->border_w[0],
  3267. st->border_c[0]);
  3268. }
  3269. } else {
  3270. if (st->has_bg)
  3271. ngui_fill_rect(l->ui, box, st->bg);
  3272. if (st->bg_image)
  3273. draw_bg_image(l, box, node, st);
  3274. if (st->border_w[0] || st->border_w[1] ||
  3275. st->border_w[2] || st->border_w[3])
  3276. draw_border_box(l->ui, box, st);
  3277. }
  3278. }
  3279. l->left = l0 + bl + pl;
  3280. l->right = l->left + content_w;
  3281. if (l->right < l->left + 8)
  3282. l->right = l->left + 8;
  3283. l->align = st->align;
  3284. l->y = top + bt + pt;
  3285. if (doc.nodes[node].tag == BR_TAG_HR) {
  3286. if (l->draw)
  3287. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  3288. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  3289. l->y += 8;
  3290. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  3291. int vw = l->right - l->left;
  3292. int vh;
  3293. if (doc.nodes[node].width_pct)
  3294. vw = vw * doc.nodes[node].width_attr / 100;
  3295. else if (doc.nodes[node].width_attr)
  3296. vw = doc.nodes[node].width_attr;
  3297. if (vw > l->right - l->left)
  3298. vw = l->right - l->left;
  3299. if (vw < 8)
  3300. vw = 8;
  3301. vh = vw * 9 / 16;
  3302. if (vh > 240)
  3303. vh = 240;
  3304. if (vh < 80)
  3305. vh = 80;
  3306. if (l->draw) {
  3307. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  3308. vw, vh}, 0xD69A);
  3309. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  3310. vw, vh}, 0x8410);
  3311. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  3312. 0x4208);
  3313. }
  3314. l->y += vh + 4;
  3315. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  3316. int vw, vh, dw = l->right - l->left;
  3317. int dh;
  3318. svg_viewbox(node, &vw, &vh);
  3319. if (dw < 8)
  3320. dw = 8;
  3321. dh = dw * vh / vw;
  3322. if (dh < 8)
  3323. dh = 8;
  3324. if (dh > 1400)
  3325. dh = 1400;
  3326. if (l->draw) {
  3327. struct ngui_rect clip = {l->left, l->y, dw, dh};
  3328. ngui_push_clip(l->ui, clip);
  3329. draw_svg(l->ui, node, l->left, l->y, dw, dh,
  3330. vw, vh, st);
  3331. ngui_pop_clip(l->ui);
  3332. }
  3333. l->y += dh;
  3334. } else {
  3335. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  3336. !st->no_bullet) {
  3337. char *m = li_marker[node];
  3338. if (!m[0]) {
  3339. unsigned int parent = doc.nodes[node].parent;
  3340. if (parent &&
  3341. doc.nodes[parent].tag == BR_TAG_OL) {
  3342. int idx = list_index(parent, node);
  3343. unsigned int n = 0;
  3344. s_append_dec(m, &n, (unsigned int)idx, 6);
  3345. s_append(m, &n, ".", 6);
  3346. } else {
  3347. s_copy(m, "-", 6);
  3348. }
  3349. }
  3350. if (l->draw) {
  3351. int mw = (int)ngui_text_width_ui(l->ui, m);
  3352. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  3353. st->color);
  3354. }
  3355. }
  3356. if (doc.nodes[node].tag == BR_TAG_TR)
  3357. layout_table_row(l, node, st, depth + 1, link);
  3358. else if (st->grid_auto)
  3359. layout_grid_auto(l, node, st, depth + 1, link);
  3360. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  3361. st->grid_gap > 0)
  3362. layout_grid_children(l, node, st, depth + 1, link);
  3363. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  3364. flex_wants_row(node, st))
  3365. layout_flex_children(l, node, st, depth + 1, link);
  3366. else
  3367. layout_children(l, node, st, depth + 1, link);
  3368. }
  3369. flush_line(l);
  3370. if (st->height_kind == 1) {
  3371. content_h = st->height;
  3372. if (st->box_sizing)
  3373. content_h -= deco_h;
  3374. } else {
  3375. content_h = l->y - (top + bt + pt);
  3376. }
  3377. if (content_h < 0)
  3378. content_h = 0;
  3379. if (st->max_height_kind) {
  3380. int mh = css_size(st->max_height_kind, st->max_height, cbw);
  3381. int max_box = st->box_sizing ? mh : mh + deco_h;
  3382. if (content_h + deco_h > max_box)
  3383. content_h = max_box - deco_h;
  3384. }
  3385. if (st->min_height_kind) {
  3386. int mh = css_size(st->min_height_kind, st->min_height, cbw);
  3387. int min_box = st->box_sizing ? mh : mh + deco_h;
  3388. if (content_h + deco_h < min_box)
  3389. content_h = min_box - deco_h;
  3390. }
  3391. if (content_h < 0)
  3392. content_h = 0;
  3393. box_h = deco_h + content_h;
  3394. if (box_h < 0)
  3395. box_h = 0;
  3396. l->y = (shifted ? normal_top : top) + box_h;
  3397. l->left = old_left;
  3398. l->right = old_right;
  3399. l->align = old_align;
  3400. l->y += st->mb;
  3401. if (!l->draw) {
  3402. if (box_h > 65535)
  3403. box_h = 65535;
  3404. block_h[node] = (unsigned short)box_h;
  3405. }
  3406. if (positioned) {
  3407. l->y = flow_y;
  3408. l->left = flow_left;
  3409. l->right = flow_right;
  3410. }
  3411. }
  3412. static int text_node_blank(const struct br_node *nd)
  3413. {
  3414. const char *t = doc.text + nd->text_off;
  3415. unsigned int i;
  3416. for (i = 0; i < nd->text_len; i++)
  3417. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  3418. t[i] != '\r')
  3419. return 0;
  3420. return 1;
  3421. }
  3422. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  3423. * text/image widths in the subtree, plus padding and margins. This keeps
  3424. * Bootstrap's floated nav items on one line instead of giving each the whole
  3425. * row. */
  3426. static int text_space(char c)
  3427. {
  3428. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  3429. }
  3430. static int intrinsic_width(struct ngui *ui, unsigned int node,
  3431. const struct br_style *pst, int depth)
  3432. {
  3433. unsigned int c;
  3434. int w = 0;
  3435. if (depth > 12)
  3436. return 0;
  3437. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  3438. struct br_node *nd = &doc.nodes[c];
  3439. struct br_style cs;
  3440. if (nd->type == BR_NODE_TEXT) {
  3441. const char *t = doc.text + nd->text_off;
  3442. unsigned int tn = nd->text_len;
  3443. if (doc.nodes[node].tag == BR_TAG_PRE) {
  3444. w += (int)ngui_text_width_px(ui, t, tn,
  3445. pst->font_px, pst->bold, pst->italic,
  3446. pst->mono);
  3447. } else {
  3448. unsigned int ti = 0;
  3449. int first = 1;
  3450. int lead = w > 0 && tn > 0 && text_space(t[0]);
  3451. int sp = (int)ngui_text_width_px(ui, " ", 1,
  3452. pst->font_px, pst->bold, pst->italic,
  3453. pst->mono);
  3454. while (ti < tn) {
  3455. unsigned int ts;
  3456. while (ti < tn && text_space(t[ti]))
  3457. ti++;
  3458. ts = ti;
  3459. while (ti < tn && !text_space(t[ti]))
  3460. ti++;
  3461. if (ti == ts)
  3462. break;
  3463. if (!first || lead)
  3464. w += sp;
  3465. lead = 0;
  3466. w += (int)ngui_text_width_px(ui,
  3467. t + ts, ti - ts,
  3468. pst->font_px, pst->bold,
  3469. pst->italic, pst->mono);
  3470. first = 0;
  3471. }
  3472. }
  3473. continue;
  3474. }
  3475. br_style_for(&doc, c, pst, &cs);
  3476. if (cs.display == BR_DISPLAY_NONE)
  3477. continue;
  3478. if (nd->tag == BR_TAG_BR) {
  3479. w += 8;
  3480. continue;
  3481. }
  3482. if (nd->tag == BR_TAG_IMG) {
  3483. /* Measure the image as layout will draw it: a CSS or
  3484. * attribute height keeps the intrinsic aspect ratio, and
  3485. * a CSS width overrides the native pixel width. Bootstrap
  3486. * sizes the Cloudron logo with height:40px only. */
  3487. int idx = nd->img_index;
  3488. int iw = 0, ih = 0;
  3489. if (idx >= 0 && idx < image_count &&
  3490. images[idx].state == 1) {
  3491. iw = (int)images[idx].native_w;
  3492. ih = (int)images[idx].native_h;
  3493. if (iw <= 0 || ih <= 0) {
  3494. iw = (int)images[idx].img.w;
  3495. ih = (int)images[idx].img.h;
  3496. }
  3497. }
  3498. if (cs.width_kind == 1) {
  3499. w += cs.width;
  3500. } else if (cs.width_kind == 2) {
  3501. w += 64;
  3502. } else if (nd->width_attr) {
  3503. w += nd->width_attr;
  3504. } else if (nd->height_attr && iw && ih) {
  3505. w += iw * (int)nd->height_attr / ih;
  3506. } else if (cs.height_kind == 1 && iw && ih) {
  3507. w += iw * (int)cs.height / ih;
  3508. } else if (iw) {
  3509. w += iw;
  3510. } else {
  3511. w += 64;
  3512. }
  3513. continue;
  3514. }
  3515. w += cs.pl + cs.pr + cs.ml + cs.mr;
  3516. w += intrinsic_width(ui, c, &cs, depth + 1);
  3517. if (w > 4096)
  3518. break;
  3519. }
  3520. return w;
  3521. }
  3522. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  3523. * the main user: .row > .col-md-* with float:left and a percentage width.
  3524. * Each column is laid out with its own left/right edge and the row advances
  3525. * to the tallest column. Returns the first child not consumed. */
  3526. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  3527. const struct br_style *pst, int depth,
  3528. unsigned short link)
  3529. {
  3530. unsigned int n = first;
  3531. int row_left = l->left, row_right = l->right;
  3532. int row_top, row_bottom, xl, xr, any = 0;
  3533. flush_line(l);
  3534. row_top = l->y;
  3535. row_bottom = l->y;
  3536. xl = row_left;
  3537. xr = row_right;
  3538. while (n) {
  3539. struct br_node *nd = &doc.nodes[n];
  3540. struct br_style cs;
  3541. unsigned short lk = link;
  3542. int colw, right;
  3543. if (nd->type == BR_NODE_TEXT) {
  3544. if (text_node_blank(nd)) {
  3545. n = nd->next;
  3546. continue;
  3547. }
  3548. break;
  3549. }
  3550. br_style_for(&doc, n, pst, &cs);
  3551. if (cs.display == BR_DISPLAY_NONE) {
  3552. n = nd->next;
  3553. continue;
  3554. }
  3555. /* A float blockifies its box: Bootstrap floats inline
  3556. * anchors too (the navbar brand and its text links), and
  3557. * their padding must be honoured. */
  3558. if (!cs.float_left)
  3559. break;
  3560. if (nd->tag == BR_TAG_A && nd->href_off)
  3561. lk = (unsigned short)n;
  3562. right = cs.float_left == 2;
  3563. if (cs.width_kind == 2)
  3564. colw = (row_right - row_left) * (int)cs.width / 100;
  3565. else if (cs.width_kind == 1)
  3566. colw = (int)cs.width;
  3567. else {
  3568. colw = intrinsic_width(l->ui, n, &cs, 0) +
  3569. cs.pl + cs.pr + cs.ml + cs.mr;
  3570. if (colw < 8)
  3571. colw = 8;
  3572. }
  3573. if (colw < 8)
  3574. colw = 8;
  3575. if (colw > row_right - row_left)
  3576. colw = row_right - row_left;
  3577. /* The float column width is already resolved. */
  3578. cs.width_kind = 0;
  3579. cs.max_width_kind = 0;
  3580. if (right) {
  3581. if (any && xr - colw < xl) {
  3582. row_top = row_bottom;
  3583. row_bottom = row_top;
  3584. xl = row_left;
  3585. xr = row_right;
  3586. }
  3587. if (xr - colw < xl)
  3588. colw = xr - xl;
  3589. if (colw < 8)
  3590. colw = 8;
  3591. l->left = xr - colw;
  3592. if (l->left < row_left)
  3593. l->left = row_left;
  3594. l->right = xr;
  3595. xr = l->left;
  3596. } else {
  3597. if (any && xl + colw > xr) {
  3598. row_top = row_bottom;
  3599. row_bottom = row_top;
  3600. xl = row_left;
  3601. xr = row_right;
  3602. }
  3603. l->left = xl;
  3604. l->right = xl + colw;
  3605. xl += colw;
  3606. }
  3607. if (l->right < l->left + 8)
  3608. l->right = l->left + 8;
  3609. l->y = row_top;
  3610. l->line_x = l->left;
  3611. l->run_x = l->left;
  3612. l->line_y = l->y;
  3613. l->line_h = 0;
  3614. l->nruns = 0;
  3615. l->space_pending = 0;
  3616. l->align = cs.align;
  3617. layout_block(l, n, &cs, depth + 1, lk);
  3618. if (l->y > row_bottom)
  3619. row_bottom = l->y;
  3620. any = 1;
  3621. n = nd->next;
  3622. }
  3623. l->left = row_left;
  3624. l->right = row_right;
  3625. l->y = row_bottom;
  3626. l->line_x = l->left;
  3627. l->run_x = l->left;
  3628. l->line_y = l->y;
  3629. l->line_h = 0;
  3630. l->nruns = 0;
  3631. l->space_pending = 0;
  3632. return n;
  3633. }
  3634. static int flex_item_width(struct lay *l, unsigned int n,
  3635. const struct br_style *cs, int avail)
  3636. {
  3637. struct br_node *nd = &doc.nodes[n];
  3638. (void)l;
  3639. int w;
  3640. if (cs->width_kind == 2)
  3641. w = avail * (int)cs->width / 100;
  3642. else if (cs->width_kind == 1)
  3643. w = (int)cs->width;
  3644. else if (nd->tag == BR_TAG_IMG) {
  3645. int idx = nd->img_index;
  3646. if (idx >= 0 && idx < image_count &&
  3647. images[idx].state == 1)
  3648. w = (int)images[idx].img.w;
  3649. else if (nd->width_attr)
  3650. w = (int)nd->width_attr;
  3651. else
  3652. w = 64;
  3653. } else {
  3654. w = intrinsic_width(l->ui, n, cs, 0);
  3655. w += cs->pl + cs->pr + cs->ml + cs->mr;
  3656. }
  3657. if (w < 24)
  3658. w = 24;
  3659. if (w > avail)
  3660. w = avail;
  3661. return w;
  3662. }
  3663. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  3664. * on one line, not one full-width block each. Place intrinsic widths from
  3665. * left to right and wrap when the row is full. */
  3666. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  3667. const struct br_style *pst, int depth,
  3668. unsigned short link)
  3669. {
  3670. unsigned int n = first;
  3671. int row_left = l->left, row_right = l->right;
  3672. int avail = row_right - row_left;
  3673. int x = row_left, y = l->y, row_h = 0, any = 0;
  3674. flush_line(l);
  3675. y = l->y;
  3676. while (n) {
  3677. struct br_node *nd = &doc.nodes[n];
  3678. struct br_style cs;
  3679. unsigned short lk = link;
  3680. int colw, h;
  3681. if (nd->type == BR_NODE_TEXT) {
  3682. if (!text_node_blank(nd))
  3683. break;
  3684. if (any)
  3685. x += 4;
  3686. n = nd->next;
  3687. continue;
  3688. }
  3689. br_style_for(&doc, n, pst, &cs);
  3690. if (cs.display == BR_DISPLAY_NONE) {
  3691. n = nd->next;
  3692. continue;
  3693. }
  3694. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  3695. break;
  3696. if (nd->tag == BR_TAG_A && nd->href_off)
  3697. lk = (unsigned short)n;
  3698. colw = flex_item_width(l, n, &cs, avail);
  3699. /* A few pixels of slack keep a single long token (boot.S)
  3700. * from wrapping at the exact content width. */
  3701. colw += 8;
  3702. if (colw > avail)
  3703. colw = avail;
  3704. cs.width_kind = 0;
  3705. cs.max_width_kind = 0;
  3706. if (any && x + colw > row_right) {
  3707. y += row_h + 2;
  3708. x = row_left;
  3709. row_h = 0;
  3710. any = 0;
  3711. }
  3712. if (any && x > row_left)
  3713. x += 4;
  3714. l->left = x;
  3715. l->right = x + colw;
  3716. if (l->right < l->left + 8)
  3717. l->right = l->left + 8;
  3718. l->y = y;
  3719. l->line_x = l->left;
  3720. l->run_x = l->left;
  3721. l->line_y = l->y;
  3722. l->line_h = 0;
  3723. l->nruns = 0;
  3724. l->space_pending = 0;
  3725. l->align = cs.align;
  3726. layout_block(l, n, &cs, depth + 1, lk);
  3727. h = l->y - y;
  3728. if (h > row_h)
  3729. row_h = h;
  3730. x += colw;
  3731. any = 1;
  3732. n = nd->next;
  3733. }
  3734. if (any)
  3735. y += row_h;
  3736. l->left = row_left;
  3737. l->right = row_right;
  3738. l->y = y;
  3739. l->line_x = l->left;
  3740. l->run_x = l->left;
  3741. l->line_y = l->y;
  3742. l->line_h = 0;
  3743. l->nruns = 0;
  3744. l->space_pending = 0;
  3745. return n;
  3746. }
  3747. struct flex_item {
  3748. unsigned int node;
  3749. unsigned short link;
  3750. int w;
  3751. };
  3752. static void layout_flex_children(struct lay *l, unsigned int parent,
  3753. const struct br_style *pst, int depth,
  3754. unsigned short link)
  3755. {
  3756. struct flex_item it[32];
  3757. unsigned int c;
  3758. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  3759. int row_left = l->left, row_right = l->right;
  3760. int avail = row_right - row_left;
  3761. int idx, row_top;
  3762. if (avail < 160 || depth > 24) {
  3763. layout_children(l, parent, pst, depth, link);
  3764. return;
  3765. }
  3766. /* If direct text is not just whitespace, normal block flow handles it
  3767. * better than pretending it is a flex item. */
  3768. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  3769. struct br_node *nd = &doc.nodes[c];
  3770. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  3771. layout_children(l, parent, pst, depth, link);
  3772. return;
  3773. }
  3774. }
  3775. for (c = doc.nodes[parent].first;
  3776. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  3777. c = doc.nodes[c].next) {
  3778. struct br_node *nd = &doc.nodes[c];
  3779. struct br_style cs;
  3780. if (nd->type == BR_NODE_TEXT)
  3781. continue;
  3782. br_style_for(&doc, c, pst, &cs);
  3783. if (cs.display == BR_DISPLAY_NONE)
  3784. continue;
  3785. it[nitem].node = c;
  3786. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  3787. (unsigned short)c : link;
  3788. it[nitem].w = 0;
  3789. if (cs.flex_grow && !cs.width_kind)
  3790. grow_count++;
  3791. else
  3792. fixed += flex_item_width(l, c, &cs, avail);
  3793. nitem++;
  3794. }
  3795. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  3796. if (grow_w < 96)
  3797. grow_w = 96;
  3798. for (idx = 0; idx < nitem; idx++) {
  3799. struct br_style cs;
  3800. br_style_for(&doc, it[idx].node, pst, &cs);
  3801. if (cs.flex_grow && !cs.width_kind)
  3802. it[idx].w = grow_w;
  3803. else
  3804. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  3805. if (it[idx].w > avail)
  3806. it[idx].w = avail;
  3807. if (it[idx].w < 8)
  3808. it[idx].w = 8;
  3809. }
  3810. row_top = l->y;
  3811. idx = 0;
  3812. while (idx < nitem) {
  3813. int start = idx, count = 0, row_w = 0;
  3814. int free_w, x, extra = 0, row_h = 0, k;
  3815. while (idx < nitem) {
  3816. int add = it[idx].w + (count ? gap : 0);
  3817. if (count && pst->flex_wrap != 2 &&
  3818. row_w + add > avail)
  3819. break;
  3820. row_w += add;
  3821. count++;
  3822. idx++;
  3823. }
  3824. if (!count) {
  3825. count = 1;
  3826. row_w = it[start].w;
  3827. idx = start + 1;
  3828. }
  3829. free_w = avail - row_w;
  3830. if (free_w < 0)
  3831. free_w = 0;
  3832. x = row_left;
  3833. if (pst->justify == 1) {
  3834. x += free_w / 2;
  3835. } else if (pst->justify == 2) {
  3836. x += free_w;
  3837. } else if (pst->justify == 3) {
  3838. extra = count > 1 ? free_w / (count - 1) : 0;
  3839. } else if (pst->justify == 4) {
  3840. extra = count ? free_w / count : 0;
  3841. x += extra / 2;
  3842. }
  3843. for (k = 0; k < count; k++) {
  3844. int node = (int)it[start + k].node;
  3845. int h = block_h[node];
  3846. if (h > row_h)
  3847. row_h = h;
  3848. }
  3849. if (pst->height_kind == 1 && pst->height > row_h)
  3850. row_h = pst->height;
  3851. for (k = 0; k < count; k++) {
  3852. struct br_style cs;
  3853. int node = (int)it[start + k].node;
  3854. int yoff = 0;
  3855. br_style_for(&doc, node, pst, &cs);
  3856. cs.width_kind = 0;
  3857. cs.max_width_kind = 0;
  3858. if (l->draw && pst->align_items &&
  3859. row_h > block_h[node]) {
  3860. if (pst->align_items == 1)
  3861. yoff = (row_h - block_h[node]) / 2;
  3862. else if (pst->align_items == 2)
  3863. yoff = row_h - block_h[node];
  3864. }
  3865. l->left = x;
  3866. l->right = x + it[start + k].w;
  3867. if (l->right < l->left + 8)
  3868. l->right = l->left + 8;
  3869. l->y = row_top + yoff;
  3870. l->line_x = l->left;
  3871. l->run_x = l->left;
  3872. l->line_y = l->y;
  3873. l->line_h = 0;
  3874. l->nruns = 0;
  3875. l->space_pending = 0;
  3876. l->align = cs.align;
  3877. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  3878. if (!l->draw) {
  3879. int h = l->y - row_top;
  3880. if (h > row_h)
  3881. row_h = h;
  3882. }
  3883. x += it[start + k].w;
  3884. if (k + 1 < count)
  3885. x += gap + extra;
  3886. }
  3887. row_top += row_h;
  3888. }
  3889. l->left = row_left;
  3890. l->right = row_right;
  3891. l->y = row_top;
  3892. l->line_x = l->left;
  3893. l->run_x = l->left;
  3894. l->line_y = l->y;
  3895. l->line_h = 0;
  3896. l->nruns = 0;
  3897. l->space_pending = 0;
  3898. }
  3899. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  3900. * plus the grid-area hints used by site shells (site notice/footer full
  3901. * width, column-start left, page-content right). Anything more elaborate
  3902. * falls back to normal block flow. */
  3903. static int grid_track_width(unsigned char kind, unsigned short val,
  3904. int avail, int other)
  3905. {
  3906. if (kind == 2)
  3907. return avail * (int)val / 100;
  3908. if (kind == 1)
  3909. return val;
  3910. return other;
  3911. }
  3912. static void layout_grid_children(struct lay *l, unsigned int parent,
  3913. const struct br_style *pst, int depth,
  3914. unsigned short link)
  3915. {
  3916. unsigned int n;
  3917. int row_left = l->left, row_right = l->right;
  3918. int avail = row_right - row_left;
  3919. int gap = pst->grid_gap;
  3920. int track_total = avail - gap;
  3921. int col0, col1, x0, x1;
  3922. int row_y, row_bottom, have_left = 0, have_right = 0;
  3923. unsigned int c;
  3924. if (avail < 32 || depth > 24)
  3925. return;
  3926. if (track_total < 16)
  3927. track_total = 16;
  3928. col0 = grid_track_width((unsigned char)(pst->width_kind),
  3929. pst->width, track_total, 0);
  3930. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  3931. pst->max_width, track_total, 0);
  3932. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  3933. int w0 = pst->width ? pst->width : 1;
  3934. int w1 = pst->max_width ? pst->max_width : 1;
  3935. col0 = track_total * w0 / (w0 + w1);
  3936. col1 = track_total - col0;
  3937. } else if (pst->width_kind == 3) {
  3938. col0 = track_total - col1;
  3939. if (col0 < 24)
  3940. col0 = 24;
  3941. } else if (pst->max_width_kind == 3) {
  3942. col1 = track_total - col0;
  3943. if (col1 < 24)
  3944. col1 = 24;
  3945. }
  3946. if (col0 < 24)
  3947. col0 = 24;
  3948. if (col1 < 24)
  3949. col1 = 24;
  3950. if (col0 + col1 > track_total) {
  3951. col1 = track_total - col0;
  3952. if (col1 < 24)
  3953. col1 = 24;
  3954. }
  3955. x0 = row_left;
  3956. x1 = row_left + col0 + gap;
  3957. /* Direct text makes a grid ambiguous; use block flow instead. */
  3958. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  3959. struct br_node *nd = &doc.nodes[c];
  3960. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  3961. layout_children(l, parent, pst, depth, link);
  3962. return;
  3963. }
  3964. }
  3965. row_y = row_bottom = l->y;
  3966. n = doc.nodes[parent].first;
  3967. while (n) {
  3968. struct br_node *nd = &doc.nodes[n];
  3969. struct br_style cs;
  3970. unsigned short lk = link;
  3971. int slot, x, w;
  3972. if (nd->type == BR_NODE_TEXT) {
  3973. n = nd->next;
  3974. continue;
  3975. }
  3976. br_style_for(&doc, n, pst, &cs);
  3977. if (cs.display == BR_DISPLAY_NONE) {
  3978. n = nd->next;
  3979. continue;
  3980. }
  3981. if (nd->tag == BR_TAG_A && nd->href_off)
  3982. lk = (unsigned short)n;
  3983. slot = cs.grid_slot;
  3984. if (!slot) {
  3985. if (!have_left)
  3986. slot = 2;
  3987. else if (!have_right)
  3988. slot = 3;
  3989. else
  3990. slot = 2;
  3991. }
  3992. if (slot == 1) {
  3993. if (have_left || have_right) {
  3994. row_y = row_bottom;
  3995. have_left = have_right = 0;
  3996. }
  3997. x = row_left;
  3998. w = avail;
  3999. } else if (slot == 2) {
  4000. if (have_left) {
  4001. row_y = row_bottom;
  4002. have_left = have_right = 0;
  4003. }
  4004. x = x0;
  4005. w = col0;
  4006. have_left = 1;
  4007. } else {
  4008. if (have_right) {
  4009. row_y = row_bottom;
  4010. have_left = have_right = 0;
  4011. }
  4012. x = x1;
  4013. w = col1;
  4014. have_right = 1;
  4015. }
  4016. cs.width_kind = 0;
  4017. cs.max_width_kind = 0;
  4018. l->left = x;
  4019. l->right = x + w;
  4020. if (l->right < l->left + 8)
  4021. l->right = l->left + 8;
  4022. l->y = row_y;
  4023. l->line_x = l->left;
  4024. l->run_x = l->left;
  4025. l->line_y = l->y;
  4026. l->line_h = 0;
  4027. l->nruns = 0;
  4028. l->space_pending = 0;
  4029. l->align = cs.align;
  4030. layout_block(l, n, &cs, depth + 1, lk);
  4031. if (l->y > row_bottom)
  4032. row_bottom = l->y;
  4033. n = nd->next;
  4034. }
  4035. l->left = row_left;
  4036. l->right = row_right;
  4037. l->y = row_bottom;
  4038. l->line_x = l->left;
  4039. l->run_x = l->left;
  4040. l->line_y = l->y;
  4041. l->line_h = 0;
  4042. l->nruns = 0;
  4043. l->space_pending = 0;
  4044. }
  4045. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  4046. * capped at four. Used by the project docs' card grids. */
  4047. static void layout_grid_auto(struct lay *l, unsigned int parent,
  4048. const struct br_style *pst, int depth,
  4049. unsigned short link)
  4050. {
  4051. unsigned int n, c;
  4052. int row_left = l->left, row_right = l->right;
  4053. int avail = row_right - row_left;
  4054. int gap = pst->grid_gap;
  4055. int minw = pst->width_kind == 1 ? pst->width : 200;
  4056. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  4057. if (avail < 32 || depth > 24) {
  4058. layout_children(l, parent, pst, depth, link);
  4059. return;
  4060. }
  4061. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  4062. struct br_node *nd = &doc.nodes[c];
  4063. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  4064. layout_children(l, parent, pst, depth, link);
  4065. return;
  4066. }
  4067. }
  4068. if (minw < 80)
  4069. minw = 80;
  4070. ncols = (avail + gap) / (minw + gap);
  4071. if (ncols < 1)
  4072. ncols = 1;
  4073. if (ncols > 4)
  4074. ncols = 4;
  4075. colw = (avail - gap * (ncols - 1)) / ncols;
  4076. if (colw < 24)
  4077. colw = 24;
  4078. x = row_left;
  4079. n = doc.nodes[parent].first;
  4080. while (n) {
  4081. struct br_node *nd = &doc.nodes[n];
  4082. struct br_style cs;
  4083. unsigned short lk = link;
  4084. int h;
  4085. if (nd->type == BR_NODE_TEXT) {
  4086. n = nd->next;
  4087. continue;
  4088. }
  4089. br_style_for(&doc, n, pst, &cs);
  4090. if (cs.display == BR_DISPLAY_NONE) {
  4091. n = nd->next;
  4092. continue;
  4093. }
  4094. if (nd->tag == BR_TAG_A && nd->href_off)
  4095. lk = (unsigned short)n;
  4096. cs.width_kind = 0;
  4097. cs.max_width_kind = 0;
  4098. l->left = x;
  4099. l->right = x + colw;
  4100. if (l->right < l->left + 8)
  4101. l->right = l->left + 8;
  4102. l->y = y;
  4103. l->line_x = l->left;
  4104. l->run_x = l->left;
  4105. l->line_y = l->y;
  4106. l->line_h = 0;
  4107. l->nruns = 0;
  4108. l->space_pending = 0;
  4109. l->align = cs.align;
  4110. layout_block(l, n, &cs, depth + 1, lk);
  4111. h = l->y - y;
  4112. if (h > row_h)
  4113. row_h = h;
  4114. col++;
  4115. n = nd->next;
  4116. if (col == ncols) {
  4117. y += row_h + gap;
  4118. x = row_left;
  4119. row_h = 0;
  4120. col = 0;
  4121. } else {
  4122. x += colw + gap;
  4123. }
  4124. }
  4125. if (col)
  4126. y += row_h;
  4127. else if (y > start_y)
  4128. y -= gap;
  4129. l->left = row_left;
  4130. l->right = row_right;
  4131. l->y = y;
  4132. l->line_x = l->left;
  4133. l->run_x = l->left;
  4134. l->line_y = l->y;
  4135. l->line_h = 0;
  4136. l->nruns = 0;
  4137. l->space_pending = 0;
  4138. }
  4139. /* Column widths are the widest cell in each column across every row, so all
  4140. * rows line up. The table model is still deliberately basic: no colspan,
  4141. * border-collapse or percentage columns. */
  4142. static void table_columns(struct lay *l, unsigned int table,
  4143. const struct br_style *pst, int avail,
  4144. int *raw, int maxcols, int *out_cols,
  4145. int *out_total)
  4146. {
  4147. unsigned int r, c;
  4148. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  4149. int fixed[12];
  4150. for (c = 0; c < (unsigned int)maxcols; c++) {
  4151. raw[c] = 0;
  4152. fixed[c] = 0;
  4153. }
  4154. /* Intrinsic widths of single-column cells. */
  4155. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  4156. struct br_node *rn = &doc.nodes[r];
  4157. int col = 0;
  4158. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  4159. continue;
  4160. for (c = rn->first; c; c = doc.nodes[c].next) {
  4161. struct br_node *cn = &doc.nodes[c];
  4162. struct br_style cs;
  4163. int w, span;
  4164. if (cn->type != BR_NODE_ELEM ||
  4165. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  4166. continue;
  4167. span = cn->colspan ? cn->colspan : 1;
  4168. br_style_for(&doc, c, pst, &cs);
  4169. if (cs.display == BR_DISPLAY_NONE)
  4170. continue;
  4171. if (col + span > maxcols)
  4172. span = maxcols - col;
  4173. if (span < 1)
  4174. break;
  4175. w = intrinsic_width(l->ui, c, &cs, 0) + cs.pl + cs.pr +
  4176. cs.ml + cs.mr +
  4177. cs.border_w[0] + cs.border_w[1] +
  4178. cs.border_w[2] + cs.border_w[3];
  4179. if (w < 24)
  4180. w = 24;
  4181. if (span == 1) {
  4182. if (w > raw[col])
  4183. raw[col] = w;
  4184. }
  4185. if (col + span > cols)
  4186. cols = col + span;
  4187. col += span;
  4188. }
  4189. }
  4190. /* A colspan cell only has to be as wide as the sum of its columns. */
  4191. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  4192. struct br_node *rn = &doc.nodes[r];
  4193. int col = 0;
  4194. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  4195. continue;
  4196. for (c = rn->first; c; c = doc.nodes[c].next) {
  4197. struct br_node *cn = &doc.nodes[c];
  4198. struct br_style cs;
  4199. int span, w, sum, i;
  4200. if (cn->type != BR_NODE_ELEM ||
  4201. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  4202. continue;
  4203. span = cn->colspan ? cn->colspan : 1;
  4204. if (col + span > maxcols)
  4205. span = maxcols - col;
  4206. if (span < 1)
  4207. break;
  4208. if (span > 1) {
  4209. br_style_for(&doc, c, pst, &cs);
  4210. if (cs.display != BR_DISPLAY_NONE) {
  4211. w = intrinsic_width(l->ui, c, &cs, 0) +
  4212. cs.pl + cs.pr + cs.ml + cs.mr +
  4213. cs.border_w[0] + cs.border_w[1] +
  4214. cs.border_w[2] + cs.border_w[3];
  4215. sum = 0;
  4216. for (i = 0; i < span; i++)
  4217. sum += raw[col + i];
  4218. if (w > sum)
  4219. raw[col + span - 1] += w - sum;
  4220. }
  4221. }
  4222. col += span;
  4223. }
  4224. }
  4225. /* Explicit and percentage widths override intrinsic widths. */
  4226. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  4227. struct br_node *rn = &doc.nodes[r];
  4228. int col = 0;
  4229. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  4230. continue;
  4231. for (c = rn->first; c; c = doc.nodes[c].next) {
  4232. struct br_node *cn = &doc.nodes[c];
  4233. struct br_style cs;
  4234. int span;
  4235. if (cn->type != BR_NODE_ELEM ||
  4236. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  4237. continue;
  4238. span = cn->colspan ? cn->colspan : 1;
  4239. if (col + span > maxcols)
  4240. span = maxcols - col;
  4241. if (span < 1)
  4242. break;
  4243. if (span == 1) {
  4244. br_style_for(&doc, c, pst, &cs);
  4245. if (cs.display != BR_DISPLAY_NONE) {
  4246. if (cs.width_kind == 1) {
  4247. raw[col] = cs.width;
  4248. fixed[col] = 1;
  4249. } else if (cs.width_kind == 2) {
  4250. raw[col] = avail * cs.width / 100;
  4251. fixed[col] = 1;
  4252. }
  4253. }
  4254. }
  4255. col += span;
  4256. }
  4257. }
  4258. for (c = 0; c < (unsigned int)cols; c++) {
  4259. if (raw[c] < 8)
  4260. raw[c] = 8;
  4261. total += raw[c];
  4262. if (fixed[c])
  4263. fixed_sum += raw[c];
  4264. else {
  4265. free_raw += raw[c];
  4266. free_cols++;
  4267. }
  4268. }
  4269. if (fixed_sum > 0 && fixed_sum < avail) {
  4270. int free_avail = avail - fixed_sum;
  4271. int i;
  4272. if (free_raw > 0) {
  4273. for (i = 0; i < cols; i++)
  4274. if (!fixed[i])
  4275. raw[i] = free_avail * raw[i] /
  4276. free_raw;
  4277. } else if (free_cols > 0) {
  4278. for (i = 0; i < cols; i++)
  4279. if (!fixed[i])
  4280. raw[i] = free_avail / free_cols;
  4281. }
  4282. total = 0;
  4283. for (i = 0; i < cols; i++)
  4284. total += raw[i];
  4285. } else if (total < avail && total > 0) {
  4286. int i;
  4287. for (i = 0; i < cols; i++)
  4288. raw[i] = raw[i] * avail / total;
  4289. total = 0;
  4290. for (i = 0; i < cols; i++)
  4291. total += raw[i];
  4292. }
  4293. *out_cols = cols;
  4294. *out_total = total;
  4295. }
  4296. static void layout_table_row(struct lay *l, unsigned int row,
  4297. const struct br_style *pst, int depth,
  4298. unsigned short link)
  4299. {
  4300. unsigned int n, cell[12];
  4301. int raw[12], colstart[12], colspan[12];
  4302. int prefix[13];
  4303. int ncell = 0, total = 0, cols = 0, col = 0;
  4304. int row_left = l->left, row_right = l->right;
  4305. int avail = row_right - row_left;
  4306. int y = l->y, bottom = l->y;
  4307. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  4308. struct br_node *nd = &doc.nodes[n];
  4309. struct br_style cs;
  4310. int span;
  4311. if (nd->type == BR_NODE_TEXT) {
  4312. if (text_node_blank(nd))
  4313. continue;
  4314. layout_children(l, row, pst, depth, link);
  4315. return;
  4316. }
  4317. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  4318. layout_children(l, row, pst, depth, link);
  4319. return;
  4320. }
  4321. br_style_for(&doc, n, pst, &cs);
  4322. if (cs.display == BR_DISPLAY_NONE)
  4323. continue;
  4324. if (ncell >= 12) {
  4325. layout_children(l, row, pst, depth, link);
  4326. return;
  4327. }
  4328. span = nd->colspan ? nd->colspan : 1;
  4329. if (span > 12 - col)
  4330. span = 12 - col;
  4331. if (span < 1)
  4332. continue;
  4333. cell[ncell] = n;
  4334. colstart[ncell] = col;
  4335. colspan[ncell] = span;
  4336. col += span;
  4337. ncell++;
  4338. }
  4339. if (ncell < 1 || avail < 32) {
  4340. layout_children(l, row, pst, depth, link);
  4341. return;
  4342. }
  4343. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  4344. &total);
  4345. if (cols < 2 || total <= 0) {
  4346. int c;
  4347. for (c = 0; c < ncell; c++) {
  4348. struct br_style cs;
  4349. br_style_for(&doc, cell[c], pst, &cs);
  4350. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0) +
  4351. cs.pl + cs.pr + cs.ml + cs.mr;
  4352. if (raw[c] < 24)
  4353. raw[c] = 24;
  4354. total += raw[c];
  4355. }
  4356. }
  4357. prefix[0] = row_left;
  4358. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  4359. prefix[n + 1] = prefix[n] + raw[n];
  4360. for (n = 0; n < (unsigned int)ncell; n++) {
  4361. struct br_style cs;
  4362. int start = colstart[n];
  4363. int end = start + colspan[n];
  4364. int w;
  4365. if (end > cols)
  4366. end = cols;
  4367. if (start >= cols)
  4368. continue;
  4369. w = prefix[end] - prefix[start];
  4370. br_style_for(&doc, cell[n], pst, &cs);
  4371. /* The column width already reflects the cell's width property. */
  4372. cs.width_kind = 0;
  4373. cs.max_width_kind = 0;
  4374. if (w < 24)
  4375. w = 24;
  4376. if (w < 8)
  4377. w = 8;
  4378. l->left = prefix[start];
  4379. l->right = l->left + w;
  4380. l->y = y;
  4381. l->line_x = l->left;
  4382. l->run_x = l->left;
  4383. l->line_y = l->y;
  4384. l->line_h = 0;
  4385. l->nruns = 0;
  4386. l->space_pending = 0;
  4387. l->align = cs.align;
  4388. layout_block(l, cell[n], &cs, depth + 1, link);
  4389. if (l->y > bottom)
  4390. bottom = l->y;
  4391. }
  4392. l->left = row_left;
  4393. l->right = row_right;
  4394. l->y = bottom;
  4395. l->line_x = l->left;
  4396. l->run_x = l->left;
  4397. l->line_y = l->y;
  4398. l->line_h = 0;
  4399. l->nruns = 0;
  4400. l->space_pending = 0;
  4401. }
  4402. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  4403. * flow so they sit above it, like CSS painting order. Their flow origin is
  4404. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  4405. struct br_deferred {
  4406. unsigned int node;
  4407. int flow_y, flow_left, flow_right;
  4408. unsigned short link;
  4409. signed short z_index;
  4410. unsigned char z_set;
  4411. unsigned int order;
  4412. };
  4413. static struct br_deferred deferred[16];
  4414. static int ndeferred;
  4415. static void layout_children(struct lay *l, unsigned int parent,
  4416. const struct br_style *pst, int depth,
  4417. unsigned short link)
  4418. {
  4419. unsigned int n;
  4420. if (depth > 24)
  4421. return;
  4422. n = doc.nodes[parent].first;
  4423. while (n) {
  4424. struct br_node *nd = &doc.nodes[n];
  4425. struct br_style cs;
  4426. unsigned short lk = link;
  4427. if (nd->type == BR_NODE_TEXT) {
  4428. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  4429. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  4430. n = nd->next;
  4431. continue;
  4432. }
  4433. br_style_for(&doc, n, pst, &cs);
  4434. if (cs.display == BR_DISPLAY_NONE) {
  4435. n = nd->next;
  4436. continue;
  4437. }
  4438. if (nd->tag == BR_TAG_A && nd->href_off)
  4439. lk = (unsigned short)n;
  4440. if (cs.pos == 1 || cs.pos == 2) {
  4441. if (l->draw && ndeferred < 16) {
  4442. deferred[ndeferred].node = n;
  4443. deferred[ndeferred].flow_y = l->y;
  4444. deferred[ndeferred].flow_left = l->left;
  4445. deferred[ndeferred].flow_right = l->right;
  4446. deferred[ndeferred].link = lk;
  4447. deferred[ndeferred].z_index = cs.z_index;
  4448. deferred[ndeferred].z_set = cs.z_set;
  4449. deferred[ndeferred].order = (unsigned int)ndeferred;
  4450. ndeferred++;
  4451. } else {
  4452. layout_block(l, n, &cs, depth + 1, lk);
  4453. }
  4454. if (cs.pos == 1 && block_h[n] &&
  4455. doc.nodes[n].class_off) {
  4456. const char *cl = doc.attrs +
  4457. doc.nodes[n].class_off;
  4458. if ((contains_ci(cl, "poster-wrapper") ||
  4459. contains_ci(cl, "ts-picture")) &&
  4460. !has_skeleton_sibling(n))
  4461. l->y += block_h[n];
  4462. }
  4463. n = nd->next;
  4464. continue;
  4465. }
  4466. if (nd->tag == BR_TAG_BR) {
  4467. flush_line(l);
  4468. n = nd->next;
  4469. continue;
  4470. }
  4471. if (nd->tag == BR_TAG_HR) {
  4472. flush_line(l);
  4473. if (l->draw)
  4474. ngui_fill_rect(l->ui,
  4475. (struct ngui_rect){l->left, l->y + 2,
  4476. l->right - l->left, 1}, BR_GRAY);
  4477. l->y += 8;
  4478. n = nd->next;
  4479. continue;
  4480. }
  4481. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  4482. nd->tag == BR_TAG_SELECT) {
  4483. if (!(nd->tag == BR_TAG_INPUT &&
  4484. s_eq(br_type(&doc, n), "hidden")))
  4485. add_form_run(l, n, &cs, lk);
  4486. n = nd->next;
  4487. continue;
  4488. }
  4489. if (nd->tag == BR_TAG_IMG) {
  4490. add_image_run(l, n, &cs, lk);
  4491. n = nd->next;
  4492. continue;
  4493. }
  4494. if (nd->tag == BR_TAG_VIDEO) {
  4495. layout_block(l, n, &cs, depth + 1, lk);
  4496. n = nd->next;
  4497. continue;
  4498. }
  4499. if (cs.float_left) {
  4500. n = layout_float_group(l, n, pst, depth, lk);
  4501. continue;
  4502. }
  4503. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  4504. n = layout_inline_blocks(l, n, pst, depth, link);
  4505. continue;
  4506. }
  4507. if (cs.display == BR_DISPLAY_BLOCK || br_tag_is_block(nd->tag))
  4508. layout_block(l, n, &cs, depth + 1, lk);
  4509. else {
  4510. layout_children(l, n, &cs, depth + 1, lk);
  4511. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  4512. l->space_pending = 1;
  4513. }
  4514. n = nd->next;
  4515. }
  4516. }
  4517. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  4518. * runs and a recursive page can otherwise overflow the stack. */
  4519. static struct lay layout_state;
  4520. static int measure_page(int left, int right)
  4521. {
  4522. struct lay *l = &layout_state;
  4523. struct br_style base = base_style();
  4524. unsigned int i;
  4525. for (i = 0; i < BR_MAX_NODES; i++) {
  4526. block_h[i] = 0;
  4527. img_top[i] = 0;
  4528. img_h[i] = 0;
  4529. }
  4530. l->draw = 0;
  4531. l->ui = 0;
  4532. l->left = left;
  4533. l->right = right;
  4534. l->y = 0;
  4535. l->line_x = left;
  4536. l->run_x = left;
  4537. l->line_y = 0;
  4538. l->line_h = 0;
  4539. l->align = BR_ALIGN_LEFT;
  4540. l->depth = 0;
  4541. l->nruns = 0;
  4542. l->space_pending = 0;
  4543. layout_children(l, doc.root, &base, 0, 0);
  4544. return l->y + 8;
  4545. }
  4546. static int deferred_cmp(const struct br_deferred *a,
  4547. const struct br_deferred *b)
  4548. {
  4549. int az = a->z_set ? a->z_index : 0;
  4550. int bz = b->z_set ? b->z_index : 0;
  4551. if (az != bz)
  4552. return az < bz ? -1 : 1;
  4553. if (a->order != b->order)
  4554. return a->order < b->order ? -1 : 1;
  4555. return 0;
  4556. }
  4557. static void sort_deferred(void)
  4558. {
  4559. int i;
  4560. for (i = 1; i < ndeferred; i++) {
  4561. struct br_deferred key = deferred[i];
  4562. int j = i;
  4563. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  4564. deferred[j] = deferred[j - 1];
  4565. j--;
  4566. }
  4567. deferred[j] = key;
  4568. }
  4569. }
  4570. static void render_page(int left, int right, int y0)
  4571. {
  4572. struct lay *l = &layout_state;
  4573. struct br_style base = base_style();
  4574. l->draw = 1;
  4575. l->ui = &ui;
  4576. l->left = left;
  4577. l->right = right;
  4578. l->y = y0;
  4579. l->line_x = left;
  4580. l->run_x = left;
  4581. l->line_y = y0;
  4582. l->line_h = 0;
  4583. l->align = BR_ALIGN_LEFT;
  4584. l->depth = 0;
  4585. l->nruns = 0;
  4586. l->space_pending = 0;
  4587. nhits = 0;
  4588. ndeferred = 0;
  4589. layout_children(l, doc.root, &base, 0, 0);
  4590. sort_deferred();
  4591. {
  4592. int i;
  4593. for (i = 0; i < ndeferred; i++) {
  4594. struct br_style st;
  4595. br_style_for(&doc, deferred[i].node, &base, &st);
  4596. if (st.display == BR_DISPLAY_NONE)
  4597. continue;
  4598. l->draw = 1;
  4599. l->left = deferred[i].flow_left;
  4600. l->right = deferred[i].flow_right;
  4601. l->y = deferred[i].flow_y;
  4602. l->line_x = l->left;
  4603. l->run_x = l->left;
  4604. l->line_y = l->y;
  4605. l->line_h = 0;
  4606. l->nruns = 0;
  4607. l->space_pending = 0;
  4608. l->align = st.align;
  4609. if (st.pos == 2 && block_h[deferred[i].node]) {
  4610. struct ngui_rect clip;
  4611. int ch = block_h[deferred[i].node] + 24;
  4612. clip.x = page_rect.x;
  4613. clip.y = page_rect.y;
  4614. clip.w = page_rect.w - 12;
  4615. if (ch > page_rect.h)
  4616. ch = page_rect.h;
  4617. clip.h = ch;
  4618. ngui_push_clip(&ui, clip);
  4619. if (st.has_bg)
  4620. ngui_fill_rect(&ui, clip, st.bg);
  4621. layout_block(l, deferred[i].node, &st, 0,
  4622. deferred[i].link);
  4623. ngui_pop_clip(&ui);
  4624. } else {
  4625. layout_block(l, deferred[i].node, &st, 0,
  4626. deferred[i].link);
  4627. }
  4628. }
  4629. }
  4630. }
  4631. /* ---- UI ---- */
  4632. static int find_hit(int x, int y)
  4633. {
  4634. int i;
  4635. for (i = nhits - 1; i >= 0; i--) {
  4636. struct hit *h = &hits[i];
  4637. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  4638. y < h->y + h->h)
  4639. return (int)h->node;
  4640. }
  4641. return 0;
  4642. }
  4643. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  4644. {
  4645. int x = r.x + 4, y = r.y + 4, h = 22;
  4646. int compact = r.w < 560;
  4647. int go_w = r.w < 420 ? 32 : 42;
  4648. int in_x, in_w, res;
  4649. ngui_fill_rect(&ui, r, ui.theme.panel);
  4650. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  4651. ui.theme.border);
  4652. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  4653. NGUI_ICON_CHEVRON_LEFT))
  4654. *action |= ACT_BACK;
  4655. x += 32;
  4656. if (!compact) {
  4657. if (ngui_icon_button(&ui, ID_FORWARD,
  4658. (struct ngui_rect){x, y, 28, h},
  4659. NGUI_ICON_CHEVRON_RIGHT))
  4660. *action |= ACT_FORWARD;
  4661. x += 32;
  4662. }
  4663. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  4664. NGUI_ICON_REFRESH))
  4665. *action |= ACT_RELOAD;
  4666. x += 32;
  4667. if (!compact) {
  4668. if (ngui_icon_button(&ui, ID_HOME,
  4669. (struct ngui_rect){x, y, 28, h},
  4670. NGUI_ICON_HOME))
  4671. *action |= ACT_HOME;
  4672. x += 32;
  4673. }
  4674. in_x = x + 2;
  4675. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  4676. if (in_w < 60)
  4677. in_w = 60;
  4678. res = ngui_text_input(&ui, ID_URL,
  4679. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  4680. if (res & NGUI_INPUT_SUBMIT)
  4681. *action |= ACT_NAV;
  4682. if (res & NGUI_INPUT_CANCEL)
  4683. ngui_set_focus(&ui, 0);
  4684. if (ngui_button(&ui, ID_GO,
  4685. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  4686. "Go"))
  4687. *action |= ACT_NAV;
  4688. }
  4689. static int page_hover_node(void)
  4690. {
  4691. if (!ui.inside)
  4692. return 0;
  4693. if (ui.mouse_x < page_rect.x ||
  4694. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  4695. ui.mouse_y < page_rect.y ||
  4696. ui.mouse_y >= page_rect.y + page_rect.h)
  4697. return 0;
  4698. return find_hit(ui.mouse_x, ui.mouse_y);
  4699. }
  4700. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  4701. {
  4702. int x, y, w = page.w, h = page.h;
  4703. if (!src || w <= 0 || h <= 0)
  4704. return;
  4705. for (y = 0; y < h; y++) {
  4706. unsigned short *s = src + (page.y + y) * sw + page.x;
  4707. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  4708. for (x = 0; x + 1 < w; x += 2) {
  4709. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  4710. }
  4711. if (x < w)
  4712. d[x] = s[x];
  4713. }
  4714. }
  4715. static void draw_page(struct ngui_rect page)
  4716. {
  4717. int left, right, ch;
  4718. int old_panel, old_dim;
  4719. unsigned short *saved_px;
  4720. int saved_w, saved_h, use_buf;
  4721. page_rect = page;
  4722. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  4723. page_cache_valid && layout_valid &&
  4724. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  4725. page_scroll.offset == page_cache_scroll &&
  4726. page_cache_nnode == doc.nnode &&
  4727. page_cache_x == page.x && page_cache_y == page.y &&
  4728. page_cache_w == page.w && page_cache_h == page.h) {
  4729. blit_page(page, page_backbuf, pagebuf_w);
  4730. return;
  4731. }
  4732. ngui_fill_rect(&ui, page, ui.theme.bg);
  4733. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  4734. const char *s = page_loading ? "Loading..." : "No page";
  4735. int w = (int)ngui_text_width_ui(&ui, s);
  4736. ngui_text(&ui, page.x + (page.w - w) / 2,
  4737. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  4738. page_scroll.content_h = 0;
  4739. page_scroll.view_h = page.h;
  4740. page_cache_valid = 0;
  4741. return;
  4742. }
  4743. if (page.w < 40 || page.h < 40) {
  4744. page_cache_valid = 0;
  4745. return;
  4746. }
  4747. saved_px = ui.px;
  4748. saved_w = ui.w;
  4749. saved_h = ui.h;
  4750. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  4751. if (use_buf) {
  4752. ui.px = page_backbuf;
  4753. ui.w = pagebuf_w;
  4754. ui.h = pagebuf_h;
  4755. ngui_fill_rect(&ui, page, ui.theme.bg);
  4756. }
  4757. left = page.x + 8;
  4758. right = page.x + page.w - 16;
  4759. if (!layout_valid || left != layout_left || right != layout_right ||
  4760. layout_nnode != doc.nnode) {
  4761. layout_content_h = measure_page(left, right);
  4762. layout_valid = 1;
  4763. layout_left = left;
  4764. layout_right = right;
  4765. layout_nnode = doc.nnode;
  4766. }
  4767. ch = layout_content_h;
  4768. page_scroll.content_h = ch;
  4769. page_scroll.view_h = page.h;
  4770. ngui_scroll_begin(&ui, page, &page_scroll);
  4771. render_page(left, right, page.y + 4 - page_scroll.offset);
  4772. old_panel = ui.theme.panel_alt;
  4773. old_dim = ui.theme.text_dim;
  4774. ui.theme.panel_alt = 0xC618;
  4775. ui.theme.text_dim = 0x8410;
  4776. ngui_scroll_end(&ui, page, &page_scroll);
  4777. ui.theme.panel_alt = old_panel;
  4778. ui.theme.text_dim = old_dim;
  4779. if (use_buf) {
  4780. ui.px = saved_px;
  4781. ui.w = saved_w;
  4782. ui.h = saved_h;
  4783. blit_page(page, page_backbuf, pagebuf_w);
  4784. page_cache_valid = 1;
  4785. page_cache_scroll = page_scroll.offset;
  4786. page_cache_nnode = doc.nnode;
  4787. page_cache_x = page.x;
  4788. page_cache_y = page.y;
  4789. page_cache_w = page.w;
  4790. page_cache_h = page.h;
  4791. } else {
  4792. page_cache_valid = 0;
  4793. }
  4794. }
  4795. static void draw_status(struct ngui_rect r)
  4796. {
  4797. char msg[BR_URL_MAX + 32];
  4798. unsigned int n = 0;
  4799. int hover = page_hover_node();
  4800. unsigned short color;
  4801. const char *kind;
  4802. ngui_fill_rect(&ui, r, ui.theme.panel);
  4803. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  4804. ui.theme.border);
  4805. if (hover) {
  4806. const char *href = br_href(&doc, (unsigned int)hover);
  4807. char url[BR_URL_MAX];
  4808. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  4809. s_append(msg, &n, "Link: ", sizeof(msg));
  4810. s_append(msg, &n, url, sizeof(msg));
  4811. } else {
  4812. s_copy(msg, "Link", sizeof(msg));
  4813. }
  4814. color = ui.theme.accent;
  4815. } else if (status_text[0]) {
  4816. s_copy(msg, status_text, sizeof(msg));
  4817. color = status_error ? ui.theme.error : ui.theme.text;
  4818. } else if (page_title[0]) {
  4819. s_copy(msg, page_title, sizeof(msg));
  4820. color = ui.theme.text;
  4821. } else {
  4822. s_copy(msg, "Ready", sizeof(msg));
  4823. color = ui.theme.text_dim;
  4824. }
  4825. kind = s_eq(page_url, "about:home") ? "HOME" :
  4826. page_is_local ? "FILE" :
  4827. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  4828. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  4829. {
  4830. int kw = (int)ngui_text_width_ui(&ui, kind);
  4831. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  4832. ui.theme.text_dim);
  4833. }
  4834. }
  4835. static void draw(unsigned int *action)
  4836. {
  4837. struct ngui_rect r = {0, 0, ui.w, ui.h};
  4838. struct ngui_rect toolbar, status, page;
  4839. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  4840. status = ngui_cut_bottom(&r, BR_STATUS_H);
  4841. page = r;
  4842. draw_toolbar(toolbar, action);
  4843. draw_page(page);
  4844. draw_status(status);
  4845. }
  4846. static void redraw_now(void)
  4847. {
  4848. unsigned int action = 0;
  4849. ngui_begin(&ui);
  4850. draw(&action);
  4851. ngui_end(&ui);
  4852. }
  4853. static void handle_keys(unsigned int *action)
  4854. {
  4855. int k, scrolled = 0;
  4856. /* Batch queued page keys: a slow full-page render must not make a
  4857. * held Page Down advance only once every few frames. */
  4858. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  4859. scrolled++;
  4860. if (scrolled)
  4861. ngui_invalidate(&ui);
  4862. if (ngui_focus(&ui))
  4863. return;
  4864. while ((k = ngui_key(&ui)) != 0) {
  4865. switch (k) {
  4866. case NGUI_KEY_ESC:
  4867. *action |= ACT_CLOSE;
  4868. break;
  4869. case NGUI_KEY_TAB:
  4870. case 0x0C: /* Ctrl+L */
  4871. ngui_set_focus(&ui, ID_URL);
  4872. break;
  4873. case 0x12: /* Ctrl+R */
  4874. *action |= ACT_RELOAD;
  4875. break;
  4876. case NGUI_KEY_BACKSPACE:
  4877. *action |= ACT_BACK;
  4878. break;
  4879. case NGUI_KEY_UP:
  4880. ngui_scroll_to(&page_scroll,
  4881. page_scroll.offset - 24);
  4882. ngui_invalidate(&ui);
  4883. break;
  4884. case NGUI_KEY_DOWN:
  4885. ngui_scroll_to(&page_scroll,
  4886. page_scroll.offset + 24);
  4887. ngui_invalidate(&ui);
  4888. break;
  4889. case NGUI_KEY_HOME:
  4890. ngui_scroll_to(&page_scroll, 0);
  4891. ngui_invalidate(&ui);
  4892. break;
  4893. case NGUI_KEY_END:
  4894. ngui_scroll_to(&page_scroll,
  4895. page_scroll.content_h -
  4896. page_scroll.view_h);
  4897. ngui_invalidate(&ui);
  4898. break;
  4899. default:
  4900. break;
  4901. }
  4902. }
  4903. }
  4904. static void handle_page_click(unsigned int *action)
  4905. {
  4906. int node;
  4907. char url[BR_URL_MAX];
  4908. if (!ui.pressed)
  4909. return;
  4910. if (ui.press_x < page_rect.x ||
  4911. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  4912. ui.press_y < page_rect.y ||
  4913. ui.press_y >= page_rect.y + page_rect.h)
  4914. return;
  4915. node = find_hit(ui.press_x, ui.press_y);
  4916. if (!node)
  4917. return;
  4918. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  4919. sizeof(url)) != 0)
  4920. return;
  4921. s_copy(click_url, url, sizeof(click_url));
  4922. *action |= ACT_NAV;
  4923. }
  4924. void _start(const char *arg)
  4925. {
  4926. struct win_info wi;
  4927. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  4928. u_win_create(960, 640, "Browser", &wi) != 0 &&
  4929. u_win_create(780, 540, "Browser", &wi) != 0) {
  4930. u_puts("browser: no graphics window\n");
  4931. u_exit(1);
  4932. }
  4933. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  4934. url_in.placeholder = "http://...";
  4935. br_doc_init(&doc);
  4936. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  4937. ui.theme.accent);
  4938. br_set_viewport(wi.width);
  4939. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  4940. s_copy(cwd, "/", sizeof(cwd));
  4941. heap_clear();
  4942. origin_cache_load();
  4943. css_cache_init();
  4944. script_cache_init();
  4945. page_scroll.offset = 0;
  4946. page_scroll.content_h = 0;
  4947. if (arg && arg[0]) {
  4948. navigate(arg, 1);
  4949. } else {
  4950. load_home(1);
  4951. /* Start ready to type: keep the home page, but leave the address
  4952. * bar empty instead of showing "about:home". */
  4953. ngui_input_set(&url_in, "");
  4954. ngui_set_focus(&ui, ID_URL);
  4955. }
  4956. for (;;) {
  4957. unsigned int action = 0;
  4958. unsigned int now;
  4959. click_url[0] = '\0';
  4960. if (pending_action) {
  4961. action |= pending_action & ACT_WAIT_NAV;
  4962. if (pending_url[0])
  4963. s_copy(click_url, pending_url, sizeof(click_url));
  4964. pending_action = 0;
  4965. pending_url[0] = '\0';
  4966. cancel_fetch = 0;
  4967. } else if (preload_active) {
  4968. if (preload_wait)
  4969. preload_wait = 0;
  4970. else
  4971. preload_step();
  4972. } else if (preload_pending &&
  4973. page_scroll.offset != preload_scroll) {
  4974. preload_scroll = page_scroll.offset;
  4975. preload_pending = 0;
  4976. preload_node = 0;
  4977. preload_active = 1;
  4978. }
  4979. js_browser_tick();
  4980. if (pending_action)
  4981. continue;
  4982. now = u_ticks_ms();
  4983. if (status_until && (int)(now - status_until) >= 0) {
  4984. status_text[0] = '\0';
  4985. status_until = 0;
  4986. status_error = 0;
  4987. ngui_invalidate(&ui);
  4988. }
  4989. if (!ngui_begin(&ui)) {
  4990. /* A queued navigation (e.g. Enter in the URL bar during
  4991. * a slow fetch) must be handled even when this frame
  4992. * needs no redraw. */
  4993. if (!action) {
  4994. u_sleep_ms(10);
  4995. continue;
  4996. }
  4997. } else {
  4998. draw(&action);
  4999. handle_keys(&action);
  5000. handle_page_click(&action);
  5001. ngui_end(&ui);
  5002. }
  5003. if (action & ACT_NAV) {
  5004. if (click_url[0]) {
  5005. navigate(click_url, 1);
  5006. click_url[0] = '\0';
  5007. } else {
  5008. navigate(url_in.text, 1);
  5009. }
  5010. }
  5011. if (action & ACT_BACK) {
  5012. if (hist_pos > 0) {
  5013. hist_pos--;
  5014. navigate(history[hist_pos], 0);
  5015. }
  5016. }
  5017. if (action & ACT_FORWARD) {
  5018. if (hist_pos + 1 < hist_len) {
  5019. hist_pos++;
  5020. navigate(history[hist_pos], 0);
  5021. }
  5022. }
  5023. if (action & ACT_RELOAD) {
  5024. if (s_eq(page_url, "about:home"))
  5025. load_home(0);
  5026. else
  5027. navigate(page_url, 0);
  5028. }
  5029. if (action & ACT_HOME)
  5030. load_home(1);
  5031. if (action & ACT_CLOSE)
  5032. quit = 1;
  5033. if (quit)
  5034. break;
  5035. if (pending_action)
  5036. continue;
  5037. u_sleep_ms(10);
  5038. }
  5039. fetch_helper_stop();
  5040. u_win_close();
  5041. u_exit(0);
  5042. }