browser.c 113 KB

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