GIF89a=( õ' 7IAXKgNgYvYx\%wh…hŽth%ˆs%—x¨}9®Œ©€&©‰%¶†(¹–.¹5·œD¹&Çš)ÇŸ5ǘ;Í£*È¡&Õ²)ׯ7×µ<Ñ»4ï°3ø‘HÖ§KͯT÷¨Yÿšqÿ»qÿÔFØ !ù ' !ÿ NETSCAPE2.0 , =( þÀ“pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§gª«ªE¯°¨¬ª±²Œ¹º¹E¾­”´ÂB¶¯ §Åȸ»ÑD¾¿Á•ÄÅ®° ÝH¾ÒLÀÆDÙ«D¶BÝïðÀ¾DÑÑÔTÌÍíH òGö¨A RÎڐ |¥ ٭&ºìE8œ¹kGÔAÞpx­a¶­ã R2XB®åE8I€Õ6Xî:vT)äžþÀq¦è³¥ì仕F~%xñ  4#ZÔ‰O|-4Bs‘X:= QÉ œš lºÒyXJŠGȦ|s hÏíK–3l7·B|¥$'7Jީܪ‰‡àá”Dæn=Pƒ ¤Òëí‰`䌨ljóá¯Éüv>á–Á¼5 ½.69ûϸd«­ºÀûnlv©‹ªîf{¬ÜãPbŸ  l5‘ޝpß ´ ˜3aÅùäI«O’ý·‘áÞ‡˜¾Æ‚ÙÏiÇÿ‹Àƒ #öó)pâš Þ½ ‘Ý{ó)vmÞü%D~ 6f s}ŃƒDØW Eþ`‡þ À…L8xá†ç˜{)x`X/> Ì}mø‚–RØ‘*|`D=‚Ø_ ^ð5 !_…'aä“OÚ—7âcð`D”Cx`ÝÂ¥ä‹éY¹—F¼¤¥Š?¡Õ™ n@`} lď’ÄÉ@4>ñd œ à‘vÒxNÃ×™@žd=ˆgsžG±æ ´²æud &p8Qñ)ˆ«lXD©øÜéAžHìySun jª×k*D¤LH] †¦§C™Jä–´Xb~ʪwStŽ6K,°£qÁœ:9ت:¨þªl¨@¡`‚ûÚ ».Û¬¯t‹ÆSÉ[:°=Š‹„‘Nåû”Ìî{¿ÂA ‡Rà›ÀÙ6úë°Ÿð0Ä_ ½;ÃϱîÉì^ÇÛÇ#Ëë¼ôº!±Ä˜íUîÅÇ;0L1óÁµö«p% AÀºU̬ݵ¼á%霼€‡¯Á~`ÏG¯»À× ­²± =4ªnpð3¾¤³¯­ü¾¦îuÙuµÙ®|%2ÊIÿür¦#0·ÔJ``8È@S@5ê¢ ö×Þ^`8EÜ]ý.뜃Âç 7 ú ȉÞj œ½Dç zý¸iþœÑÙûÄë!ˆÞÀl§Ïw‹*DçI€nEX¯¬¼ &A¬Go¼QföõFç°¯;é¦÷îŽêJ°îúôF5¡ÌQ|îúöXªæ»TÁÏyñêï]ê² o óÎC=öõ›ÒÓPB@ D×½œä(>èCÂxŽ`±«Ÿ–JЀ»Û á¤±p+eE0`ëŽ`A Ú/NE€Ø†À9‚@¤à H½7”à‡%B‰`Àl*ƒó‘–‡8 2ñ%¸ —€:Ù1Á‰E¸àux%nP1ð!‘ðC)¾P81lÑɸF#ˆ€{´âé°ÈB„0>±û °b¡Š´±O‚3È–Ù()yRpbµ¨E.Z‘D8ÊH@% òŒx+%Ù˜Æcü »¸˜fõ¬b·d`Fê™8èXH"ÉÈ-±|1Ô6iI, 2““¬$+](A*jÐ QTÂo‰.ÛU슬Œã„Ž`¯SN¡–¶Äåyše¯ª’­¬‚´b¦Éož œ)åyâ@Ì®3 ÎtT̉°&Ø+žLÀf"Ø-|žçÔ>‡Ðv¦Ðžì\‚ Q1)Ž@Žh#aP72”ˆ™¨$‚ !ù " , =( …7IAXG]KgNgYvYxR"k\%w]'}hŽth%ˆg+ˆs%—r.—m3šx3˜x¨}9®€&©€+¨‡7§‰%¶†(¹–.¹œD¹&ǘ;Í•&ײ)×»4ïÌ6ò§KÍ þ@‘pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§g «¬ E ±± ¨­¶°ººE Á´”·®C¬²§Ç¶Œ»ÓDÃÕƷ¯Ê±H½ºM×ÁGÚ¬D¶BËÁ½î½DÓôTÏÛßîG»ôõC×CÌ l&âž:'òtU³6ɹ#·Ø)€'Ü.6±&ëÍÈ» K(8p0N?!æ2"ÛˆNIJX>R¼ÐO‚M '¡¨2¸*Ÿþ>#n↠å@‚<[:¡Iïf’ ¤TÚ˘CdbÜÙ“[«ŽEú5MBo¤×@€`@„€Êt W-3 ¶Ÿ¡BíêäjIÝ…Eò9[T…$íêﯧ„…•s»Óȳ¹€ÅÚdc®UUρ#±Ùïldj?´í¼²`\ŽÁðÞu|3'ÖŒ]ë6 ¶S#²‡˜FKLÈ *N E´‘áäŠ$˜›eÄYD„ºq«.è촁ƒs \-ÔjA 9²õ÷å- üúM[Âx(ís÷ì®x€|í¡Ù’p¦‚ ŽkÛTÇDpE@WÜ ²Ç]kŠ1¨ þ€·Yb ÓÁ‰l°*n0 ç™—žzBdОu¾7ĉBl€â‰-ºx~|UåU‰  h*Hœ|e"#"?vpÄiŠe6^ˆ„+qâŠm8 #VÇá ‘å–ÄV„œ|Аè•m"сœn|@›U¶ÆÎž—Špb¥G¨ED”€±Úê2FÌIç? >Éxå Œ± ¡¤„%‘žjŸ‘ꄯ<Ìaà9ijÐ2˜D¦È&›†Z`‚å]wþ¼Â:ç6àB¤7eFJ|õÒ§Õ,¨äàFÇ®cS·Ê¶+B°,‘Þ˜ºNûãØ>PADÌHD¹æž«ÄÀnÌ¥}­#Ë’ë QÀÉSÌÂÇ2ÌXÀ{æk²lQÁ2«ÊðÀ¯w|2Í h‹ÄÂG€,m¾¶ë3ÐÙ6-´ÅE¬L°ÆIij*K½ÀÇqï`DwVÍQXœÚÔpeœ±¬Ñ q˜§Tœ½µƒ°Œìu Â<¶aØ*At¯lmEØ ü ôÛN[P1ÔÛ¦­±$ÜÆ@`ùåDpy¶yXvCAyåB`ŽD¶ 0QwG#¯ æš[^Äþ $ÀÓÝǦ{„L™[±úKÄgÌ;ï£S~¹ìGX.ôgoT.»åˆ°ùŸûù¡?1zö¦Ÿž:ÅgÁ|ìL¹ „®£œŠ‚à0œ]PÁ^p F<"•ç?!,ñ‡N4—…PÄ Á„ö¨Û:Tè@hÀ‹%táÿ:ø-žI<`þ‹p I….)^ 40D#p@ƒj4–؀:²‰1Øâr˜¼F2oW¼#Z†;$Q q” ‘ ÂK¦ñNl#29 !’F@¥Bh·ᏀL!—XFóLH‘Kh¤.«hE&JòG¨¥<™WN!€ÑÙÚˆY„@†>Œž19J" 2,/ &.GXB%ÌRÈ9B6¹W]’î×ÔW¥’IÎ$ ñ‹ÓŒE8YÆ ¼³™ñA5“à®Q.aŸB€&Ø©³ JÁ—! ¦t)K%tœ-¦JF bòNMxLôþ)ÐR¸Ð™‘ èÝ6‘O!THÌ„HÛ ‰ !ù ) , =( …AXKgNgYvYxR"k\%wh…hŽh%ˆg+ˆs%—r.—x3˜x¨}9®€&©€+¨Œ,©‡7§‰%¶†(¹–.¹5·&Çš)ǘ;Í•&×£*Ȳ)ׯ7×»4ï°3øÌ6ò‘HÖ§KÍ»Hó¯T÷¨Yÿ»qÿÇhÿ þÀ”pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§g ª« E$±²¨ª­ · °²½$E$ÂÕ««D· Í ¿¦Ç¶¸ÌŒ¾³CÃÅÆ E ééH½MÛÂGâªD­ çBêêϾD²ÒaÀà€Š1r­ðÓ¤ ÔožzU!L˜C'¾yW½UGtäÇïÙllê0×àÂuGþ)AÀs[þ·xì ÁxO%ƒûX2ó—  P£n›R/¡ÑšHše+êDm?# —‘Ç£6¡8íJ¡ŸâDiäªM¥Ö„ôj“¬¹£5oQ7°- <‡ *´lãÓŒ2r/a!l)dÈ A™ÈE¢ôÔ͆…ð ;Ö˜c ¡%ß‚’Ùˆâ¸b½—pe~C"BíëÚHïeF2§æŠ8qb t_`urŠeü wÅu3êæPv§h•"ß`íÍxçLĹÜÖ3á  ~Öº“®›¸ÏMDfJÙ °„ÛµáWõ%§œ‚à©–‚X ÓØ)@®Ñ›Eþ´wëuÅSxb8y\mÖzœ¥§ZbºE—ÂLªÌw!y(>¡™wú=Ç|ÅÝs¢d €CÁW)HÜcC$€L Ä7„r.á\{)@ð` @ äXÈ$PD” `šaG:§æˆOˆ72EÐamn]ù"ŒcÊxÑŒ° &dR8`g«iÙŸLR!¦P …d’ä¡“¦ðÎTƒ¦ià|À _ ¥ Qi#¦Šg›Æ ›noMµ ›V ã£)p ç£ÎW…š=Âeªk§†j„ ´®1ß²sÉxéW«jšl|0¯B0Û, \jÛ´›6±¬¶C ÛíWþï|ëÙ‹¸ñzĸV {ì;Ýñn¼òVˆm³I¼³.Ðã¤PN¥ ²µ¼„µCã+¹ÍByî£Ñ¾HŸ›ëê 7ìYÆFTk¨SaoaY$Dµœìï¿Ã29RÈkt Çïfñ ÇÒ:ÀÐSp¹3ÇI¨â¥DZÄ ü9Ïýögñ½­uÔ*3)O‘˜Ö[_hv ,àî×Et Ÿé¶BH€ Õ[ü±64M@ÔSÌM7dÐl5-ÄÙU܍´©zߌ3Ô€3ž„ „ ¶ÛPô½5×g› êÚ˜kN„Ý…0Îj4€Ìë°“#{þÕ3S2çKÜ'ợlø¼Ú2K{° {Û¶?žm𸧠ËI¼nEò='êüóºè^üæÃ_Û=°óž‚ì#Oý¿Í'¡½áo..ÏYìnüñCœO±Áa¿¢Kô½o,üÄËbö²çºíï{ËC Ú— "”Ï{ËK ÍÒw„õ±Oz dÕ¨à:$ ƒô—«v»] A#ð «€¿šéz)Rx׿ˆ¥‚d``èw-îyÏf×K!ð€þ­Ð|ìPľ„=Ì`ý(f” 'Pa ¥ÐBJa%Ðâf§„%Š¡}FàáÝ×6>ÉäŠG"éŽè=ø!oа^FP¼Ø©Q„ÀCÙÁ`(Ž\ÄÝ® ©Â$<n@dÄ E#ììUÒI! ‚#lù‹`k¦ÐÇ'Rró’ZýNBÈMF Í[¤+‹ðɈ-áwj¨¥þ8¾rá ,VÂh„"|½œ=×G_¦Ñ™EØ 0i*%̲˜Æda0mV‚k¾)›;„&6 p>ÓjK “¦Ç# âDÂ:ûc?:R Ó¬fÞéI-Ì“•Ã<ä=™Ï7˜3œ¨˜c2ŒW ,ˆ”8(T™P‰F¡Jhç"‚ ; 403WebShell
403Webshell
Server IP : 143.110.188.43  /  Your IP : 216.73.217.31
Web Server : Apache/2.4.57 (Ubuntu)
System : Linux Client-Droplet 6.5.0-44-generic #44-Ubuntu SMP PREEMPT_DYNAMIC Fri Jun 7 15:10:09 UTC 2024 x86_64
User : www-data ( 33)
PHP Version : 8.2.10-2ubuntu2.2
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : OFF
Directory :  /snap/core26/current/usr/lib/python3.14/_pyrepl/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /snap/core26/current/usr/lib/python3.14/_pyrepl//terminfo.py
"""Pure Python curses-like terminal capability queries."""

from dataclasses import dataclass, field
import errno
import os
from pathlib import Path
import re
import struct


# Terminfo constants
MAGIC16 = 0o432  # Magic number for 16-bit terminfo format
MAGIC32 = 0o1036  # Magic number for 32-bit terminfo format

# Special values for absent/cancelled capabilities
ABSENT_BOOLEAN = -1
ABSENT_NUMERIC = -1
CANCELLED_NUMERIC = -2
ABSENT_STRING = None
CANCELLED_STRING = None


# Standard string capability names from ncurses Caps file
# This matches the order used by ncurses when compiling terminfo
# fmt: off
_STRING_NAMES: tuple[str, ...] = (
    "cbt", "bel", "cr", "csr", "tbc", "clear", "el", "ed", "hpa", "cmdch",
    "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1", "ll",
    "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold",
    "smcup", "smdc", "dim", "smir", "invis", "prot", "rev", "smso", "smul",
    "ech", "rmacs", "sgr0", "rmcup", "rmdc", "rmir", "rmso", "rmul", "flash",
    "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip", "kbs", "ktbc",
    "kclr", "kctab", "kdch1", "kdl1", "kcud1", "krmir", "kel", "ked", "kf0",
    "kf1", "kf10", "kf2", "kf3", "kf4", "kf5", "kf6", "kf7", "kf8", "kf9",
    "khome", "kich1", "kil1", "kcub1", "kll", "knp", "kpp", "kcuf1", "kind",
    "kri", "khts", "kcuu1", "rmkx", "smkx", "lf0", "lf1", "lf10", "lf2", "lf3",
    "lf4", "lf5", "lf6", "lf7", "lf8", "lf9", "rmm", "smm", "nel", "pad", "dch",
    "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey",
    "pfloc", "pfx", "mc0", "mc4", "mc5", "rep", "rs1", "rs2", "rs3", "rf", "rc",
    "vpa", "sc", "ind", "ri", "sgr", "hts", "wind", "ht", "tsl", "uc", "hu",
    "iprog", "ka1", "ka3", "kb2", "kc1", "kc3", "mc5p", "rmp", "acsc", "pln",
    "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "enacs", "smln",
    "rmln", "kbeg", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "kend", "kent",
    "kext", "kfnd", "khlp", "kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt",
    "kprv", "kprt", "krdo", "kref", "krfr", "krpl", "krst", "kres", "ksav",
    "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "kDC", "kDL",
    "kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "kIC", "kLFT",
    "kMSG", "kMOV", "kNXT", "kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT",
    "kRES", "kSAV", "kSPD", "kUND", "rfi", "kf11", "kf12", "kf13", "kf14",
    "kf15", "kf16", "kf17", "kf18", "kf19", "kf20", "kf21", "kf22", "kf23",
    "kf24", "kf25", "kf26", "kf27", "kf28", "kf29", "kf30", "kf31", "kf32",
    "kf33", "kf34", "kf35", "kf36", "kf37", "kf38", "kf39", "kf40", "kf41",
    "kf42", "kf43", "kf44", "kf45", "kf46", "kf47", "kf48", "kf49", "kf50",
    "kf51", "kf52", "kf53", "kf54", "kf55", "kf56", "kf57", "kf58", "kf59",
    "kf60", "kf61", "kf62", "kf63", "el1", "mgc", "smgl", "smgr", "fln", "sclk",
    "dclk", "rmclk", "cwin", "wingo", "hup","dial", "qdial", "tone", "pulse",
    "hook", "pause", "wait", "u0", "u1", "u2", "u3", "u4", "u5", "u6", "u7",
    "u8", "u9", "op", "oc", "initc", "initp", "scp", "setf", "setb", "cpi",
    "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm",
    "snlq", "snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm",
    "rmicm", "rshm", "rsubm", "rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1",
    "mvpa", "mcuu1", "porder", "mcud", "mcub", "mcuf", "mcuu", "scs", "smgb",
    "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd", "rbim", "rcsd",
    "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp",
    "getm", "setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds",
    "s3ds", "smglr", "smgtb", "birep", "binel", "bicr", "colornm", "defbi",
    "endbi", "setcolor", "slines", "dispc", "smpch", "rmpch", "smsc", "rmsc",
    "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm", "ethlm",
    "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbc", "OTko", "OTma",
    "OTG2", "OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH",
    "OTGV", "OTGC","meml", "memu", "box1"
)
# fmt: on


def _get_terminfo_dirs() -> list[Path]:
    """Get list of directories to search for terminfo files.

    Based on ncurses behavior in:
    - ncurses/tinfo/db_iterator.c:_nc_next_db()
    - ncurses/tinfo/read_entry.c:_nc_read_entry()
    """
    dirs = []

    terminfo = os.environ.get("TERMINFO")
    if terminfo:
        dirs.append(terminfo)

    try:
        home = Path.home()
        dirs.append(str(home / ".terminfo"))
    except RuntimeError:
        pass

    # Check TERMINFO_DIRS
    terminfo_dirs = os.environ.get("TERMINFO_DIRS", "")
    if terminfo_dirs:
        for d in terminfo_dirs.split(":"):
            if d:
                dirs.append(d)

    dirs.extend(
        [
            "/etc/terminfo",
            "/lib/terminfo",
            "/usr/lib/terminfo",
            "/usr/share/terminfo",
            "/usr/share/lib/terminfo",
            "/usr/share/misc/terminfo",
            "/usr/local/lib/terminfo",
            "/usr/local/share/terminfo",
        ]
    )

    return [Path(d) for d in dirs if Path(d).is_dir()]


def _validate_terminal_name_or_raise(terminal_name: str) -> None:
    if not isinstance(terminal_name, str):
        raise TypeError("`terminal_name` must be a string")

    if not terminal_name:
        raise ValueError("`terminal_name` cannot be empty")

    if "\x00" in terminal_name:
        raise ValueError("NUL character found in `terminal_name`")

    t = Path(terminal_name)
    if len(t.parts) > 1:
        raise ValueError("`terminal_name` cannot contain path separators")


def _read_terminfo_file(terminal_name: str) -> bytes:
    """Find and read terminfo file for given terminal name.

    Terminfo files are stored in directories using the first character
    of the terminal name as a subdirectory.
    """
    _validate_terminal_name_or_raise(terminal_name)
    first_char = terminal_name[0].lower()
    filename = terminal_name

    for directory in _get_terminfo_dirs():
        path = directory / first_char / filename
        if path.is_file():
            return path.read_bytes()

        # Try with hex encoding of first char (for special chars)
        hex_dir = "%02x" % ord(first_char)
        path = directory / hex_dir / filename
        if path.is_file():
            return path.read_bytes()

    raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), filename)


# Hard-coded terminal capabilities for common terminals
# This is a minimal subset needed by PyREPL
_TERMINAL_CAPABILITIES = {
    # ANSI/xterm-compatible terminals
    "ansi": {
        # Bell
        "bel": b"\x07",
        # Cursor movement
        "cub": b"\x1b[%p1%dD",  # Move cursor left N columns
        "cud": b"\x1b[%p1%dB",  # Move cursor down N rows
        "cuf": b"\x1b[%p1%dC",  # Move cursor right N columns
        "cuu": b"\x1b[%p1%dA",  # Move cursor up N rows
        "cub1": b"\x08",  # Move cursor left 1 column
        "cud1": b"\n",  # Move cursor down 1 row
        "cuf1": b"\x1b[C",  # Move cursor right 1 column
        "cuu1": b"\x1b[A",  # Move cursor up 1 row
        "cup": b"\x1b[%i%p1%d;%p2%dH",  # Move cursor to row, column
        "hpa": b"\x1b[%i%p1%dG",  # Move cursor to column
        # Clear operations
        "clear": b"\x1b[H\x1b[2J",  # Clear screen and home cursor
        "el": b"\x1b[K",  # Clear to end of line
        # Insert/delete
        "dch": b"\x1b[%p1%dP",  # Delete N characters
        "dch1": b"\x1b[P",  # Delete 1 character
        "ich": b"\x1b[%p1%d@",  # Insert N characters
        "ich1": b"",  # Insert 1 character
        # Cursor visibility
        "civis": b"\x1b[?25l",  # Make cursor invisible
        "cnorm": b"\x1b[?12l\x1b[?25h",  # Make cursor normal (visible)
        # Scrolling
        "ind": b"\n",  # Scroll up one line
        "ri": b"\x1bM",  # Scroll down one line
        # Keypad mode
        "smkx": b"\x1b[?1h\x1b=",  # Enable keypad mode
        "rmkx": b"\x1b[?1l\x1b>",  # Disable keypad mode
        # Padding (not used in modern terminals)
        "pad": b"",
        # Function keys and special keys
        "kdch1": b"\x1b[3~",  # Delete key
        "kcud1": b"\x1bOB",  # Down arrow
        "kend": b"\x1bOF",  # End key
        "kent": b"\x1bOM",  # Enter key
        "khome": b"\x1bOH",  # Home key
        "kich1": b"\x1b[2~",  # Insert key
        "kcub1": b"\x1bOD",  # Left arrow
        "knp": b"\x1b[6~",  # Page down
        "kpp": b"\x1b[5~",  # Page up
        "kcuf1": b"\x1bOC",  # Right arrow
        "kcuu1": b"\x1bOA",  # Up arrow
        # Function keys F1-F20
        "kf1": b"\x1bOP",
        "kf2": b"\x1bOQ",
        "kf3": b"\x1bOR",
        "kf4": b"\x1bOS",
        "kf5": b"\x1b[15~",
        "kf6": b"\x1b[17~",
        "kf7": b"\x1b[18~",
        "kf8": b"\x1b[19~",
        "kf9": b"\x1b[20~",
        "kf10": b"\x1b[21~",
        "kf11": b"\x1b[23~",
        "kf12": b"\x1b[24~",
        "kf13": b"\x1b[1;2P",
        "kf14": b"\x1b[1;2Q",
        "kf15": b"\x1b[1;2R",
        "kf16": b"\x1b[1;2S",
        "kf17": b"\x1b[15;2~",
        "kf18": b"\x1b[17;2~",
        "kf19": b"\x1b[18;2~",
        "kf20": b"\x1b[19;2~",
    },
    # Dumb terminal - minimal capabilities
    "dumb": {
        "bel": b"\x07",  # Bell
        "cud1": b"\n",  # Move down 1 row (newline)
        "ind": b"\n",  # Scroll up one line (newline)
    },
    # Linux console
    "linux": {
        # Bell
        "bel": b"\x07",
        # Cursor movement
        "cub": b"\x1b[%p1%dD",  # Move cursor left N columns
        "cud": b"\x1b[%p1%dB",  # Move cursor down N rows
        "cuf": b"\x1b[%p1%dC",  # Move cursor right N columns
        "cuu": b"\x1b[%p1%dA",  # Move cursor up N rows
        "cub1": b"\x08",  # Move cursor left 1 column (backspace)
        "cud1": b"\n",  # Move cursor down 1 row (newline)
        "cuf1": b"\x1b[C",  # Move cursor right 1 column
        "cuu1": b"\x1b[A",  # Move cursor up 1 row
        "cup": b"\x1b[%i%p1%d;%p2%dH",  # Move cursor to row, column
        "hpa": b"\x1b[%i%p1%dG",  # Move cursor to column
        # Clear operations
        "clear": b"\x1b[H\x1b[J",  # Clear screen and home cursor (different from ansi!)
        "el": b"\x1b[K",  # Clear to end of line
        # Insert/delete
        "dch": b"\x1b[%p1%dP",  # Delete N characters
        "dch1": b"\x1b[P",  # Delete 1 character
        "ich": b"\x1b[%p1%d@",  # Insert N characters
        "ich1": b"\x1b[@",  # Insert 1 character
        # Cursor visibility
        "civis": b"\x1b[?25l\x1b[?1c",  # Make cursor invisible
        "cnorm": b"\x1b[?25h\x1b[?0c",  # Make cursor normal
        # Scrolling
        "ind": b"\n",  # Scroll up one line
        "ri": b"\x1bM",  # Scroll down one line
        # Keypad mode
        "smkx": b"\x1b[?1h\x1b=",  # Enable keypad mode
        "rmkx": b"\x1b[?1l\x1b>",  # Disable keypad mode
        # Function keys and special keys
        "kdch1": b"\x1b[3~",  # Delete key
        "kcud1": b"\x1b[B",  # Down arrow
        "kend": b"\x1b[4~",  # End key (different from ansi!)
        "khome": b"\x1b[1~",  # Home key (different from ansi!)
        "kich1": b"\x1b[2~",  # Insert key
        "kcub1": b"\x1b[D",  # Left arrow
        "knp": b"\x1b[6~",  # Page down
        "kpp": b"\x1b[5~",  # Page up
        "kcuf1": b"\x1b[C",  # Right arrow
        "kcuu1": b"\x1b[A",  # Up arrow
        # Function keys
        "kf1": b"\x1b[[A",
        "kf2": b"\x1b[[B",
        "kf3": b"\x1b[[C",
        "kf4": b"\x1b[[D",
        "kf5": b"\x1b[[E",
        "kf6": b"\x1b[17~",
        "kf7": b"\x1b[18~",
        "kf8": b"\x1b[19~",
        "kf9": b"\x1b[20~",
        "kf10": b"\x1b[21~",
        "kf11": b"\x1b[23~",
        "kf12": b"\x1b[24~",
        "kf13": b"\x1b[25~",
        "kf14": b"\x1b[26~",
        "kf15": b"\x1b[28~",
        "kf16": b"\x1b[29~",
        "kf17": b"\x1b[31~",
        "kf18": b"\x1b[32~",
        "kf19": b"\x1b[33~",
        "kf20": b"\x1b[34~",
    },
}

# Map common TERM values to capability sets
_TERM_ALIASES = {
    "xterm": "ansi",
    "xterm-color": "ansi",
    "xterm-256color": "ansi",
    "screen": "ansi",
    "screen-256color": "ansi",
    "tmux": "ansi",
    "tmux-256color": "ansi",
    "vt100": "ansi",
    "vt220": "ansi",
    "rxvt": "ansi",
    "rxvt-unicode": "ansi",
    "rxvt-unicode-256color": "ansi",
    "unknown": "dumb",
}


@dataclass
class TermInfo:
    terminal_name: str | bytes | None
    fallback: bool = True

    _capabilities: dict[str, bytes] = field(default_factory=dict)

    def __post_init__(self) -> None:
        """Initialize terminal capabilities for the given terminal type.

        Based on ncurses implementation in:
        - ncurses/tinfo/lib_setup.c:setupterm() and _nc_setupterm()
        - ncurses/tinfo/lib_setup.c:TINFO_SETUP_TERM()

        This version first attempts to read terminfo database files like ncurses,
        then, if `fallback` is True, falls back to hardcoded capabilities for
        common terminal types.
        """
        # If termstr is None or empty, try to get from environment
        if not self.terminal_name:
            self.terminal_name = os.environ.get("TERM") or "ANSI"

        if isinstance(self.terminal_name, bytes):
            self.terminal_name = self.terminal_name.decode("ascii")

        try:
            self._parse_terminfo_file(self.terminal_name)
        except (OSError, ValueError):
            if not self.fallback:
                raise

            term_type = _TERM_ALIASES.get(
                self.terminal_name, self.terminal_name
            )
            if term_type not in _TERMINAL_CAPABILITIES:
                term_type = "dumb"
            self._capabilities = _TERMINAL_CAPABILITIES[term_type].copy()

    def _parse_terminfo_file(self, terminal_name: str) -> None:
        """Parse a terminfo file.

        Populate the _capabilities dict for easy retrieval

        Based on ncurses implementation in:
        - ncurses/tinfo/read_entry.c:_nc_read_termtype()
        - ncurses/tinfo/read_entry.c:_nc_read_file_entry()
        - ncurses/tinfo/lib_ti.c:tigetstr()
        """
        data = _read_terminfo_file(terminal_name)
        too_short = f"TermInfo file for {terminal_name!r} too short"
        offset = 12
        if len(data) < offset:
            raise ValueError(too_short)

        magic, name_size, bool_count, num_count, str_count, str_size = (
            struct.unpack("<Hhhhhh", data[:offset])
        )

        if magic == MAGIC16:
            number_size = 2
        elif magic == MAGIC32:
            number_size = 4
        else:
            raise ValueError(
                f"TermInfo file for {terminal_name!r} uses unknown magic"
            )

        # Skip data than PyREPL doesn't need:
        # - names (`|`-separated ASCII strings)
        # - boolean capabilities (bytes with value 0 or 1)
        # - numbers (little-endian integers, `number_size` bytes each)
        offset += name_size
        offset += bool_count
        if offset % 2:
            # Align to even byte boundary for numbers
            offset += 1
        offset += num_count * number_size
        if offset > len(data):
            raise ValueError(too_short)

        # Read string offsets
        end_offset = offset + 2 * str_count
        if offset > len(data):
            raise ValueError(too_short)
        string_offset_data = data[offset:end_offset]
        string_offsets = [
            off for [off] in struct.iter_unpack("<h", string_offset_data)
        ]
        offset = end_offset

        # Read string table
        if offset + str_size > len(data):
            raise ValueError(too_short)
        string_table = data[offset : offset + str_size]

        # Extract strings from string table
        capabilities = {}
        for cap, off in zip(_STRING_NAMES, string_offsets):
            if off < 0:
                # CANCELLED_STRING; we do not store those
                continue
            elif off < len(string_table):
                # Find null terminator
                end = string_table.find(0, off)
                if end >= 0:
                    capabilities[cap] = string_table[off:end]
            # in other cases this is ABSENT_STRING; we don't store those.

        # Note: we don't support extended capabilities since PyREPL doesn't
        # need them.

        self._capabilities = capabilities

    def get(self, cap: str) -> bytes | None:
        """Get terminal capability string by name.
        """
        if not isinstance(cap, str):
            raise TypeError(f"`cap` must be a string, not {type(cap)}")

        return self._capabilities.get(cap)


def tparm(cap_bytes: bytes, *params: int) -> bytes:
    """Parameterize a terminal capability string.

    Based on ncurses implementation in:
    - ncurses/tinfo/lib_tparm.c:tparm()
    - ncurses/tinfo/lib_tparm.c:tparam_internal()

    The ncurses version implements a full stack-based interpreter for
    terminfo parameter strings. This pure Python version implements only
    the subset of parameter substitution operations needed by PyREPL:
    - %i (increment parameters for 1-based indexing)
    - %p[1-9]%d (parameter substitution)
    - %p[1-9]%{n}%+%d (parameter plus constant)
    """
    if not isinstance(cap_bytes, bytes):
        raise TypeError(f"`cap` must be bytes, not {type(cap_bytes)}")

    result = cap_bytes

    # %i - increment parameters (1-based instead of 0-based)
    increment = b"%i" in result
    if increment:
        result = result.replace(b"%i", b"")

    # Replace %p1%d, %p2%d, etc. with actual parameter values
    for i in range(len(params)):
        pattern = b"%%p%d%%d" % (i + 1)
        if pattern in result:
            value = params[i]
            if increment:
                value += 1
            result = result.replace(pattern, str(value).encode("ascii"))

    # Handle %p1%{1}%+%d (parameter plus constant)
    # Used in some cursor positioning sequences
    pattern_re = re.compile(rb"%p(\d)%\{(\d+)\}%\+%d")
    matches = list(pattern_re.finditer(result))
    for match in reversed(matches):  # reversed to maintain positions
        param_idx = int(match.group(1))
        constant = int(match.group(2))
        value = params[param_idx] + constant
        result = (
            result[: match.start()]
            + str(value).encode("ascii")
            + result[match.end() :]
        )

    return result

Youez - 2016 - github.com/yon3zu
LinuXploit