diff options
author | onefang | 2020-03-16 13:04:59 +1000 |
---|---|---|
committer | onefang | 2020-03-16 13:04:59 +1000 |
commit | 002165485b73cabc64d74cfad7d72f81b62523b0 (patch) | |
tree | e725517c64f89ed695f7c2f7d00680c3eabb43aa /src/boxes | |
parent | Adding old documentation. (diff) | |
download | opensim-SC_OLD-002165485b73cabc64d74cfad7d72f81b62523b0.zip opensim-SC_OLD-002165485b73cabc64d74cfad7d72f81b62523b0.tar.gz opensim-SC_OLD-002165485b73cabc64d74cfad7d72f81b62523b0.tar.bz2 opensim-SC_OLD-002165485b73cabc64d74cfad7d72f81b62523b0.tar.xz |
Shuffle stuff.
Diffstat (limited to 'src/boxes')
-rw-r--r-- | src/boxes/BOXES.txt | 1130 | ||||
-rw-r--r-- | src/boxes/BUGS.txt | 6 | ||||
-rw-r--r-- | src/boxes/README.md | 30 | ||||
-rw-r--r-- | src/boxes/boxes.c | 2506 | ||||
-rw-r--r-- | src/boxes/dumbsh.c | 283 | ||||
-rw-r--r-- | src/boxes/handlekeys.c | 445 | ||||
-rw-r--r-- | src/boxes/handlekeys.h | 76 | ||||
-rw-r--r-- | src/boxes/showkey.c | 149 |
8 files changed, 4625 insertions, 0 deletions
diff --git a/src/boxes/BOXES.txt b/src/boxes/BOXES.txt new file mode 100644 index 0000000..745b7c9 --- /dev/null +++ b/src/boxes/BOXES.txt | |||
@@ -0,0 +1,1130 @@ | |||
1 | What's needed for MC like program. Call the library toyboxes, and the MC clone toysoldier. B-) | ||
2 | |||
3 | Use ANSI for terminal control. | ||
4 | UTF-8 support is welcome in toybox where it makes sense, here it makes sense. | ||
5 | |||
6 | Command defining - key, name, script, context. | ||
7 | Internal commands for the scripts. | ||
8 | Which can depend on the context. | ||
9 | Context is important. Gotta handle stuff like vi modes, MC browse / view / edit modes, less search popping into readline mode, etc. | ||
10 | Learnable keys ala GIMP. | ||
11 | |||
12 | Split the screen up into boxes. | ||
13 | Each box is a context. | ||
14 | Current box should have it's box graphics drawn in a different colour to highlight it. | ||
15 | Tab/shift-Tab cycles through boxes. | ||
16 | Though the editor has it's own use for tab. Ctrl-tab as an alias perhaps? | ||
17 | Horizontal / vertical splits, with some sort of size control. | ||
18 | Each box can be split h or v once, | ||
19 | with a control of what proportion the current box has (initially half), | ||
20 | a minimum size set by the contents, | ||
21 | and initially a copy of the pointer to the function that supplies it's contents / deals with it's input / includes it's context. | ||
22 | Later it can have that pointer set to something else. | ||
23 | Any given box can be deleted, which deletes it's sub boxes, drops it's pointer, and merges it's area with the one it split from. | ||
24 | See if screen and tmux agree on keys to use for box control. | ||
25 | Though, as usual, it's definable, but screen/tmux can be the defaults. | ||
26 | Choose to make a box full screen. With menu to select other boxes, or swap back to full set of boxes. | ||
27 | Can be without borders and such. | ||
28 | |||
29 | The borders can be the usual box graphics, +-| characters, or inverse spaces, in that order of priority. | ||
30 | Show bits of text on top and bottom borders (left and right sides of them). | ||
31 | MC includes a couple of tiny mouse controlled widgets. | ||
32 | Perhaps a scroll widget in left or right borders. Emacs dired has that. | ||
33 | |||
34 | Single line 'boxes', across the entire terminal, or across each box. | ||
35 | Should be context sensitive. | ||
36 | Menu - a list of commands showing their names and keys, with sub menus. | ||
37 | Function keys - Any function keys with commands showing the command names and key. | ||
38 | Perhaps could just be a specialized menu. | ||
39 | Programmable status line. | ||
40 | |||
41 | Contents scrolling. | ||
42 | Virtual memory buffers. | ||
43 | If a file viewer, just mmap it. | ||
44 | Editor should be able to only load in bits of a large file, perhaps with a UNDO/REDO buffer. | ||
45 | If command output, can create a temp file and mmap it. | ||
46 | |||
47 | file viewer (less, man). | ||
48 | editor (vi, mcedit, nano). | ||
49 | Like e3, make generic editor, with pluggable command keys, that kick in depending on how it's called. | ||
50 | Uses a file list in a box to select files for opening. | ||
51 | Poor mans top and similar commands. | ||
52 | Top at least could make use of internal boxes, with the command list using a sortable list. | ||
53 | Put command output in boxes. Each line can be selected and operated on. | ||
54 | Title bar across top, with click to sort style column names. | ||
55 | Each line is a single line 'box'. | ||
56 | ls. | ||
57 | ls with display options. | ||
58 | archive listing | ||
59 | find command result. | ||
60 | All these can show current directory with diving in and out, or tree and current directory in a sub box. | ||
61 | Also, allow an edit mode for editing the file attributes that are displayed, inline and full box if possible. | ||
62 | Shell console, with various text substitutions on input. | ||
63 | Can be a single line 'box' as well as an ordinary box. | ||
64 | Though the ordinary ones show their output in their box, | ||
65 | but the single line one should swap to a full screen, which can be a full screen box. | ||
66 | |||
67 | A box has content. Each content type is a context. So we can have - | ||
68 | Plain scrollable text view. | ||
69 | Fancy text view (hex and so on). | ||
70 | Text edit. | ||
71 | Directory browse. | ||
72 | Script controlled. | ||
73 | |||
74 | Popup widgets centered on box/boxes that they affect. | ||
75 | Labels, Text line (with optional history), check boxes, radio buttons, OK/Cancel/etc buttons, popup select list (useful for history to, can be just a menu specilization). | ||
76 | Widget sets, though try to keep things simple enough to not need them. | ||
77 | Notifications, with the addition of an abort button. | ||
78 | If a single widget in the popup, prompt in a single line "box" near the bottom (like nano). | ||
79 | Options. | ||
80 | Keep options down to a bare minimum. | ||
81 | Command params. | ||
82 | Fetch command params from internal toybox structures, map them to the appropriate widget. | ||
83 | F2 menu - list of commands to apply to file/s or current directory. | ||
84 | The list is selectable by file type. | ||
85 | Should use the same code as the menu box, and allow sub menus. | ||
86 | Context sensitive history lists for selecting stuff. | ||
87 | Could also be a widget inside the popup when needed. | ||
88 | Search / replace. | ||
89 | Delete / save confirmation. | ||
90 | Command progress meter. | ||
91 | Use xargs, and have it output something useful per 'argument' for the progress meter. | ||
92 | xargs has an option to print the command to stdout, and to ask for confirmation per command. | ||
93 | xargs can run multiple threads. | ||
94 | |||
95 | Scripting, so we can make things fancy and tie it together. | ||
96 | Don't forget to make it 'scriptable' via internal C. | ||
97 | MC uses that for the F2 menu, user menu, and archive access. | ||
98 | We should use scripts to define most of the above. | ||
99 | I'd like to use Lua, but shell is likely a better choice. | ||
100 | Coz toybox will have a shell. | ||
101 | And MC scripts are mostly shell bits. | ||
102 | Should have an actual toyboxes command that you can feed toyboxes scripts into. | ||
103 | Might actually get away with using that to define most of MC, AND be the editor plugins. | ||
104 | See how far I get, but that's what I'll start with for testing. | ||
105 | I should reuse the old emu protocol for this. | ||
106 | Not gonna actually sort function names or key combos. | ||
107 | A linear search is good enough for keys, they only come in at human speeds. | ||
108 | People might want the scripts to run faster, but in toybox we strive for simplicity. | ||
109 | Well, maybe a binary search within each modules function block that is sorted by hand in the source code. | ||
110 | On the other hand, might be able to make use of the toybox command parsing infrastructure for script functions. | ||
111 | Leaving that as a problem for toybox itself. | ||
112 | But it's not reusable, it uses globals, and not sure if we can screw with those globals. | ||
113 | |||
114 | NOTE - toybox is designed to only deal with one command per process. So we can't call other toybox commands internally. | ||
115 | Or can we? Toysh does it. | ||
116 | |||
117 | Events | ||
118 | We need a time event. Top has a resolution of hundredths of a second, though says that only tenths is officially supported. | ||
119 | Tenths makes sense for human speed UI. Hundredths makes sense if you want video frame rates. lol | ||
120 | Termios only allows tenths of seconds for read anyway. | ||
121 | Hmm, seems read() wants to wait for at least one byte, it's a between byte counter. Doh! | ||
122 | Select() is likely less simple, poll() the same, and epoll() seems to be linux specific. All allow more precise timeouts. | ||
123 | On the other hand, Rob is using poll() in netcat. | ||
124 | |||
125 | Common bits / differences. | ||
126 | Initial toybox command arguments. | ||
127 | Ability to change those within the editor. | ||
128 | Files - passed as arguments, or can add / remove them from the running editor. | ||
129 | Process the file through some proggy, or just some function of the editor script. | ||
130 | Save / save as / backups. | ||
131 | Modelines are actualy discouraged as a security issue by the standard, but encouraged by toybox to use vi modelines. | ||
132 | Filename completion. | ||
133 | Filename prompts could have a couple of features. | ||
134 | Can pass things in and out of a shell command, append to the file, edit a specific fixed section of a file or special file (disk block editing!), or use stdin and stdout (joe in a pipe). | ||
135 | Directory / file browsing in a window. | ||
136 | Windows per current design. | ||
137 | Multiple files in the command line each have their own window. | ||
138 | Different / same file in each. | ||
139 | Each has it's own cursor / marks / block, etc. | ||
140 | Delete / scroll some other window. | ||
141 | Open a file in some other window, possibly creating one first. | ||
142 | Show one window full screen. | ||
143 | Method to show some hidden window, can be hidden if there's not enough space for them all. | ||
144 | Buffers - holds the contents of the files being edited / viewed. | ||
145 | Attached to windows, but can shift them around? | ||
146 | Edit / view / read only, named / unnamed buffers. | ||
147 | Special purpose buffers. | ||
148 | Emacs has - scratch, help, grep, compile, gdb, man, shell, probably others. | ||
149 | Though most of those are just running some other command in a window. | ||
150 | Kill ring buffer. | ||
151 | Kill goes to the buffer, delete just vanishes, on the other hand, this is really the difference between "cut" and "delete". | ||
152 | "Yank" just means "paste from kill buffer" then. | ||
153 | Emacs can have different working directory for each buffer, OR one global directory. | ||
154 | List them, perform some operation on the members of the list. Go through them all, prompting to save modified buffers. | ||
155 | Display text - navigate within it, scroll it in various ways. | ||
156 | Many ways to display otherwise unprintable text. | ||
157 | Inverted video for high bit characters. | ||
158 | Just show high bit characters. | ||
159 | UTF8. | ||
160 | ^X | ||
161 | Could be a problem with "where's my cursor" for the code. | ||
162 | Hex mode, wrap mode, raw / parsed mode, as well as formatted / unformatted mode. | ||
163 | Parsed mode has the text being processed by some command specified in the config file. | ||
164 | Formatted mode converts common formatting stuff to bold / underline. | ||
165 | Line numbers. | ||
166 | Scrolling can be definable amounts. | ||
167 | Some editors count buffer lines, some display lines. | ||
168 | Move to top, bottom, middle of screen / line. | ||
169 | Marks. | ||
170 | One mark and cursor. | ||
171 | Hmmm, Emacs uses the idea of a "point" which is between characters, with the "cursor" on the right side. | ||
172 | Not sure if this will be a problem. | ||
173 | Emacs has only one mark, and everything between point and mark is the "region", a block I think. | ||
174 | Multiple marks - numbered, named, just arbitrary, automated marks for various reasons. Line / line and character marks. | ||
175 | Next / previous / goto / remove one / all marks. | ||
176 | Whitespace / word boundaries / line / paragraph / "sections", etc. Should be definable. | ||
177 | Vi has multiples types of all of them. Pffft | ||
178 | Smooth scrolling (line by line). | ||
179 | Slow serial line support - do we need it? | ||
180 | Maybe. B-( | ||
181 | Status line. | ||
182 | Show cursor position, details of file / character under cursor / working directory. Often used for line input of parameters to. | ||
183 | Top of screen, bottom, above the key display in nano. Can have left, middle, right widgets. | ||
184 | Nano has essentially two status lines. | ||
185 | Expert mode to turn it off, disable it for more screen space. | ||
186 | Regexs - basic / extra / extended | ||
187 | Replacable stuff in search & replace. Ex/vi has this as an option. | ||
188 | Commands - invoked immediately with no echo, or typed via readline. | ||
189 | Pre command numbers (usually not echoed) / post command arguments. Also pre command regexs and other things to select the lines to work on. | ||
190 | Methods of repeating commands. Repeat last / next command, possibly X times. | ||
191 | Direction / motion. | ||
192 | Execute line / buffer / file. | ||
193 | Select lines, apply command to them. | ||
194 | Parameter expansion. | ||
195 | Key handling. | ||
196 | Bind / learn keys. | ||
197 | Emacs has "keymaps" for major and minor modes, as well as a global one. | ||
198 | Unbind keys. Mask keys from a lower level, but without actually binding them to anything, a NOP. | ||
199 | Command keys can be one or more keys. | ||
200 | Emacs and wordstar generally use a control key followed by some other key. | ||
201 | Show help page in a window with key bindings. Show binding for specific key. | ||
202 | Shortcut keys display. Nano has two lines of 6 each, showing only the most common. MC has one line, showing 10 function keys. No one else cares? | ||
203 | Esc key same as Alt / Meta key OR used for function keys OR used by itself. sigh | ||
204 | Meta key used to insert high bit characters. | ||
205 | Abort current command key. | ||
206 | Emacs has a keymap per buffer, which is the keybindings. | ||
207 | A global keymap. | ||
208 | The buffers major mode keymap. | ||
209 | Minor modes can have keymaps that override the major mode keymap when the minor mode is turned on. | ||
210 | Del <-> BS swapping. | ||
211 | Readline type widget. Called "minibuffer" in emacs. | ||
212 | For command parameters, also just go to one at the bottom to type commands into. | ||
213 | A fullscreen editor could be considered to just be a stack of these. | ||
214 | History, completion, editing, escape from. Position and length. | ||
215 | Same editing keys, and treat it just like a one line window. | ||
216 | Restricted or different editing keys while in some random line editing mode. | ||
217 | Moving readline to some other line (the basis of full screen editing perhaps). | ||
218 | Perhaps allow it to autoexpand if the input covers multiple lines. | ||
219 | Though that might be better to do as just creating more lines, then moving the readline between them. | ||
220 | Still would need the prompt on the top one, and to know to send them all at once when done. | ||
221 | How exactly does one create multiple lines? | ||
222 | Only way that makes sense is if the ENTER key is different from the "now do this" key. | ||
223 | Or wrapping long lines instead of scrolling them. | ||
224 | The prompt could include the default in (). | ||
225 | Mouse support - left click, double click, scroll wheel. | ||
226 | Only used to click on a widget, move cursor, or scroll around. | ||
227 | Shift click is used for X cut and paste support, think that just works from the terminal. | ||
228 | Shell - In a window / full screen. | ||
229 | Make editor a background task with bg / fg standard shell stuff. | ||
230 | Pass a block or buffer as stdin. Append / insert stdout to the buffer. | ||
231 | The shell output can just appended to the window contents as text that can be edited like every other window. When the cursor is at the bottom of the shell windov, stuff typed in is the next shell command. | ||
232 | Simple editing. | ||
233 | Move cursor, insert, delete, overwrite. | ||
234 | Basic editing. | ||
235 | Modes. | ||
236 | Vi has a lot of them - command, insert, ex, and moooore. | ||
237 | Emacs has definable modes that are a different concept to vi. | ||
238 | There are "major" and "minor" modes per buffer. | ||
239 | Major modes is for file type specific editing like "editing C, latex, etc" or "Dired". | ||
240 | Includes things like indenting, syntax highlighting, function boundaries (for ctags I guess), invoking the right compiler, keymaps, etc. | ||
241 | Can include other specialisations, like a python shell, and dired. | ||
242 | Minor modes are extras you can add, they seem to be things like "autofill", "wrap", "overwrite", "line numbers", etc. | ||
243 | Insert / overwrite mode. | ||
244 | Automatic detection of file type (typically source files) to put editor into different modes. | ||
245 | Cut, copy, paste, delete - blocks, word / line /etc, to end / beginning line, others. | ||
246 | To / from other buffers, files, "clipfile", maybe even the clipboard/s (thought that's an X thing I think). | ||
247 | Blocks - cut, copy, move, write to file. | ||
248 | Unhighlight block. | ||
249 | Search / replace - regex / shell glob / straight text / whole words. Case / charset sensitive. Forward / backward. | ||
250 | Regexs - basic / extra / extended | ||
251 | File / all files / within selection. Wrap around searching. | ||
252 | Incremental. Interactive / all replace. Inverted (find non matches). | ||
253 | Highlight / filter found. | ||
254 | Regex for the replace bit. Replacable stuff in search & replace. Ex/vi has this as an option. | ||
255 | Can search mixed hex and strings. | ||
256 | History, repeat, repeat in other direction. | ||
257 | Modified state. | ||
258 | Can be used by some commands to pester the user. | ||
259 | Ability to turn that state off. | ||
260 | Tabs / spaces / half tabs. Setting tab size. | ||
261 | Advanced editing. | ||
262 | Insert a character that is otherwise hard to insert, like command keys. | ||
263 | Insert date/time. | ||
264 | Quick search for a character in current line / forward / back. | ||
265 | "Smart" home, home goes to actual beginning, or first non blank. | ||
266 | Replace lots of space horizontally / vertically with just one / zero spaces. | ||
267 | Insert empty line/s above / below. | ||
268 | End of line space removal. | ||
269 | Allow cursor beyond end of line. | ||
270 | Visible white space. | ||
271 | DOS / Mac line ending convert. On the other hand, might just be good to do that transparently, remember on read, convert on save. | ||
272 | Change text encoding. | ||
273 | Add a newline at end of file if it's missing one. | ||
274 | Think we are doing that anyway, but an option to turn that off might be good. | ||
275 | Transpose, upper, lower, reverse case, capitalize words. | ||
276 | Adding a prefix / suffix string to selected lines. | ||
277 | Indent / outdent / line wrapping / centreing which can be auto / manual. Left and right margins. | ||
278 | Column blocks. | ||
279 | Deleting might just replace the column block with spaces / tabs. | ||
280 | Macros. Various ways of defining / invoking a macro. | ||
281 | Nested macros. | ||
282 | Auto expanding abbreviations. | ||
283 | Auto save after certain commands, or certain time. | ||
284 | Multi level undo / redo. Also undo current line (revert it?). | ||
285 | Disable undo. | ||
286 | Ability to list the undo "records"? | ||
287 | Emacs undo boundaries? | ||
288 | Spell checker. | ||
289 | Pretty printer (likely via shell command like indent). | ||
290 | Email quote handling. | ||
291 | Count / highlight lines matching or not matching regexes. | ||
292 | Sort block. | ||
293 | Persistant cursor position and selection. | ||
294 | Complete the word being typed based on other words in the file. | ||
295 | Code editing. | ||
296 | Ctags - basically lookup a symbol (word cursor is on) in the ctags files, which gives you a position in some other file that defines this symbol. Then display this other file somehow, probably allowing editing. | ||
297 | Ctags is in the standards, but do we want to write a toybox version? | ||
298 | Bracket / character matching. Goto / highlight matching bracket. Auto insert the closing one. | ||
299 | Include "insert one, blink the other". | ||
300 | Auto detect code block for indenting? | ||
301 | Syntax highlighting. | ||
302 | Next / previous error (compile errors usually). | ||
303 | |||
304 | Readline. | ||
305 | toybox has get_line() and get_rawline(), but they are not interactive readlines. | ||
306 | In order to have our readline() be useful for generic use, the keystrokes that do stuff must be definable. | ||
307 | So, what do we need? | ||
308 | GNU readline has (leaving out a few things) - | ||
309 | Editing | ||
310 | How is a "word" defined?. | ||
311 | Hitting ENTER anywhere in the line submits it. An editor would want to actually insert the ENTER into the text. | ||
312 | Move cursor / insert / delete / backspace / undo (all the way back) / revert. | ||
313 | Perhaps redo might be nice. | ||
314 | Move cursor to start / end of line, forward / back one word, redraw. | ||
315 | Cut / copy / paste. Kill ring with ring rotation? | ||
316 | Entire line. | ||
317 | All spaces around cursor. | ||
318 | From cursor to mark. | ||
319 | Highlighted block. | ||
320 | From cursor to start / end of line. | ||
321 | to end of word, or end of next word if between words. | ||
322 | to beginning of word, or of the previous word if between words. | ||
323 | to previous white space. Different from above coz apparently white space is different from word boundaries. shrugs | ||
324 | Numbers in front of commands. Vi and emacs probably need this? More and less "needs" this. Otherwise... eww. | ||
325 | For repeats, or sometimes to reverse the direction if it's negative. | ||
326 | Insert / overwrite mode. | ||
327 | Upper and lower casing characters or words. | ||
328 | Transpose characters / words. | ||
329 | Marks - setting a mark and moving the cursor to it / swapping with it. | ||
330 | Character search within the string - forward / back. | ||
331 | Insert comment - bloat we don't need. | ||
332 | History. | ||
333 | Back / forward one line. Goto start / end of history. | ||
334 | Incremental and non incremental searching, forwards or back. | ||
335 | During incremental search - ability to abort and restore original line. | ||
336 | Remember the last (incremental?) search. | ||
337 | Either return the found history (ENTER), or allow editing (editing keys). | ||
338 | Option to save edited history lines, and mark them as edited. | ||
339 | Show key bindings / macros / etc. | ||
340 | Tab completion. | ||
341 | List / select completions. | ||
342 | Cycle through the matches. | ||
343 | Macros! | ||
344 | Config files. | ||
345 | Not likely to emulate these, we have our own needs, and it's not a standard. | ||
346 | Expansions. | ||
347 | MC will want argument expansions at least. | ||
348 | Though perhaps this is best left to the code that calls this to expand the result. | ||
349 | |||
350 | more | ||
351 | Can handle switch between multiple files. | ||
352 | Searches are regexs. Can also search for non matches. | ||
353 | Multiple marks. | ||
354 | Forward and back half screenful, with "half" being the specified number, but defaulting to actual half. | ||
355 | Shell commands (not in the standard). | ||
356 | Invoke the editor mentioned in EDITOR, or default to vi. Pass line number if it's vi. | ||
357 | Print info about file. | ||
358 | Ctags. | ||
359 | Some commands are single letters, some are ":" followed by a single letter, possible with more text, then ENTER. | ||
360 | Or other variations. | ||
361 | |||
362 | less | ||
363 | Has bracket matching, but only from top-open / bottom-close. | ||
364 | Can search between multiple files, or add more. | ||
365 | Files on the command line, add / remove files, just open a new file now. | ||
366 | Highlight found text. | ||
367 | Filter found lines. | ||
368 | Option to NOT do regex search. | ||
369 | Change the command line arguments while running. | ||
370 | Shell commands with replacable params. | ||
371 | Input processor - some proggy that the input file is processed through, the output of that is shown. | ||
372 | Um, why not use pipes and input redirection? | ||
373 | |||
374 | ed - obsolete for toybox, ancestor of ex. | ||
375 | A line editor. | ||
376 | In command mode, type the command, then ENTER. | ||
377 | In input mode, type text, with "." on a line by itself to go back to command mode. | ||
378 | Uses one or two optional line addresses (can be regex) followed by a single character command, then arguments. | ||
379 | The "address" can be various symbols with various meanings, see the manual. | ||
380 | Usual basic editing and navigation commands. | ||
381 | Join lines. | ||
382 | Mark lines. | ||
383 | Display lines (with line numbers). | ||
384 | Copy / move lines. | ||
385 | Apply a command to a bunch of lines matching / not matching the address. | ||
386 | Insert a file / write lines to a file. | ||
387 | Search and replace. | ||
388 | Undo. | ||
389 | Shell command, with filename replacement character. | ||
390 | |||
391 | sed | ||
392 | Stream editor. | ||
393 | Fairly similar to ed, except it applies a script of commands to each line in turn. | ||
394 | Branch to a label within the script. Can test if a substitution happened before deciding to branch. | ||
395 | Includes a "hold space" for cut and paste type operations, as well as swapping. | ||
396 | Can output line numbers. | ||
397 | Can read in a file, or write to one. | ||
398 | Can be commented. | ||
399 | |||
400 | ex - obsolete for toybox, but part of vi. | ||
401 | A line editor, apparently the line oriented editing mode for vi. | ||
402 | So while the command itself is obsolete, it's internal stuff might be needed for vi. | ||
403 | In fact a lot of the standard for vi just refers to ex. | ||
404 | ":" means to perform an ex command from vi. lol | ||
405 | Starts in command mode (":" prompt). | ||
406 | Basically a "type command then ENTER" command mode. | ||
407 | Text input mode (append, insert, change) ended by "." on it's own line. | ||
408 | Has line addresses before the commands, similar to ed. | ||
409 | Commands have complex parsing requirements. Ewww. | ||
410 | Has some really basic command line editing. | ||
411 | Has a bunch of buffers, with modes. Commands apply to a named buffer, or the unnamed one if no name is given. | ||
412 | Abbreviations and maps. Same thing? They interact. lol | ||
413 | Think the difference is that maps don't have to have blank space after them. | ||
414 | They expand during typing. | ||
415 | Seems that maps are for binding to keys? | ||
416 | Set various options. | ||
417 | Shell command, with optional interaction. | ||
418 | Read commands from a file. | ||
419 | Can scan ctags files looking for regexs. | ||
420 | Can switch to "open" and "visual" modes, whatever they are. | ||
421 | "Visual" mode is just vi. | ||
422 | "Open" mode I think is a vi for dumb terminals? | ||
423 | Has a concept of "window", also not sure what that is. Might just be the number of terminal lines. | ||
424 | Shell escape - pass selected lines to a shell command, replace them with whatever it returns. | ||
425 | Shift lines back and forth. Indent and outdent in other words. | ||
426 | Execute a buffer as ex commands. | ||
427 | Regexs have extra thingies. | ||
428 | Replace commands can refer to other bits of text using parameters. See the manual. | ||
429 | Autowrite - basicaly save the file after certain commands. | ||
430 | Mode that strips out non printables on file read. | ||
431 | Can be made ed compatible. lol | ||
432 | Can display line numbers. | ||
433 | Paragraph boundary pairs can be set. | ||
434 | Definable scroll distance. | ||
435 | Visual and open modes have "sections", with definable pairs of boundary characters. | ||
436 | Can show matching braces. | ||
437 | Can optionally warn on some commands if the buffers are modified. | ||
438 | Margin auto wrap and end of line blanks removal. | ||
439 | Can wrap searches. | ||
440 | "modelines" (as used at the top of toybox source files) are apparently is strongly discouraged by the standard. shrugs | ||
441 | Overlaping copies are allowed. | ||
442 | Automatic marks created sometimes. | ||
443 | |||
444 | vi | ||
445 | Notable for it's variety of modes, and it's standard command mode that uses non echoed ordinary keys for common commands. | ||
446 | "Visual" editor, a screen oriented superset of ex, that lets you use ex commands. | ||
447 | A lot of the standard simply refers to ex. | ||
448 | Seems to mostly be similar to ex commands, only done full screen, and with full screen navigation. | ||
449 | Has "open" and "visual" modes, but not sure what they are. Also "ex" mode, with means using ex commands. | ||
450 | I think "open" mode is for dumb terminals, it's all done on the bottom line, perhaps with full screen redraws. | ||
451 | "Visual" mode then must be full screen editing. | ||
452 | Text input mode can return to command mode with Esc. | ||
453 | Has five kinds of "words" and four kinds of "bigwords", six types of "sections", four types of "paragraphs", and three types of "sentences". | ||
454 | There can be a multi digit count before commands, it's not echoed anywhere when not in a command line mode, the command key then does its command count times. | ||
455 | For instance typing "12h" does not echo anything, but just moves the cursor back 12 places when the "h" is hit. | ||
456 | Lots of those seem to be letters, or control keys, though there are others. | ||
457 | [count] ! motion shell-commands <newline> run a shell command, replacing count lines with the output. Looks like you get to type and edit the command while you see it. | ||
458 | Move to matching brace. | ||
459 | Repeat last command, for specific commands. | ||
460 | Move to last context, where I think "context" means where we was before the last command, it gets a special mark. | ||
461 | Move to words, bigwords, sections, paragraphs, etc. | ||
462 | Reverse case. | ||
463 | Find character in current line. Move cursor to before / after specific character. | ||
464 | Move to top / middle / bottom of screen. | ||
465 | Insert empty line above / below. | ||
466 | Paste above / below, depending on if the buffer is line or character mode as well. | ||
467 | Replace count characters with the entered character. | ||
468 | Undo current line. | ||
469 | Some editing command keys while in text input mode. | ||
470 | |||
471 | nano | ||
472 | Has a file browser mode. | ||
473 | Has a title bar, with three areas for showing status type info. | ||
474 | And a status line, which shows messages and lets users type stuff like file names. | ||
475 | Optional shortcut lists show 12 of the most common keystrokes in the current mode, and can be mouse clickable. | ||
476 | Mouse moves the cursor, double click sets marks. | ||
477 | "Smart" home - the usual go to first non blank, or go to actual start of line. | ||
478 | Tabs to spaces. | ||
479 | Multiple file buffers. | ||
480 | Search and replace history. | ||
481 | Deal with DOS / Mac line endings sanely. | ||
482 | Restricted mode. | ||
483 | Smooth scrolling. | ||
484 | Setting tab size. | ||
485 | Syntax highlighting. | ||
486 | Display cursor position. | ||
487 | Backspace and delete fixes, coz that's always confusing. | ||
488 | Autoindent. | ||
489 | Optional line wrap. | ||
490 | "Soft wrapping", no idea what that is. | ||
491 | External spell checker. | ||
492 | Undo and redo. | ||
493 | Hard to use method to insert otherwise unusable characters. | ||
494 | Optional search case sensitivity. | ||
495 | Optional regex searches. | ||
496 | Email quote handling. | ||
497 | Source code bracket handling of some sort. | ||
498 | Turning command line options on and off within the editor. | ||
499 | Write selected text to a file. | ||
500 | |||
501 | microemacs (microGNUemacs lol) | ||
502 | Go to line number. | ||
503 | Scratch buffer, help buffer, grep buffer, compile buffer. | ||
504 | Named buffers - per file. Can have their own working directory, or a global one for all. | ||
505 | Kill a named buffer, prompting if it's changed. | ||
506 | List buffers. | ||
507 | Has the concept of "modes", default ones are - fill (wrap), indent, overwrite, and notab. | ||
508 | Can set a list of (minor?) modes as default for buffer creation. | ||
509 | Run a script (commands from a file). | ||
510 | Split windows. B-) | ||
511 | Window / buffer specific cursor and mark (depending on which emacs you have). | ||
512 | Can swap them. | ||
513 | Esc key same as Alt-key. | ||
514 | Get help, describe binding, describe key briefly (hit a key, it's binding is displayed). | ||
515 | Apropros - prompt the user for a string, open help buffer, list all commands with that string. | ||
516 | Auto execute - a shell glob pattern that is matched on files read into buffers, then executes a command. | ||
517 | Recenter - position cursor in center of screen / center of line / center of line counted from the bottom. | ||
518 | Open line - open up some space by inserting empty lines below cursor, leaving cursor at the top of them. | ||
519 | Quoted insert - insert the next key verbatim, ignoring what it's bound to. | ||
520 | Universal argument - repeat the next command 4 times, can apply to itself. | ||
521 | Toggle read only. | ||
522 | Find file read only. | ||
523 | Find alternate file - loading a different file into the current buffer, erasing the original buffer contents. | ||
524 | Find file in buffer, or load it into new buffer, then switch to it. | ||
525 | Find file other window - opens file in new buffer, splitting the window if needed. | ||
526 | Delete window. | ||
527 | Delete other windows. | ||
528 | Split window. | ||
529 | Enlarge / shrink window. | ||
530 | Next / previous window. | ||
531 | Scroll other window - scrolls the next window X pages. | ||
532 | Switch to buffer other window - "switch to buffer in another window"? | ||
533 | Switch to buffer - ask which buffer should be in this window. | ||
534 | Switch to a shell screen, and back again. | ||
535 | What cursor position - show a bunch of info about cursor position and what's there. | ||
536 | Next / previous error. | ||
537 | Dired - basically a multi window MC. lol | ||
538 | Save some buffers - looks for buffers that need saving and prompts user. | ||
539 | Just one space - delete all white space around cursor, then insert one single space. | ||
540 | Query replace - an interactive search and replace. Also a replace all with no interaction. | ||
541 | Oh nice - can do a search and replace with a regex for both the search string, AND for the replacable strings (selecting which ones get replaced with that regex). | ||
542 | Beginning / end of buffer. | ||
543 | Capitalize / upper / lower word. | ||
544 | Delete word. | ||
545 | Delete blank lines. | ||
546 | Delete horizontal / vertical space. | ||
547 | Delete leading / trailing space. | ||
548 | Delete lines non / matching regex after cursor. | ||
549 | Hmm, difference between "kill" and "delete"? | ||
550 | "Kill" goes into the kill buffer, "delete" just vanishes. | ||
551 | "Yank" inserts things from the kill buffer. | ||
552 | Kill buffer is a ring buffer in full emacs, but might not be a ring in microemacs. | ||
553 | So it's just an old fashioned concept for "cut and paste". | ||
554 | Fill paragraph - just means to wrap and justify it. Command to ask the user what the wrap column is. | ||
555 | Copy region as kill. | ||
556 | Execute extended command - does the readline thing to ask user for a command and arguments to run. | ||
557 | Execute one buffer / line. | ||
558 | Not modified - turn off the modified flag in current buffer. | ||
559 | Blink and insert - insert a character, then search backwards for it's match (bracket, or the character itself) and blink that. | ||
560 | Mini buffer - it's just a readline for command arguments and such, but treated as a one line window, with an uneditable prompt. | ||
561 | It does have the trick of expanding to more lines if it's content goes over multiple lines. | ||
562 | The prompt can include a default argument in (). | ||
563 | Numbers can proceed commands, seems to be what the universal argument is for. | ||
564 | Looks like they have a key to introduce them, then get put into the mini buffer. | ||
565 | "Digit-argument" and "negative-argument" might be the functions for that. | ||
566 | Swap Del and BS. | ||
567 | C program "mode" - no idea what that involves. | ||
568 | Count regex non / matches. | ||
569 | Define key (includes a keymap, what ever they are). Can also undefine a key, and there's a "global" keymap. Can also bind keys in specific modes. | ||
570 | Meta key can insert 8 bit characters, or not. | ||
571 | Keyboard quit - abort current action. | ||
572 | Insert spaces instead of tabs. | ||
573 | Toggle overwrite / insert mode. | ||
574 | Add a prefix string to lines in a selected region. Or set that string. | ||
575 | Show working directory in the status line. | ||
576 | Refresh screen, including recomputing window sizes if needed. | ||
577 | Scroll window without changing cursor position within window. | ||
578 | Toggle read only. | ||
579 | Undo boundaries? | ||
580 | Undo on/off. | ||
581 | List undo records for current buffer, in a new buffer. | ||
582 | |||
583 | wordstar (joe, turbo C) - Using joe, which also comes in emacs and pico flavours. | ||
584 | Help window, with commands to page through that help text. | ||
585 | Something about "inverting" 8 bit characters, but we want to be 8 bit clean. Not a WordStar thing I think. shrugs | ||
586 | Ah, for displaying high bit characters in other languages, normally inverts the display, but "as is" mode just prints them normally. | ||
587 | Option to auto append a new line at end of files on save. | ||
588 | Option to disable the status line. | ||
589 | Windowed & buffered like emacs, but for when it's pretending to be emacs. | ||
590 | Can be windowed anyway. | ||
591 | Split window on same file. | ||
592 | Make one window full screen. | ||
593 | Can move to hidden windows (hidden when there's not enough space for them all). | ||
594 | Horizontal split only. | ||
595 | Height change. | ||
596 | Multiple files on the command line go to multiple windows. | ||
597 | Option to define how many lines are kept on screen between page up / down commands. | ||
598 | Option to not use X lines at the top, for embedding in a BBS. | ||
599 | Multi level undo and redo. | ||
600 | Scrolling. | ||
601 | Automatic detection of source code files, other types get word wraping and autoindent by default. | ||
602 | Can set left and right margins for word wrapping. | ||
603 | Can center between them to. | ||
604 | Can manually indent lines, highlighted blocks, or autodetected code blocks. | ||
605 | Command to insert a single space while in overwrite mode. | ||
606 | Overwrite mode makes backspace just move left, no deleting. | ||
607 | File name completion. | ||
608 | History. History is described as a single line read only edit window, just like other windows, so the usual commands will work in them. | ||
609 | Status line can be edited in the setup string, to add or remove escape sequences that include various things. | ||
610 | Also a command to show the cursor position and character code in the status line. | ||
611 | Suspend the proggy and go to shell. Actually, I think most editors have this in some form or another. | ||
612 | Most seem to use the shell foreground/background thingy for this. | ||
613 | Search prompts for the thing to search, then prompts for a bunch of character flags that are search options. | ||
614 | One of the options is if this is a replace command, then it prompts for the replacement text. | ||
615 | It's regexs are slash escaped. | ||
616 | Highlighted block can be sent through a shell filter command. | ||
617 | Highlighted block can be un highlighted. | ||
618 | Macros keyed by digit, and can be nested. | ||
619 | Repeat command, hit the repeat, type the numbers, hit the command you want repeated. | ||
620 | Also works with characters. | ||
621 | Column select mode. | ||
622 | Delete block command replaces the entire column with spaces and tabs instead of deleting. | ||
623 | Ctags support, prompt for symbol (default is word the cursor is on), search ctags files, replace the file in the current window with the file ctags points to, and the cursor position of the symbol definition. | ||
624 | Shell in a window. | ||
625 | Very intersening, the shell output is just appended to the window contents as text that can be edited like every other window. When the cursor is at the bottom of the shell windov, stuff typed in is the next shell command. | ||
626 | Filename prompts have a couple of features. Can pass things in and out of a shell command, append to the file, edit a specific fixed section of a file or special file (disk block editing!), or use stdin and stdout (joe in a pipe). | ||
627 | Keys can be bound in the settings file. | ||
628 | |||
629 | mc viewer | ||
630 | Hex mode. | ||
631 | Can search mixed hex and strings. | ||
632 | Wrap mode. | ||
633 | Raw / parsed mode toggle, as well as formatted / unformatted mode toggle. | ||
634 | Parsed mode has the text being processed by some command specified in the config file. | ||
635 | Formatted mode converts common formatting stuff to bold / underline. | ||
636 | |||
637 | mcedit / cool edit | ||
638 | User menu - run a script, insert result. | ||
639 | Mark columns. | ||
640 | Bookmarks, toggle, next, previous, "flush" (meaning to remove all bookmarks.) | ||
641 | Copy / cut insert clipfile as well as prompting for a file. | ||
642 | Highlight all lines with found text. | ||
643 | Search for hexidecimal, within selection, for whole words, and in "all charsets". | ||
644 | Goto matching bracket. | ||
645 | Show line numbers. | ||
646 | Find "declaration", back from and forward to declaration. | ||
647 | It's ctags support. | ||
648 | Change text encoding. | ||
649 | Create, invoke, and delete macros (hotkeys). | ||
650 | Spell check. | ||
651 | Email current file. | ||
652 | Sort selected lines. | ||
653 | Insert output of shell command. | ||
654 | Format (wrap) paragraph. | ||
655 | Run external format script on selection. | ||
656 | Insert date/time. | ||
657 | Half tabs. | ||
658 | Persistant cursor position and selection. | ||
659 | Visible white space. | ||
660 | Optional go beyond end of line. | ||
661 | Learn keys. | ||
662 | Syntax highlighting. | ||
663 | Edit syntax and menu files. | ||
664 | |||
665 | Make the fancy features optional in the "wrap if(constant) around things so the compiler can optimise it out" way that Rob likes. | ||
666 | So the basic compile choices are - | ||
667 | File / stdout viewer. | ||
668 | Editor (the following options might depend on how the "pluggable" part is done). | ||
669 | Minimal vi? | ||
670 | Nice to have vi? | ||
671 | Minimal emacs? | ||
672 | Nice to have emacs? | ||
673 | Nano? | ||
674 | Minimal mcedit/cooledit? | ||
675 | Nice to have mcedit/cooledit? | ||
676 | Lists. | ||
677 | Simple top like. | ||
678 | Fancy top like. | ||
679 | Simple shell. | ||
680 | Fancy shell. | ||
681 | Basic MC. | ||
682 | Full on MC with all bells and whistles. | ||
683 | With the fancy compile options being (only if they are substantial amounts of code to support) - | ||
684 | Full popups or mere single line prompts? | ||
685 | One pane, or multiple panes? | ||
686 | Function key single line 'box'? | ||
687 | Menu? | ||
688 | Status line? | ||
689 | Border texts? | ||
690 | Border widgets? | ||
691 | Sortable lists? | ||
692 | History lists? | ||
693 | Progress bar? | ||
694 | Shell text substitutions? | ||
695 | Scriptable? | ||
696 | Learnable keys? | ||
697 | |||
698 | Probably got most of what we need to do screen / tmux / multitail, and other full screen terminal stuffs. | ||
699 | |||
700 | Are we ncurses yet? Or twin? lol | ||
701 | |||
702 | ------------------------------------------------------------------------------------------------------ | ||
703 | |||
704 | NOTES | ||
705 | |||
706 | From Rob - | ||
707 | ---------- | ||
708 | |||
709 | On 06/21/2012 09:28 AM, David Seikel wrote: | ||
710 | > What are the chances that get_optflags() could be made re usable by | ||
711 | > toys? | ||
712 | |||
713 | Well, right now you can put a NULL as your optstring and then set | ||
714 | which->options yourself and call get_optflags(). | ||
715 | |||
716 | > For toys that need to make their own little scripting system for | ||
717 | > example. Currently it seems to want to use the toys global, and I'm | ||
718 | > not sure if it's safe to screw with that after pulling all of my toys | ||
719 | > options out of it. | ||
720 | > | ||
721 | > Would it get reused like that for shell internal commands? | ||
722 | |||
723 | Already does. In toys/toysh.c function run_pipeline() look for the | ||
724 | TOYFLAG_NOFORK bit. | ||
725 | |||
726 | This probably needs to be genericized somewhere in lib, but I never got | ||
727 | around to it. | ||
728 | |||
729 | From Rob - | ||
730 | ---------- | ||
731 | |||
732 | I need to write a getline() with cursor control, which means I need to | ||
733 | query the tty size. The magic for that is: | ||
734 | |||
735 | struct winsize tty = { 0, 0, 0, 0 }; | ||
736 | int ret = ioctl(1, TIOCGWINSZ, &tty); | ||
737 | |||
738 | plus $COLUMNS and $LINES, plus echo -e "\e[s\e[999C\e[999B\e[6n\e[u" | ||
739 | |||
740 | Add command history parsing to getline(). | ||
741 | |||
742 | From Rob - | ||
743 | ---------- | ||
744 | |||
745 | Digging up ancient issues from toybox development, one of which is an | ||
746 | interesting design issue with querying the terminal size. | ||
747 | |||
748 | When you're on a serial console (happens a lot in the embedded world), | ||
749 | the local tty device doesn't know the width and height of the window at | ||
750 | the far end, so ioctl(TIOCGWINSZ) can't report it to you. | ||
751 | |||
752 | If the term program at the other end supports ansi escape sequences | ||
753 | (everything does, including xterms), there's an escape sequence you can | ||
754 | use to ask it, but there's multiple levels of non-obvious to the | ||
755 | implementation. | ||
756 | |||
757 | The escape sequence itself is "\e[6n", to which the terminal program | ||
758 | responds with another escape sequence, "\e[YY;XXR" where the "XX" part | ||
759 | is a decimal number with the current cursor's Y location, and XX is the | ||
760 | cursor X location. (Both decimal, top left is 1;1.) | ||
761 | |||
762 | Since what we want is the size of the screen, we wrap that in some more | ||
763 | commands, saving the current position, moving to the cursor 999 down and | ||
764 | 999 to the right (which should stick it at the lower right corner), | ||
765 | query that position, and the jump back to the saved location. The full | ||
766 | escape sequence is therefore "\e[s\e[999C\e[999B\e[6n\e[u". | ||
767 | |||
768 | The problem is, the response comes back from the terminal program on | ||
769 | stdin: along with whatever else is coming in on stdin. There could be a | ||
770 | delay of a significant fraction of a second (especially through a rial | ||
771 | port, even when you aren't overcommitted and swapping), and there's no | ||
772 | guarantee the terminal will actually respond. So blocking and waiting | ||
773 | for a response isn't the greatest idea, and can eat other input the user | ||
774 | has queued up. | ||
775 | |||
776 | This means you need to do a nonblocking read, assemble an ansi sequence | ||
777 | a piece at a time (luckily the term programs generate these atomically | ||
778 | so you don't get part of an ansi sequence with user-typed keys in the | ||
779 | middle of it), and keep any other data you get for use later. The | ||
780 | logical place to do this is in the line editing code the shell has to | ||
781 | have anyway, which responds to cursor keys, page up and down, and so on. | ||
782 | |||
783 | From Rob - | ||
784 | ---------- | ||
785 | |||
786 | Less has to get it _right_, as does line editing for a command shell. | ||
787 | Even before you get to cursor up: unix tty handling is epically crappy. | ||
788 | My commodore 64 could backspace past the left edge of the screen and | ||
789 | continue from the right edge one line up. A TRS-80 could do this. Unix | ||
790 | derivatives _can't_, you have to know when you're at the left edge of | ||
791 | the screen and do the ansi sequences for "cursor up one, jump right | ||
792 | 999". Which means you have to know when backspace puts you at the left | ||
793 | edge of the screen, which means you need to know when outputting normal | ||
794 | characters put you off the _right_ edge of the screen... | ||
795 | |||
796 | That's right: if you don't know what your current screen size is, your | ||
797 | command shell can't backspace past a line wrap. Welcome to unix | ||
798 | terminal handling. | ||
799 | |||
800 | From Rob - | ||
801 | ---------- | ||
802 | |||
803 | Here's a fun one: | ||
804 | |||
805 | cat /proc/mounts | less | ||
806 | |||
807 | When less outputs the escape sequence to query terminal parameters, it | ||
808 | has to peek not stdin but /dev/tty. Except the cursor keys scrolling up | ||
809 | and down also come from /dev/tty, as do "user hit forward slash and | ||
810 | wants to type in a search regex"... Innit fun? | ||
811 | |||
812 | Plus you have to figure out the width of what you're outputting, which | ||
813 | means isprint() and probably UTF8 awareness... (Flashbacks to | ||
814 | fontmetrics in java 1.1, but we can assume monospace text grid...) | ||
815 | |||
816 | From Rob - | ||
817 | ---------- | ||
818 | |||
819 | Alas, POSIX does not seem to like simple. To start with, the spec | ||
820 | requires "more" to be terminal aware, which isn't entirely surprising | ||
821 | given what it does. But it's not just _height_ aware, it's width aware | ||
822 | too. | ||
823 | |||
824 | It's actually kinda fiddly: more needs to be able to wrap lines at the | ||
825 | screen size to figure out when to prompt, but the first 32 ascii | ||
826 | characters (all the stuff below space) don't consistently print one | ||
827 | character. Some print nothing, some move the cursor around (tab, | ||
828 | newline, linefeed, backspace, form feed, whatever the heck "vertical | ||
829 | tab" does...) | ||
830 | |||
831 | In theory I can hijack catv and just escape most of the low-ascii | ||
832 | weirdness (so it's two characters, but it's _consistently_ two | ||
833 | characters whatever $TERM thinks). In practice, when not hooked up to a | ||
834 | tty more is supposed to act like cat and pass data through unmodified... | ||
835 | |||
836 | I plan to do the simplest standards conformant implementation I can, and | ||
837 | every once in a while I go "you know, the standard's nuts, let's just | ||
838 | document the divergence"... | ||
839 | |||
840 | |||
841 | From Rob - | ||
842 | ---------- | ||
843 | |||
844 | Keep in mind that Unix doesn't implement backspace sanely (like the | ||
845 | commodore 64 did), thus you have to figure out when you're at the left | ||
846 | edge of the screen (keeping track of your cursor position) | ||
847 | |||
848 | That's why if you do "echo -n this will screw bash up" and then cursor | ||
849 | up a few times bash's command history gets all wonky because it _thinks_ | ||
850 | it knows where the cursor is but actually started farther to the right. | ||
851 | (I contributed ansi escape screen position querying code to busybox to | ||
852 | improve the situation for ash.) | ||
853 | |||
854 | From Rob - | ||
855 | ---------- | ||
856 | |||
857 | The question here is how much of this we already need to do for shell | ||
858 | history, which is what I was going to implement first. (Actually the one | ||
859 | I've already sat down and wrestled with is "more", which turns out to | ||
860 | have rather a lot of these issues as well. Knowing what printable | ||
861 | characters actually _print_ so you know where your darn cursor is and | ||
862 | where the screen wraps. You'd think less would have more issues here, | ||
863 | but more actually hits just about all of 'em...) | ||
864 | |||
865 | Moving the cursor isn't the issue. Querying the screen size is a | ||
866 | reasonably contained issue. Knowing how the cursor will move when you | ||
867 | print out an arbitrary string: that's the hard part. (utf8 awareness is | ||
868 | kinda required here. And I'm assuming a monospaced font even in klingon. | ||
869 | And replacing the !isprint() characters below space with escape | ||
870 | sequences...) | ||
871 | |||
872 | |||
873 | From Rob and others - | ||
874 | --------------------- | ||
875 | |||
876 | http://lists.busybox.net/pipermail/busybox/2008-October/067348.html | ||
877 | |||
878 | http://lists.busybox.net/pipermail/busybox/2009-May/069314.html | ||
879 | |||
880 | From Rob - | ||
881 | ---------- | ||
882 | |||
883 | Implementing ascii programming in the library itself was what I was | ||
884 | referring to. (It's on my todo list...) All sorts of stuff needs it: | ||
885 | more, toysh, vi... Even ls wants to know the width of the screen for -C | ||
886 | mode. | ||
887 | |||
888 | The problem is parsing the replies, since the user could type arbitrary | ||
889 | stuff. It's stdout that needs to be a tty (because "ls | blah" is not | ||
890 | going to a tty even if stdin is a tty), but the input _could_ come back | ||
891 | in on stdin if that's another filehandle to the same tty... as could any | ||
892 | other random input. If you're filtering all your input through a line | ||
893 | reading function that needs to parse cursor keys to implement command | ||
894 | history, doing this is easy. But if _all_ you care about is the probe | ||
895 | response and you want to leave the rest of the input alone, it's kinda | ||
896 | hard. | ||
897 | |||
898 | What I might wind up doing is adding it to toysh and having that export | ||
899 | COLUMNS and LINES environment variables. It wouldn't catch resizes in | ||
900 | the middle of a command, but I think I'm ok with that... | ||
901 | |||
902 | |||
903 | ------------------------------------------------------------------------------------------------------ | ||
904 | |||
905 | /* | ||
906 | key / mouse -> command | ||
907 | menu choice -> command | ||
908 | border click -> command | ||
909 | popup + args -> command | ||
910 | typed string -> command | ||
911 | script call -> command | ||
912 | script callback -> command | ||
913 | C call -> command | ||
914 | |||
915 | Arguments - should use the same argument defining stuff as used by the toys. | ||
916 | Keys and menus have to have fixed arguments, and take the rest from their content. | ||
917 | Popup and typed get their arguments from what the user selected in the popup, or typed. | ||
918 | Popup is told what it's widgets are and how they map to arguments. | ||
919 | Popups eventually construct a command string. | ||
920 | Script call uses generic text to call the command and set it's arguments. | ||
921 | Script callback should be similar. | ||
922 | C calls can call the functions direct, or even just pass a string command. | ||
923 | |||
924 | So every command call involves it's content, and can take default arguments from that content, to be overridden by arguments. | ||
925 | Keys and menus just have arguments coded into their string on definition, though might mostly be argument less. | ||
926 | Popups have a structure that defines their argument widgets, and how to turn them into command arguments. | ||
927 | Popups need to be created from string commands to. | ||
928 | Typed commands can just have their arguments as part of the typed string. | ||
929 | Scripts and callbacks just send a string that is treated the same way as typed commands. | ||
930 | C can do the same as scripts, but should be able to call things directly. | ||
931 | |||
932 | Sending commands back to scripts, should use the same format as our commands. | ||
933 | |||
934 | Would be nice to have parameter substitution to, but that would have to be per content. | ||
935 | |||
936 | Use an event system. | ||
937 | |||
938 | --------------------------------------------- | ||
939 | |||
940 | Events | ||
941 | keystroke / mouse click | ||
942 | menu item select | ||
943 | timer | ||
944 | draw all | ||
945 | scroll contents | ||
946 | box was redrawn? | ||
947 | box destroyed | ||
948 | leave box | ||
949 | enter box | ||
950 | |||
951 | void doScript(struct content *content, char commandString, struct event *event, void *blob) | ||
952 | |||
953 | Define a command | ||
954 | name, argsDefinitionString, pointer to C function - void myCommand(struct box *box, char *command, struct ToyboxArguments *args, struct event *event, void *blob) | ||
955 | |||
956 | Define a key | ||
957 | keyName, commandString | ||
958 | |||
959 | Define a menu item | ||
960 | menuTitle, commandString | ||
961 | |||
962 | Define a border widget | ||
963 | borderPosition, borderType, textOrCommand | ||
964 | |||
965 | Define a popup | ||
966 | popupName, commandStub, thingThatMapsWidgetsToArgs | ||
967 | |||
968 | Define a script callback | ||
969 | name, command, someKey | ||
970 | |||
971 | --------------------------------------------- | ||
972 | |||
973 | Script interface. | ||
974 | |||
975 | We might have multiple scripts running, but only one per box. | ||
976 | But what if a script wants to split it's box? | ||
977 | They can't access our data structures, and we can't access theirs. | ||
978 | All needs to be done via stdin/stdout plain text, which should all look like the commands in the rest of the system. | ||
979 | |||
980 | Scripts can register simple callbacks on these events - key, menu, timer, box destroyed. | ||
981 | The first three might want to return a damage list. | ||
982 | The last means that the box wants to be destroyed, but the script gets a chance to clean up. | ||
983 | |||
984 | Scripts need to be able to hook into the damage system, so there needs to be a text representation of damage areas. | ||
985 | |||
986 | boxes <-> script | ||
987 | |||
988 | Boxes knows which script is attached to which box. | ||
989 | Registering a key for the box is optional, and it's only passed back if it exists. | ||
990 | A split box gets no key, or can have the key optionally sent with the split command. | ||
991 | So how does the script deal with stuff coming from multiple boxes? | ||
992 | |||
993 | <- keyForBox someKey | ||
994 | <- registerKey keyName, commandString arguments | ||
995 | <- registerKey keyName, callBackCommand arguments | ||
996 | user hits a key | ||
997 | if the key has a command, execute it. | ||
998 | if the command is not one of ours, send it to the script instead | ||
999 | -> callBackCommand arguments, someKey | ||
1000 | otherwise do our command | ||
1001 | else | ||
1002 | send the key event to the script. | ||
1003 | -> handleEvent keyName, someKey | ||
1004 | |||
1005 | In any case, the script might want to change things in response. | ||
1006 | Note that it could do these at any time. | ||
1007 | <- damage x, y, h, w | ||
1008 | line | ||
1009 | line | ||
1010 | line | ||
1011 | line | ||
1012 | -> doneRedraw someKey | ||
1013 | <- border borderPosition, borderType, textOrCommand | ||
1014 | <- status line | ||
1015 | |||
1016 | * | ||
1017 | */ | ||
1018 | |||
1019 | |||
1020 | struct function | ||
1021 | { | ||
1022 | name // Name for script purposes. | ||
1023 | description // Human name for the menus. | ||
1024 | type | ||
1025 | union | ||
1026 | { | ||
1027 | *scriptCallback | ||
1028 | *cFunction | ||
1029 | } | ||
1030 | }; | ||
1031 | |||
1032 | struct command | ||
1033 | { | ||
1034 | key // Note that any given context might have different keys for any given function. | ||
1035 | *function | ||
1036 | }; | ||
1037 | |||
1038 | struct item | ||
1039 | { | ||
1040 | type | ||
1041 | union | ||
1042 | { | ||
1043 | *command | ||
1044 | *menu | ||
1045 | } | ||
1046 | } | ||
1047 | |||
1048 | struct menu | ||
1049 | { | ||
1050 | *items[] // Circular pointer definiton for sub menus. | ||
1051 | } | ||
1052 | |||
1053 | struct context // Somehow I get the feeling I'm having a failure of imagination here with the menus and function keys. Might be better to manage them seperately per box, but have common ones available? Nano might have a problem with this. | ||
1054 | { | ||
1055 | *commands[] // The master list, the ones pointed to by the menu structs should be in this list. | ||
1056 | menu *menu // Can be NULL. | ||
1057 | menu *functionKeys // Can be NULL. | ||
1058 | // This can be used as the sub struct for various context types. Like viewer, editor, file browser, top, etc. | ||
1059 | // Could even be an object hierarchy, like generic editor, which Basic vi inherits from. | ||
1060 | }; | ||
1061 | |||
1062 | char borderchars[][] | ||
1063 | { | ||
1064 | // usual box graphic symbols | ||
1065 | '-|+', | ||
1066 | // ANSI code for inverse spaces. | ||
1067 | } | ||
1068 | |||
1069 | struct borderWidget | ||
1070 | { | ||
1071 | text | ||
1072 | *clickFunction(int position) | ||
1073 | } | ||
1074 | |||
1075 | struct border | ||
1076 | { | ||
1077 | *topLeftWidget | ||
1078 | *topRightWidget | ||
1079 | *bottomLeftWidget | ||
1080 | *bottomRightWidget | ||
1081 | *leftWidget | ||
1082 | *rightWidget | ||
1083 | } | ||
1084 | |||
1085 | struct damage | ||
1086 | { | ||
1087 | X, Y, W, H // The rectangle to be redrawn. | ||
1088 | char **lines // Pointer to an array of text lines, or NULL. | ||
1089 | *damage // Perhaps a linked list might be in order, for fast redraws. | ||
1090 | } | ||
1091 | |||
1092 | struct content // For various instances of context types, in other words, the editor might have several files open, so one of these per file. | ||
1093 | { | ||
1094 | minW, minH, maxW, maxH | ||
1095 | *context | ||
1096 | *handleEvents() // Should set the damage list if it needs a redraw, and flags if border or status line needs updating. | ||
1097 | // Keyboard / mouse events if the box did not handle them itself. | ||
1098 | // DrawAll event for when drawing the box for the first time, on reveals for coming out of full screen, or user hit the redraw key. | ||
1099 | // Scroll event if the content wants to handle that itself. | ||
1100 | // Timer event for things like top that might want to have this called regularly. | ||
1101 | *doneRedraw() // The box is done with it's redraw, so we can free the damage list or whatever now. | ||
1102 | *delete() | ||
1103 | // This can be used as the sub struct for various content types. | ||
1104 | }; | ||
1105 | |||
1106 | struct contentData | ||
1107 | { | ||
1108 | *border // Can be NULL. | ||
1109 | *statusLine // Text of the status line, or NULL if none. | ||
1110 | offsetX, offsetY, W, H // Offset and size within the content, coz box handles scrolling, usually. | ||
1111 | bool redrawStatus, redrawBorder | ||
1112 | *damage // Can be NULL. If not NULL after content->doneRedraw(), box will free it and it's children. | ||
1113 | void *data // The content controls this blob, it's specific to each box. | ||
1114 | } | ||
1115 | |||
1116 | struct box | ||
1117 | { | ||
1118 | box *sub, *parent | ||
1119 | bool noBorderOnFullScreen | ||
1120 | bool horizontalSplit // Marks if it's horizontally or vertically split. | ||
1121 | splitProportion // proportion of this boxes part of the split, the sub box gets the rest. | ||
1122 | *content | ||
1123 | contentData // Data blob specific to this box, passed to each content function. For sharing contents, like a split pane editor for instance. Not a pointer, but the struct. | ||
1124 | X, Y, W, H // Position and size of the box itself, not the content. Calculated, but cached coz that might be needed for speed. | ||
1125 | cX, cY // Position of the content within the box. Calculated, but cached coz that might be needed for speed. | ||
1126 | }; | ||
1127 | |||
1128 | box root; // Always a full screen, parent of the rest of the boxes, or the only box. | ||
1129 | box current; | ||
1130 | bool currentIsFullScreen; | ||
diff --git a/src/boxes/BUGS.txt b/src/boxes/BUGS.txt new file mode 100644 index 0000000..87c3d4b --- /dev/null +++ b/src/boxes/BUGS.txt | |||
@@ -0,0 +1,6 @@ | |||
1 | xterm current box characters are wrong | ||
2 | joe - ^K^D not working, but ^Kd is | ||
3 | Even odder, ^D works, all other ^K^? combinations work. | ||
4 | F1 seems to not work, at least under xterm. | ||
5 | |||
6 | should clear the command line prompt when not in use | ||
diff --git a/src/boxes/README.md b/src/boxes/README.md new file mode 100644 index 0000000..4f1e29e --- /dev/null +++ b/src/boxes/README.md | |||
@@ -0,0 +1,30 @@ | |||
1 | boxes | ||
2 | ===== | ||
3 | |||
4 | A test bed for a generic editor / pager thingy for the toybox project. | ||
5 | |||
6 | The toybox project is at http://www.landley.net/code/toybox/ and boxes | ||
7 | is covered by the same license that toybox is. Basically that's a two | ||
8 | clause BSD license, but see the LICENSE file from toybox for details. | ||
9 | |||
10 | This is a work in progress, proof of concept, playground, packaged up as | ||
11 | one big toy, to be self contained until the mess is cleaned up. This | ||
12 | "boxes" toy itself will go away, to be replaced by individual editor / | ||
13 | pager toys and library bits. Nothing is set in stone, lots of mess | ||
14 | inside, there's bugs, but at least it shows the general direction my | ||
15 | mind is wandering in. As a bonus, it actually works, you can edit | ||
16 | stuff. | ||
17 | |||
18 | Please don't actually include this in toybox. Just look at it and sneer | ||
19 | / giggle, depending on your nature. Drop it into the toys directory to | ||
20 | try it out, it's just one big toy. | ||
21 | |||
22 | If you want to see how it can be used to build specific editors, start | ||
23 | at the end and work backwards. Reading the lengthy comments at the | ||
24 | beginning would also be useful. | ||
25 | |||
26 | Toybox uses mecurial instead of git, but I keep all my stuff on github. | ||
27 | Boxes will hopefully be incorporated into toybox in a highly altered | ||
28 | form some day in the future. So this is just a temporary git repo for | ||
29 | my convenience. If and when boxes migrates to toybox, this repo will be | ||
30 | retired. | ||
diff --git a/src/boxes/boxes.c b/src/boxes/boxes.c new file mode 100644 index 0000000..fb5367a --- /dev/null +++ b/src/boxes/boxes.c | |||
@@ -0,0 +1,2506 @@ | |||
1 | /* boxes.c - Generic editor development sandbox. | ||
2 | * | ||
3 | * Copyright 2012 David Seikel <won_fang@yahoo.com.au> | ||
4 | * | ||
5 | * Not in SUSv4. An entirely new invention, thus no web site either. | ||
6 | * See - | ||
7 | * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html | ||
8 | * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/more.html | ||
9 | * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html | ||
10 | * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/vi.html | ||
11 | * http://linux.die.net/man/1/less | ||
12 | |||
13 | USE_BOXES(NEWTOY(boxes, "w#h#m(mode):a(stickchars)1", TOYFLAG_USR|TOYFLAG_BIN)) | ||
14 | |||
15 | config BOXES | ||
16 | bool "boxes" | ||
17 | default n | ||
18 | help | ||
19 | usage: boxes [-m|--mode mode] [-a|--stickchars] [-w width] [-h height] | ||
20 | |||
21 | Generic text editor and pager. | ||
22 | |||
23 | Mode selects which editor or text viewr it emulates, the choices are - | ||
24 | emacs is a microemacs type editor. | ||
25 | joe is a joe / wordstar type editor. | ||
26 | less is a less type pager. | ||
27 | mcedit (the default) is cooledit / mcedit type editor. | ||
28 | more is a more type pager. | ||
29 | nano is a nano / pico type editor. | ||
30 | vi is a vi type editor. | ||
31 | |||
32 | Stick chars means to use ASCII for the boxes instead of "graphics" characters. | ||
33 | */ | ||
34 | |||
35 | #include "toys.h" | ||
36 | #include "lib/handlekeys.h" | ||
37 | |||
38 | GLOBALS( | ||
39 | char *mode; | ||
40 | long h, w; | ||
41 | ) | ||
42 | |||
43 | #define TT this.boxes | ||
44 | |||
45 | #define FLAG_a 2 | ||
46 | #define FLAG_m 4 | ||
47 | #define FLAG_h 8 | ||
48 | #define FLAG_w 16 | ||
49 | |||
50 | |||
51 | /* This is trying to be a generic text editing, text viewing, and terminal | ||
52 | * handling system. The current code is a work in progress, and the design | ||
53 | * may change. Certainly at this moment it's only partly written. It is | ||
54 | * "usable" though, for a very small value of "usable". In the following | ||
55 | * I'll use "editors" to refer to the toys using this, though not all will | ||
56 | * be editors. | ||
57 | * | ||
58 | * The things it is targeting are - vi and more (part of the standards, so | ||
59 | * part of the toybox TODO), less (also on the toybox TODO), joe and | ||
60 | * wordstar (coz Rob said they would be good to include), nano (again Rob | ||
61 | * thinks it would be good and I agree), microemacs (to avoid religous | ||
62 | * wars), and mcedit (coz that's what I actually use). The ex editor comes | ||
63 | * along for the ride coz vi is basically a screen editor wrapper around | ||
64 | * the ex line editor. Sed might be supported coz I'll need to do basic | ||
65 | * editing functions that are common to the editors, and sed needs the same | ||
66 | * editing functions. | ||
67 | * | ||
68 | * I will also use this for a midnight commander clone as discussed on the | ||
69 | * mailing list. This would have things in common with emacs dired, so we | ||
70 | * might get that as well. Parts of this code could also be used for a | ||
71 | * file chooser, as used by some of the editors we are targeting. Finally, | ||
72 | * the terminal handling stuff might be useful for other toys, so should be | ||
73 | * generic in it's own right. Oh, screen is listed in the toybox TODO as | ||
74 | * "maybe", so I'll poke at that to. | ||
75 | * | ||
76 | * The basic building blocks are box, content, context, edit line, and | ||
77 | * view. A box is an on screen rectanglur area. Content is a file, and | ||
78 | * the text that is in that file. A context represents a particular editor | ||
79 | * type, it has key mappings and other similar stuff. The edit line is a | ||
80 | * single line where editing happens, it's similar to readline. A view is | ||
81 | * a view into a content, there can be many, it represents that portion of | ||
82 | * the content that is on screen right now. | ||
83 | * | ||
84 | * I plan on splitting these things up a bit so they can be used | ||
85 | * separately. Then I can make actually toybox libraries out of them. For | ||
86 | * now it's all one big file for ease of development. | ||
87 | * | ||
88 | * The screen is split into boxes, by default there are only two, the main | ||
89 | * text area and the command line at the bottom. Each box contains a view, | ||
90 | * and each view points to a content (file) for it's text. A content can | ||
91 | * have many views. Each content has a context (editor). There is only | ||
92 | * ever one edit line, it's the line that is being edited at the moment. | ||
93 | * The edit line moves within and between boxes (including the command | ||
94 | * line) as needed. | ||
95 | * | ||
96 | * The justification for boxes is that most of the editors we are trying to | ||
97 | * emulate include some splitting up of the screen area for various | ||
98 | * reasons, and some of them include a split window system as well. So | ||
99 | * this boxes concept covers command line, main editing area, split windows, | ||
100 | * menus, on screen display of command keys, file selection, and anything | ||
101 | * else that might be needed. | ||
102 | * | ||
103 | * To keep things simple boxes are organised as a binary tree of boxes. | ||
104 | * There is a root box, it's a global. Each box can have two sub boxes. | ||
105 | * Only the leaf nodes of the box tree are visible on the screen. Each box | ||
106 | * with sub boxes is split either horizontally or vertically. Navigating | ||
107 | * through the boxes goes depth first. | ||
108 | * | ||
109 | * A content keeps track of a file and it's text. Each content also has a | ||
110 | * context, which is a collection of the things that define a particular | ||
111 | * editor. (I might move the context pointer from content to view, makes | ||
112 | * more sense I think.) | ||
113 | * | ||
114 | * A context is the heart of the generic part of the system. Any given | ||
115 | * toybox command that uses this system would basically define a context | ||
116 | * and pass that to the rest of the system. See the end of this file for a | ||
117 | * few examples. A context holds a list of command to C function mappings, | ||
118 | * key to command mappings, and a list of modes. | ||
119 | * | ||
120 | * Most of the editors targetted include a command line where the user | ||
121 | * types in editor commands, and each of those editors has different | ||
122 | * commands. They would mostly use the same editing C functions though, or | ||
123 | * short wrappers around them. The vi context at the end of this file is a | ||
124 | * good example, it has a bunch of short C wrappers around some editing | ||
125 | * functions, or uses standard C editing functions directly. So a context | ||
126 | * has an editor command to C function mapping. | ||
127 | * | ||
128 | * The editors respond to keystrokes, and those keystrokes invoke editor | ||
129 | * commands, often in a modal way. So there are keystroke to editor | ||
130 | * command mappings. To cater for editing modes, each context has a list | ||
131 | * of modes, and each mode can have key to command mappings, as well as | ||
132 | * menu to command mappings, and a list of displayed key/command pairs. | ||
133 | * Menu and key/command pair display is not written yet. Most editors have | ||
134 | * a system for remapping key to command mappings, that's not supported | ||
135 | * yet. Emacs has a heirarchy of key to command mappings, that's not | ||
136 | * supported yet. Some twiddling of the current design would be needed for | ||
137 | * those. | ||
138 | * | ||
139 | * The key mappings used can be multiple keystrokes in a sequence, the | ||
140 | * system caters for that. Some can be multi byte like function keys, and | ||
141 | * even different strings of bytes depending on the terminal type. To | ||
142 | * simplify this, there is a table that maps various terminals ideas of | ||
143 | * special keys to key names, and the mapping of keys to commands uses | ||
144 | * those key names. | ||
145 | * | ||
146 | * A view represents the on screen visible portion of a content within a | ||
147 | * box. To cater for split window style editors, a content can have many | ||
148 | * views. It deals with keeping track of what's shown on screen, mapping | ||
149 | * the on screen representation of the text to the stored text during input | ||
150 | * and output. Each box holds one view. | ||
151 | * | ||
152 | * The edit line is basically a movable readline. There are editing C | ||
153 | * functions for moving it up and down lines within a view, and for | ||
154 | * shifting the edit line to some other box. So an editor would map the | ||
155 | * cursor keys for "up a line" and "down a line" to these C functions for | ||
156 | * example. Actual readline style functionality is just the bottom command | ||
157 | * box being a single line view, with the history file loaded into it's | ||
158 | * content, and the Enter key mapped to the editor contexts "do this | ||
159 | * command" function. Using most of the system with not much special casing. | ||
160 | * | ||
161 | * | ||
162 | * I assume that there wont be a terribly large number of boxes. | ||
163 | * Things like minimum box sizes, current maximum screen sizes, and the fact | ||
164 | * that they all have to be on the screen mean that this assumption should | ||
165 | * be safe. It's likely that most of the time there will be only a few at | ||
166 | * most. The point is there is a built in limit, there's only so many non | ||
167 | * overlapping boxes with textual contents that you can squeeze onto one | ||
168 | * terminal screen at once. | ||
169 | * | ||
170 | * I assume that there will only be one command line, no matter how many boxes, | ||
171 | * and that the command line is for the current box. | ||
172 | * | ||
173 | * I use a wide screen monitor and small font. | ||
174 | * My usual terminal is 104 x 380 characters. | ||
175 | * There will be people with bigger monitors and smaller fonts. | ||
176 | * So use sixteen bits for storing screen positions and the like. | ||
177 | * Eight bits wont cut it. | ||
178 | * | ||
179 | * | ||
180 | * These are the escape sequences we send - | ||
181 | * \x1B[m reset attributes and colours | ||
182 | * \x1B[1m turn on bold | ||
183 | * \x1B[%d;%dH move cursor | ||
184 | * Plus some experimentation with turning on mouse reporting that's not | ||
185 | * currently used. | ||
186 | * | ||
187 | * | ||
188 | * TODO - disentangle boxes from views. | ||
189 | * | ||
190 | * TODO - should split this up into editing, UI, and boxes parts, | ||
191 | * so the developer can leave out bits they are not using. | ||
192 | * | ||
193 | * TODO - Show status line instead of command line when it's not being edited. | ||
194 | * | ||
195 | * TODO - should review it all for UTF8 readiness. Think I can pull that off | ||
196 | * by keeping everything on the output side as "screen position", and using | ||
197 | * the formatter to sort out the input to output mapping. | ||
198 | * | ||
199 | * TODO - see if there are any simple shortcuts to avoid recalculating | ||
200 | * everything all the time. And to avoid screen redraws. | ||
201 | */ | ||
202 | |||
203 | /* Robs "It's too big" lament. | ||
204 | |||
205 | > So when you give me code, assume I'm dumber than you. Because in this | ||
206 | > context, I am. I need bite sized pieces, each of which I can | ||
207 | > understand in its entirety before moving on to the next. | ||
208 | |||
209 | As I mentioned in my last email to the Aboriginal linux list, I wrote | ||
210 | the large blob so I could see how the ideas all work to do the generic | ||
211 | editor stuff and other things. It kinda needs to be that big to do | ||
212 | anything that is actually useful. So, onto musings about cutting it up | ||
213 | into bite sized bits... | ||
214 | |||
215 | You mentioned on the Aboriginal Linux list that you wanted a | ||
216 | "readline", and you listed some features. My reply was that you had | ||
217 | basically listed the features of my "basic editor". The main | ||
218 | difference between "readline" and a full screen editor, is that the | ||
219 | editor is fullscreen, while the "readline" is one line. They both have | ||
220 | to deal with a list of lines, going up and down through those lines, | ||
221 | editing the contents of those lines, one line at a time. For persistent | ||
222 | line history, they both have to save and load those lines to a file. | ||
223 | Other than that "readline" adds other behaviour, like moving the | ||
224 | current line to the end when you hit return and presenting that line to | ||
225 | the caller (here's the command). So just making "readline" wont cut | ||
226 | out much of the code. In fact, my "readline" is really just a thin | ||
227 | wrapper around the rest of the code. | ||
228 | |||
229 | Starting from the other end of the size spectrum, I guess "find out | ||
230 | terminal size" is a small enough bite sized chunk. To actually do | ||
231 | anything useful with that you would probably start to write stuff I've | ||
232 | already written though. Would be better off just using the stuff I've | ||
233 | already written. On the other hand, maybe that would be useful for | ||
234 | "ls" listings and the like, then we can start with just that bit? | ||
235 | |||
236 | I guess the smallest useful command I have in my huge blob of code | ||
237 | would be "more". I could even cut it down more. Show a page of text, | ||
238 | show the next page of text when you hit the space bar, quit when you | ||
239 | hit "q". Even then, I would estimate it would only cut out a third of | ||
240 | the code. | ||
241 | |||
242 | On the other hand, there's a bunch of crap in that blob that is for | ||
243 | future plans, and is not doing anything now. | ||
244 | |||
245 | In the end though, breaking it up into suitable bite sized bits might | ||
246 | be almost as hard as writing it in the first place. I'll see what I | ||
247 | can do, when I find some time. I did want to break it up into three | ||
248 | bits anyway, and there's a TODO to untangle a couple of bits that are | ||
249 | currently too tightly coupled. | ||
250 | |||
251 | */ | ||
252 | |||
253 | /* Robs contradiction | ||
254 | |||
255 | On Thu, 27 Dec 2012 06:06:53 -0600 Rob Landley <rob@landley.net> wrote: | ||
256 | |||
257 | > On 12/27/2012 12:56:07 AM, David Seikel wrote: | ||
258 | > > On Thu, 27 Dec 2012 00:37:46 -0600 Rob Landley <rob@landley.net> | ||
259 | > > wrote: | ||
260 | > > > Since ls isn't doiing any of that, probing would just be awkward | ||
261 | > > > so toysh should set COLUMNS to a sane value. The problem is, | ||
262 | > > > we're not using toysh yet because it's still just a stub... | ||
263 | > > | ||
264 | > > I got some or all of that terminal sizing stuff in my editor thingy | ||
265 | > > already if I remember correctly. I remember you wanted me to cut it | ||
266 | > > down into tiny bits to start with, so you don't have to digest the | ||
267 | > > huge lump I sent. | ||
268 | > | ||
269 | > Basically what I'd like is a self-contained line reader. More or less | ||
270 | > a getline variant that can handle cursoring left and right to insert | ||
271 | > stuff, handle backspace past a wordwrap (which on unix requires | ||
272 | > knowing the screen width and your current cursor position), and one | ||
273 | > that lets up/down escape sequences be hooked for less/more screen | ||
274 | > scrolling, vi line movement, shell command history, and so on. | ||
275 | |||
276 | Which is most of an editor already, so how to break it up into bite | ||
277 | sized morsels? | ||
278 | |||
279 | > There's sort of three levels here, the first is "parse raw input, | ||
280 | > assembling escape sequences into cursor-left and similar as | ||
281 | > necessary". (That's the one I had to redo in busybox vi because they | ||
282 | > didn't do it right.) | ||
283 | > | ||
284 | > The second is "edit a line of text, handling cursoring _within_ the | ||
285 | > line". That's the better/interactive getline(). | ||
286 | > | ||
287 | > The third is handling escapes from that line triggering behavior in | ||
288 | > the larger command (cursor up and cursor down do different things in | ||
289 | > less, in vi, and in shell command history). | ||
290 | > | ||
291 | > The fiddly bit is that terminal_size() sort of has to integrate with | ||
292 | > all of these. Possibly I need to have width and height be members of | ||
293 | > struct toy_context. Or have the better_getline() take a pointer to a | ||
294 | > state structure it can update, containing that info... | ||
295 | |||
296 | */ | ||
297 | |||
298 | |||
299 | static char *borderChars[][6] = | ||
300 | { | ||
301 | {"-", "|", "+", "+", "+", "+"}, // "stick" characters. | ||
302 | {"\xE2\x94\x80", "\xE2\x94\x82", "\xE2\x94\x8C", "\xE2\x94\x90", "\xE2\x94\x94", "\xE2\x94\x98"}, // UTF-8 | ||
303 | {"\x71", "\x78", "\x6C", "\x6B", "\x6D", "\x6A"}, // VT100 alternate character set. | ||
304 | {"\xC4", "\xB3", "\xDA", "\xBF", "\xC0", "\xD9"} // DOS | ||
305 | }; | ||
306 | |||
307 | static char *borderCharsCurrent[][6] = | ||
308 | { | ||
309 | {"=", "#", "+", "+", "+", "+"}, // "stick" characters. | ||
310 | {"\xE2\x95\x90", "\xE2\x95\x91", "\xE2\x95\x94", "\xE2\x95\x97", "\xE2\x95\x9A", "\xE2\x95\x9D"}, // UTF-8 | ||
311 | {"\x71", "\x78", "\x6C", "\x6B", "\x6D", "\x6A"}, // VT100 alternate character set has none of these. B-( | ||
312 | {"\xCD", "\xBA", "\xC9", "\xBB", "\xC8", "\xBC"} // DOS | ||
313 | }; | ||
314 | |||
315 | |||
316 | typedef struct _box box; | ||
317 | typedef struct _view view; | ||
318 | |||
319 | typedef void (*boxFunction) (box *box); | ||
320 | typedef void (*eventHandler) (view *view); | ||
321 | |||
322 | struct function | ||
323 | { | ||
324 | char *name; // Name for script purposes. | ||
325 | char *description; // Human name for the menus. | ||
326 | char type; | ||
327 | union | ||
328 | { | ||
329 | eventHandler handler; | ||
330 | char *scriptCallback; | ||
331 | }; | ||
332 | }; | ||
333 | |||
334 | struct keyCommand | ||
335 | { | ||
336 | char *key, *command; | ||
337 | }; | ||
338 | |||
339 | struct item | ||
340 | { | ||
341 | char *text; // What's shown to humans. | ||
342 | struct key *key; // Shortcut key while the menu is displayed. | ||
343 | // If there happens to be a key bound to the same command, the menu system should find that and show it to. | ||
344 | char type; | ||
345 | union | ||
346 | { | ||
347 | char *command; | ||
348 | struct item *items; // An array of next level menu items. | ||
349 | }; | ||
350 | }; | ||
351 | |||
352 | struct borderWidget | ||
353 | { | ||
354 | char *text, *command; | ||
355 | }; | ||
356 | |||
357 | // TODO - a generic "part of text", and what is used to define them. | ||
358 | // For instance - word, line, paragraph, section. | ||
359 | // Each context can have a collection of these. | ||
360 | |||
361 | struct mode | ||
362 | { | ||
363 | struct keyCommand *keys; // An array of key to command mappings. | ||
364 | struct item *items; // An array of top level menu items. | ||
365 | struct item *functionKeys; // An array of single level "menus". Used to show key commands. | ||
366 | uint8_t flags; // commandMode. | ||
367 | }; | ||
368 | |||
369 | /* | ||
370 | Have a common menu up the top. | ||
371 | MC has a menu that changes per mode. | ||
372 | Nano has no menu. | ||
373 | Have a common display of certain keys down the bottom. | ||
374 | MC is one row of F1 to F10, but changes for edit / view / file browse. But those are contexts here. | ||
375 | Nano is 12 random Ctrl keys, possibly in two lines, that changes depending on the editor mode, like editing the prompt line for various reasons, help. | ||
376 | */ | ||
377 | struct context // Defines a context for content. Text viewer, editor, file browser for instance. | ||
378 | { | ||
379 | struct function *commands; // The master list, the ones pointed to by the menus etc should be in this list. | ||
380 | struct mode *modes; // A possible empty array of modes, indexed by the view. | ||
381 | // OR might be better to have these as a linked list, so that things like Emacs can have it's mode keymap hierarcy. | ||
382 | eventHandler handler; // TODO - Might be better to put this in the modes. I think vi will need that. | ||
383 | // Should set the damage list if it needs a redraw, and flags if border or status line needs updating. | ||
384 | // Keyboard / mouse events if the box did not handle them itself. | ||
385 | // DrawAll event for when drawing the box for the first time, on reveals for coming out of full screen, or user hit the redraw key. | ||
386 | // Scroll event if the content wants to handle that itself. | ||
387 | // Timer event for things like top that might want to have this called regularly. | ||
388 | boxFunction doneRedraw; // The box is done with it's redraw, so we can free the damage list or whatever now. | ||
389 | boxFunction delete; | ||
390 | // This can be used as the sub struct for various context types. Like viewer, editor, file browser, top, etc. | ||
391 | // Could even be an object hierarchy, like generic editor, which Basic vi inherits from. | ||
392 | // Or not, since the commands might be different / more of them. | ||
393 | }; | ||
394 | |||
395 | // TODO - might be better off just having a general purpose "widget" which includes details of where it gets attached. | ||
396 | // Status lines can have them to. | ||
397 | struct border | ||
398 | { | ||
399 | struct borderWidget *topLeft, *topMiddle, *topRight; | ||
400 | struct borderWidget *bottomLeft, *bottomMiddle, *bottomRight; | ||
401 | struct borderWidget *left, *right; | ||
402 | }; | ||
403 | |||
404 | struct line | ||
405 | { | ||
406 | struct line *next, *prev; | ||
407 | uint32_t length; // Careful, this is the length of the allocated memory for real lines, but the number of lines in the header node. | ||
408 | char *line; // Should be blank for the header. | ||
409 | }; | ||
410 | |||
411 | struct damage | ||
412 | { | ||
413 | struct damage *next; // A list for faster draws? | ||
414 | uint16_t X, Y, W, H; // The rectangle to be redrawn. | ||
415 | uint16_t offset; // Offest from the left for showing lines. | ||
416 | struct line *lines; // Pointer to a list of text lines, or NULL. | ||
417 | // Note - likely a pointer into the middle of the line list in a content. | ||
418 | }; | ||
419 | |||
420 | struct content // For various instances of context types. | ||
421 | // Editor / text viewer might have several files open, so one of these per file. | ||
422 | // MC might have several directories open, one of these per directory. No idea why you might want to do this. lol | ||
423 | { | ||
424 | struct context *context; | ||
425 | char *name, *file, *path; | ||
426 | struct line lines; | ||
427 | // file type | ||
428 | // double linked list of bookmarks, pointer to line, character position, length (or ending position?), type, blob for types to keep context. | ||
429 | uint16_t minW, minH, maxW, maxH; | ||
430 | uint8_t flags; // readOnly, modified. | ||
431 | // This can be used as the sub struct for various content types. | ||
432 | }; | ||
433 | |||
434 | struct _view | ||
435 | { | ||
436 | struct content *content; | ||
437 | box *box; | ||
438 | struct border *border; // Can be NULL. | ||
439 | char *statusLine; // Text of the status line, or NULL if none. | ||
440 | int mode; // For those contexts that can be modal. Normally used to index the keys, menus, and key displays. | ||
441 | struct damage *damage; // Can be NULL. If not NULL after context->doneRedraw(), box will free it and it's children. | ||
442 | // TODO - Gotta be careful of overlapping views. | ||
443 | void *data; // The context controls this blob, it's specific to each box. | ||
444 | uint32_t offsetX, offsetY; // Offset within the content, coz box handles scrolling, usually. | ||
445 | uint16_t X, Y, W, H; // Position and size of the content area within the box. Calculated, but cached coz that might be needed for speed. | ||
446 | uint16_t cX, cY; // Cursor position within the content. | ||
447 | uint16_t iX, oW; // Cursor position inside the lines input text, in case the formatter makes it different, and output length. | ||
448 | char *output; // The current line formatted for output. | ||
449 | uint8_t flags; // redrawStatus, redrawBorder; | ||
450 | |||
451 | // Assumption is that each box has it's own editLine (likely the line being edited), or that there's a box that is just the editLine (emacs minibuffer, and command lines for other proggies). | ||
452 | struct line *line; // Pointer to the current line, might be the only line. | ||
453 | char *prompt; // Optional prompt for the editLine. | ||
454 | |||
455 | // Display mode / format hook. | ||
456 | // view specific bookmarks, including highlighted block and it's type. | ||
457 | // Linked list of selected lines for a filtered view, or processing only those lines. | ||
458 | // Linked list of pointers to struct keyCommand, for emacs keymaps hierarchy, and anything similar in other editors. Plus some way of dealing with emacs minor mode keymaps. | ||
459 | }; | ||
460 | |||
461 | struct _box | ||
462 | { | ||
463 | box *sub1, *sub2, *parent; | ||
464 | view *view; // This boxes view into it's content. For sharing contents, like a split pane editor for instance, there might be more than one box with this content, but a different view. | ||
465 | // If it's just a parent box, it wont have this, so just make it a damn pointer, that's the simplest thing. lol | ||
466 | // TODO - Are parent boxes getting a view anyway? | ||
467 | uint16_t X, Y, W, H; // Position and size of the box itself, not the content. Calculated, but cached coz that might be needed for speed. | ||
468 | float split; // Ratio of sub1's part of the split, the sub2 box gets the rest. | ||
469 | uint8_t flags; // Various flags. | ||
470 | }; | ||
471 | |||
472 | |||
473 | // Sometimes you just can't avoid circular definitions. | ||
474 | void drawBox(box *box); | ||
475 | |||
476 | |||
477 | #define BOX_HSPLIT 1 // Marks if it's a horizontally or vertically split. | ||
478 | #define BOX_BORDER 2 // Mark if it has a border, often full screen boxes wont. | ||
479 | |||
480 | static int overWriteMode; | ||
481 | static box *rootBox; // Parent of the rest of the boxes, or the only box. Always a full screen. | ||
482 | static box *currentBox; | ||
483 | static view *commandLine; | ||
484 | static int commandMode; | ||
485 | |||
486 | #define MEM_SIZE 128 // Chunk size for line memory allocation. | ||
487 | |||
488 | // Inserts the line after the given line, or at the end of content if no line. | ||
489 | struct line *addLine(struct content *content, struct line *line, char *text, uint32_t length) | ||
490 | { | ||
491 | struct line *result = NULL; | ||
492 | uint32_t len; | ||
493 | |||
494 | if (!length) | ||
495 | length = strlen(text); | ||
496 | // Round length up. | ||
497 | len = (((length + 1) / MEM_SIZE) + 1) * MEM_SIZE; | ||
498 | result = xzalloc(sizeof(struct line)); | ||
499 | result->line = xzalloc(len); | ||
500 | result->length = len; | ||
501 | strncpy(result->line, text, length); | ||
502 | |||
503 | if (content) | ||
504 | { | ||
505 | if (!line) | ||
506 | line = content->lines.prev; | ||
507 | |||
508 | result->next = line->next; | ||
509 | result->prev = line; | ||
510 | |||
511 | line->next->prev = result; | ||
512 | line->next = result; | ||
513 | |||
514 | content->lines.length++; | ||
515 | } | ||
516 | else | ||
517 | { | ||
518 | result->next = result; | ||
519 | result->prev = result; | ||
520 | } | ||
521 | |||
522 | return result; | ||
523 | } | ||
524 | |||
525 | void freeLine(struct content *content, struct line *line) | ||
526 | { | ||
527 | line->next->prev = line->prev; | ||
528 | line->prev->next = line->next; | ||
529 | if (content) | ||
530 | content->lines.length--; | ||
531 | free(line->line); | ||
532 | free(line); | ||
533 | } | ||
534 | |||
535 | void loadFile(struct content *content) | ||
536 | { | ||
537 | int fd = open(content->path, O_RDONLY); | ||
538 | |||
539 | if (-1 != fd) | ||
540 | { | ||
541 | char *temp = NULL; | ||
542 | long len; | ||
543 | |||
544 | do | ||
545 | { | ||
546 | // TODO - get_rawline() is slow, and wont help much with DOS and Mac line endings. | ||
547 | temp = get_rawline(fd, &len, '\n'); | ||
548 | if (temp) | ||
549 | { | ||
550 | if (temp[len - 1] == '\n') | ||
551 | temp[--len] = '\0'; | ||
552 | addLine(content, NULL, temp, len); | ||
553 | } | ||
554 | } while (temp); | ||
555 | close(fd); | ||
556 | } | ||
557 | } | ||
558 | |||
559 | // TODO - load and save should be able to deal with pipes, and with loading only parts of files, to load more parts later. | ||
560 | |||
561 | void saveFile(struct content *content) | ||
562 | { | ||
563 | // TODO - Should do "Save as" as well. Which is just a matter of changing content->path before calling this. | ||
564 | int fd; | ||
565 | |||
566 | fd = open(content->path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); | ||
567 | |||
568 | if (-1 != fd) | ||
569 | { | ||
570 | struct line *line = content->lines.next; | ||
571 | |||
572 | while (&(content->lines) != line) // We are at the end if we have wrapped to the beginning. | ||
573 | { | ||
574 | write(fd, line->line, strlen(line->line)); | ||
575 | write(fd, "\n", 1); | ||
576 | line = line->next; | ||
577 | } | ||
578 | close(fd); | ||
579 | } | ||
580 | else | ||
581 | { | ||
582 | fprintf(stderr, "Can't open file %s\n", content->path); | ||
583 | exit(1); | ||
584 | } | ||
585 | } | ||
586 | |||
587 | struct content *addContent(char *name, struct context *context, char *filePath) | ||
588 | { | ||
589 | struct content *result = xzalloc(sizeof(struct content)); | ||
590 | |||
591 | result->lines.next = &(result->lines); | ||
592 | result->lines.prev = &(result->lines); | ||
593 | result->name = strdup(name); | ||
594 | result->context = context; | ||
595 | |||
596 | if (filePath) | ||
597 | { | ||
598 | result->path = strdup(filePath); | ||
599 | loadFile(result); | ||
600 | } | ||
601 | |||
602 | return result; | ||
603 | } | ||
604 | |||
605 | // General purpose line moosher. Used for appends, inserts, overwrites, and deletes. | ||
606 | // TODO - should have the same semantics as mooshStrings, only it deals with whole lines in double linked lists. | ||
607 | // We need content so we can adjust it's number of lines if needed. | ||
608 | void mooshLines(struct content *content, struct line *result, struct line *moosh, uint16_t index, uint16_t length, int insert) | ||
609 | { | ||
610 | } | ||
611 | |||
612 | // General purpose string moosher. Used for appends, inserts, overwrites, and deletes. | ||
613 | void mooshStrings(struct line *result, char *moosh, uint16_t index, uint16_t length, int insert) | ||
614 | { | ||
615 | char *c, *pos; | ||
616 | int limit = strlen(result->line); | ||
617 | int mooshLen = 0, resultLen; | ||
618 | |||
619 | if (moosh) | ||
620 | mooshLen = strlen(moosh); | ||
621 | |||
622 | /* | ||
623 | * moosh == NULL a deletion | ||
624 | * length == 0 simple insertion | ||
625 | * length < mooshlen delete some, insert moosh | ||
626 | * length == mooshlen exact overwrite. | ||
627 | * length > mooshlen delete a lot, insert moosh | ||
628 | */ | ||
629 | |||
630 | mooshLen -= length; | ||
631 | resultLen = limit + mooshLen; | ||
632 | |||
633 | // If we need more space, allocate more. | ||
634 | if (resultLen > result->length) | ||
635 | { | ||
636 | result->length = resultLen + MEM_SIZE; | ||
637 | result->line = xrealloc(result->line, result->length); | ||
638 | } | ||
639 | |||
640 | if (limit <= index) // At end, just add to end. | ||
641 | { | ||
642 | // TODO - Possibly add spaces to pad out to where index is? | ||
643 | // Would be needed for "go beyond end of line" and "column blocks". | ||
644 | // Both of those are advanced editing. | ||
645 | index = limit; | ||
646 | insert = 1; | ||
647 | } | ||
648 | |||
649 | pos = &(result->line[index]); | ||
650 | |||
651 | if (insert) // Insert / delete before current character, so move it and the rest up / down mooshLen bytes. | ||
652 | { | ||
653 | if (0 < mooshLen) // Gotta move things up. | ||
654 | { | ||
655 | c = &(result->line[limit]); | ||
656 | while (c >= pos) | ||
657 | { | ||
658 | *(c + mooshLen) = *c; | ||
659 | c--; | ||
660 | } | ||
661 | } | ||
662 | else if (0 > mooshLen) // Gotta move things down. | ||
663 | { | ||
664 | c = pos; | ||
665 | while (*c) | ||
666 | { | ||
667 | *c = *(c - mooshLen); // A double negative. | ||
668 | c++; | ||
669 | } | ||
670 | } | ||
671 | } | ||
672 | |||
673 | if (moosh) | ||
674 | { | ||
675 | c = moosh; | ||
676 | do | ||
677 | { | ||
678 | *pos++ = *c++; | ||
679 | } | ||
680 | while (*c); | ||
681 | } | ||
682 | } | ||
683 | |||
684 | // TODO - Should draw the current border in green, the text as default (or highlight / bright). | ||
685 | // Then allow one other box to be red bordered (MC / dired destination box). | ||
686 | // All other boxes with dark gray border, and dim text. | ||
687 | void drawLine(int y, int start, int end, char *left, char *internal, char *contents, char *right, int current) | ||
688 | { | ||
689 | int size = strlen(internal); | ||
690 | int len = (end - start) * size, x = 0; | ||
691 | char line[len + 1]; | ||
692 | |||
693 | if ('\0' != left[0]) // Assumes that if one side has a border, then so does the other. | ||
694 | len -= 2 * size; | ||
695 | |||
696 | if (contents) | ||
697 | { | ||
698 | // strncpy wont add a null at the end if the source is longer, but will pad with nulls if source is shorter. | ||
699 | // So it's best to put a safety null in first. | ||
700 | line[len] = '\0'; | ||
701 | strncpy(line, contents, len); | ||
702 | // Make sure the following while loop pads out line with the internal character. | ||
703 | x = strlen(line); | ||
704 | } | ||
705 | while (x < len) | ||
706 | { | ||
707 | strcpy(&line[x], internal); | ||
708 | x += size; | ||
709 | } | ||
710 | line[x++] = '\0'; | ||
711 | if ('\0' == left[0]) // Assumes that if one side has a border, then so does the other. | ||
712 | { | ||
713 | if (current) | ||
714 | printf("\x1B[1m\x1B[%d;%dH%s\x1B[m", y + 1, start + 1, line); | ||
715 | else | ||
716 | printf("\x1B[m\x1B[%d;%dH%s", y + 1, start + 1, line); | ||
717 | } | ||
718 | else | ||
719 | { | ||
720 | if (current) | ||
721 | printf("\x1B[1m\x1B[%d;%dH%s%s%s\x1B[m", y + 1, start + 1, left, line, right); | ||
722 | else | ||
723 | printf("\x1B[m\x1B[%d;%dH%s%s%s", y + 1, start + 1, left, line, right); | ||
724 | } | ||
725 | } | ||
726 | |||
727 | void formatCheckCursor(view *view, long *cX, long *cY, char *input) | ||
728 | { | ||
729 | int i = 0, o = 0, direction = (*cX) - view->cX; | ||
730 | |||
731 | // Adjust the cursor if needed, depending on the contents of the line, and the direction of travel. | ||
732 | while (input[i]) | ||
733 | { | ||
734 | // When o is equal to the cX position, update the iX position to be where i is. | ||
735 | if ('\t' == input[i]) | ||
736 | { | ||
737 | int j = 8 - (i % 8); | ||
738 | |||
739 | // Check if the cursor is in the middle of the tab. | ||
740 | if (((*cX) > o) && ((*cX) < (o + j))) | ||
741 | { | ||
742 | if (0 <= direction) | ||
743 | { | ||
744 | *cX = (o + j); | ||
745 | view->iX = i + 1; | ||
746 | } | ||
747 | else | ||
748 | { | ||
749 | *cX = o; | ||
750 | view->iX = i; | ||
751 | } | ||
752 | } | ||
753 | o += j; | ||
754 | } | ||
755 | else | ||
756 | { | ||
757 | if ((*cX) == o) | ||
758 | view->iX = i; | ||
759 | o++; | ||
760 | } | ||
761 | i++; | ||
762 | } | ||
763 | // One more check in case the cursor is at the end of the line. | ||
764 | if ((*cX) == o) | ||
765 | view->iX = i; | ||
766 | } | ||
767 | |||
768 | // TODO - Should convert control characters to reverse video, and deal with UTF8. | ||
769 | |||
770 | /* FIXME - We get passed a NULL input, apparently when the file length is close to the screen length. - | ||
771 | > On Thu, 6 Sep 2012 11:56:17 +0800 Roy Tam <roytam@gmail.com> wrote: | ||
772 | > | ||
773 | > > 2012/9/6 David Seikel <onefang@gmail.com>: | ||
774 | > > >> Program received signal SIGSEGV, Segmentation fault. | ||
775 | > > >> formatLine (view=0x8069168, input=0x0, output=0x806919c) | ||
776 | > > >> at toys/other/boxes.c:843 | ||
777 | > > >> 843 int len = strlen(input), i = 0, o = 0; | ||
778 | > > >> (gdb) bt | ||
779 | > > >> #0 formatLine (view=0x8069168, input=0x0, output=0x806919c) | ||
780 | > > >> at toys/other/boxes.c:843 | ||
781 | > > >> #1 0x0804f1dd in moveCursorAbsolute (view=0x8069168, cX=0, | ||
782 | > > >> cY=10, sX=0, sY=0) at toys/other/boxes.c:951 | ||
783 | > > >> #2 0x0804f367 in moveCursorRelative (view=0x8069168, cX=0, | ||
784 | > > >> cY=10, sX=0, sY=0) at toys/other/boxes.c:1011 | ||
785 | > > >> #3 0x0804f479 in upLine (view=0x8069168, event=0x0) at | ||
786 | > > >> toys/other/boxes.c:1442 #4 0x0804fb63 in handleKey | ||
787 | > > >> (view=0x8069168, i=2, keyName=<optimized out>, buffer=0xbffffad8 | ||
788 | > > >> "\033[A") at toys/other/boxes.c:1593 #5 0x0805008d in editLine | ||
789 | > > >> (view=0x8069168, X=-1, Y=-1, W=-1, H=-1) at | ||
790 | > > >> toys/other/boxes.c:1785 #6 0x08050288 in boxes_main () at | ||
791 | > > >> toys/other/boxes.c:2482 #7 0x0804b262 in toy_exec | ||
792 | > > >> (argv=0xbffffd58) at main.c:104 #8 0x0804b29d in toybox_main () | ||
793 | > > >> at main.c:118 #9 0x0804b262 in toy_exec (argv=0xbffffd54) at | ||
794 | > > >> main.c:104 #10 0x0804b29d in toybox_main () at main.c:118 | ||
795 | > > >> #11 0x0804affa in main (argc=5, argv=0xbffffd54) at main.c:159 | ||
796 | > > > | ||
797 | > > > No segfault here when I try that, nor with different files. As I | ||
798 | > > > said, it has bugs. I have seen other cases before when NULL lines | ||
799 | > > > are passed around near that code. Guess I've not got them all. | ||
800 | > > > Might help to mention what terminal proggy you are using, it's | ||
801 | > > > size in characters, toybox version, OS, etc. Something is | ||
802 | > > > different between you and me. | ||
803 | > > | ||
804 | > > Terminal Program: PuTTY | ||
805 | > > Windows size: 80 * 25 chars | ||
806 | > > Toybox version: hg head | ||
807 | > > OS: Linux 3.2 (Debian wheezy) | ||
808 | > > File: Toybox LICENSE file | ||
809 | > | ||
810 | > I'll install PuTTY, try toybox hg head, and play with them later, see | ||
811 | > if I can reproduce that segfault. I use the last released tarball of | ||
812 | > toybox, an old Ubuntu, and a bunch of other terminal proggies. I did | ||
813 | > not know that PuTTY had been ported to Unix. | ||
814 | > | ||
815 | > But as I mentioned, not interested in a bug hunt right now. That will | ||
816 | > be more appropriate when it's less of a "sandbox for testing the | ||
817 | > ideas" and more of a "good enough to bother using". Always good to | ||
818 | > have other terminals for testing though. | ||
819 | |||
820 | Seems to be sensitive to the number of lines. On my usual huge | ||
821 | roxterm, using either toybox 0.4 or hg head, doing this - | ||
822 | |||
823 | ./toybox boxes -m less LICENSE -h 25 | ||
824 | |||
825 | and just hitting down arrow until you get to the bottom of the page | ||
826 | segfaults as well. -h means "pretend the terminal is that many lines | ||
827 | high", there's a similar -w as well. 80x25 in any other terminal did | ||
828 | the same. For that particular file (17 lines long), any value of -h | ||
829 | between 19 and 34 will segfault after some moving around. -h 35 makes | ||
830 | it segfault straight away. Less than 19 or over 35 is fine. Longer | ||
831 | files don't have that problem, though I suspect it will happen on | ||
832 | shortish files where the number of lines is about the length of the | ||
833 | screen. | ||
834 | |||
835 | I guess that somewhere I'm doing maths wrong and getting an out of | ||
836 | bounds line number when the file length is close to the screen length. | ||
837 | I'll make note of that, and fix it when I next get time to beat on | ||
838 | boxes. | ||
839 | |||
840 | Thanks for reporting it Roy. | ||
841 | */ | ||
842 | |||
843 | int formatLine(view *view, char *input, char **output) | ||
844 | { | ||
845 | int len = strlen(input), i = 0, o = 0; | ||
846 | |||
847 | *output = xrealloc(*output, len + 1); | ||
848 | |||
849 | while (input[i]) | ||
850 | { | ||
851 | if ('\t' == input[i]) | ||
852 | { | ||
853 | int j = 8 - (i % 8); | ||
854 | |||
855 | *output = xrealloc(*output, len + j + 1); | ||
856 | for (; j; j--) | ||
857 | { | ||
858 | (*output)[o++] = ' '; | ||
859 | len++; | ||
860 | } | ||
861 | len--; // Not counting the actual tab character itself. | ||
862 | } | ||
863 | else | ||
864 | (*output)[o++] = input[i]; | ||
865 | i++; | ||
866 | } | ||
867 | (*output)[o++] = '\0'; | ||
868 | |||
869 | return len; | ||
870 | } | ||
871 | |||
872 | void drawContentLine(view *view, int y, int start, int end, char *left, char *internal, char *contents, char *right, int current) | ||
873 | { | ||
874 | char *temp = NULL; | ||
875 | int offset = view->offsetX, len; | ||
876 | |||
877 | if (contents == view->line->line) | ||
878 | { | ||
879 | view->oW = formatLine(view, contents, &(view->output)); | ||
880 | temp = view->output; | ||
881 | len = view->oW; | ||
882 | } | ||
883 | else // Only time we are not drawing the current line, and only used for drawing the entire page. | ||
884 | len = formatLine(NULL, contents, &(temp)); | ||
885 | |||
886 | if (offset > len) | ||
887 | offset = len; | ||
888 | drawLine(y, start, end, left, internal, &(temp[offset]), right, current); | ||
889 | } | ||
890 | |||
891 | void updateLine(view *view) | ||
892 | { | ||
893 | int y, len; | ||
894 | |||
895 | // Coz things might change out from under us, find the current view. Again. | ||
896 | if (commandMode) view = commandLine; | ||
897 | else view = currentBox->view; | ||
898 | |||
899 | // TODO - When doing scripts and such, might want to turn off the line update until finished. | ||
900 | // Draw the prompt and the current line. | ||
901 | y = view->Y + (view->cY - view->offsetY); | ||
902 | len = strlen(view->prompt); | ||
903 | drawLine(y, view->X, view->X + view->W, "", " ", view->prompt, "", 0); | ||
904 | drawContentLine(view, y, view->X + len, view->X + view->W, "", " ", view->line->line, "", 1); | ||
905 | // Move the cursor. | ||
906 | printf("\x1B[%d;%dH", y + 1, view->X + len + (view->cX - view->offsetX) + 1); | ||
907 | fflush(stdout); | ||
908 | } | ||
909 | |||
910 | void doCommand(view *view, char *command) | ||
911 | { | ||
912 | if (command) | ||
913 | { | ||
914 | struct function *functions = view->content->context->commands; | ||
915 | int i; | ||
916 | |||
917 | // TODO - Some editors have a shortcut command concept. The smallest unique first part of each command will match, as well as anything longer. | ||
918 | // A further complication is if we are not implementing some commands that might change what is "shortest unique prefix". | ||
919 | |||
920 | for (i = 0; functions[i].name; i++) | ||
921 | { | ||
922 | if (strcmp(functions[i].name, command) == 0) | ||
923 | { | ||
924 | if (functions[i].handler) | ||
925 | { | ||
926 | functions[i].handler(view); | ||
927 | updateLine(view); | ||
928 | } | ||
929 | break; | ||
930 | } | ||
931 | } | ||
932 | } | ||
933 | } | ||
934 | |||
935 | int moveCursorAbsolute(view *view, long cX, long cY, long sX, long sY) | ||
936 | { | ||
937 | struct line *newLine = view->line; | ||
938 | long oX = view->offsetX, oY = view->offsetY; | ||
939 | long lX = view->oW, lY = view->content->lines.length - 1; | ||
940 | long nY = view->cY; | ||
941 | uint16_t w = view->W - 1, h = view->H - 1; | ||
942 | int moved = 0, updatedY = 0, endOfLine = 0; | ||
943 | |||
944 | // Check if it's still within the contents. | ||
945 | if (0 > cY) // Trying to move before the beginning of the content. | ||
946 | cY = 0; | ||
947 | else if (lY < cY) // Trying to move beyond end of the content. | ||
948 | cY = lY; | ||
949 | if (0 > cX) // Trying to move before the beginning of the line. | ||
950 | { | ||
951 | // See if we can move to the end of the previous line. | ||
952 | if (view->line->prev != &(view->content->lines)) | ||
953 | { | ||
954 | cY--; | ||
955 | endOfLine = 1; | ||
956 | } | ||
957 | else | ||
958 | cX = 0; | ||
959 | } | ||
960 | else if (lX < cX) // Trying to move beyond end of line. | ||
961 | { | ||
962 | // See if we can move to the begining of the next line. | ||
963 | if (view->line->next != &(view->content->lines)) | ||
964 | { | ||
965 | cY++; | ||
966 | cX = 0; | ||
967 | } | ||
968 | else | ||
969 | cX = lX; | ||
970 | } | ||
971 | |||
972 | // Find the new line. | ||
973 | while (nY != cY) | ||
974 | { | ||
975 | updatedY = 1; | ||
976 | if (nY < cY) | ||
977 | { | ||
978 | newLine = newLine->next; | ||
979 | nY++; | ||
980 | if (view->content->lines.prev == newLine) // We are at the end if we have wrapped to the beginning. | ||
981 | break; | ||
982 | } | ||
983 | else | ||
984 | { | ||
985 | newLine = newLine->prev; | ||
986 | nY--; | ||
987 | if (view->content->lines.next == newLine) // We are at the end if we have wrapped to the beginning. | ||
988 | break; | ||
989 | } | ||
990 | } | ||
991 | cY = nY; | ||
992 | |||
993 | // Check if we have moved past the end of the new line. | ||
994 | if (updatedY) | ||
995 | { | ||
996 | // Format it. | ||
997 | view->oW = formatLine(view, newLine->line, &(view->output)); | ||
998 | if (view->oW < cX) | ||
999 | endOfLine = 1; | ||
1000 | if (endOfLine) | ||
1001 | cX = view->oW; | ||
1002 | } | ||
1003 | |||
1004 | // Let the formatter decide if it wants to adjust things. | ||
1005 | // It's up to the formatter to deal with things if it changes cY. | ||
1006 | // On the other hand, changing cX is it's job. | ||
1007 | formatCheckCursor(view, &cX, &cY, newLine->line); | ||
1008 | |||
1009 | // Check the scrolling. | ||
1010 | lY -= view->H - 1; | ||
1011 | oX += sX; | ||
1012 | oY += sY; | ||
1013 | |||
1014 | if (oY > cY) // Trying to move above the box. | ||
1015 | oY += cY - oY; | ||
1016 | else if ((oY + h) < cY) // Trying to move below the box | ||
1017 | oY += cY - (oY + h); | ||
1018 | if (oX > cX) // Trying to move to the left of the box. | ||
1019 | oX += cX - oX; | ||
1020 | else if ((oX + w) <= cX) // Trying to move to the right of the box. | ||
1021 | oX += cX - (oX + w); | ||
1022 | |||
1023 | if (oY < 0) | ||
1024 | oY = 0; | ||
1025 | if (oY >= lY) | ||
1026 | oY = lY; | ||
1027 | if (oX < 0) | ||
1028 | oX = 0; | ||
1029 | // TODO - Should limit oX to less than the longest line, minus box width. | ||
1030 | // Gonna be a pain figuring out what the longest line is. | ||
1031 | // On the other hand, don't think that will be an actual issue unless "move past end of line" is enabled, and that's an advanced editor thing. | ||
1032 | // Though still might want to do that for the longest line on the new page to be. | ||
1033 | |||
1034 | if ((view->cX != cX) || (view->cY != cY)) | ||
1035 | moved = 1; | ||
1036 | |||
1037 | // Actually update stuff, though some have been done already. | ||
1038 | view->cX = cX; | ||
1039 | view->cY = cY; | ||
1040 | view->line = newLine; | ||
1041 | |||
1042 | // Handle scrolling. | ||
1043 | if ((view->offsetX != oX) || (view->offsetY != oY)) | ||
1044 | { | ||
1045 | view->offsetX = oX; | ||
1046 | view->offsetY = oY; | ||
1047 | |||
1048 | if (view->box) | ||
1049 | drawBox(view->box); | ||
1050 | } | ||
1051 | |||
1052 | return moved; | ||
1053 | } | ||
1054 | |||
1055 | int moveCursorRelative(view *view, long cX, long cY, long sX, long sY) | ||
1056 | { | ||
1057 | return moveCursorAbsolute(view, view->cX + cX, view->cY + cY, sX, sY); | ||
1058 | } | ||
1059 | |||
1060 | void sizeViewToBox(box *box, int X, int Y, int W, int H) | ||
1061 | { | ||
1062 | uint16_t one = 1, two = 2; | ||
1063 | |||
1064 | if (!(box->flags & BOX_BORDER)) | ||
1065 | { | ||
1066 | one = 0; | ||
1067 | two = 0; | ||
1068 | } | ||
1069 | box->view->X = X; | ||
1070 | box->view->Y = Y; | ||
1071 | box->view->W = W; | ||
1072 | box->view->H = H; | ||
1073 | if (0 > X) box->view->X = box->X + one; | ||
1074 | if (0 > Y) box->view->Y = box->Y + one; | ||
1075 | if (0 > W) box->view->W = box->W - two; | ||
1076 | if (0 > H) box->view->H = box->H - two; | ||
1077 | } | ||
1078 | |||
1079 | view *addView(char *name, struct context *context, char *filePath, uint16_t X, uint16_t Y, uint16_t W, uint16_t H) | ||
1080 | { | ||
1081 | view *result = xzalloc(sizeof(struct _view)); | ||
1082 | |||
1083 | result->X = X; | ||
1084 | result->Y = Y; | ||
1085 | result->W = W; | ||
1086 | result->H = H; | ||
1087 | |||
1088 | result->content = addContent(name, context, filePath); | ||
1089 | result->prompt = xzalloc(1); | ||
1090 | // If there was content, format it's first line as usual, otherwise create an empty first line. | ||
1091 | if (result->content->lines.next != &(result->content->lines)) | ||
1092 | { | ||
1093 | result->line = result->content->lines.next; | ||
1094 | result->oW = formatLine(result, result->line->line, &(result->output)); | ||
1095 | } | ||
1096 | else | ||
1097 | { | ||
1098 | result->line = addLine(result->content, NULL, "\0", 0); | ||
1099 | result->output = xzalloc(1); | ||
1100 | } | ||
1101 | |||
1102 | return result; | ||
1103 | } | ||
1104 | |||
1105 | box *addBox(char *name, struct context *context, char *filePath, uint16_t X, uint16_t Y, uint16_t W, uint16_t H) | ||
1106 | { | ||
1107 | box *result = xzalloc(sizeof(struct _box)); | ||
1108 | |||
1109 | result->X = X; | ||
1110 | result->Y = Y; | ||
1111 | result->W = W; | ||
1112 | result->H = H; | ||
1113 | result->view = addView(name, context, filePath, X, Y, W, H); | ||
1114 | result->view->box = result; | ||
1115 | sizeViewToBox(result, X, Y, W, H); | ||
1116 | |||
1117 | return result; | ||
1118 | } | ||
1119 | |||
1120 | void freeBox(box *box) | ||
1121 | { | ||
1122 | if (box) | ||
1123 | { | ||
1124 | freeBox(box->sub1); | ||
1125 | freeBox(box->sub2); | ||
1126 | if (box->view) | ||
1127 | { | ||
1128 | // In theory the line should not be part of the content if there is no content, so we should free it. | ||
1129 | if (!box->view->content) | ||
1130 | freeLine(NULL, box->view->line); | ||
1131 | free(box->view->prompt); | ||
1132 | free(box->view->output); | ||
1133 | free(box->view); | ||
1134 | } | ||
1135 | free(box); | ||
1136 | } | ||
1137 | } | ||
1138 | |||
1139 | void drawBox(box *box) | ||
1140 | { | ||
1141 | // This could be heavily optimized, but let's keep things simple for now. | ||
1142 | // Optimized for sending less characters I mean, on slow serial links for instance. | ||
1143 | |||
1144 | char **bchars = (toys.optflags & FLAG_a) ? borderChars[0] : borderChars[1]; | ||
1145 | char *left = "\0", *right = "\0"; | ||
1146 | struct line *lines = NULL; | ||
1147 | int y = box->Y, current = (box == currentBox); | ||
1148 | uint16_t h = box->Y + box->H; | ||
1149 | |||
1150 | if (current) | ||
1151 | bchars = (toys.optflags & FLAG_a) ? borderCharsCurrent[0] : borderCharsCurrent[1]; | ||
1152 | |||
1153 | // Slow and laborious way to figure out where in the linked list of lines we start from. | ||
1154 | // Wont scale well, but is simple. | ||
1155 | if (box->view && box->view->content) | ||
1156 | { | ||
1157 | int i = box->view->offsetY; | ||
1158 | |||
1159 | lines = &(box->view->content->lines); | ||
1160 | while (i--) | ||
1161 | { | ||
1162 | lines = lines->next; | ||
1163 | if (&(box->view->content->lines) == lines) // We are at the end if we have wrapped to the beginning. | ||
1164 | break; | ||
1165 | } | ||
1166 | } | ||
1167 | |||
1168 | if (box->flags & BOX_BORDER) | ||
1169 | { | ||
1170 | h--; | ||
1171 | left = right = bchars[1]; | ||
1172 | drawLine(y++, box->X, box->X + box->W, bchars[2], bchars[0], NULL, bchars[3], current); | ||
1173 | } | ||
1174 | |||
1175 | while (y < h) | ||
1176 | { | ||
1177 | char *line = ""; | ||
1178 | |||
1179 | if (lines) | ||
1180 | { | ||
1181 | lines = lines->next; | ||
1182 | if (&(box->view->content->lines) == lines) // We are at the end if we have wrapped to the beginning. | ||
1183 | lines = NULL; | ||
1184 | else | ||
1185 | line = lines->line; | ||
1186 | // Figure out which line is our current line while we are here. | ||
1187 | if (box->view->Y + (box->view->cY - box->view->offsetY) == y) | ||
1188 | box->view->line = lines; | ||
1189 | } | ||
1190 | drawContentLine(box->view, y++, box->X, box->X + box->W, left, " ", line, right, current); | ||
1191 | } | ||
1192 | if (box->flags & BOX_BORDER) | ||
1193 | drawLine(y++, box->X, box->X + box->W, bchars[4], bchars[0], NULL, bchars[5], current); | ||
1194 | fflush(stdout); | ||
1195 | } | ||
1196 | |||
1197 | void drawBoxes(box *box) | ||
1198 | { | ||
1199 | if (box->sub1) // If there's one sub box, there's always two. | ||
1200 | { | ||
1201 | drawBoxes(box->sub1); | ||
1202 | drawBoxes(box->sub2); | ||
1203 | } | ||
1204 | else | ||
1205 | drawBox(box); | ||
1206 | } | ||
1207 | |||
1208 | void calcBoxes(box *box) | ||
1209 | { | ||
1210 | if (box->sub1) // If there's one sub box, there's always two. | ||
1211 | { | ||
1212 | box->sub1->X = box->X; | ||
1213 | box->sub1->Y = box->Y; | ||
1214 | box->sub1->W = box->W; | ||
1215 | box->sub1->H = box->H; | ||
1216 | box->sub2->X = box->X; | ||
1217 | box->sub2->Y = box->Y; | ||
1218 | box->sub2->W = box->W; | ||
1219 | box->sub2->H = box->H; | ||
1220 | if (box->flags & BOX_HSPLIT) | ||
1221 | { | ||
1222 | box->sub1->H *= box->split; | ||
1223 | box->sub2->H -= box->sub1->H; | ||
1224 | box->sub2->Y += box->sub1->H; | ||
1225 | } | ||
1226 | else | ||
1227 | { | ||
1228 | box->sub1->W *= box->split; | ||
1229 | box->sub2->W -= box->sub1->W; | ||
1230 | box->sub2->X += box->sub1->W; | ||
1231 | } | ||
1232 | sizeViewToBox(box->sub1, -1, -1, -1, -1); | ||
1233 | calcBoxes(box->sub1); | ||
1234 | sizeViewToBox(box->sub2, -1, -1, -1, -1); | ||
1235 | calcBoxes(box->sub2); | ||
1236 | } | ||
1237 | // Move the cursor to where it is, to check it's not now outside the box. | ||
1238 | moveCursorAbsolute(box->view, box->view->cX, box->view->cY, 0, 0); | ||
1239 | |||
1240 | // We could call drawBoxes() here, but this is recursive, and so is drawBoxes(). | ||
1241 | // The combination might be deadly. Drawing the content of a box might be an expensive operation. | ||
1242 | // Later we might use a dirty box flag to deal with this, if it's not too much of a complication. | ||
1243 | } | ||
1244 | |||
1245 | void deleteBox(view *view) | ||
1246 | { | ||
1247 | box *box = view->box; | ||
1248 | |||
1249 | if (box->parent) | ||
1250 | { | ||
1251 | struct _box *oldBox = box, *otherBox = box->parent->sub1; | ||
1252 | |||
1253 | if (otherBox == oldBox) | ||
1254 | otherBox = box->parent->sub2; | ||
1255 | if (currentBox->parent == box->parent) | ||
1256 | currentBox = box->parent; | ||
1257 | box = box->parent; | ||
1258 | box->X = box->sub1->X; | ||
1259 | box->Y = box->sub1->Y; | ||
1260 | if (box->flags & BOX_HSPLIT) | ||
1261 | box->H = box->sub1->H + box->sub2->H; | ||
1262 | else | ||
1263 | box->W = box->sub1->W + box->sub2->W; | ||
1264 | box->flags &= ~BOX_HSPLIT; | ||
1265 | // Move the other sub boxes contents up to this box. | ||
1266 | box->sub1 = otherBox->sub1; | ||
1267 | box->sub2 = otherBox->sub2; | ||
1268 | if (box->sub1) | ||
1269 | { | ||
1270 | box->sub1->parent = box; | ||
1271 | box->sub2->parent = box; | ||
1272 | box->flags = otherBox->flags; | ||
1273 | if (currentBox == box) | ||
1274 | currentBox = box->sub1; | ||
1275 | } | ||
1276 | else | ||
1277 | { | ||
1278 | if (!box->parent) | ||
1279 | box->flags &= ~BOX_BORDER; | ||
1280 | box->split = 1.0; | ||
1281 | } | ||
1282 | otherBox->sub1 = NULL; | ||
1283 | otherBox->sub2 = NULL; | ||
1284 | // Safe to free the boxes now that we have all their contents. | ||
1285 | freeBox(otherBox); | ||
1286 | freeBox(oldBox); | ||
1287 | } | ||
1288 | // Otherwise it must be a single full screen box. Never delete that one, unless we are quitting. | ||
1289 | |||
1290 | // Start the recursive recalculation of all the sub boxes. | ||
1291 | calcBoxes(box); | ||
1292 | drawBoxes(box); | ||
1293 | } | ||
1294 | |||
1295 | void cloneBox(struct _box *box, struct _box *sub) | ||
1296 | { | ||
1297 | sub->parent = box; | ||
1298 | // Only a full screen box has no border. | ||
1299 | sub->flags |= BOX_BORDER; | ||
1300 | sub->view = xmalloc(sizeof(struct _view)); | ||
1301 | // TODO - After this is more stable, should check if the memcpy() is simpler than - xzalloc() then copy a few things manually. | ||
1302 | // Might even be able to arrange the structure so we can memcpy just part of it, leaving the rest blank. | ||
1303 | memcpy(sub->view, box->view, sizeof(struct _view)); | ||
1304 | sub->view->damage = NULL; | ||
1305 | sub->view->data = NULL; | ||
1306 | sub->view->output = NULL; | ||
1307 | sub->view->box = sub; | ||
1308 | if (box->view->prompt) | ||
1309 | sub->view->prompt = strdup(box->view->prompt); | ||
1310 | } | ||
1311 | |||
1312 | void splitBox(box *box, float split) | ||
1313 | { | ||
1314 | uint16_t size; | ||
1315 | int otherBox = 0; | ||
1316 | |||
1317 | // First some sanity checks. | ||
1318 | if (0.0 > split) | ||
1319 | { | ||
1320 | // TODO - put this in the status line, or just silently fail. Also, better message. lol | ||
1321 | fprintf(stderr, "User is crazy.\n"); | ||
1322 | return; | ||
1323 | } | ||
1324 | else if (1.0 <= split) // User meant to unsplit, and it may already be split. | ||
1325 | { | ||
1326 | // Actually, this means that the OTHER sub box gets deleted. | ||
1327 | if (box->parent) | ||
1328 | { | ||
1329 | if (box == box->parent->sub1) | ||
1330 | deleteBox(box->parent->sub2->view); | ||
1331 | else | ||
1332 | deleteBox(box->parent->sub1->view); | ||
1333 | } | ||
1334 | return; | ||
1335 | } | ||
1336 | else if (0.0 < split) // This is the normal case, so do nothing. | ||
1337 | { | ||
1338 | } | ||
1339 | else // User meant to delete this, zero split. | ||
1340 | { | ||
1341 | deleteBox(box->view); | ||
1342 | return; | ||
1343 | } | ||
1344 | if (box->flags & BOX_HSPLIT) | ||
1345 | size = box->H; | ||
1346 | else | ||
1347 | size = box->W; | ||
1348 | if (6 > size) // Is there room for 2 borders for each sub box and one character of content each? | ||
1349 | // TODO - also should check the contents minimum size. | ||
1350 | // No need to check the no border case, that's only for full screen. | ||
1351 | // People using terminals smaller than 6 characters get what they deserve. | ||
1352 | { | ||
1353 | // TODO - put this in the status line, or just silently fail. | ||
1354 | fprintf(stderr, "Box is too small to split.\n"); | ||
1355 | return; | ||
1356 | } | ||
1357 | |||
1358 | // Note that a split box is actually three boxes. The parent, which is not drawn, and the two subs, which are. | ||
1359 | // Based on the assumption that there wont be lots of boxes, this keeps things simple. | ||
1360 | // It's possible that the box has already been split, and this is called just to update the split. | ||
1361 | box->split = split; | ||
1362 | if (NULL == box->sub1) // If not split already, do so. | ||
1363 | { | ||
1364 | box->sub1 = xzalloc(sizeof(struct _box)); | ||
1365 | box->sub2 = xzalloc(sizeof(struct _box)); | ||
1366 | cloneBox(box, box->sub1); | ||
1367 | cloneBox(box, box->sub2); | ||
1368 | if (box->flags & BOX_HSPLIT) | ||
1369 | { | ||
1370 | // Split the boxes in the middle of the content. | ||
1371 | box->sub2->view->offsetY += (box->H * box->split) - 2; | ||
1372 | // Figure out which sub box the cursor will be in, then update the cursor in the other box. | ||
1373 | if (box->sub1->view->cY < box->sub2->view->offsetY) | ||
1374 | box->sub2->view->cY = box->sub2->view->offsetY; | ||
1375 | else | ||
1376 | { | ||
1377 | box->sub1->view->cY = box->sub2->view->offsetY - 1; | ||
1378 | otherBox = 1; | ||
1379 | } | ||
1380 | } | ||
1381 | else | ||
1382 | { | ||
1383 | // Split the boxes in the middle of the content. | ||
1384 | box->sub2->view->offsetX += (box->W * box->split) - 2; | ||
1385 | // Figure out which sub box the cursor will be in, then update the cursor in the other box. | ||
1386 | if (box->sub1->view->cX < box->sub2->view->offsetX) | ||
1387 | box->sub2->view->cX = box->sub2->view->offsetX; | ||
1388 | else | ||
1389 | { | ||
1390 | box->sub1->view->cX = box->sub2->view->offsetX - 1; | ||
1391 | otherBox = 1; | ||
1392 | } | ||
1393 | } | ||
1394 | } | ||
1395 | |||
1396 | if ((currentBox == box) && (box->sub1)) | ||
1397 | { | ||
1398 | if (otherBox) | ||
1399 | currentBox = box->sub2; | ||
1400 | else | ||
1401 | currentBox = box->sub1; | ||
1402 | } | ||
1403 | |||
1404 | // Start the recursive recalculation of all the sub boxes. | ||
1405 | calcBoxes(box); | ||
1406 | drawBoxes(box); | ||
1407 | } | ||
1408 | |||
1409 | // TODO - Might be better to just have a double linked list of boxes, and traverse that instead. | ||
1410 | // Except that leaves a problem when deleting boxes, could end up with a blank space. | ||
1411 | void switchBoxes(view *view) | ||
1412 | { | ||
1413 | box *box = view->box; | ||
1414 | |||
1415 | // The assumption here is that box == currentBox. | ||
1416 | struct _box *oldBox = currentBox; | ||
1417 | struct _box *thisBox = box; | ||
1418 | int backingUp = 0; | ||
1419 | |||
1420 | // Depth first traversal. | ||
1421 | while ((oldBox == currentBox) && (thisBox->parent)) | ||
1422 | { | ||
1423 | if (thisBox == thisBox->parent->sub1) | ||
1424 | { | ||
1425 | if (backingUp && (thisBox->parent)) | ||
1426 | currentBox = thisBox->parent->sub2; | ||
1427 | else if (thisBox->sub1) | ||
1428 | currentBox = thisBox->sub1; | ||
1429 | else | ||
1430 | currentBox = thisBox->parent->sub2; | ||
1431 | } | ||
1432 | else if (thisBox == thisBox->parent->sub2) | ||
1433 | { | ||
1434 | thisBox = thisBox->parent; | ||
1435 | backingUp = 1; | ||
1436 | } | ||
1437 | } | ||
1438 | |||
1439 | // If we have not found the next box to move to, move back to the beginning. | ||
1440 | if (oldBox == currentBox) | ||
1441 | currentBox = rootBox; | ||
1442 | |||
1443 | // If we ended up on a parent box, go to it's first sub. | ||
1444 | while (currentBox->sub1) | ||
1445 | currentBox = currentBox->sub1; | ||
1446 | |||
1447 | // Just redraw them all. | ||
1448 | drawBoxes(rootBox); | ||
1449 | } | ||
1450 | |||
1451 | // TODO - It might be better to do away with this bunch of single line functions | ||
1452 | // and map script commands directly to lower functions. | ||
1453 | // How to deal with the various argument needs? | ||
1454 | // Might be where we can re use the toybox argument stuff. | ||
1455 | |||
1456 | void halveBoxHorizontally(view *view) | ||
1457 | { | ||
1458 | view->box->flags |= BOX_HSPLIT; | ||
1459 | splitBox(view->box, 0.5); | ||
1460 | } | ||
1461 | |||
1462 | void halveBoxVertically(view *view) | ||
1463 | { | ||
1464 | view->box->flags &= ~BOX_HSPLIT; | ||
1465 | splitBox(view->box, 0.5); | ||
1466 | } | ||
1467 | |||
1468 | void switchMode(view *view) | ||
1469 | { | ||
1470 | currentBox->view->mode++; | ||
1471 | // Assumes that modes will always have a key mapping, which I think is a safe bet. | ||
1472 | if (NULL == currentBox->view->content->context->modes[currentBox->view->mode].keys) | ||
1473 | currentBox->view->mode = 0; | ||
1474 | commandMode = currentBox->view->content->context->modes[currentBox->view->mode].flags & 1; | ||
1475 | } | ||
1476 | |||
1477 | void leftChar(view *view) | ||
1478 | { | ||
1479 | moveCursorRelative(view, -1, 0, 0, 0); | ||
1480 | } | ||
1481 | |||
1482 | void rightChar(view *view) | ||
1483 | { | ||
1484 | moveCursorRelative(view, 1, 0, 0, 0); | ||
1485 | } | ||
1486 | |||
1487 | void upLine(view *view) | ||
1488 | { | ||
1489 | moveCursorRelative(view, 0, -1, 0, 0); | ||
1490 | } | ||
1491 | |||
1492 | void downLine(view *view) | ||
1493 | { | ||
1494 | moveCursorRelative(view, 0, 1, 0, 0); | ||
1495 | } | ||
1496 | |||
1497 | void upPage(view *view) | ||
1498 | { | ||
1499 | moveCursorRelative(view, 0, 0 - (view->H - 1), 0, 0 - (view->H - 1)); | ||
1500 | } | ||
1501 | |||
1502 | void downPage(view *view) | ||
1503 | { | ||
1504 | moveCursorRelative(view, 0, view->H - 1, 0, view->H - 1); | ||
1505 | } | ||
1506 | |||
1507 | void endOfLine(view *view) | ||
1508 | { | ||
1509 | moveCursorAbsolute(view, strlen(view->prompt) + view->oW, view->cY, 0, 0); | ||
1510 | } | ||
1511 | |||
1512 | void startOfLine(view *view) | ||
1513 | { | ||
1514 | // TODO - add the advanced editing "smart home". | ||
1515 | moveCursorAbsolute(view, strlen(view->prompt), view->cY, 0, 0); | ||
1516 | } | ||
1517 | |||
1518 | void splitLine(view *view) | ||
1519 | { | ||
1520 | // TODO - should move this into mooshLines(). | ||
1521 | addLine(view->content, view->line, &(view->line->line[view->iX]), 0); | ||
1522 | view->line->line[view->iX] = '\0'; | ||
1523 | moveCursorAbsolute(view, 0, view->cY + 1, 0, 0); | ||
1524 | if (view->box) | ||
1525 | drawBox(view->box); | ||
1526 | } | ||
1527 | |||
1528 | void deleteChar(view *view) | ||
1529 | { | ||
1530 | // TODO - should move this into mooshLines(). | ||
1531 | // If we are at the end of the line, then join this and the next line. | ||
1532 | if (view->oW == view->cX) | ||
1533 | { | ||
1534 | // Only if there IS a next line. | ||
1535 | if (&(view->content->lines) != view->line->next) | ||
1536 | { | ||
1537 | mooshStrings(view->line, view->line->next->line, view->iX, 1, !overWriteMode); | ||
1538 | view->line->next->line = NULL; | ||
1539 | freeLine(view->content, view->line->next); | ||
1540 | // TODO - should check if we are on the last page, then deal with scrolling. | ||
1541 | if (view->box) | ||
1542 | drawBox(view->box); | ||
1543 | } | ||
1544 | } | ||
1545 | else | ||
1546 | mooshStrings(view->line, NULL, view->iX, 1, !overWriteMode); | ||
1547 | } | ||
1548 | |||
1549 | void backSpaceChar(view *view) | ||
1550 | { | ||
1551 | if (moveCursorRelative(view, -1, 0, 0, 0)) | ||
1552 | deleteChar(view); | ||
1553 | } | ||
1554 | |||
1555 | void saveContent(view *view) | ||
1556 | { | ||
1557 | saveFile(view->content); | ||
1558 | } | ||
1559 | |||
1560 | void executeLine(view *view) | ||
1561 | { | ||
1562 | struct line *result = view->line; | ||
1563 | |||
1564 | // Don't bother doing much if there's nothing on this line. | ||
1565 | if (result->line[0]) | ||
1566 | { | ||
1567 | doCommand(currentBox->view, result->line); | ||
1568 | // If we are not at the end of the history contents. | ||
1569 | if (&(view->content->lines) != result->next) | ||
1570 | { | ||
1571 | struct line *line = view->content->lines.prev; | ||
1572 | |||
1573 | // Remove the line first. | ||
1574 | result->next->prev = result->prev; | ||
1575 | result->prev->next = result->next; | ||
1576 | // Check if the last line is already blank, then remove it. | ||
1577 | if ('\0' == line->line[0]) | ||
1578 | { | ||
1579 | freeLine(view->content, line); | ||
1580 | line = view->content->lines.prev; | ||
1581 | } | ||
1582 | // Then add it to the end. | ||
1583 | result->next = line->next; | ||
1584 | result->prev = line; | ||
1585 | line->next->prev = result; | ||
1586 | line->next = result; | ||
1587 | view->cY = view->content->lines.length - 1; | ||
1588 | } | ||
1589 | moveCursorAbsolute(view, 0, view->content->lines.length, 0, 0); | ||
1590 | // Make sure there is one blank line at the end. | ||
1591 | if ('\0' != view->line->line[0]) | ||
1592 | { | ||
1593 | endOfLine(view); | ||
1594 | splitLine(view); | ||
1595 | } | ||
1596 | } | ||
1597 | |||
1598 | saveFile(view->content); | ||
1599 | } | ||
1600 | |||
1601 | void quit(view *view) | ||
1602 | { | ||
1603 | handle_keys_quit(); | ||
1604 | } | ||
1605 | |||
1606 | void nop(view *view) | ||
1607 | { | ||
1608 | // 'tis a nop, don't actually do anything. | ||
1609 | } | ||
1610 | |||
1611 | |||
1612 | typedef void (*CSIhandler) (long extra, int *code, int count); | ||
1613 | |||
1614 | struct CSI | ||
1615 | { | ||
1616 | char *code; | ||
1617 | CSIhandler func; | ||
1618 | }; | ||
1619 | |||
1620 | static void termSize(long extra, int *params, int count) | ||
1621 | { | ||
1622 | struct _view *view = (struct _view *) extra; // Though we pretty much stomp on this straight away. | ||
1623 | int r = params[0], c = params[1]; | ||
1624 | |||
1625 | // The defaults are 1, which get ignored by the heuristic below. | ||
1626 | // Check it's not an F3 key variation, coz some of them use the same CSI function code. | ||
1627 | // This is a heuristic, we are checking against an unusable terminal size. | ||
1628 | // TODO - Double check what the maximum F3 variations can be. | ||
1629 | if ((2 == count) && (8 < r) && (8 < c)) | ||
1630 | { | ||
1631 | commandLine->Y = r; | ||
1632 | commandLine->W = c; | ||
1633 | rootBox->W = c; | ||
1634 | rootBox->H = r - 1; | ||
1635 | sizeViewToBox(rootBox, -1, -1, -1, -1); | ||
1636 | calcBoxes(rootBox); | ||
1637 | drawBoxes(rootBox); | ||
1638 | |||
1639 | // Move the cursor to where it is, to check it's not now outside the terminal window. | ||
1640 | moveCursorAbsolute(rootBox->view, rootBox->view->cX, rootBox->view->cY, 0, 0); | ||
1641 | |||
1642 | // We have no idea which is the current view now. | ||
1643 | if (commandMode) view = commandLine; | ||
1644 | else view = currentBox->view; | ||
1645 | updateLine(view); | ||
1646 | } | ||
1647 | } | ||
1648 | |||
1649 | struct CSI CSIcommands[] = | ||
1650 | { | ||
1651 | {"R", termSize} // Parameters are cursor line and column. Note this may be sent at other times, not just during terminal resize. | ||
1652 | }; | ||
1653 | |||
1654 | |||
1655 | // Callback for incoming sequences from the terminal. | ||
1656 | static int handleEvent(long extra, struct keyevent *event) | ||
1657 | { | ||
1658 | switch (event->type) | ||
1659 | { | ||
1660 | case HK_CSI : | ||
1661 | { | ||
1662 | int j; | ||
1663 | |||
1664 | for (j = 0; j < ARRAY_LEN(CSIcommands); j++) | ||
1665 | { | ||
1666 | if (strcmp(CSIcommands[j].code, event->sequence) == 0) | ||
1667 | { | ||
1668 | CSIcommands[j].func(extra, event->params, event->count); | ||
1669 | break; | ||
1670 | } | ||
1671 | } | ||
1672 | break; | ||
1673 | } | ||
1674 | |||
1675 | case HK_KEYS : | ||
1676 | { | ||
1677 | struct _view *view = (struct _view *) extra; // Though we pretty much stomp on this straight away. | ||
1678 | struct keyCommand *commands = currentBox->view->content->context->modes[currentBox->view->mode].keys; | ||
1679 | int j, l = strlen(event->sequence); | ||
1680 | |||
1681 | // Coz things might change out from under us, find the current view. | ||
1682 | if (commandMode) view = commandLine; | ||
1683 | else view = currentBox->view; | ||
1684 | |||
1685 | // Search for a key sequence bound to a command. | ||
1686 | for (j = 0; commands[j].key; j++) | ||
1687 | { | ||
1688 | if (strncmp(commands[j].key, event->sequence, l) == 0) | ||
1689 | { | ||
1690 | // If it's a partial match, keep accumulating them. | ||
1691 | if (strlen(commands[j].key) != l) | ||
1692 | return 0; | ||
1693 | else | ||
1694 | { | ||
1695 | doCommand(view, commands[j].command); | ||
1696 | return 1; | ||
1697 | } | ||
1698 | } | ||
1699 | } | ||
1700 | |||
1701 | // See if it's ordinary keys. | ||
1702 | // NOTE - with vi style ordinary keys can be commands, | ||
1703 | // but they would be found by the command check above first. | ||
1704 | if (!event->isTranslated) | ||
1705 | { | ||
1706 | // TODO - Should check for tabs to, and insert them. | ||
1707 | // Though better off having a function for that? | ||
1708 | mooshStrings(view->line, event->sequence, view->iX, 0, !overWriteMode); | ||
1709 | view->oW = formatLine(view, view->line->line, &(view->output)); | ||
1710 | moveCursorRelative(view, strlen(event->sequence), 0, 0, 0); | ||
1711 | updateLine(view); | ||
1712 | } | ||
1713 | break; | ||
1714 | } | ||
1715 | |||
1716 | default : break; | ||
1717 | } | ||
1718 | |||
1719 | // Tell handle_keys to drop it, coz we dealt with it, or it's not one of ours. | ||
1720 | return 1; | ||
1721 | } | ||
1722 | |||
1723 | |||
1724 | // The default command to function mappings, with help text. Any editor that does not have it's own commands can use these for keystroke binding and such. | ||
1725 | // Though most of the editors have their own variation. | ||
1726 | // TODO - Maybe just use the joe one as default, it uses short names at least. | ||
1727 | // Though vi is the only one in POSIX, so might be better to treat that one as the "standard" default. | ||
1728 | // With some commands from others for stuff vi doesn't support. | ||
1729 | struct function simpleEditCommands[] = | ||
1730 | { | ||
1731 | {"backSpaceChar", "Back space last character.", 0, {backSpaceChar}}, | ||
1732 | {"deleteBox", "Delete a box.", 0, {deleteBox}}, | ||
1733 | {"deleteChar", "Delete current character.", 0, {deleteChar}}, | ||
1734 | {"downLine", "Move cursor down one line.", 0, {downLine}}, | ||
1735 | {"downPage", "Move cursor down one page.", 0, {downPage}}, | ||
1736 | {"endOfLine", "Go to end of line.", 0, {endOfLine}}, | ||
1737 | {"executeLine", "Execute a line as a script.", 0, {executeLine}}, | ||
1738 | {"leftChar", "Move cursor left one character.", 0, {leftChar}}, | ||
1739 | {"quit", "Quit the application.", 0, {quit}}, | ||
1740 | {"rightChar", "Move cursor right one character.", 0, {rightChar}}, | ||
1741 | {"save", "Save.", 0, {saveContent}}, | ||
1742 | {"splitH", "Split box in half horizontally.", 0, {halveBoxHorizontally}}, | ||
1743 | {"splitLine", "Split line at cursor.", 0, {splitLine}}, | ||
1744 | {"splitV", "Split box in half vertically.", 0, {halveBoxVertically}}, | ||
1745 | {"startOfLine", "Go to start of line.", 0, {startOfLine}}, | ||
1746 | {"switchBoxes", "Switch to another box.", 0, {switchBoxes}}, | ||
1747 | {"switchMode", "Switch between command and box.", 0, {switchMode}}, | ||
1748 | {"upLine", "Move cursor up one line.", 0, {upLine}}, | ||
1749 | {"upPage", "Move cursor up one page.", 0, {upPage}}, | ||
1750 | {NULL, NULL, 0, {NULL}} | ||
1751 | }; | ||
1752 | |||
1753 | // Construct a simple command line. | ||
1754 | |||
1755 | // The key to command mappings. | ||
1756 | // TODO - Should not move off the ends of the line to the next / previous line. | ||
1757 | struct keyCommand simpleCommandKeys[] = | ||
1758 | { | ||
1759 | {"BS", "backSpaceChar"}, | ||
1760 | {"Del", "deleteChar"}, | ||
1761 | {"Down", "downLine"}, | ||
1762 | {"End", "endOfLine"}, | ||
1763 | {"F10", "quit"}, | ||
1764 | {"Home", "startOfLine"}, | ||
1765 | {"Left", "leftChar"}, | ||
1766 | {"Enter", "executeLine"}, | ||
1767 | {"Return", "executeLine"}, | ||
1768 | {"Right", "rightChar"}, | ||
1769 | {"Esc", "switchMode"}, | ||
1770 | {"Up", "upLine"}, | ||
1771 | {NULL, NULL} | ||
1772 | }; | ||
1773 | |||
1774 | |||
1775 | // Construct a simple emacs editor. | ||
1776 | |||
1777 | // Mostly control keys, some meta keys. | ||
1778 | // Ctrl-h and Ctrl-x have more keys in the commands. Some of those extra keys are commands by themselves. Up to "Ctrl-x 4 Ctrl-g" which apparently is identical to just Ctrl-g. shrugs | ||
1779 | // Ctrl-h is backspace / del. Pffft. | ||
1780 | // Meta key is either Alt-keystroke, Esc keystroke, or an actual Meta-keystroke (do they still exist?). | ||
1781 | // TODO - Alt and Meta not supported yet, so using Esc. | ||
1782 | // Windows commands. | ||
1783 | |||
1784 | // readline uses these same commands, and defaults to emacs keystrokes. | ||
1785 | struct function simpleEmacsCommands[] = | ||
1786 | { | ||
1787 | {"delete-backward-char", "Back space last character.", 0, {backSpaceChar}}, | ||
1788 | {"delete-window", "Delete a box.", 0, {deleteBox}}, | ||
1789 | {"delete-char", "Delete current character.", 0, {deleteChar}}, | ||
1790 | {"next-line", "Move cursor down one line.", 0, {downLine}}, | ||
1791 | {"scroll-up", "Move cursor down one page.", 0, {downPage}}, | ||
1792 | {"end-of-line", "Go to end of line.", 0, {endOfLine}}, | ||
1793 | {"accept-line", "Execute a line as a script.", 0, {executeLine}}, // From readline, which uses emacs commands, coz mg at least does not seem to have this. | ||
1794 | {"backward-char", "Move cursor left one character.", 0, {leftChar}}, | ||
1795 | {"save-buffers-kill-emacs", "Quit the application.", 0, {quit}}, // TODO - Does more than just quit. | ||
1796 | {"forward-char", "Move cursor right one character.", 0, {rightChar}}, | ||
1797 | {"save-buffer", "Save.", 0, {saveContent}}, | ||
1798 | {"split-window-horizontally", "Split box in half horizontally.", 0, {halveBoxHorizontally}}, // TODO - Making this one up for now, mg does not have it. | ||
1799 | {"newline", "Split line at cursor.", 0, {splitLine}}, | ||
1800 | {"split-window-vertically", "Split box in half vertically.", 0, {halveBoxVertically}}, | ||
1801 | {"beginning-of-line", "Go to start of line.", 0, {startOfLine}}, | ||
1802 | {"other-window", "Switch to another box.", 0, {switchBoxes}}, // There is also "previous-window" for going in the other direction, which we don't support yet. | ||
1803 | {"execute-extended-command", "Switch between command and box.", 0, {switchMode}}, // Actually a one time invocation of the command line. | ||
1804 | {"previous-line", "Move cursor up one line.", 0, {upLine}}, | ||
1805 | {"scroll-down", "Move cursor up one page.", 0, {upPage}}, | ||
1806 | {NULL, NULL, 0, {NULL}} | ||
1807 | }; | ||
1808 | |||
1809 | // The key to command mappings. | ||
1810 | struct keyCommand simpleEmacsKeys[] = | ||
1811 | { | ||
1812 | {"BS", "delete-backward-char"}, | ||
1813 | {"Del", "delete-backward-char"}, | ||
1814 | {"^D", "delete-char"}, | ||
1815 | {"Down", "next-line"}, | ||
1816 | {"^N", "next-line"}, | ||
1817 | {"End", "end-of-line"}, | ||
1818 | {"^E", "end-of-line"}, | ||
1819 | {"^X^C", "save-buffers-kill-emacs"}, | ||
1820 | {"^X^S", "save-buffer"}, | ||
1821 | {"Home", "beginning-of-line"}, | ||
1822 | {"^A", "beginning-of-line"}, | ||
1823 | {"Left", "backward-char"}, | ||
1824 | {"^B", "backward-char"}, | ||
1825 | {"PgDn", "scroll-up"}, | ||
1826 | {"^V", "scroll-up"}, | ||
1827 | {"PgUp", "scroll-down"}, | ||
1828 | {"Escv", "scroll-down"}, // M-v | ||
1829 | {"Enter", "newline"}, | ||
1830 | {"Return", "newline"}, | ||
1831 | {"Right", "forward-char"}, | ||
1832 | {"^F", "forward-char"}, | ||
1833 | {"Escx", "execute-extended-command"}, // M-x | ||
1834 | {"^X2", "split-window-vertically"}, | ||
1835 | {"^XP", "other-window"}, | ||
1836 | {"^X0", "delete-window"}, | ||
1837 | {"Up", "previous-line"}, | ||
1838 | {"^P", "previous-line"}, | ||
1839 | {NULL, NULL} | ||
1840 | }; | ||
1841 | |||
1842 | struct keyCommand simpleEmacsCommandKeys[] = | ||
1843 | { | ||
1844 | {"Del", "delete-backwards-char"}, | ||
1845 | {"^D", "delete-char"}, | ||
1846 | {"Down", "next-line"}, | ||
1847 | {"^N", "next-line"}, | ||
1848 | {"End", "end-of-line"}, | ||
1849 | {"^E", "end-of-line"}, | ||
1850 | {"Home", "beginning-of-line"}, | ||
1851 | {"^A", "beginning-of-line"}, | ||
1852 | {"Left", "backward-char"}, | ||
1853 | {"^B", "backward-char"}, | ||
1854 | {"Right", "forward-char"}, | ||
1855 | {"^F", "forward-char"}, | ||
1856 | {"Up", "previous-line"}, | ||
1857 | {"^P", "previous-line"}, | ||
1858 | {"Enter", "accept-line"}, | ||
1859 | {"Return", "accept-line"}, | ||
1860 | {"Escx", "execute-extended-command"}, | ||
1861 | {NULL, NULL} | ||
1862 | }; | ||
1863 | |||
1864 | // An array of various modes. | ||
1865 | struct mode simpleEmacsMode[] = | ||
1866 | { | ||
1867 | {simpleEmacsKeys, NULL, NULL, 0}, | ||
1868 | {simpleEmacsCommandKeys, NULL, NULL, 1}, | ||
1869 | {NULL, NULL, NULL} | ||
1870 | }; | ||
1871 | |||
1872 | // Put it all together into a simple editor context. | ||
1873 | struct context simpleEmacs = | ||
1874 | { | ||
1875 | simpleEmacsCommands, | ||
1876 | simpleEmacsMode, | ||
1877 | NULL, | ||
1878 | NULL, | ||
1879 | NULL | ||
1880 | }; | ||
1881 | |||
1882 | |||
1883 | // Construct a simple joe / wordstar editor, using joe is the reference, seems to be the popular Unix variant. | ||
1884 | // Esc x starts up the command line. | ||
1885 | // Has multi control key combos. Mostly Ctrl-K, Ctrl-[ (Esc), (Ctrl-B, Ctrl-Q in wordstar and delphi), but might be others. | ||
1886 | // Can't find a single list of command mappings for joe, gotta search all over. sigh | ||
1887 | // Even the command line keystroke I stumbled on (Esc x) is not documented. | ||
1888 | // Note that you don't have to let go of the Ctrl key for the second keystroke, but you can. | ||
1889 | |||
1890 | // From http://joe-editor.sourceforge.net/list.html | ||
1891 | // TODO - Some of these might be wrong. Just going by the inadequate joe docs for now. | ||
1892 | struct function simpleJoeCommands[] = | ||
1893 | { | ||
1894 | {"backs", "Back space last character.", 0, {backSpaceChar}}, | ||
1895 | {"abort", "Delete a box.", 0, {deleteBox}}, // TODO - Should do quit if it's the last window. | ||
1896 | {"delch", "Delete current character.", 0, {deleteChar}}, | ||
1897 | {"dnarw", "Move cursor down one line.", 0, {downLine}}, | ||
1898 | {"pgdn", "Move cursor down one page.", 0, {downPage}}, | ||
1899 | {"eol", "Go to end of line.", 0, {endOfLine}}, | ||
1900 | {"ltarw", "Move cursor left one character.", 0, {leftChar}}, | ||
1901 | {"killjoe", "Quit the application.", 0, {quit}}, | ||
1902 | {"rtarw", "Move cursor right one character.", 0, {rightChar}}, | ||
1903 | {"save", "Save.", 0, {saveContent}}, | ||
1904 | {"splitw", "Split box in half horizontally.", 0, {halveBoxHorizontally}}, | ||
1905 | {"open", "Split line at cursor.", 0, {splitLine}}, | ||
1906 | {"bol", "Go to start of line.", 0, {startOfLine}}, | ||
1907 | {"home", "Go to start of line.", 0, {startOfLine}}, | ||
1908 | {"nextw", "Switch to another box.", 0, {switchBoxes}}, // This is "next window", there's also "previous window" which we don't support yet. | ||
1909 | {"execmd", "Switch between command and box.", 0, {switchMode}}, // Actually I think this just switches to the command mode, not back and forth. Or it might execute the actual command. | ||
1910 | {"uparw", "Move cursor up one line.", 0, {upLine}}, | ||
1911 | {"pgup", "Move cursor up one page.", 0, {upPage}}, | ||
1912 | |||
1913 | // Not an actual joe command. | ||
1914 | {"executeLine", "Execute a line as a script.", 0, {executeLine}}, // Perhaps this should be execmd? | ||
1915 | {NULL, NULL, 0, {NULL}} | ||
1916 | }; | ||
1917 | |||
1918 | struct keyCommand simpleJoeKeys[] = | ||
1919 | { | ||
1920 | {"BS", "backs"}, | ||
1921 | {"^D", "delch"}, | ||
1922 | {"Down", "dnarw"}, | ||
1923 | {"^N", "dnarw"}, | ||
1924 | {"^E", "eol"}, | ||
1925 | {"^C", "killjoe"}, | ||
1926 | {"^Kd", "save"}, | ||
1927 | {"^K^D" "save"}, | ||
1928 | {"^A", "bol"}, | ||
1929 | {"Left", "ltarw"}, | ||
1930 | {"^B", "ltarw"}, | ||
1931 | {"^V", "pgdn"}, // Actually half a page. | ||
1932 | {"^U", "pgup"}, // Actually half a page. | ||
1933 | {"Enter", "open"}, | ||
1934 | {"Return", "open"}, | ||
1935 | {"Right", "rtarw"}, | ||
1936 | {"^F", "rtarw"}, | ||
1937 | {"Escx", "execmd"}, | ||
1938 | {"Esc^X", "execmd"}, | ||
1939 | {"^Ko", "splitw"}, | ||
1940 | {"^K^O", "splitw"}, | ||
1941 | {"^Kn", "nextw"}, | ||
1942 | {"^K^N", "nextw"}, | ||
1943 | {"^Kx", "killjoe"}, // TODO - Should ask if it should save if it's been modified. A good generic thing to do anyway. | ||
1944 | {"^K^X", "abort"}, // TODO - These two both close a window, and quit if that was the last window. | ||
1945 | {"Up", "uparw"}, | ||
1946 | {"^P", "uparw"}, | ||
1947 | {NULL, NULL} | ||
1948 | }; | ||
1949 | |||
1950 | struct keyCommand simpleJoeCommandKeys[] = | ||
1951 | { | ||
1952 | {"BS", "backs"}, | ||
1953 | {"^D", "delch"}, | ||
1954 | {"Down", "dnarw"}, | ||
1955 | {"^N", "dnarw"}, | ||
1956 | {"^E", "eol"}, | ||
1957 | {"^A", "bol"}, | ||
1958 | {"Left", "ltarw"}, | ||
1959 | {"^B", "ltarw"}, | ||
1960 | {"Right", "rtarw"}, | ||
1961 | {"^F", "rtarw"}, | ||
1962 | {"Escx", "execmd"}, | ||
1963 | {"Esc^X", "execmd"}, | ||
1964 | {"Up", "uparw"}, | ||
1965 | {"^P", "uparw"}, | ||
1966 | {"Enter", "executeLine"}, | ||
1967 | {"Return", "executeLine"}, | ||
1968 | {NULL, NULL} | ||
1969 | }; | ||
1970 | |||
1971 | struct mode simpleJoeMode[] = | ||
1972 | { | ||
1973 | {simpleJoeKeys, NULL, NULL, 0}, | ||
1974 | {simpleJoeCommandKeys, NULL, NULL, 1}, | ||
1975 | {NULL, NULL, NULL, 0} | ||
1976 | }; | ||
1977 | |||
1978 | struct context simpleJoe = | ||
1979 | { | ||
1980 | simpleJoeCommands, | ||
1981 | simpleJoeMode, | ||
1982 | NULL, | ||
1983 | NULL, | ||
1984 | NULL | ||
1985 | }; | ||
1986 | |||
1987 | |||
1988 | // Simple more and / or less. | ||
1989 | // '/' and '?' for search command mode. I think they both have some ex commands with the usual : command mode starter. | ||
1990 | // No cursor movement, just scrolling. | ||
1991 | // TODO - Put content into read only mode. | ||
1992 | // TODO - actually implement read only mode where up and down one line do actual scrolling instead of cursor movement. | ||
1993 | |||
1994 | struct keyCommand simpleLessKeys[] = | ||
1995 | { | ||
1996 | {"Down", "downLine"}, | ||
1997 | {"j", "downLine"}, | ||
1998 | {"Enter", "downLine"}, | ||
1999 | {"Return", "downLine"}, | ||
2000 | {"End", "endOfLine"}, | ||
2001 | {"q", "quit"}, | ||
2002 | {":q", "quit"}, // TODO - A vi ism, should do ex command stuff instead. | ||
2003 | {"ZZ", "quit"}, | ||
2004 | {"PgDn", "downPage"}, | ||
2005 | {"f", "downPage"}, | ||
2006 | {" ", "downPage"}, | ||
2007 | {"^F", "downPage"}, | ||
2008 | {"Left", "leftChar"}, | ||
2009 | {"Right", "rightChar"}, | ||
2010 | {"PgUp", "upPage"}, | ||
2011 | {"b", "upPage"}, | ||
2012 | {"^B", "upPage"}, | ||
2013 | {"Up", "upLine"}, | ||
2014 | {"k", "upLine"}, | ||
2015 | {NULL, NULL} | ||
2016 | }; | ||
2017 | |||
2018 | struct mode simpleLessMode[] = | ||
2019 | { | ||
2020 | {simpleLessKeys, NULL, NULL, 0}, | ||
2021 | {simpleCommandKeys, NULL, NULL, 1}, | ||
2022 | {NULL, NULL, NULL} | ||
2023 | }; | ||
2024 | |||
2025 | struct context simpleLess = | ||
2026 | { | ||
2027 | simpleEditCommands, | ||
2028 | simpleLessMode, | ||
2029 | NULL, | ||
2030 | NULL, | ||
2031 | NULL | ||
2032 | }; | ||
2033 | |||
2034 | struct keyCommand simpleMoreKeys[] = | ||
2035 | { | ||
2036 | {"j", "downLine"}, | ||
2037 | {"Enter", "downLine"}, | ||
2038 | {"Return", "downLine"}, | ||
2039 | {"q", "quit"}, | ||
2040 | {":q", "quit"}, // See comments for "less". | ||
2041 | {"ZZ", "quit"}, | ||
2042 | {"f", "downPage"}, | ||
2043 | {" ", "downPage"}, | ||
2044 | {"^F", "downPage"}, | ||
2045 | {"b", "upPage"}, | ||
2046 | {"^B", "upPage"}, | ||
2047 | {"k", "upLine"}, | ||
2048 | {NULL, NULL} | ||
2049 | }; | ||
2050 | |||
2051 | struct mode simpleMoreMode[] = | ||
2052 | { | ||
2053 | {simpleMoreKeys, NULL, NULL, 0}, | ||
2054 | {simpleCommandKeys, NULL, NULL, 1}, | ||
2055 | {NULL, NULL, NULL} | ||
2056 | }; | ||
2057 | |||
2058 | struct context simpleMore = | ||
2059 | { | ||
2060 | simpleEditCommands, | ||
2061 | simpleMoreMode, | ||
2062 | NULL, | ||
2063 | NULL, | ||
2064 | NULL | ||
2065 | }; | ||
2066 | |||
2067 | |||
2068 | // Construct a simple mcedit / cool edit editor. | ||
2069 | |||
2070 | struct keyCommand simpleMceditKeys[] = | ||
2071 | { | ||
2072 | {"BS", "backSpaceChar"}, | ||
2073 | {"Del", "deleteChar"}, | ||
2074 | {"Down", "downLine"}, | ||
2075 | {"End", "endOfLine"}, | ||
2076 | {"F10", "quit"}, | ||
2077 | {"Esc0", "quit"}, | ||
2078 | {"F2", "save"}, | ||
2079 | {"Esc2", "save"}, | ||
2080 | {"Home", "startOfLine"}, | ||
2081 | {"Left", "leftChar"}, | ||
2082 | {"PgDn", "downPage"}, | ||
2083 | {"PgUp", "upPage"}, | ||
2084 | {"Enter", "splitLine"}, | ||
2085 | {"Return", "splitLine"}, | ||
2086 | {"Right", "rightChar"}, | ||
2087 | {"Shift F2", "switchMode"}, // MC doesn't have a command mode. | ||
2088 | {"Esc:", "switchMode"}, // Sorta vi like, and coz tmux is screwing with the shift function keys somehow. | ||
2089 | {"Esc|", "splitV"}, // MC doesn't have a split window concept, so make these up to match tmux more or less. | ||
2090 | {"Esc-", "splitH"}, | ||
2091 | {"Esco", "switchBoxes"}, | ||
2092 | {"Escx", "deleteBox"}, | ||
2093 | {"Up", "upLine"}, | ||
2094 | {NULL, NULL} | ||
2095 | }; | ||
2096 | |||
2097 | struct mode simpleMceditMode[] = | ||
2098 | { | ||
2099 | {simpleMceditKeys, NULL, NULL, 0}, | ||
2100 | {simpleCommandKeys, NULL, NULL, 1}, | ||
2101 | {NULL, NULL, NULL} | ||
2102 | }; | ||
2103 | |||
2104 | struct context simpleMcedit = | ||
2105 | { | ||
2106 | simpleEditCommands, | ||
2107 | simpleMceditMode, | ||
2108 | NULL, | ||
2109 | NULL, | ||
2110 | NULL | ||
2111 | }; | ||
2112 | |||
2113 | |||
2114 | // Simple nano editor. | ||
2115 | // Has key to function bindings, but no command line mode. Has "enter parameter on this line" mode for some commands. | ||
2116 | // Control and meta keys, only singles, unlike emacs and joe. | ||
2117 | // Can have multiple buffers, but no windows. Think I can skip that for simple editor. | ||
2118 | |||
2119 | struct function simpleNanoCommands[] = | ||
2120 | { | ||
2121 | {"backSpaceChar", "Back space last character.", 0, {backSpaceChar}}, | ||
2122 | {"delete", "Delete current character.", 0, {deleteChar}}, | ||
2123 | {"down", "Move cursor down one line.", 0, {downLine}}, | ||
2124 | {"downPage", "Move cursor down one page.", 0, {downPage}}, | ||
2125 | {"end", "Go to end of line.", 0, {endOfLine}}, | ||
2126 | {"left", "Move cursor left one character.", 0, {leftChar}}, | ||
2127 | {"exit", "Quit the application.", 0, {quit}}, | ||
2128 | {"right", "Move cursor right one character.", 0, {rightChar}}, | ||
2129 | {"writeout", "Save.", 0, {saveContent}}, | ||
2130 | {"enter", "Split line at cursor.", 0, {splitLine}}, | ||
2131 | {"home", "Go to start of line.", 0, {startOfLine}}, | ||
2132 | {"up", "Move cursor up one line.", 0, {upLine}}, | ||
2133 | {"upPage", "Move cursor up one page.", 0, {upPage}}, | ||
2134 | {NULL, NULL, 0, {NULL}} | ||
2135 | }; | ||
2136 | |||
2137 | |||
2138 | // Hmm, back space, page up, and page down don't seem to have bindable commands according to the web page, but they are bound to keys anyway. | ||
2139 | struct keyCommand simpleNanoKeys[] = | ||
2140 | { | ||
2141 | // TODO - Delete key is ^H dammit. Find the alternate Esc sequence for Del. | ||
2142 | // {"^H", "backSpaceChar"}, // ? | ||
2143 | {"BS", "backSpaceChar"}, | ||
2144 | {"^D", "delete"}, | ||
2145 | {"Del", "delete"}, | ||
2146 | {"^N", "down"}, | ||
2147 | {"Down", "down"}, | ||
2148 | {"^E", "end"}, | ||
2149 | {"End", "end"}, | ||
2150 | {"^X", "exit"}, | ||
2151 | {"F2", "exit"}, | ||
2152 | {"^O", "writeout"}, | ||
2153 | {"F3", "writeout"}, | ||
2154 | {"^A", "home"}, | ||
2155 | {"Home", "home"}, | ||
2156 | {"^B", "left"}, | ||
2157 | {"Left", "left"}, | ||
2158 | {"^V", "downPage"}, // ? | ||
2159 | {"PgDn", "downPage"}, | ||
2160 | {"^Y", "upPage"}, // ? | ||
2161 | {"PgUp", "upPage"}, | ||
2162 | {"Enter", "enter"}, // TODO - Not sure if this is correct. | ||
2163 | {"Return", "enter"}, // TODO - Not sure if this is correct. | ||
2164 | {"^F", "right"}, | ||
2165 | {"Right", "right"}, | ||
2166 | {"^P", "up"}, | ||
2167 | {"Up", "up"}, | ||
2168 | {NULL, NULL} | ||
2169 | }; | ||
2170 | |||
2171 | struct mode simpleNanoMode[] = | ||
2172 | { | ||
2173 | {simpleNanoKeys, NULL, NULL, 0}, | ||
2174 | {NULL, NULL, NULL} | ||
2175 | }; | ||
2176 | |||
2177 | struct context simpleNano = | ||
2178 | { | ||
2179 | simpleNanoCommands, | ||
2180 | simpleNanoMode, | ||
2181 | NULL, | ||
2182 | NULL, | ||
2183 | NULL | ||
2184 | }; | ||
2185 | |||
2186 | |||
2187 | // Construct a simple vi editor. | ||
2188 | // Only vi is not so simple. lol | ||
2189 | // The "command line" modes are /, ?, :, and !, | ||
2190 | // / is regex search. | ||
2191 | // ? is regex search backwards. | ||
2192 | // : is ex command mode. | ||
2193 | // ! is replace text with output from shell command mode. | ||
2194 | // Arrow keys do the right thing in "normal" mode, but not in insert mode. | ||
2195 | // "i" goes into insert mode, "Esc" (or Ctrl-[ or Ctrl-C) gets you out. So much for "you can do it all touch typing on the home row". Pffft | ||
2196 | // Ah, the Esc key WAS a lot closer to the home row (where Tab usually is now) on the original keyboard vi was designed for, ADM3A. | ||
2197 | // Which is also the keyboard with the arrow keys marked on h, j, k, and l keys. | ||
2198 | // Did I mention that vi is just a horrid historic relic that should have died long ago? | ||
2199 | // Emacs looks to have the same problem, originally designed for an ancient keyboard that is nothing like what people actually use these days. | ||
2200 | // "h", "j", "k", "l" move cursor, which is just random keys for dvorak users. | ||
2201 | // ":" goes into ex command mode. | ||
2202 | // ":q" deletes current window in vim. | ||
2203 | // ":qa!" goes into ex mode and does some sort of quit command. | ||
2204 | // The 'q' is short for quit, the ! is an optional argument to quit. No idea yet what the a is for, all windows? | ||
2205 | // Del or "x" to delete a character. Del in insert mode. | ||
2206 | // "X" to backspace. BS or Ctrl-H to backspace in insert mode. | ||
2207 | // NOTE - Backspace in normal mode just moves left. | ||
2208 | // Tab or Ctrl-I to insert a tab in insert mode. | ||
2209 | // Return in normal mode goes to the start of the next line, or splits the line in insert mode. | ||
2210 | // ":help" opens a window with help text. | ||
2211 | // Vim window commands. | ||
2212 | |||
2213 | // Vi needs extra variables and functions. | ||
2214 | static int viTempExMode; | ||
2215 | |||
2216 | void viMode(view *view) | ||
2217 | { | ||
2218 | currentBox->view->mode = 0; | ||
2219 | commandMode = 0; | ||
2220 | viTempExMode = 0; | ||
2221 | } | ||
2222 | |||
2223 | void viInsertMode(view *view) | ||
2224 | { | ||
2225 | currentBox->view->mode = 1; | ||
2226 | commandMode = 0; | ||
2227 | } | ||
2228 | |||
2229 | void viExMode(view *view) | ||
2230 | { | ||
2231 | currentBox->view->mode = 2; | ||
2232 | commandMode = 1; | ||
2233 | // TODO - Should change this based on the event, : or Q. | ||
2234 | viTempExMode = 1; | ||
2235 | commandLine->prompt = xrealloc(commandLine->prompt, 2); | ||
2236 | strcpy(commandLine->prompt, ":"); | ||
2237 | } | ||
2238 | |||
2239 | void viBackSpaceChar(view *view) | ||
2240 | { | ||
2241 | if ((2 == currentBox->view->mode) && (0 == view->cX) && viTempExMode) | ||
2242 | viMode(view); | ||
2243 | else | ||
2244 | backSpaceChar(view); | ||
2245 | } | ||
2246 | |||
2247 | void viStartOfNextLine(view *view) | ||
2248 | { | ||
2249 | startOfLine(view); | ||
2250 | downLine(view); | ||
2251 | } | ||
2252 | |||
2253 | struct function simpleViCommands[] = | ||
2254 | { | ||
2255 | // These are actual ex commands. | ||
2256 | {"insert", "Switch to insert mode.", 0, {viInsertMode}}, | ||
2257 | {"quit", "Quit the application.", 0, {quit}}, | ||
2258 | {"visual", "Switch to visual mode.", 0, {viMode}}, | ||
2259 | {"write", "Save.", 0, {saveContent}}, | ||
2260 | |||
2261 | // These are not ex commands. | ||
2262 | {"backSpaceChar", "Back space last character.", 0, {viBackSpaceChar}}, | ||
2263 | {"deleteBox", "Delete a box.", 0, {deleteBox}}, | ||
2264 | {"deleteChar", "Delete current character.", 0, {deleteChar}}, | ||
2265 | {"downLine", "Move cursor down one line.", 0, {downLine}}, | ||
2266 | {"downPage", "Move cursor down one page.", 0, {downPage}}, | ||
2267 | {"endOfLine", "Go to end of line.", 0, {endOfLine}}, | ||
2268 | {"executeLine", "Execute a line as a script.", 0, {executeLine}}, | ||
2269 | {"exMode", "Switch to ex mode.", 0, {viExMode}}, | ||
2270 | {"leftChar", "Move cursor left one character.", 0, {leftChar}}, | ||
2271 | {"rightChar", "Move cursor right one character.", 0, {rightChar}}, | ||
2272 | {"splitH", "Split box in half horizontally.", 0, {halveBoxHorizontally}}, | ||
2273 | {"splitLine", "Split line at cursor.", 0, {splitLine}}, | ||
2274 | {"splitV", "Split box in half vertically.", 0, {halveBoxVertically}}, | ||
2275 | {"startOfLine", "Go to start of line.", 0, {startOfLine}}, | ||
2276 | {"startOfNLine", "Go to start of next line.", 0, {viStartOfNextLine}}, | ||
2277 | {"switchBoxes", "Switch to another box.", 0, {switchBoxes}}, | ||
2278 | {"upLine", "Move cursor up one line.", 0, {upLine}}, | ||
2279 | {"upPage", "Move cursor up one page.", 0, {upPage}}, | ||
2280 | {NULL, NULL, 0, {NULL}} | ||
2281 | }; | ||
2282 | |||
2283 | struct keyCommand simpleViNormalKeys[] = | ||
2284 | { | ||
2285 | {"BS", "leftChar"}, | ||
2286 | {"X", "backSpaceChar"}, | ||
2287 | {"Del", "deleteChar"}, | ||
2288 | {"x", "deleteChar"}, | ||
2289 | {"Down", "downLine"}, | ||
2290 | {"j", "downLine"}, | ||
2291 | {"End", "endOfLine"}, | ||
2292 | {"Home", "startOfLine"}, | ||
2293 | {"Left", "leftChar"}, | ||
2294 | {"h", "leftChar"}, | ||
2295 | {"PgDn", "downPage"}, | ||
2296 | {"^F", "downPage"}, | ||
2297 | {"PgUp", "upPage"}, | ||
2298 | {"^B", "upPage"}, | ||
2299 | {"Enter", "startOfNextLine"}, | ||
2300 | {"Return", "startOfNextLine"}, | ||
2301 | {"Right", "rightChar"}, | ||
2302 | {"l", "rightChar"}, | ||
2303 | {"i", "insert"}, | ||
2304 | {":", "exMode"}, // This is the temporary ex mode that you can backspace out of. Or any command backs you out. | ||
2305 | {"Q", "exMode"}, // This is the ex mode you need to do the "visual" command to get out of. | ||
2306 | {"^Wv", "splitV"}, | ||
2307 | {"^W^V", "splitV"}, | ||
2308 | {"^Ws", "splitH"}, | ||
2309 | {"^WS", "splitH"}, | ||
2310 | {"^W^S", "splitH"}, | ||
2311 | {"^Ww", "switchBoxes"}, | ||
2312 | {"^W^W", "switchBoxes"}, | ||
2313 | {"^Wq", "deleteBox"}, | ||
2314 | {"^W^Q", "deleteBox"}, | ||
2315 | {"Up", "upLine"}, | ||
2316 | {"k", "upLine"}, | ||
2317 | {NULL, NULL} | ||
2318 | }; | ||
2319 | |||
2320 | struct keyCommand simpleViInsertKeys[] = | ||
2321 | { | ||
2322 | {"BS", "backSpaceChar"}, | ||
2323 | {"Del", "deleteChar"}, | ||
2324 | {"Return", "splitLine"}, | ||
2325 | {"Esc", "visual"}, | ||
2326 | {"^C", "visual"}, | ||
2327 | {NULL, NULL} | ||
2328 | }; | ||
2329 | |||
2330 | struct keyCommand simpleExKeys[] = | ||
2331 | { | ||
2332 | {"BS", "backSpaceChar"}, | ||
2333 | {"Del", "deleteChar"}, | ||
2334 | {"Down", "downLine"}, | ||
2335 | {"End", "endOfLine"}, | ||
2336 | {"Home", "startOfLine"}, | ||
2337 | {"Left", "leftChar"}, | ||
2338 | {"Enter", "executeLine"}, | ||
2339 | {"Return", "executeLine"}, | ||
2340 | {"Right", "rightChar"}, | ||
2341 | {"Esc", "visual"}, | ||
2342 | {"Up", "upLine"}, | ||
2343 | {NULL, NULL} | ||
2344 | }; | ||
2345 | |||
2346 | struct mode simpleViMode[] = | ||
2347 | { | ||
2348 | {simpleViNormalKeys, NULL, NULL, 0}, | ||
2349 | {simpleViInsertKeys, NULL, NULL, 0}, | ||
2350 | {simpleExKeys, NULL, NULL, 1}, | ||
2351 | {NULL, NULL, NULL} | ||
2352 | }; | ||
2353 | |||
2354 | struct context simpleVi = | ||
2355 | { | ||
2356 | simpleViCommands, | ||
2357 | simpleViMode, | ||
2358 | NULL, | ||
2359 | NULL, | ||
2360 | NULL | ||
2361 | }; | ||
2362 | |||
2363 | |||
2364 | // TODO - simple sed editor? May be out of scope for "simple", so leave it until later? | ||
2365 | // Probably entirely useless for "simple". | ||
2366 | |||
2367 | |||
2368 | // TODO - have any unrecognised escape key sequence start up a new box (split one) to show the "show keys" content. | ||
2369 | // That just adds each "Key is X" to the end of the content, and allows scrolling, as well as switching between other boxes. | ||
2370 | |||
2371 | void boxes_main(void) | ||
2372 | { | ||
2373 | struct context *context = &simpleMcedit; // The default is mcedit, coz that's what I use. | ||
2374 | struct termios termio, oldtermio; | ||
2375 | char *prompt = "Enter a command : "; | ||
2376 | unsigned W = 80, H = 24; | ||
2377 | |||
2378 | // For testing purposes, figure out which context we use. When this gets real, the toybox multiplexer will sort this out for us instead. | ||
2379 | if (toys.optflags & FLAG_m) | ||
2380 | { | ||
2381 | if (strcmp(TT.mode, "emacs") == 0) | ||
2382 | context = &simpleEmacs; | ||
2383 | else if (strcmp(TT.mode, "joe") == 0) | ||
2384 | context = &simpleJoe; | ||
2385 | else if (strcmp(TT.mode, "less") == 0) | ||
2386 | context = &simpleLess; | ||
2387 | else if (strcmp(TT.mode, "mcedit") == 0) | ||
2388 | context = &simpleMcedit; | ||
2389 | else if (strcmp(TT.mode, "more") == 0) | ||
2390 | context = &simpleMore; | ||
2391 | else if (strcmp(TT.mode, "nano") == 0) | ||
2392 | context = &simpleNano; | ||
2393 | else if (strcmp(TT.mode, "vi") == 0) | ||
2394 | context = &simpleVi; | ||
2395 | } | ||
2396 | |||
2397 | // TODO - Should do an isatty() here, though not sure about the usefullness of driving this from a script or redirected input, since it's supposed to be a UI for terminals. | ||
2398 | // It would STILL need the terminal size for output though. Perhaps just bitch and abort if it's not a tty? | ||
2399 | // On the other hand, sed don't need no stinkin' UI. And things like more or less should be usable on the end of a pipe. | ||
2400 | |||
2401 | // Grab the old terminal settings and save it. | ||
2402 | tcgetattr(0, &oldtermio); | ||
2403 | tcflush(0, TCIFLUSH); | ||
2404 | termio = oldtermio; | ||
2405 | |||
2406 | // Mould the terminal to our will. | ||
2407 | /* | ||
2408 | IUCLC (not in POSIX) Map uppercase characters to lowercase on input. | ||
2409 | IXON Enable XON/XOFF flow control on output. | ||
2410 | IXOFF Enable XON/XOFF flow control on input. | ||
2411 | IXANY (not in POSIX.1; XSI) Enable any character to restart output. | ||
2412 | |||
2413 | ECHO Echo input characters. | ||
2414 | ECHOE If ICANON is also set, the ERASE character erases the preceding input character, and WERASE erases the preceding word. | ||
2415 | ECHOK If ICANON is also set, the KILL character erases the current line. | ||
2416 | ECHONL If ICANON is also set, echo the NL character even if ECHO is not set. | ||
2417 | TOSTOP Send the SIGTTOU signal to the process group of a background process which tries to write to its controlling terminal. | ||
2418 | ICANON Enable canonical mode. This enables the special characters EOF, EOL, EOL2, ERASE, KILL, LNEXT, REPRINT, STATUS, and WERASE, and buffers by lines. | ||
2419 | |||
2420 | VTIME Timeout in deciseconds for non-canonical read. | ||
2421 | VMIN Minimum number of characters for non-canonical read. | ||
2422 | |||
2423 | raw mode turning off ICANON, IEXTEN, and ISIG kills most special key processing. | ||
2424 | termio.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); | ||
2425 | termio.c_oflag &= ~OPOST; | ||
2426 | termio.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); | ||
2427 | termio.c_cflag &= ~(CSIZE | PARENB); | ||
2428 | termio.c_cflag |= CS8; | ||
2429 | |||
2430 | IGNBRK ignore BREAK | ||
2431 | BRKINT complicated, bet in this context, sends BREAK as '\x00' | ||
2432 | PARMRK characters with parity or frame erors are sent as '\x00' | ||
2433 | ISTRIP strip 8th byte | ||
2434 | INLCR translate LF to CR in input | ||
2435 | IGLCR ignore CR | ||
2436 | OPOST enable implementation defined output processing | ||
2437 | ISIG generate signals on INTR (SIGINT on ^C), QUIT (SIGQUIT on ^\\), SUSP (SIGTSTP on ^Z), DSUSP (SIGTSTP on ^Y) | ||
2438 | IEXTEN enable implementation defined input processing, turns on some key -> signal -tuff | ||
2439 | CSIZE mask for character sizes, so in this case, we mask them all out | ||
2440 | PARENB enable parity | ||
2441 | CS8 8 bit characters | ||
2442 | |||
2443 | VEOF "sends" EOF on ^D, ICANON turns that on. | ||
2444 | VSTART restart output on ^Q, IXON turns that on. | ||
2445 | VSTATUS display status info and sends SIGINFO (STATUS) on ^T. Not in POSIX, not supported in Linux. ICANON turns that on. | ||
2446 | VSTOP stop output on ^S, IXON turns that on. | ||
2447 | */ | ||
2448 | termio.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IUCLC | IXON | IXOFF | IXANY); | ||
2449 | termio.c_oflag &= ~OPOST; | ||
2450 | termio.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | TOSTOP | ICANON | ISIG | IEXTEN); | ||
2451 | termio.c_cflag &= ~(CSIZE | PARENB); | ||
2452 | termio.c_cflag |= CS8; | ||
2453 | termio.c_cc[VTIME]=0; // deciseconds. | ||
2454 | termio.c_cc[VMIN]=1; | ||
2455 | tcsetattr(0, TCSANOW, &termio); | ||
2456 | |||
2457 | terminal_size(&W, &H); | ||
2458 | if (toys.optflags & FLAG_w) | ||
2459 | W = TT.w; | ||
2460 | if (toys.optflags & FLAG_h) | ||
2461 | H = TT.h; | ||
2462 | |||
2463 | // Create the main box. Right now the system needs one for wrapping around while switching. The H - 1 bit is to leave room for our example command line. | ||
2464 | rootBox = addBox("root", context, toys.optargs[0], 0, 0, W, H - 1); | ||
2465 | currentBox = rootBox; | ||
2466 | |||
2467 | // Create the command line view, sharing the same context as the root. It will differentiate based on the view mode of the current box. | ||
2468 | // Also load the command line history as it's file. | ||
2469 | // TODO - different contexts will have different history files, though what to do about ones with no history, and ones with different histories for different modes? | ||
2470 | commandLine = addView("command", rootBox->view->content->context, ".boxes.history", 0, H, W, 1); | ||
2471 | // Add a prompt to it. | ||
2472 | commandLine->prompt = xrealloc(commandLine->prompt, strlen(prompt) + 1); | ||
2473 | strcpy(commandLine->prompt, prompt); | ||
2474 | // Move to the end of the history. | ||
2475 | moveCursorAbsolute(commandLine, 0, commandLine->content->lines.length, 0, 0); | ||
2476 | |||
2477 | // All the mouse tracking methods suck one way or another. sigh | ||
2478 | // http://rtfm.etla.org/xterm/ctlseq.html documents xterm stuff, near the bottom is the mouse stuff. | ||
2479 | // http://leonerds-code.blogspot.co.uk/2012/04/wide-mouse-support-in-libvterm.html is helpful. | ||
2480 | // Enable mouse (VT200 normal tracking mode, UTF8 encoding). The limit is 2015. Seems to only be in later xterms. | ||
2481 | // fputs("\x1B[?1005h", stdout); | ||
2482 | // Enable mouse (VT340 locator reporting mode). In theory has no limit. Wont actually work though. | ||
2483 | // On the other hand, only allows for four buttons, so only half a mouse wheel. | ||
2484 | // Responds with "\1B[e;p;r;c;p&w" where e is event type, p is a bitmap of buttons pressed, r and c are the mouse coords in decimal, and p is the "page number". | ||
2485 | // fputs("\x1B[1;2'z\x1B[1;3'{", stdout); | ||
2486 | // Enable mouse (VT200 normal tracking mode). Has a limit of 256 - 32 rows and columns. An xterm exclusive I think, but works in roxterm at least. No wheel reports. | ||
2487 | // Responds with "\x1B[Mbxy" where x and y are the mouse coords, and b is bit encoded buttons and modifiers - 0=MB1 pressed, 1=MB2 pressed, 2=MB3 pressed, 3=release, 4=Shift, 8=Meta, 16=Control | ||
2488 | // fputs("\x1B[?1000h", stdout); | ||
2489 | // fflush(stdout); | ||
2490 | |||
2491 | calcBoxes(currentBox); | ||
2492 | drawBoxes(currentBox); | ||
2493 | // Do the first cursor update. | ||
2494 | updateLine(currentBox->view); | ||
2495 | |||
2496 | // Run the main loop. | ||
2497 | handle_keys((long) currentBox->view, handleEvent); | ||
2498 | |||
2499 | // TODO - Should remember to turn off mouse reporting when we leave. | ||
2500 | |||
2501 | // Restore the old terminal settings. | ||
2502 | tcsetattr(0, TCSANOW, &oldtermio); | ||
2503 | |||
2504 | puts(""); | ||
2505 | fflush(stdout); | ||
2506 | } | ||
diff --git a/src/boxes/dumbsh.c b/src/boxes/dumbsh.c new file mode 100644 index 0000000..9ad0204 --- /dev/null +++ b/src/boxes/dumbsh.c | |||
@@ -0,0 +1,283 @@ | |||
1 | /* dumbsh.c - A really dumb shell, to demonstrate handle_keys usage. | ||
2 | * | ||
3 | * Copyright 2014 David Seikel <won_fang@yahoo.com.au> | ||
4 | * | ||
5 | * Not a real shell, so doesn't follow any standards, | ||
6 | * coz it wont implement them anyway. | ||
7 | |||
8 | USE_DUMBSH(NEWTOY(dumbsh, "", TOYFLAG_USR|TOYFLAG_BIN)) | ||
9 | |||
10 | config DUMBSH | ||
11 | bool "dumbsh" | ||
12 | default n | ||
13 | help | ||
14 | usage: dumbsh | ||
15 | |||
16 | A really dumb shell. | ||
17 | */ | ||
18 | |||
19 | #include "toys.h" | ||
20 | #include "lib/handlekeys.h" | ||
21 | |||
22 | typedef void (*eventHandler) (void); | ||
23 | |||
24 | struct keyCommand | ||
25 | { | ||
26 | char *key; | ||
27 | eventHandler handler; | ||
28 | }; | ||
29 | |||
30 | GLOBALS( | ||
31 | unsigned h, w; | ||
32 | int x, y; | ||
33 | struct double_list *history; | ||
34 | ) | ||
35 | |||
36 | #define TT this.dumbsh | ||
37 | |||
38 | // Sanity check cursor location and update the current line. | ||
39 | static void updateLine() | ||
40 | { | ||
41 | if (0 > TT.x) TT.x = 0; | ||
42 | if (0 > TT.y) TT.y = 0; | ||
43 | if (TT.w < TT.x) TT.x = TT.w; | ||
44 | if (TT.h < TT.y) TT.y = TT.h; | ||
45 | if (strlen(toybuf) < TT.x) TT.x = strlen(toybuf); | ||
46 | printf("\x1B[%d;0H%-*s\x1B[%d;%dH", | ||
47 | TT.y + 1, TT.w, toybuf, TT.y + 1, TT.x + 1); | ||
48 | fflush(stdout); | ||
49 | } | ||
50 | |||
51 | // The various commands. | ||
52 | static void deleteChar() | ||
53 | { | ||
54 | int j; | ||
55 | |||
56 | for (j = TT.x; toybuf[j]; j++) | ||
57 | toybuf[j] = toybuf[j + 1]; | ||
58 | updateLine(); | ||
59 | } | ||
60 | |||
61 | static void backSpaceChar() | ||
62 | { | ||
63 | if (TT.x) | ||
64 | { | ||
65 | TT.x--; | ||
66 | deleteChar(); | ||
67 | } | ||
68 | } | ||
69 | |||
70 | // This is where we would actually deal with | ||
71 | // what ever command the user had typed in. | ||
72 | // For now we just move on to the next line. | ||
73 | // TODO - We would want to redirect I/O, capture some keys (^C), | ||
74 | // but pass the rest on. | ||
75 | // Dunno yet how to deal with that. | ||
76 | // We still want handle_keys to be doing it's thing, | ||
77 | // so maybe handing it another fd, and a callback. | ||
78 | // A function to add and remove fd and callback pairs for | ||
79 | // handle_keys to check? | ||
80 | static void doCommand() | ||
81 | { | ||
82 | toybuf[0] = 0; | ||
83 | TT.x = 0; | ||
84 | TT.y++; | ||
85 | printf("\n"); | ||
86 | fflush(stdout); | ||
87 | updateLine(); | ||
88 | } | ||
89 | |||
90 | static void endOfLine() | ||
91 | { | ||
92 | TT.x = strlen(toybuf); | ||
93 | updateLine(); | ||
94 | } | ||
95 | |||
96 | static void leftChar() | ||
97 | { | ||
98 | TT.x--; | ||
99 | updateLine(); | ||
100 | } | ||
101 | |||
102 | static void nextHistory() | ||
103 | { | ||
104 | TT.history = TT.history->next; | ||
105 | strcpy(toybuf, TT.history->data); | ||
106 | TT.x = strlen(toybuf); | ||
107 | updateLine(); | ||
108 | } | ||
109 | |||
110 | static void prevHistory() | ||
111 | { | ||
112 | TT.history = TT.history->prev; | ||
113 | strcpy(toybuf, TT.history->data); | ||
114 | TT.x = strlen(toybuf); | ||
115 | updateLine(); | ||
116 | } | ||
117 | |||
118 | static void quit() | ||
119 | { | ||
120 | handle_keys_quit(); | ||
121 | } | ||
122 | |||
123 | static void rightChar() | ||
124 | { | ||
125 | TT.x++; | ||
126 | updateLine(); | ||
127 | } | ||
128 | |||
129 | static void startOfLine() | ||
130 | { | ||
131 | TT.x = 0; | ||
132 | updateLine(); | ||
133 | } | ||
134 | |||
135 | // The key to command mappings, Emacs style. | ||
136 | static const struct keyCommand simpleEmacsKeys[] = | ||
137 | { | ||
138 | {"BS", backSpaceChar}, | ||
139 | {"Del", deleteChar}, | ||
140 | {"^D", deleteChar}, | ||
141 | {"Return", doCommand}, | ||
142 | {"Enter", doCommand}, | ||
143 | {"Down", nextHistory}, | ||
144 | {"^N", nextHistory}, | ||
145 | {"End", endOfLine}, | ||
146 | {"^E", endOfLine}, | ||
147 | {"Left", leftChar}, | ||
148 | {"^B", leftChar}, | ||
149 | {"^X^C", quit}, | ||
150 | {"^C", quit}, | ||
151 | {"Right", rightChar}, | ||
152 | {"^F", rightChar}, | ||
153 | {"Home", startOfLine}, | ||
154 | {"^A", startOfLine}, | ||
155 | {"Up", prevHistory}, | ||
156 | {"^P", prevHistory} | ||
157 | }; | ||
158 | |||
159 | // Callback for incoming sequences from the terminal. | ||
160 | static int handleEvent(long extra, struct keyevent *event) | ||
161 | { | ||
162 | switch (event->type) | ||
163 | { | ||
164 | case HK_KEYS : | ||
165 | { | ||
166 | int j, l = strlen(event->sequence); | ||
167 | |||
168 | // Search for a key sequence bound to a command. | ||
169 | for (j = 0; j < ARRAY_LEN(simpleEmacsKeys); j++) | ||
170 | { | ||
171 | if (strncmp(simpleEmacsKeys[j].key, event->sequence, l) == 0) | ||
172 | { | ||
173 | // If it's a partial match, keep accumulating them. | ||
174 | if (strlen(simpleEmacsKeys[j].key) != l) | ||
175 | return 0; | ||
176 | else | ||
177 | { | ||
178 | if (simpleEmacsKeys[j].handler) simpleEmacsKeys[j].handler(); | ||
179 | return 1; | ||
180 | } | ||
181 | } | ||
182 | } | ||
183 | |||
184 | // See if it's ordinary keys. | ||
185 | // NOTE - with vi style ordinary keys can be commands, | ||
186 | // but they would be found by the command check above first. | ||
187 | if (!event->isTranslated) | ||
188 | { | ||
189 | if (TT.x < sizeof(toybuf)) | ||
190 | { | ||
191 | int j, l = strlen(event->sequence); | ||
192 | |||
193 | for (j = strlen(toybuf); j >= TT.x; j--) | ||
194 | toybuf[j + l] = toybuf[j]; | ||
195 | for (j = 0; j < l; j++) | ||
196 | toybuf[TT.x + j] = event->sequence[j]; | ||
197 | TT.x += l; | ||
198 | updateLine(); | ||
199 | } | ||
200 | } | ||
201 | break; | ||
202 | } | ||
203 | |||
204 | case HK_CSI : | ||
205 | { | ||
206 | // Is it a cursor location report? | ||
207 | if (strcmp("R", event->sequence) == 0) | ||
208 | { | ||
209 | // Parameters are cursor line and column. | ||
210 | // NOTE - This may be sent at other times, not just during terminal resize. | ||
211 | // We are assuming here that it's a resize. | ||
212 | // The defaults are 1, which get ignored by the heuristic below. | ||
213 | int r = event->params[0], c = event->params[1]; | ||
214 | |||
215 | // Check it's not an F3 key variation, coz some of them use | ||
216 | // the same CSI function command. | ||
217 | // This is a heuristic, we are checking against an unusable terminal size. | ||
218 | if ((2 == event->count) && (8 < r) && (8 < c)) | ||
219 | { | ||
220 | TT.h = r; | ||
221 | TT.w = c; | ||
222 | updateLine(); | ||
223 | } | ||
224 | break; | ||
225 | } | ||
226 | } | ||
227 | |||
228 | default : break; | ||
229 | } | ||
230 | |||
231 | // Tell handle_keys to drop it, coz we dealt with it, or it's not one of ours. | ||
232 | return 1; | ||
233 | } | ||
234 | |||
235 | void dumbsh_main(void) | ||
236 | { | ||
237 | struct termios termIo, oldTermIo; | ||
238 | char *t = getenv("HOME"); | ||
239 | int fd; | ||
240 | |||
241 | // Load bash history. | ||
242 | t = xmprintf("%s/%s", t ? t : "", ".bash_history"); | ||
243 | if (-1 != (fd = open(t, O_RDONLY))) | ||
244 | { | ||
245 | while ((t = get_line(fd))) TT.history = dlist_add(&TT.history, t); | ||
246 | close(fd); | ||
247 | } | ||
248 | if (!TT.history) | ||
249 | TT.history = dlist_add(&TT.history, ""); | ||
250 | |||
251 | // Grab the old terminal settings and save it. | ||
252 | tcgetattr(0, &oldTermIo); | ||
253 | tcflush(0, TCIFLUSH); | ||
254 | termIo = oldTermIo; | ||
255 | |||
256 | // Mould the terminal to our will. | ||
257 | // In this example we are turning off all the terminal smarts, but real code | ||
258 | // might not want that. | ||
259 | termIo.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | ||
260 | | IUCLC | IXON | IXOFF | IXANY); | ||
261 | termIo.c_oflag &= ~OPOST; | ||
262 | termIo.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | TOSTOP | ICANON | ISIG | ||
263 | | IEXTEN); | ||
264 | termIo.c_cflag &= ~(CSIZE | PARENB); | ||
265 | termIo.c_cflag |= CS8; | ||
266 | termIo.c_cc[VTIME]=0; // deciseconds. | ||
267 | termIo.c_cc[VMIN]=1; | ||
268 | tcsetattr(0, TCSANOW, &termIo); | ||
269 | |||
270 | // Let the mouldy old terminal mold us. | ||
271 | TT.w = 80; | ||
272 | TT.h = 24; | ||
273 | terminal_size(&TT.w, &TT.h); | ||
274 | |||
275 | // Let's rock! | ||
276 | updateLine(); | ||
277 | handle_keys(0, handleEvent); | ||
278 | |||
279 | // Clean up. | ||
280 | tcsetattr(0, TCSANOW, &oldTermIo); | ||
281 | puts(""); | ||
282 | fflush(stdout); | ||
283 | } | ||
diff --git a/src/boxes/handlekeys.c b/src/boxes/handlekeys.c new file mode 100644 index 0000000..8bae529 --- /dev/null +++ b/src/boxes/handlekeys.c | |||
@@ -0,0 +1,445 @@ | |||
1 | /* handlekeys.c - Generic terminal input handler. | ||
2 | * | ||
3 | * Copyright 2012 David Seikel <won_fang@yahoo.com.au> | ||
4 | */ | ||
5 | |||
6 | // I use camelCaseNames internally, instead of underscore_names as is preferred | ||
7 | // in the rest of toybox. A small limit of 80 characters per source line infers | ||
8 | // shorter names should be used. CamelCaseNames are shorter. Externally visible | ||
9 | // stuff is underscore_names as usual. Plus, I'm used to camelCaseNames, my | ||
10 | // fingers twitch that way. | ||
11 | |||
12 | #include "toys.h" | ||
13 | #include "handlekeys.h" | ||
14 | |||
15 | struct key | ||
16 | { | ||
17 | char *code; | ||
18 | char *name; | ||
19 | }; | ||
20 | |||
21 | // This table includes some variations I have found on some terminals. | ||
22 | // http://rtfm.etla.org/xterm/ctlseq.html has a useful guide. | ||
23 | // TODO - Don't think I got all the linux console or xterm variations. | ||
24 | // TODO - Add more shift variations, plus Ctrl & Alt variations when needed. | ||
25 | // TODO - tmux messes with the shift function keys somehow. | ||
26 | // TODO - Add other miscelany that does not use an escape sequence. | ||
27 | |||
28 | // This is sorted by type, though there is some overlap. | ||
29 | // Human typing speeds wont need fast searching speeds on this small table. | ||
30 | // So simple wins out over speed, and sorting by terminal type wins | ||
31 | // the simple test. | ||
32 | static struct key keys[] = | ||
33 | { | ||
34 | // Control characters. | ||
35 | // Commented out coz it's the C string terminator, and may confuse things. | ||
36 | //{"\x00", "^@"}, // NUL | ||
37 | {"\x01", "^A"}, // SOH Apparently sometimes sent as Home. | ||
38 | {"\x02", "^B"}, // STX | ||
39 | {"\x03", "^C"}, // ETX SIGINT Emacs and vi. | ||
40 | {"\x04", "^D"}, // EOT EOF Emacs, joe, and nano. | ||
41 | {"\x05", "^E"}, // ENQ Apparently sometimes sent as End | ||
42 | {"\x06", "^F"}, // ACK | ||
43 | {"\x07", "^G"}, // BEL | ||
44 | {"\x08", "Del"}, // BS Delete key, usually. | ||
45 | {"\x09", "Tab"}, // HT | ||
46 | {"\x0A", "Enter"}, // LF Roxterm translates Ctrl-M to this. | ||
47 | {"\x0B", "^K"}, // VT | ||
48 | {"\x0C", "^L"}, // FF | ||
49 | {"\x0D", "Return"}, // CR Other Enter/Return key, usually. | ||
50 | {"\x0E", "^N"}, // SO | ||
51 | {"\x0F", "^O"}, // SI DISCARD | ||
52 | {"\x10", "^P"}, // DLE | ||
53 | {"\x11", "^Q"}, // DC1 SIGCONT Vi. | ||
54 | {"\x12", "^R"}, // DC2 | ||
55 | {"\x13", "^S"}, // DC3 SIGSTOP can't be caught. Emacs and vi. | ||
56 | {"\x14", "^T"}, // DC4 SIGINFO STATUS | ||
57 | {"\x15", "^U"}, // NAK KILL character | ||
58 | {"\x16", "^V"}, // SYN LNEXT | ||
59 | {"\x17", "^W"}, // ETB WERASE | ||
60 | {"\x18", "^X"}, // CAN KILL character | ||
61 | {"\x19", "^Y"}, // EM DSUSP SIGTSTP | ||
62 | {"\x1A", "^Z"}, // SUB SIGTSTP | ||
63 | // Commented out coz it's the ANSI start byte in the below multibyte keys. | ||
64 | // Handled in the code with a timeout. | ||
65 | //{"\x1B", "Esc"}, // ESC Esc key. | ||
66 | {"\x1C", "^\\"}, // FS SIGQUIT | ||
67 | {"\x1D", "^]"}, // GS | ||
68 | {"\x1E", "^^"}, // RS | ||
69 | {"\x1F", "^_"}, // US | ||
70 | {"\x7F", "BS"}, // Backspace key, usually. Ctrl-? perhaps? | ||
71 | // Commented out for the same reason Esc is. | ||
72 | //{"\x9B", "CSI"}, // CSI The eight bit encoding of "Esc [". | ||
73 | |||
74 | // "Usual" xterm CSI sequences, with ";1" omitted for no modifiers. | ||
75 | // Even though we have a proper CSI parser, | ||
76 | // these should still be in this table. Coz we would need a table anyway | ||
77 | // in the CSI parser, so might as well keep them with the others. | ||
78 | // Also, less code, no need to have a separate scanner for that other table. | ||
79 | {"\x9B\x31~", "Home"}, // Duplicate, think I've seen this somewhere. | ||
80 | {"\x9B\x32~", "Ins"}, | ||
81 | {"\x9B\x33~", "Del"}, | ||
82 | {"\x9B\x34~", "End"}, // Duplicate, think I've seen this somewhere. | ||
83 | {"\x9B\x35~", "PgUp"}, | ||
84 | {"\x9B\x36~", "PgDn"}, | ||
85 | {"\x9B\x37~", "Home"}, | ||
86 | {"\x9B\x38~", "End"}, | ||
87 | {"\x9B\x31\x31~", "F1"}, | ||
88 | {"\x9B\x31\x32~", "F2"}, | ||
89 | {"\x9B\x31\x33~", "F3"}, | ||
90 | {"\x9B\x31\x34~", "F4"}, | ||
91 | {"\x9B\x31\x35~", "F5"}, | ||
92 | {"\x9B\x31\x37~", "F6"}, | ||
93 | {"\x9B\x31\x38~", "F7"}, | ||
94 | {"\x9B\x31\x39~", "F8"}, | ||
95 | {"\x9B\x32\x30~", "F9"}, | ||
96 | {"\x9B\x32\x31~", "F10"}, | ||
97 | {"\x9B\x32\x33~", "F11"}, | ||
98 | {"\x9B\x32\x34~", "F12"}, | ||
99 | |||
100 | // As above, ";2" means shift modifier. | ||
101 | {"\x9B\x31;2~", "Shift Home"}, | ||
102 | {"\x9B\x32;2~", "Shift Ins"}, | ||
103 | {"\x9B\x33;2~", "Shift Del"}, | ||
104 | {"\x9B\x34;2~", "Shift End"}, | ||
105 | {"\x9B\x35;2~", "Shift PgUp"}, | ||
106 | {"\x9B\x36;2~", "Shift PgDn"}, | ||
107 | {"\x9B\x37;2~", "Shift Home"}, | ||
108 | {"\x9B\x38;2~", "Shift End"}, | ||
109 | {"\x9B\x31\x31;2~", "Shift F1"}, | ||
110 | {"\x9B\x31\x32;2~", "Shift F2"}, | ||
111 | {"\x9B\x31\x33;2~", "Shift F3"}, | ||
112 | {"\x9B\x31\x34;2~", "Shift F4"}, | ||
113 | {"\x9B\x31\x35;2~", "Shift F5"}, | ||
114 | {"\x9B\x31\x37;2~", "Shift F6"}, | ||
115 | {"\x9B\x31\x38;2~", "Shift F7"}, | ||
116 | {"\x9B\x31\x39;2~", "Shift F8"}, | ||
117 | {"\x9B\x32\x30;2~", "Shift F9"}, | ||
118 | {"\x9B\x32\x31;2~", "Shift F10"}, | ||
119 | {"\x9B\x32\x33;2~", "Shift F11"}, | ||
120 | {"\x9B\x32\x34;2~", "Shift F12"}, | ||
121 | |||
122 | // "Normal" Some terminals are special, and it seems they only have | ||
123 | // four function keys. | ||
124 | {"\x9B\x41", "Up"}, | ||
125 | {"\x9B\x42", "Down"}, | ||
126 | {"\x9B\x43", "Right"}, | ||
127 | {"\x9B\x44", "Left"}, | ||
128 | {"\x9B\x46", "End"}, | ||
129 | {"\x9BH", "Home"}, | ||
130 | {"\x9BP", "F1"}, | ||
131 | {"\x9BQ", "F2"}, | ||
132 | {"\x9BR", "F3"}, | ||
133 | {"\x9BS", "F4"}, | ||
134 | {"\x9B\x31;2P", "Shift F1"}, | ||
135 | {"\x9B\x31;2Q", "Shift F2"}, | ||
136 | {"\x9B\x31;2R", "Shift F3"}, | ||
137 | {"\x9B\x31;2S", "Shift F4"}, | ||
138 | |||
139 | // "Application" Esc O is known as SS3 | ||
140 | {"\x1BOA", "Up"}, | ||
141 | {"\x1BOB", "Down"}, | ||
142 | {"\x1BOC", "Right"}, | ||
143 | {"\x1BOD", "Left"}, | ||
144 | {"\x1BOF", "End"}, | ||
145 | {"\x1BOH", "Home"}, | ||
146 | {"\x1BOn", "Del"}, | ||
147 | {"\x1BOp", "Ins"}, | ||
148 | {"\x1BOq", "End"}, | ||
149 | {"\x1BOw", "Home"}, | ||
150 | {"\x1BOP", "F1"}, | ||
151 | {"\x1BOQ", "F2"}, | ||
152 | {"\x1BOR", "F3"}, | ||
153 | {"\x1BOS", "F4"}, | ||
154 | {"\x1BOT", "F5"}, | ||
155 | // These two conflict with the above four function key variations. | ||
156 | {"\x9BR", "F6"}, | ||
157 | {"\x9BS", "F7"}, | ||
158 | {"\x9BT", "F8"}, | ||
159 | {"\x9BU", "F9"}, | ||
160 | {"\x9BV", "F10"}, | ||
161 | {"\x9BW", "F11"}, | ||
162 | {"\x9BX", "F12"}, | ||
163 | |||
164 | // Can't remember, but saw them somewhere. | ||
165 | {"\x1BO1;2P", "Shift F1"}, | ||
166 | {"\x1BO1;2Q", "Shift F2"}, | ||
167 | {"\x1BO1;2R", "Shift F3"}, | ||
168 | {"\x1BO1;2S", "Shift F4"}, | ||
169 | }; | ||
170 | |||
171 | static volatile sig_atomic_t sigWinch; | ||
172 | static int stillRunning; | ||
173 | |||
174 | static void handleSIGWINCH(int signalNumber) | ||
175 | { | ||
176 | sigWinch = 1; | ||
177 | } | ||
178 | |||
179 | void handle_keys(long extra, int (*handle_event)(long extra, struct keyevent *event)) | ||
180 | { | ||
181 | struct keyevent event; | ||
182 | fd_set selectFds; | ||
183 | struct timespec timeOut; | ||
184 | struct sigaction sigAction, oldSigAction; | ||
185 | sigset_t signalMask; | ||
186 | char buffer[20], sequence[20]; | ||
187 | int buffIndex = 0, pendingEsc = 0; | ||
188 | |||
189 | buffer[0] = 0; | ||
190 | sequence[0] = 0; | ||
191 | |||
192 | // Terminals send the SIGWINCH signal when they resize. | ||
193 | memset(&sigAction, 0, sizeof(sigAction)); | ||
194 | sigAction.sa_handler = handleSIGWINCH; | ||
195 | sigAction.sa_flags = SA_RESTART; // Useless if we are using poll. | ||
196 | if (sigaction(SIGWINCH, &sigAction, &oldSigAction)) | ||
197 | perror_exit("can't set signal handler for SIGWINCH"); | ||
198 | sigemptyset(&signalMask); | ||
199 | sigaddset(&signalMask, SIGWINCH); | ||
200 | |||
201 | // TODO - OS buffered keys might be a problem, but we can't do the | ||
202 | // usual timestamp filter for now. | ||
203 | |||
204 | stillRunning = 1; | ||
205 | while (stillRunning) | ||
206 | { | ||
207 | int j, p, csi = 0; | ||
208 | |||
209 | // Apparently it's more portable to reset these each time. | ||
210 | FD_ZERO(&selectFds); | ||
211 | FD_SET(0, &selectFds); | ||
212 | timeOut.tv_sec = 0; timeOut.tv_nsec = 100000000; // One tenth of a second. | ||
213 | |||
214 | // We got a "terminal size changed" signal, ask the terminal | ||
215 | // how big it is now. | ||
216 | if (sigWinch) | ||
217 | { | ||
218 | // Send - save cursor position, down 999, right 999, | ||
219 | // request cursor position, restore cursor position. | ||
220 | fputs("\x1B[s\x1B[999C\x1B[999B\x1B[6n\x1B[u", stdout); | ||
221 | fflush(stdout); | ||
222 | sigWinch = 0; | ||
223 | } | ||
224 | |||
225 | // TODO - Should only ask for a time out after we get an Escape, or | ||
226 | // the user requested time ticks. | ||
227 | // I wanted to use poll, but that would mean using ppoll, which is | ||
228 | // Linux only, and involves defining swear words to get it. | ||
229 | p = pselect(0 + 1, &selectFds, NULL, NULL, &timeOut, &signalMask); | ||
230 | if (0 > p) | ||
231 | { | ||
232 | if (EINTR == errno) | ||
233 | continue; | ||
234 | perror_exit("poll"); | ||
235 | } | ||
236 | else if (0 == p) // A timeout, trigger a time event. | ||
237 | { | ||
238 | if (pendingEsc) | ||
239 | { | ||
240 | // After a short delay to check, this is a real Escape key, | ||
241 | // not part of an escape sequence, so deal with it. | ||
242 | strcat(sequence, "Esc"); | ||
243 | buffer[0] = buffIndex = 0; | ||
244 | } | ||
245 | // TODO - Call some sort of timer tick callback. This wont be | ||
246 | // a precise timed event, but don't think we need one. | ||
247 | } | ||
248 | else if ((0 < p) && FD_ISSET(0, &selectFds)) | ||
249 | { | ||
250 | j = xread(0, &buffer[buffIndex], sizeof(buffer) - (buffIndex + 1)); | ||
251 | if (j == 0) // End of file. | ||
252 | stillRunning = 0; | ||
253 | else | ||
254 | { | ||
255 | buffIndex += j; | ||
256 | buffer[buffIndex] = 0; | ||
257 | |||
258 | // Send raw keystrokes, mostly for things like showkey. | ||
259 | event.type = HK_RAW; | ||
260 | event.sequence = buffer; | ||
261 | event.isTranslated = 0; | ||
262 | handle_event(extra, &event); | ||
263 | |||
264 | if (sizeof(buffer) < (buffIndex + 1)) // Ran out of buffer. | ||
265 | { | ||
266 | buffer[buffIndex] = 0; | ||
267 | fprintf(stderr, "Full buffer - %s -> %s\n", buffer, sequence); | ||
268 | for (j = 0; buffer[j]; j++) | ||
269 | fprintf(stderr, "(%x) %c, ", (int) buffer[j], buffer[j]); | ||
270 | fflush(stderr); | ||
271 | buffer[0] = buffIndex = 0; | ||
272 | } | ||
273 | } | ||
274 | } | ||
275 | |||
276 | // Check for lone Esc first, wait a bit longer if it is. | ||
277 | pendingEsc = ((0 == buffer[1]) && ('\x1B' == buffer[0])); | ||
278 | if (pendingEsc) continue; | ||
279 | |||
280 | // Check if it's a CSI before we check for the known key sequences. | ||
281 | // C29B is the UTF8 encoding of CSI. | ||
282 | // In all cases we reduce CSI to 9B to keep the keys table shorter. | ||
283 | if ((('\x1B' == buffer[0]) && ('[' == buffer[1])) | ||
284 | || (('\xC2' == buffer[0]) && ('\x9B' == buffer[1]))) | ||
285 | { | ||
286 | buffer[0] = '\x9B'; | ||
287 | for (j = 1; buffer[j]; j++) | ||
288 | buffer[j] = buffer[j + 1]; | ||
289 | buffIndex--; | ||
290 | } | ||
291 | csi = ('\x9B' == buffer[0]); | ||
292 | |||
293 | // Check for known key sequences. | ||
294 | // For a real timeout checked Esc, buffer is now empty, so this for loop | ||
295 | // wont find it anyway. While it's true we could avoid it by checking, | ||
296 | // the user already had to wait for a time out, and this loop wont take THAT long. | ||
297 | for (j = 0; j < ARRAY_LEN(keys); j++) | ||
298 | { | ||
299 | if (strcmp(keys[j].code, buffer) == 0) | ||
300 | { | ||
301 | strcat(sequence, keys[j].name); | ||
302 | buffer[0] = buffIndex = 0; | ||
303 | csi = 0; | ||
304 | break; | ||
305 | } | ||
306 | } | ||
307 | |||
308 | // Find out if it's a CSI sequence that's not in the known key sequences. | ||
309 | if (csi) | ||
310 | { | ||
311 | /* ECMA-048 section 5.2 defines this, and is unreadable. | ||
312 | * So I'll include some notes here that tries to simplify that. | ||
313 | * | ||
314 | * The CSI format is - CSI [private] n1 ; n2 [extra] final | ||
315 | * Each of those parts, except for the initial CSI bytes, is an ordinary | ||
316 | * ASCII character. | ||
317 | * | ||
318 | * The optional [private] part is one of these characters "<=>?". | ||
319 | * If the first byte is one of these, then this is a private command, if | ||
320 | * it's one of the other n1 ones, it's not private. | ||
321 | * | ||
322 | * Next is a semi colon separated list of parameters (n1, n2, etc), which | ||
323 | * can be any characters from this set "01234567890:;<=>?". What the non | ||
324 | * digit ones mean is up to the command. Parameters can be left out, but | ||
325 | * their defaults are command dependant. | ||
326 | * | ||
327 | * Next is an optional [extra] part from this set of characters | ||
328 | * "!#$%&'()*+,-./", which includes double quotes. Can be many of these, | ||
329 | * likely isn't. | ||
330 | * | ||
331 | * Finally is the "final" from this set of characters "@[\]^_`{|}~", plus | ||
332 | * upper and lower case letters. It's private if it's one of these | ||
333 | * "pqrstuvwxyz{|}~". Though the "private" ~ is used for key codes. | ||
334 | * | ||
335 | * A full CSI command is the private, extra, and final parts. | ||
336 | * | ||
337 | * Any C0 controls, DEL (0x7f), or higher characters are undefined. | ||
338 | * TODO - So abort the current CSI and start from scratch on one of those. | ||
339 | */ | ||
340 | |||
341 | if ('M' == buffer[1]) | ||
342 | { | ||
343 | // We have a mouse report, which is CSI M ..., where the rest is | ||
344 | // binary encoded, more or less. Not fitting into the CSI format. | ||
345 | // To make things worse, can't tell how long this will be. | ||
346 | // So leave it up to the caller to tell us if they used it. | ||
347 | event.type = HK_MOUSE; | ||
348 | event.sequence = buffer; | ||
349 | event.isTranslated = 0; | ||
350 | if (handle_event(extra, &event)) | ||
351 | { | ||
352 | buffer[0] = buffIndex = 0; | ||
353 | sequence[0] = 0; | ||
354 | } | ||
355 | } | ||
356 | else | ||
357 | { | ||
358 | char *t, csFinal[8]; | ||
359 | int csIndex = 1, csParams[8]; | ||
360 | |||
361 | csFinal[0] = 0; | ||
362 | p = 0; | ||
363 | |||
364 | // Unspecified params default to a value that is command dependant. | ||
365 | // However, they will never be negative, so we can use -1 to flag | ||
366 | // a default value. | ||
367 | for (j = 0; j < ARRAY_LEN(csParams); j++) | ||
368 | csParams[j] = -1; | ||
369 | |||
370 | // Check for the private bit. | ||
371 | if (index("<=>?", buffer[1])) | ||
372 | { | ||
373 | csFinal[0] = buffer[1]; | ||
374 | csFinal[1] = 0; | ||
375 | csIndex++; | ||
376 | } | ||
377 | |||
378 | // Decode parameters. | ||
379 | j = csIndex; | ||
380 | do | ||
381 | { | ||
382 | // So we know when we get to the end of parameter space. | ||
383 | t = index("01234567890:;<=>?", buffer[j + 1]); | ||
384 | // See if we passed a paremeter. | ||
385 | if ((';' == buffer[j]) || (!t)) | ||
386 | { | ||
387 | // Only stomp on the ; if it's really the ;. | ||
388 | if (t) | ||
389 | buffer[j] = 0; | ||
390 | // Empty parameters are default parameters, so only deal with | ||
391 | // non defaults. | ||
392 | if (';' != buffer[csIndex] || (!t)) | ||
393 | { | ||
394 | // TODO - Might be ":" in the number somewhere, but we are not | ||
395 | // expecting any in anything we do. | ||
396 | csParams[p] = atoi(&buffer[csIndex]); | ||
397 | } | ||
398 | p++; | ||
399 | csIndex = j + 1; | ||
400 | } | ||
401 | j++; | ||
402 | } | ||
403 | while (t); | ||
404 | |||
405 | // Check if we got the final byte, and send it to the callback. | ||
406 | strcat(csFinal, &buffer[csIndex]); | ||
407 | t = csFinal + strlen(csFinal) - 1; | ||
408 | if (('\x40' <= (*t)) && ((*t) <= '\x7e')) | ||
409 | { | ||
410 | event.type = HK_CSI; | ||
411 | event.sequence = csFinal; | ||
412 | event.isTranslated = 1; | ||
413 | event.count = p; | ||
414 | event.params = csParams; | ||
415 | handle_event(extra, &event); | ||
416 | buffer[0] = buffIndex = 0; | ||
417 | sequence[0] = 0; | ||
418 | } | ||
419 | } | ||
420 | } | ||
421 | |||
422 | // Pass the result to the callback. | ||
423 | if (sequence[0] || buffer[0]) | ||
424 | { | ||
425 | char b[strlen(sequence) + strlen(buffer) + 1]; | ||
426 | |||
427 | sprintf(b, "%s%s", sequence, buffer); | ||
428 | event.type = HK_KEYS; | ||
429 | event.sequence = b; | ||
430 | event.isTranslated = (0 != sequence[0]); | ||
431 | if (handle_event(extra, &event)) | ||
432 | { | ||
433 | buffer[0] = buffIndex = 0; | ||
434 | sequence[0] = 0; | ||
435 | } | ||
436 | } | ||
437 | } | ||
438 | |||
439 | sigaction(SIGWINCH, &oldSigAction, NULL); | ||
440 | } | ||
441 | |||
442 | void handle_keys_quit() | ||
443 | { | ||
444 | stillRunning = 0; | ||
445 | } | ||
diff --git a/src/boxes/handlekeys.h b/src/boxes/handlekeys.h new file mode 100644 index 0000000..868183f --- /dev/null +++ b/src/boxes/handlekeys.h | |||
@@ -0,0 +1,76 @@ | |||
1 | /* handlekeys.h - Generic terminal input handler. | ||
2 | * | ||
3 | * Copyright 2012 David Seikel <won_fang@yahoo.com.au> | ||
4 | */ | ||
5 | |||
6 | enum keyeventtype{ | ||
7 | HK_CSI, | ||
8 | HK_KEYS, | ||
9 | HK_MOUSE, | ||
10 | HK_RAW | ||
11 | }; | ||
12 | |||
13 | struct keyevent { | ||
14 | enum keyeventtype type; // The type of this event. | ||
15 | char *sequence; // Either a translated sequence, or raw bytes. | ||
16 | int isTranslated; // Whether or not sequence is translated. | ||
17 | int count; // Number of entries in params. | ||
18 | int *params; // For CSI events, the decoded parameters. | ||
19 | }; | ||
20 | |||
21 | /* An input loop that handles keystrokes and terminal CSI commands. | ||
22 | * | ||
23 | * Reads stdin, trying to translate raw keystrokes into something more readable. | ||
24 | * See the keys[] array at the top of handlekeys.c for what byte sequences get | ||
25 | * translated into what key names. See dumbsh.c for an example of usage. | ||
26 | * A 0.1 second delay is used to detect the Esc key being pressed, and not Esc | ||
27 | * being part of a raw keystroke. | ||
28 | * | ||
29 | * handle_keys also tries to decode CSI commands that terminals can send. | ||
30 | * Some keystrokes are CSI commands, but those are translated as key sequences | ||
31 | * instead of CSI commands. | ||
32 | * | ||
33 | * handle_keys also sets up a SIGWINCH handler to catch terminal resizes, | ||
34 | * and sends a request to the terminal to report it's current size when it gets | ||
35 | * a SIGWINCH. This is the main reason for HK_CSI, as those reports are | ||
36 | * sent as CSI. It's still up to the user code to recognise and deal with the | ||
37 | * terminal resize response, but at least it's nicely decoded for you. | ||
38 | * | ||
39 | * Arguments - | ||
40 | * extra - arbitrary data that gets passed back to the callbacks. | ||
41 | * handle_event - a callback to handle sequences. | ||
42 | * | ||
43 | * handle_event is called when a complete sequence has been accumulated. It is | ||
44 | * passed a keyevent structure. The type member of that structure determines | ||
45 | * what sort of event this is. What's in the rest of the keyevent depends on | ||
46 | * the type - | ||
47 | * | ||
48 | * HK_CSI | ||
49 | * sequence is the fully decoded CSI command, including the private and intermediate characters. | ||
50 | * isTranslated is 1, since the CSI command has been translated. | ||
51 | * count is the count of translated CSI parameters. | ||
52 | * params is an array of translateted CSI parameters. | ||
53 | * Empty parameters are set to -1, coz -1 parameters are not legal, | ||
54 | * and empty ones should default to something that is command dependant. | ||
55 | * | ||
56 | * HK_KEYS | ||
57 | * sequence the keystrokes as ASCII, either translated or not. | ||
58 | * isTranslated if 0, then sequence is ordinary keys, otherwise | ||
59 | * sequence is the names of keys, from the keys[] array. | ||
60 | * count and params are not used. | ||
61 | * | ||
62 | * For HK_KEYS handle_event should return 1 if the sequence has been dealt with, | ||
63 | * or ignored. It should return 0, if handle_keys should keep adding more | ||
64 | * translated keystroke sequences on the end, and try again later. | ||
65 | * 0 should really only be used if it's a partial match, and we need more | ||
66 | * keys in the sequence to make a full match. | ||
67 | * | ||
68 | * HK_MOUSE | ||
69 | * sequence is the raw bytes of the mouse report. The rest are not used. | ||
70 | * | ||
71 | */ | ||
72 | void handle_keys(long extra, int (*handle_event)(long extra, struct keyevent *event)); | ||
73 | |||
74 | |||
75 | /* Call this when you want handle_keys to return. */ | ||
76 | void handle_keys_quit(); | ||
diff --git a/src/boxes/showkey.c b/src/boxes/showkey.c new file mode 100644 index 0000000..de1f804 --- /dev/null +++ b/src/boxes/showkey.c | |||
@@ -0,0 +1,149 @@ | |||
1 | /* showkey.c - Shows the keys pressed. | ||
2 | * | ||
3 | * Copyright 2014 David Seikel <won_fang@yahoo.com.au> | ||
4 | * | ||
5 | * Not actually a standard, seems to be three different versions. | ||
6 | * The original kbd - http://kbd-project.org/ | ||
7 | * The kbd fork console-tools - http://lct.sourceforge.net/ | ||
8 | * A utility invented by Eric S. Raymond - http://catb.org/esr/showkey/ | ||
9 | |||
10 | USE_SHOWKEY(NEWTOY(showkey, "", TOYFLAG_USR|TOYFLAG_BIN)) | ||
11 | |||
12 | config SHOWKEY | ||
13 | bool "showkey" | ||
14 | default n | ||
15 | help | ||
16 | usage: showkey | ||
17 | |||
18 | Shows the keys pressed. | ||
19 | */ | ||
20 | |||
21 | #include "toys.h" | ||
22 | #include "lib/handlekeys.h" | ||
23 | |||
24 | typedef void (*eventHandler) (void); | ||
25 | |||
26 | struct keyCommand | ||
27 | { | ||
28 | char *key; | ||
29 | eventHandler handler; | ||
30 | }; | ||
31 | |||
32 | GLOBALS( | ||
33 | unsigned h, w; | ||
34 | int x, y; | ||
35 | ) | ||
36 | |||
37 | #define TT this.showkey | ||
38 | |||
39 | |||
40 | static void quit() | ||
41 | { | ||
42 | printf("Quitting.\r\n"); | ||
43 | handle_keys_quit(); | ||
44 | } | ||
45 | |||
46 | // The key to command mappings. | ||
47 | static struct keyCommand simpleKeys[] = | ||
48 | { | ||
49 | {"^C", quit} | ||
50 | }; | ||
51 | |||
52 | // Callback for incoming sequences from the terminal. | ||
53 | static int handleEvent(long extra, struct keyevent *event) | ||
54 | { | ||
55 | int i; | ||
56 | |||
57 | switch (event->type) | ||
58 | { | ||
59 | case HK_RAW : | ||
60 | { | ||
61 | printf("RAW "); | ||
62 | for (i = 0; event->sequence[i]; i++) | ||
63 | { | ||
64 | printf("(%x) ", (int) event->sequence[i]); | ||
65 | if (32 > event->sequence[i]) | ||
66 | printf("^%c, ", (int) event->sequence[i] + 'A' - 1); | ||
67 | else | ||
68 | printf("%c, ", (int) event->sequence[i]); | ||
69 | } | ||
70 | printf("-> "); | ||
71 | break; | ||
72 | } | ||
73 | |||
74 | case HK_KEYS : | ||
75 | { | ||
76 | int l = strlen(event->sequence); | ||
77 | |||
78 | if (event->isTranslated) | ||
79 | printf("TRANSLATED - "); | ||
80 | else | ||
81 | printf("KEY - "); | ||
82 | printf("%s\r\n", event->sequence); | ||
83 | |||
84 | // Search for a key sequence bound to a command. | ||
85 | for (i = 0; i < ARRAY_LEN(simpleKeys); i++) | ||
86 | { | ||
87 | if (strncmp(simpleKeys[i].key, event->sequence, l) == 0) | ||
88 | { | ||
89 | // If it's a partial match, keep accumulating them. | ||
90 | if (strlen(simpleKeys[i].key) != l) | ||
91 | return 0; | ||
92 | else | ||
93 | if (simpleKeys[i].handler) simpleKeys[i].handler(); | ||
94 | } | ||
95 | } | ||
96 | break; | ||
97 | } | ||
98 | |||
99 | case HK_CSI : | ||
100 | { | ||
101 | // Is it a cursor location report? | ||
102 | if (strcmp("R", event->sequence) == 0) | ||
103 | { | ||
104 | printf("CSI cursor position - line %d, column %d\r\n", event->params[0], event->params[1]); | ||
105 | return 1; | ||
106 | } | ||
107 | |||
108 | printf("CSI command %s - ", event->sequence); | ||
109 | for (i = 0; i < event->count; i++) | ||
110 | printf("%d ", event->params[i]); | ||
111 | printf("\r\n"); | ||
112 | break; | ||
113 | } | ||
114 | |||
115 | default : break; | ||
116 | } | ||
117 | |||
118 | return 1; | ||
119 | } | ||
120 | |||
121 | void showkey_main(void) | ||
122 | { | ||
123 | struct termios termIo, oldTermIo; | ||
124 | |||
125 | // Grab the old terminal settings and save it. | ||
126 | tcgetattr(0, &oldTermIo); | ||
127 | tcflush(0, TCIFLUSH); | ||
128 | termIo = oldTermIo; | ||
129 | |||
130 | // Mould the terminal to our will. | ||
131 | // In this example we are turning off all the terminal smarts, but real code | ||
132 | // might not want that. | ||
133 | termIo.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | ||
134 | | IUCLC | IXON | IXOFF | IXANY); | ||
135 | termIo.c_oflag &= ~OPOST; | ||
136 | termIo.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | TOSTOP | ICANON | ISIG | ||
137 | | IEXTEN); | ||
138 | termIo.c_cflag &= ~(CSIZE | PARENB); | ||
139 | termIo.c_cflag |= CS8; | ||
140 | termIo.c_cc[VTIME]=0; // deciseconds. | ||
141 | termIo.c_cc[VMIN]=1; | ||
142 | tcsetattr(0, TCSANOW, &termIo); | ||
143 | |||
144 | handle_keys(0, handleEvent); | ||
145 | |||
146 | tcsetattr(0, TCSANOW, &oldTermIo); | ||
147 | puts(""); | ||
148 | fflush(stdout); | ||
149 | } | ||