123456789module view1011#flag -I@VMODROOT/vendor/shim12#flag @VMODROOT/vendor/shim/koh_term.c13#include "koh_term.h"1415fn C.koh_term_raw(enable int) int1617fn C.koh_term_size(rows &int, cols &int) int1819fn C.koh_read_key(buf &char, cap int) int2021fn C.koh_wait_key(buf &char, cap int, milliseconds int) int2223pub enum KeyKind {24 rune25 up26 down27 left28 right29 enter30 escape31 tab32 backtab33 backspace34 delete35 home36 end37 page_up38 page_down39 interrupt40 eof41 unknown42}4344pub struct Key {45pub:46 kind KeyKind47 text string48}4950pub fn terminal_size() (int, int) {51 mut rows := 052 mut cols := 053 C.koh_term_size(&rows, &cols)54 return rows, cols55}5657pub fn raw_mode(enable bool) {58 if !enable {59 C.koh_term_raw(0)60 return61 }62 C.koh_term_raw(1)63}64656667pub fn read_key() Key {68 mut buf := []u8{len: 16}69 n := C.koh_read_key(unsafe { &char(buf.data) }, buf.len)70 if n <= 0 {71 return Key{72 kind: .eof73 }74 }75 return decode(buf[..n])76}7778798081pub fn read_key_timeout(milliseconds int) (Key, bool) {82 mut buf := []u8{len: 16}83 n := C.koh_wait_key(unsafe { &char(buf.data) }, buf.len, milliseconds)84 if n == 0 {85 return Key{86 kind: .unknown87 }, true88 }89 if n < 0 {90 return Key{91 kind: .eof92 }, false93 }94 return decode(buf[..n]), false95}96979899fn decode(bytes []u8) Key {100 if bytes.len == 1 {101 b := bytes[0]102 match b {103 0x03 {104 return Key{105 kind: .interrupt106 }107 }108 0x04 {109 return Key{110 kind: .eof111 }112 }113 0x09 {114 return Key{115 kind: .tab116 }117 }118 0x0d, 0x0a {119 return Key{120 kind: .enter121 }122 }123 0x7f, 0x08 {124 return Key{125 kind: .backspace126 }127 }128 0x1b {129 return Key{130 kind: .escape131 }132 }133 else {134 if b >= 0x20 {135 return Key{136 kind: .rune137 text: bytes.bytestr()138 }139 }140 return Key{141 kind: .unknown142 }143 }144 }145 }146 if bytes[0] == 0x1b {147 sequence := bytes[1..].bytestr()148 return match sequence {149 '[A', 'OA' {150 Key{151 kind: .up152 }153 }154 '[B', 'OB' {155 Key{156 kind: .down157 }158 }159 '[C', 'OC' {160 Key{161 kind: .right162 }163 }164 '[D', 'OD' {165 Key{166 kind: .left167 }168 }169 '[H', 'OH', '[1~' {170 Key{171 kind: .home172 }173 }174 '[F', 'OF', '[4~' {175 Key{176 kind: .end177 }178 }179 '[3~' {180 Key{181 kind: .delete182 }183 }184 '[5~' {185 Key{186 kind: .page_up187 }188 }189 '[6~' {190 Key{191 kind: .page_down192 }193 }194 '[Z' {195 Key{196 kind: .backtab197 }198 }199 200 201 else {202 Key{203 kind: .unknown204 }205 }206 }207 }208 209 210 return Key{211 kind: .rune212 text: bytes.bytestr()213 }214}