aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/boxes
diff options
context:
space:
mode:
authoronefang2020-09-08 21:34:54 +1000
committeronefang2020-09-08 21:34:54 +1000
commitbd58d3012c26d16150f650c389d1136741d3939d (patch)
tree3d2aec8bfe0a0c9061ddb4814e71aff33b9b8dc8 /src/boxes
parentAdd the old bash scripts. (diff)
downloadopensim-SC-bd58d3012c26d16150f650c389d1136741d3939d.zip
opensim-SC-bd58d3012c26d16150f650c389d1136741d3939d.tar.gz
opensim-SC-bd58d3012c26d16150f650c389d1136741d3939d.tar.bz2
opensim-SC-bd58d3012c26d16150f650c389d1136741d3939d.tar.xz
Add the SledjChisl stuff.
Diffstat (limited to 'src/boxes')
-rw-r--r--src/boxes/BOXES.txt1130
-rw-r--r--src/boxes/BUGS.txt6
-rw-r--r--src/boxes/README34
-rw-r--r--src/boxes/boxes.c2517
-rw-r--r--src/boxes/dumbsh.c283
-rw-r--r--src/boxes/handlekeys.c445
-rw-r--r--src/boxes/handlekeys.h76
-rw-r--r--src/boxes/showkey.c149
8 files changed, 4640 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 @@
1What's needed for MC like program. Call the library toyboxes, and the MC clone toysoldier. B-)
2
3Use ANSI for terminal control.
4UTF-8 support is welcome in toybox where it makes sense, here it makes sense.
5
6Command 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
12Split 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
67A 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
74Popup 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
95Scripting, 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
114NOTE - 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
117Events
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
125Common 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
304Readline.
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
350more
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
362less
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
374ed - 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
391sed
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
400ex - 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
444vi
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
471nano
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
501microemacs (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
583wordstar (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
629mc 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
637mcedit / 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
665Make 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
698Probably got most of what we need to do screen / tmux / multitail, and other full screen terminal stuffs.
699
700Are we ncurses yet? Or twin? lol
701
702------------------------------------------------------------------------------------------------------
703
704NOTES
705
706From Rob -
707----------
708
709On 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
713Well, right now you can put a NULL as your optstring and then set
714which->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
723Already does. In toys/toysh.c function run_pipeline() look for the
724TOYFLAG_NOFORK bit.
725
726This probably needs to be genericized somewhere in lib, but I never got
727around to it.
728
729From Rob -
730----------
731
732I need to write a getline() with cursor control, which means I need to
733query the tty size. The magic for that is:
734
735struct winsize tty = { 0, 0, 0, 0 };
736int ret = ioctl(1, TIOCGWINSZ, &tty);
737
738plus $COLUMNS and $LINES, plus echo -e "\e[s\e[999C\e[999B\e[6n\e[u"
739
740Add command history parsing to getline().
741
742From Rob -
743----------
744
745Digging up ancient issues from toybox development, one of which is an
746interesting design issue with querying the terminal size.
747
748When you're on a serial console (happens a lot in the embedded world),
749the local tty device doesn't know the width and height of the window at
750the far end, so ioctl(TIOCGWINSZ) can't report it to you.
751
752If the term program at the other end supports ansi escape sequences
753(everything does, including xterms), there's an escape sequence you can
754use to ask it, but there's multiple levels of non-obvious to the
755implementation.
756
757The escape sequence itself is "\e[6n", to which the terminal program
758responds with another escape sequence, "\e[YY;XXR" where the "XX" part
759is a decimal number with the current cursor's Y location, and XX is the
760cursor X location. (Both decimal, top left is 1;1.)
761
762Since what we want is the size of the screen, we wrap that in some more
763commands, saving the current position, moving to the cursor 999 down and
764999 to the right (which should stick it at the lower right corner),
765query that position, and the jump back to the saved location. The full
766escape sequence is therefore "\e[s\e[999C\e[999B\e[6n\e[u".
767
768The problem is, the response comes back from the terminal program on
769stdin: along with whatever else is coming in on stdin. There could be a
770delay of a significant fraction of a second (especially through a rial
771port, even when you aren't overcommitted and swapping), and there's no
772guarantee the terminal will actually respond. So blocking and waiting
773for a response isn't the greatest idea, and can eat other input the user
774has queued up.
775
776This means you need to do a nonblocking read, assemble an ansi sequence
777a piece at a time (luckily the term programs generate these atomically
778so you don't get part of an ansi sequence with user-typed keys in the
779middle of it), and keep any other data you get for use later. The
780logical place to do this is in the line editing code the shell has to
781have anyway, which responds to cursor keys, page up and down, and so on.
782
783From Rob -
784----------
785
786Less has to get it _right_, as does line editing for a command shell.
787Even before you get to cursor up: unix tty handling is epically crappy.
788My commodore 64 could backspace past the left edge of the screen and
789continue from the right edge one line up. A TRS-80 could do this. Unix
790derivatives _can't_, you have to know when you're at the left edge of
791the screen and do the ansi sequences for "cursor up one, jump right
792999". Which means you have to know when backspace puts you at the left
793edge of the screen, which means you need to know when outputting normal
794characters put you off the _right_ edge of the screen...
795
796That's right: if you don't know what your current screen size is, your
797command shell can't backspace past a line wrap. Welcome to unix
798terminal handling.
799
800From Rob -
801----------
802
803Here's a fun one:
804
805cat /proc/mounts | less
806
807When less outputs the escape sequence to query terminal parameters, it
808has to peek not stdin but /dev/tty. Except the cursor keys scrolling up
809and down also come from /dev/tty, as do "user hit forward slash and
810wants to type in a search regex"... Innit fun?
811
812Plus you have to figure out the width of what you're outputting, which
813means isprint() and probably UTF8 awareness... (Flashbacks to
814fontmetrics in java 1.1, but we can assume monospace text grid...)
815
816From Rob -
817----------
818
819Alas, POSIX does not seem to like simple. To start with, the spec
820requires "more" to be terminal aware, which isn't entirely surprising
821given what it does. But it's not just _height_ aware, it's width aware
822too.
823
824It's actually kinda fiddly: more needs to be able to wrap lines at the
825screen size to figure out when to prompt, but the first 32 ascii
826characters (all the stuff below space) don't consistently print one
827character. Some print nothing, some move the cursor around (tab,
828newline, linefeed, backspace, form feed, whatever the heck "vertical
829tab" does...)
830
831In theory I can hijack catv and just escape most of the low-ascii
832weirdness (so it's two characters, but it's _consistently_ two
833characters whatever $TERM thinks). In practice, when not hooked up to a
834tty more is supposed to act like cat and pass data through unmodified...
835
836I plan to do the simplest standards conformant implementation I can, and
837every once in a while I go "you know, the standard's nuts, let's just
838document the divergence"...
839
840
841From Rob -
842----------
843
844Keep in mind that Unix doesn't implement backspace sanely (like the
845commodore 64 did), thus you have to figure out when you're at the left
846edge of the screen (keeping track of your cursor position)
847
848That's why if you do "echo -n this will screw bash up" and then cursor
849up a few times bash's command history gets all wonky because it _thinks_
850it knows where the cursor is but actually started farther to the right.
851(I contributed ansi escape screen position querying code to busybox to
852improve the situation for ash.)
853
854From Rob -
855----------
856
857The question here is how much of this we already need to do for shell
858history, which is what I was going to implement first. (Actually the one
859I've already sat down and wrestled with is "more", which turns out to
860have rather a lot of these issues as well. Knowing what printable
861characters actually _print_ so you know where your darn cursor is and
862where the screen wraps. You'd think less would have more issues here,
863but more actually hits just about all of 'em...)
864
865Moving the cursor isn't the issue. Querying the screen size is a
866reasonably contained issue. Knowing how the cursor will move when you
867print out an arbitrary string: that's the hard part. (utf8 awareness is
868kinda required here. And I'm assuming a monospaced font even in klingon.
869And replacing the !isprint() characters below space with escape
870sequences...)
871
872
873From Rob and others -
874---------------------
875
876http://lists.busybox.net/pipermail/busybox/2008-October/067348.html
877
878http://lists.busybox.net/pipermail/busybox/2009-May/069314.html
879
880From Rob -
881----------
882
883Implementing ascii programming in the library itself was what I was
884referring to. (It's on my todo list...) All sorts of stuff needs it:
885more, toysh, vi... Even ls wants to know the width of the screen for -C
886mode.
887
888The problem is parsing the replies, since the user could type arbitrary
889stuff. It's stdout that needs to be a tty (because "ls | blah" is not
890going to a tty even if stdin is a tty), but the input _could_ come back
891in on stdin if that's another filehandle to the same tty... as could any
892other random input. If you're filtering all your input through a line
893reading function that needs to parse cursor keys to implement command
894history, doing this is easy. But if _all_ you care about is the probe
895response and you want to leave the rest of the input alone, it's kinda
896hard.
897
898What I might wind up doing is adding it to toysh and having that export
899COLUMNS and LINES environment variables. It wouldn't catch resizes in
900the middle of a command, but I think I'm ok with that...
901
902
903------------------------------------------------------------------------------------------------------
904
905/*
906key / mouse -> command
907menu choice -> command
908border click -> command
909popup + args -> command
910typed string -> command
911script call -> command
912script callback -> command
913C call -> command
914
915Arguments - 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
924So every command call involves it's content, and can take default arguments from that content, to be overridden by arguments.
925Keys and menus just have arguments coded into their string on definition, though might mostly be argument less.
926Popups have a structure that defines their argument widgets, and how to turn them into command arguments.
927Popups need to be created from string commands to.
928Typed commands can just have their arguments as part of the typed string.
929Scripts and callbacks just send a string that is treated the same way as typed commands.
930C can do the same as scripts, but should be able to call things directly.
931
932Sending commands back to scripts, should use the same format as our commands.
933
934Would be nice to have parameter substitution to, but that would have to be per content.
935
936Use an event system.
937
938---------------------------------------------
939
940Events
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
951void doScript(struct content *content, char commandString, struct event *event, void *blob)
952
953Define 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
956Define a key
957 keyName, commandString
958
959Define a menu item
960 menuTitle, commandString
961
962Define a border widget
963 borderPosition, borderType, textOrCommand
964
965Define a popup
966 popupName, commandStub, thingThatMapsWidgetsToArgs
967
968Define a script callback
969 name, command, someKey
970
971---------------------------------------------
972
973Script interface.
974
975We might have multiple scripts running, but only one per box.
976 But what if a script wants to split it's box?
977They can't access our data structures, and we can't access theirs.
978All needs to be done via stdin/stdout plain text, which should all look like the commands in the rest of the system.
979
980Scripts can register simple callbacks on these events - key, menu, timer, box destroyed.
981The first three might want to return a damage list.
982The last means that the box wants to be destroyed, but the script gets a chance to clean up.
983
984Scripts need to be able to hook into the damage system, so there needs to be a text representation of damage areas.
985
986boxes <-> script
987
988Boxes knows which script is attached to which box.
989Registering a key for the box is optional, and it's only passed back if it exists.
990A 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
996user 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
1020struct 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
1032struct command
1033{
1034 key // Note that any given context might have different keys for any given function.
1035 *function
1036};
1037
1038struct item
1039{
1040 type
1041 union
1042 {
1043 *command
1044 *menu
1045 }
1046}
1047
1048struct menu
1049{
1050 *items[] // Circular pointer definiton for sub menus.
1051}
1052
1053struct 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
1062char borderchars[][]
1063{
1064 // usual box graphic symbols
1065 '-|+',
1066 // ANSI code for inverse spaces.
1067}
1068
1069struct borderWidget
1070{
1071 text
1072 *clickFunction(int position)
1073}
1074
1075struct border
1076{
1077 *topLeftWidget
1078 *topRightWidget
1079 *bottomLeftWidget
1080 *bottomRightWidget
1081 *leftWidget
1082 *rightWidget
1083}
1084
1085struct 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
1092struct 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
1106struct 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
1116struct 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
1128box root; // Always a full screen, parent of the rest of the boxes, or the only box.
1129box current;
1130bool 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 @@
1xterm current box characters are wrong
2joe - ^K^D not working, but ^Kd is
3 Even odder, ^D works, all other ^K^? combinations work.
4F1 seems to not work, at least under xterm.
5
6should clear the command line prompt when not in use
diff --git a/src/boxes/README b/src/boxes/README
new file mode 100644
index 0000000..e01bb6b
--- /dev/null
+++ b/src/boxes/README
@@ -0,0 +1,34 @@
1boxes
2=====
3
4A test bed for a generic editor / pager thingy for the toybox project.
5
6The toybox project is at http://www.landley.net/code/toybox/ and boxes
7is covered by the same license that toybox is. Basically that's a two
8clause BSD license, but see the LICENSE file from toybox for details.
9
10This is a work in progress, proof of concept, playground, packaged up as
11one 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 /
13pager toys and library bits. Nothing is set in stone, lots of mess
14inside, there's bugs, but at least it shows the general direction my
15mind is wandering in. As a bonus, it actually works, you can edit
16stuff.
17
18Please 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
20try it out, it's just one big toy.
21
22If you want to see how it can be used to build specific editors, start
23at the end and work backwards. Reading the lengthy comments at the
24beginning would also be useful.
25
26Toybox uses mecurial instead of git, but I keep all my stuff on github.
27Boxes will hopefully be incorporated into toybox in a highly altered
28form some day in the future. So this is just a temporary git repo for
29my convenience. If and when boxes migrates to toybox, this repo will be
30retired.
31
32
33BTW, toybox REQUIRES a README file here, a README.md file isn't good
34enough.
diff --git a/src/boxes/boxes.c b/src/boxes/boxes.c
new file mode 100644
index 0000000..4f542e1
--- /dev/null
+++ b/src/boxes/boxes.c
@@ -0,0 +1,2517 @@
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
13USE_BOXES(NEWTOY(boxes, "w#h#m(mode):a(stickchars)1", TOYFLAG_USR|TOYFLAG_BIN))
14
15config BOXES
16 bool "boxes"
17 default y
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
38GLOBALS(
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
209As I mentioned in my last email to the Aboriginal linux list, I wrote
210the large blob so I could see how the ideas all work to do the generic
211editor stuff and other things. It kinda needs to be that big to do
212anything that is actually useful. So, onto musings about cutting it up
213into bite sized bits...
214
215You mentioned on the Aboriginal Linux list that you wanted a
216"readline", and you listed some features. My reply was that you had
217basically listed the features of my "basic editor". The main
218difference between "readline" and a full screen editor, is that the
219editor is fullscreen, while the "readline" is one line. They both have
220to deal with a list of lines, going up and down through those lines,
221editing the contents of those lines, one line at a time. For persistent
222line history, they both have to save and load those lines to a file.
223Other than that "readline" adds other behaviour, like moving the
224current line to the end when you hit return and presenting that line to
225the caller (here's the command). So just making "readline" wont cut
226out much of the code. In fact, my "readline" is really just a thin
227wrapper around the rest of the code.
228
229Starting from the other end of the size spectrum, I guess "find out
230terminal size" is a small enough bite sized chunk. To actually do
231anything useful with that you would probably start to write stuff I've
232already written though. Would be better off just using the stuff I've
233already 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
236I guess the smallest useful command I have in my huge blob of code
237would be "more". I could even cut it down more. Show a page of text,
238show the next page of text when you hit the space bar, quit when you
239hit "q". Even then, I would estimate it would only cut out a third of
240the code.
241
242On the other hand, there's a bunch of crap in that blob that is for
243future plans, and is not doing anything now.
244
245In the end though, breaking it up into suitable bite sized bits might
246be almost as hard as writing it in the first place. I'll see what I
247can do, when I find some time. I did want to break it up into three
248bits anyway, and there's a TODO to untangle a couple of bits that are
249currently too tightly coupled.
250
251*/
252
253/* Robs contradiction
254
255On 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
276Which is most of an editor already, so how to break it up into bite
277sized 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
299static 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
307static 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
316typedef struct _box box;
317typedef struct _view view;
318
319typedef void (*boxFunction) (box *box);
320typedef void (*eventHandler) (view *view);
321
322struct 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
334struct keyCommand
335{
336 char *key, *command;
337};
338
339struct 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
352struct 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
361struct 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/*
370Have a common menu up the top.
371 MC has a menu that changes per mode.
372 Nano has no menu.
373Have 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*/
377struct 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.
397struct border
398{
399 struct borderWidget *topLeft, *topMiddle, *topRight;
400 struct borderWidget *bottomLeft, *bottomMiddle, *bottomRight;
401 struct borderWidget *left, *right;
402};
403
404struct 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
411struct 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
420struct 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
434struct _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
461struct _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.
474void 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
480static int overWriteMode;
481static box *rootBox; // Parent of the rest of the boxes, or the only box. Always a full screen.
482static box *currentBox;
483static view *commandLine;
484static 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.
489struct 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
525void 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
535void 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 = 0;
543
544 do
545 {
546 // TODO - get_line() is slow, and wont help much with DOS and Mac line endings.
547 temp = get_line(fd);
548 if (temp)
549 addLine(content, NULL, temp, len);
550 } while (temp);
551 close(fd);
552 }
553}
554
555// TODO - load and save should be able to deal with pipes, and with loading only parts of files, to load more parts later.
556
557void saveFile(struct content *content)
558{
559// TODO - Should do "Save as" as well. Which is just a matter of changing content->path before calling this.
560 int fd;
561
562 fd = open(content->path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
563
564 if (-1 != fd)
565 {
566 struct line *line = content->lines.next;
567
568 while (&(content->lines) != line) // We are at the end if we have wrapped to the beginning.
569 {
570 write(fd, line->line, strlen(line->line));
571 write(fd, "\n", 1);
572 line = line->next;
573 }
574 close(fd);
575 }
576 else
577 {
578 fprintf(stderr, "Can't open file %s\n", content->path);
579 exit(1);
580 }
581}
582
583struct content *addContent(char *name, struct context *context, char *filePath)
584{
585 struct content *result = xzalloc(sizeof(struct content));
586
587 result->lines.next = &(result->lines);
588 result->lines.prev = &(result->lines);
589 result->name = strdup(name);
590 result->context = context;
591
592 if (filePath)
593 {
594 result->path = strdup(filePath);
595 loadFile(result);
596 }
597
598 return result;
599}
600
601// General purpose line moosher. Used for appends, inserts, overwrites, and deletes.
602// TODO - should have the same semantics as mooshStrings, only it deals with whole lines in double linked lists.
603// We need content so we can adjust it's number of lines if needed.
604void mooshLines(struct content *content, struct line *result, struct line *moosh, uint16_t index, uint16_t length, int insert)
605{
606}
607
608// General purpose string moosher. Used for appends, inserts, overwrites, and deletes.
609void mooshStrings(struct line *result, char *moosh, uint16_t index, uint16_t length, int insert)
610{
611 char *c, *pos;
612 int limit = strlen(result->line);
613 int mooshLen = 0, resultLen;
614
615 if (moosh)
616 mooshLen = strlen(moosh);
617
618 /*
619 * moosh == NULL a deletion
620 * length == 0 simple insertion
621 * length < mooshlen delete some, insert moosh
622 * length == mooshlen exact overwrite.
623 * length > mooshlen delete a lot, insert moosh
624 */
625
626 mooshLen -= length;
627 resultLen = limit + mooshLen;
628
629 // If we need more space, allocate more.
630 if (resultLen > result->length)
631 {
632 result->length = resultLen + MEM_SIZE;
633 result->line = xrealloc(result->line, result->length);
634 }
635
636 if (limit <= index) // At end, just add to end.
637 {
638 // TODO - Possibly add spaces to pad out to where index is?
639 // Would be needed for "go beyond end of line" and "column blocks".
640 // Both of those are advanced editing.
641 index = limit;
642 insert = 1;
643 }
644
645 pos = &(result->line[index]);
646
647 if (insert) // Insert / delete before current character, so move it and the rest up / down mooshLen bytes.
648 {
649 if (0 < mooshLen) // Gotta move things up.
650 {
651 c = &(result->line[limit]);
652 while (c >= pos)
653 {
654 *(c + mooshLen) = *c;
655 c--;
656 }
657 }
658 else if (0 > mooshLen) // Gotta move things down.
659 {
660 c = pos;
661 while (*c)
662 {
663 *c = *(c - mooshLen); // A double negative.
664 c++;
665 }
666 }
667 }
668
669 if (moosh)
670 {
671 c = moosh;
672 do
673 {
674 *pos++ = *c++;
675 }
676 while (*c);
677 }
678}
679
680// TODO - Should draw the current border in green, the text as default (or highlight / bright).
681// Then allow one other box to be red bordered (MC / dired destination box).
682// All other boxes with dark gray border, and dim text.
683void drawLine(int y, int start, int end, char *left, char *internal, char *contents, char *right, int current)
684{
685 int size = strlen(internal);
686 int len = (end - start) * size, x = 0;
687 char line[len + 1];
688
689 if ('\0' != left[0]) // Assumes that if one side has a border, then so does the other.
690 len -= 2 * size;
691
692 if (contents)
693 {
694 // strncpy wont add a null at the end if the source is longer, but will pad with nulls if source is shorter.
695 // So it's best to put a safety null in first.
696 line[len] = '\0';
697 strncpy(line, contents, len);
698 // Make sure the following while loop pads out line with the internal character.
699 x = strlen(line);
700 }
701 while (x < len)
702 {
703 strcpy(&line[x], internal);
704 x += size;
705 }
706 line[x++] = '\0';
707 if ('\0' == left[0]) // Assumes that if one side has a border, then so does the other.
708 {
709 if (current)
710 printf("\x1B[1m\x1B[%d;%dH%s\x1B[m", y + 1, start + 1, line);
711 else
712 printf("\x1B[m\x1B[%d;%dH%s", y + 1, start + 1, line);
713 }
714 else
715 {
716 if (current)
717 printf("\x1B[1m\x1B[%d;%dH%s%s%s\x1B[m", y + 1, start + 1, left, line, right);
718 else
719 printf("\x1B[m\x1B[%d;%dH%s%s%s", y + 1, start + 1, left, line, right);
720 }
721}
722
723void formatCheckCursor(view *view, long *cX, long *cY, char *input)
724{
725 int i = 0, o = 0, direction = (*cX) - view->cX;
726
727 // Adjust the cursor if needed, depending on the contents of the line, and the direction of travel.
728 while (input[i])
729 {
730 // When o is equal to the cX position, update the iX position to be where i is.
731 if ('\t' == input[i])
732 {
733 int j = 8 - (i % 8);
734
735 // Check if the cursor is in the middle of the tab.
736 if (((*cX) > o) && ((*cX) < (o + j)))
737 {
738 if (0 <= direction)
739 {
740 *cX = (o + j);
741 view->iX = i + 1;
742 }
743 else
744 {
745 *cX = o;
746 view->iX = i;
747 }
748 }
749 o += j;
750 }
751 else
752 {
753 if ((*cX) == o)
754 view->iX = i;
755 o++;
756 }
757 i++;
758 }
759 // One more check in case the cursor is at the end of the line.
760 if ((*cX) == o)
761 view->iX = i;
762}
763
764// TODO - Should convert control characters to reverse video, and deal with UTF8.
765
766/* FIXME - We get passed a NULL input, apparently when the file length is close to the screen length. -
767> On Thu, 6 Sep 2012 11:56:17 +0800 Roy Tam <roytam@gmail.com> wrote:
768>
769> > 2012/9/6 David Seikel <onefang@gmail.com>:
770> > >> Program received signal SIGSEGV, Segmentation fault.
771> > >> formatLine (view=0x8069168, input=0x0, output=0x806919c)
772> > >> at toys/other/boxes.c:843
773> > >> 843 int len = strlen(input), i = 0, o = 0;
774> > >> (gdb) bt
775> > >> #0 formatLine (view=0x8069168, input=0x0, output=0x806919c)
776> > >> at toys/other/boxes.c:843
777> > >> #1 0x0804f1dd in moveCursorAbsolute (view=0x8069168, cX=0,
778> > >> cY=10, sX=0, sY=0) at toys/other/boxes.c:951
779> > >> #2 0x0804f367 in moveCursorRelative (view=0x8069168, cX=0,
780> > >> cY=10, sX=0, sY=0) at toys/other/boxes.c:1011
781> > >> #3 0x0804f479 in upLine (view=0x8069168, event=0x0) at
782> > >> toys/other/boxes.c:1442 #4 0x0804fb63 in handleKey
783> > >> (view=0x8069168, i=2, keyName=<optimized out>, buffer=0xbffffad8
784> > >> "\033[A") at toys/other/boxes.c:1593 #5 0x0805008d in editLine
785> > >> (view=0x8069168, X=-1, Y=-1, W=-1, H=-1) at
786> > >> toys/other/boxes.c:1785 #6 0x08050288 in boxes_main () at
787> > >> toys/other/boxes.c:2482 #7 0x0804b262 in toy_exec
788> > >> (argv=0xbffffd58) at main.c:104 #8 0x0804b29d in toybox_main ()
789> > >> at main.c:118 #9 0x0804b262 in toy_exec (argv=0xbffffd54) at
790> > >> main.c:104 #10 0x0804b29d in toybox_main () at main.c:118
791> > >> #11 0x0804affa in main (argc=5, argv=0xbffffd54) at main.c:159
792> > >
793> > > No segfault here when I try that, nor with different files. As I
794> > > said, it has bugs. I have seen other cases before when NULL lines
795> > > are passed around near that code. Guess I've not got them all.
796> > > Might help to mention what terminal proggy you are using, it's
797> > > size in characters, toybox version, OS, etc. Something is
798> > > different between you and me.
799> >
800> > Terminal Program: PuTTY
801> > Windows size: 80 * 25 chars
802> > Toybox version: hg head
803> > OS: Linux 3.2 (Debian wheezy)
804> > File: Toybox LICENSE file
805>
806> I'll install PuTTY, try toybox hg head, and play with them later, see
807> if I can reproduce that segfault. I use the last released tarball of
808> toybox, an old Ubuntu, and a bunch of other terminal proggies. I did
809> not know that PuTTY had been ported to Unix.
810>
811> But as I mentioned, not interested in a bug hunt right now. That will
812> be more appropriate when it's less of a "sandbox for testing the
813> ideas" and more of a "good enough to bother using". Always good to
814> have other terminals for testing though.
815
816Seems to be sensitive to the number of lines. On my usual huge
817roxterm, using either toybox 0.4 or hg head, doing this -
818
819./toybox boxes -m less LICENSE -h 25
820
821and just hitting down arrow until you get to the bottom of the page
822segfaults as well. -h means "pretend the terminal is that many lines
823high", there's a similar -w as well. 80x25 in any other terminal did
824the same. For that particular file (17 lines long), any value of -h
825between 19 and 34 will segfault after some moving around. -h 35 makes
826it segfault straight away. Less than 19 or over 35 is fine. Longer
827files don't have that problem, though I suspect it will happen on
828shortish files where the number of lines is about the length of the
829screen.
830
831I guess that somewhere I'm doing maths wrong and getting an out of
832bounds line number when the file length is close to the screen length.
833I'll make note of that, and fix it when I next get time to beat on
834boxes.
835
836Thanks for reporting it Roy.
837*/
838
839int formatLine(view *view, char *input, char **output)
840{
841 int len = strlen(input), i = 0, o = 0;
842
843 *output = xrealloc(*output, len + 1);
844
845 while (input[i])
846 {
847 if ('\t' == input[i])
848 {
849 int j = 8 - (i % 8);
850
851 *output = xrealloc(*output, len + j + 1);
852 for (; j; j--)
853 {
854 (*output)[o++] = ' ';
855 len++;
856 }
857 len--; // Not counting the actual tab character itself.
858 }
859 else
860 (*output)[o++] = input[i];
861 i++;
862 }
863 (*output)[o++] = '\0';
864
865 return len;
866}
867
868void drawContentLine(view *view, int y, int start, int end, char *left, char *internal, char *contents, char *right, int current)
869{
870 char *temp = NULL;
871 int offset = view->offsetX, len;
872
873 if (contents == view->line->line)
874 {
875 view->oW = formatLine(view, contents, &(view->output));
876 temp = view->output;
877 len = view->oW;
878 }
879 else // Only time we are not drawing the current line, and only used for drawing the entire page.
880 len = formatLine(NULL, contents, &(temp));
881
882 if (offset > len)
883 offset = len;
884 drawLine(y, start, end, left, internal, &(temp[offset]), right, current);
885}
886
887void updateLine(view *view)
888{
889 int y, len;
890
891 // Coz things might change out from under us, find the current view. Again.
892 if (commandMode) view = commandLine;
893 else view = currentBox->view;
894
895 // TODO - When doing scripts and such, might want to turn off the line update until finished.
896 // Draw the prompt and the current line.
897 y = view->Y + (view->cY - view->offsetY);
898 len = strlen(view->prompt);
899 drawLine(y, view->X, view->X + view->W, "", " ", view->prompt, "", 0);
900 drawContentLine(view, y, view->X + len, view->X + view->W, "", " ", view->line->line, "", 1);
901 // Move the cursor.
902 printf("\x1B[%d;%dH", y + 1, view->X + len + (view->cX - view->offsetX) + 1);
903 fflush(stdout);
904}
905
906void doCommand(view *view, char *command)
907{
908 if (command)
909 {
910 struct function *functions = view->content->context->commands;
911 int i;
912
913// TODO - Some editors have a shortcut command concept. The smallest unique first part of each command will match, as well as anything longer.
914// A further complication is if we are not implementing some commands that might change what is "shortest unique prefix".
915
916 for (i = 0; functions[i].name; i++)
917 {
918 if (strcmp(functions[i].name, command) == 0)
919 {
920 if (functions[i].handler)
921 {
922 functions[i].handler(view);
923 updateLine(view);
924 }
925 break;
926 }
927 }
928 }
929}
930
931int moveCursorAbsolute(view *view, long cX, long cY, long sX, long sY)
932{
933 struct line *newLine = view->line;
934 long oX = view->offsetX, oY = view->offsetY;
935 long lX = view->oW, lY = view->content->lines.length - 1;
936 long nY = view->cY;
937 uint16_t w = view->W - 1, h = view->H - 1;
938 int moved = 0, updatedY = 0, endOfLine = 0;
939
940 // Check if it's still within the contents.
941 if (0 > cY) // Trying to move before the beginning of the content.
942 cY = 0;
943 else if (lY < cY) // Trying to move beyond end of the content.
944 cY = lY;
945 if (0 > cX) // Trying to move before the beginning of the line.
946 {
947 // See if we can move to the end of the previous line.
948 if (view->line->prev != &(view->content->lines))
949 {
950 cY--;
951 endOfLine = 1;
952 }
953 else
954 cX = 0;
955 }
956 else if (lX < cX) // Trying to move beyond end of line.
957 {
958 // See if we can move to the begining of the next line.
959 if (view->line->next != &(view->content->lines))
960 {
961 cY++;
962 cX = 0;
963 }
964 else
965 cX = lX;
966 }
967
968 // Find the new line.
969 while (nY != cY)
970 {
971 updatedY = 1;
972 if (nY < cY)
973 {
974 newLine = newLine->next;
975 nY++;
976 if (view->content->lines.prev == newLine) // We are at the end if we have wrapped to the beginning.
977 break;
978 }
979 else
980 {
981 newLine = newLine->prev;
982 nY--;
983 if (view->content->lines.next == newLine) // We are at the end if we have wrapped to the beginning.
984 break;
985 }
986 }
987 cY = nY;
988
989 // Check if we have moved past the end of the new line.
990 if (updatedY)
991 {
992 // Format it.
993 view->oW = formatLine(view, newLine->line, &(view->output));
994 if (view->oW < cX)
995 endOfLine = 1;
996 if (endOfLine)
997 cX = view->oW;
998 }
999
1000 // Let the formatter decide if it wants to adjust things.
1001 // It's up to the formatter to deal with things if it changes cY.
1002 // On the other hand, changing cX is it's job.
1003 formatCheckCursor(view, &cX, &cY, newLine->line);
1004
1005 // Check the scrolling.
1006 lY -= view->H - 1;
1007 oX += sX;
1008 oY += sY;
1009
1010 if (oY > cY) // Trying to move above the box.
1011 oY += cY - oY;
1012 else if ((oY + h) < cY) // Trying to move below the box
1013 oY += cY - (oY + h);
1014 if (oX > cX) // Trying to move to the left of the box.
1015 oX += cX - oX;
1016 else if ((oX + w) <= cX) // Trying to move to the right of the box.
1017 oX += cX - (oX + w);
1018
1019 if (oY < 0)
1020 oY = 0;
1021 if (oY >= lY)
1022 oY = lY;
1023 if (oX < 0)
1024 oX = 0;
1025 // TODO - Should limit oX to less than the longest line, minus box width.
1026 // Gonna be a pain figuring out what the longest line is.
1027 // 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.
1028 // Though still might want to do that for the longest line on the new page to be.
1029
1030 if ((view->cX != cX) || (view->cY != cY))
1031 moved = 1;
1032
1033 // Actually update stuff, though some have been done already.
1034 view->cX = cX;
1035 view->cY = cY;
1036 view->line = newLine;
1037
1038 // Handle scrolling.
1039 if ((view->offsetX != oX) || (view->offsetY != oY))
1040 {
1041 view->offsetX = oX;
1042 view->offsetY = oY;
1043
1044 if (view->box)
1045 drawBox(view->box);
1046 }
1047
1048 return moved;
1049}
1050
1051int moveCursorRelative(view *view, long cX, long cY, long sX, long sY)
1052{
1053 return moveCursorAbsolute(view, view->cX + cX, view->cY + cY, sX, sY);
1054}
1055
1056void sizeViewToBox(box *box, int X, int Y, int W, int H)
1057{
1058 uint16_t one = 1, two = 2;
1059
1060 if (!(box->flags & BOX_BORDER))
1061 {
1062 one = 0;
1063 two = 0;
1064 }
1065 box->view->X = X;
1066 box->view->Y = Y;
1067 box->view->W = W;
1068 box->view->H = H;
1069 if (0 > X) box->view->X = box->X + one;
1070 if (0 > Y) box->view->Y = box->Y + one;
1071 if (0 > W) box->view->W = box->W - two;
1072 if (0 > H) box->view->H = box->H - two;
1073}
1074
1075view *addView(char *name, struct context *context, char *filePath, uint16_t X, uint16_t Y, uint16_t W, uint16_t H)
1076{
1077 view *result = xzalloc(sizeof(struct _view));
1078
1079 result->X = X;
1080 result->Y = Y;
1081 result->W = W;
1082 result->H = H;
1083
1084 result->content = addContent(name, context, filePath);
1085 result->prompt = xzalloc(1);
1086 // If there was content, format it's first line as usual, otherwise create an empty first line.
1087 if (result->content->lines.next != &(result->content->lines))
1088 {
1089 result->line = result->content->lines.next;
1090 result->oW = formatLine(result, result->line->line, &(result->output));
1091 }
1092 else
1093 {
1094 result->line = addLine(result->content, NULL, "\0", 0);
1095 result->output = xzalloc(1);
1096 }
1097
1098 return result;
1099}
1100
1101box *addBox(char *name, struct context *context, char *filePath, uint16_t X, uint16_t Y, uint16_t W, uint16_t H)
1102{
1103 box *result = xzalloc(sizeof(struct _box));
1104
1105 result->X = X;
1106 result->Y = Y;
1107 result->W = W;
1108 result->H = H;
1109 result->view = addView(name, context, filePath, X, Y, W, H);
1110 result->view->box = result;
1111 sizeViewToBox(result, X, Y, W, H);
1112
1113 return result;
1114}
1115
1116void freeBox(box *box)
1117{
1118 if (box)
1119 {
1120 freeBox(box->sub1);
1121 freeBox(box->sub2);
1122 if (box->view)
1123 {
1124 // In theory the line should not be part of the content if there is no content, so we should free it.
1125 if (!box->view->content)
1126 freeLine(NULL, box->view->line);
1127 free(box->view->prompt);
1128 free(box->view->output);
1129 free(box->view);
1130 }
1131 free(box);
1132 }
1133}
1134
1135void drawBox(box *box)
1136{
1137 // This could be heavily optimized, but let's keep things simple for now.
1138 // Optimized for sending less characters I mean, on slow serial links for instance.
1139
1140 char **bchars = (toys.optflags & FLAG_a) ? borderChars[0] : borderChars[1];
1141 char *left = "\0", *right = "\0";
1142 struct line *lines = NULL;
1143 int y = box->Y, current = (box == currentBox);
1144 uint16_t h = box->Y + box->H;
1145
1146 if (current)
1147 bchars = (toys.optflags & FLAG_a) ? borderCharsCurrent[0] : borderCharsCurrent[1];
1148
1149 // Slow and laborious way to figure out where in the linked list of lines we start from.
1150 // Wont scale well, but is simple.
1151 if (box->view && box->view->content)
1152 {
1153 int i = box->view->offsetY;
1154
1155 lines = &(box->view->content->lines);
1156 while (i--)
1157 {
1158 lines = lines->next;
1159 if (&(box->view->content->lines) == lines) // We are at the end if we have wrapped to the beginning.
1160 break;
1161 }
1162 }
1163
1164 if (box->flags & BOX_BORDER)
1165 {
1166 h--;
1167 left = right = bchars[1];
1168 drawLine(y++, box->X, box->X + box->W, bchars[2], bchars[0], NULL, bchars[3], current);
1169 }
1170
1171 while (y < h)
1172 {
1173 char *line = "";
1174
1175 if (lines)
1176 {
1177 lines = lines->next;
1178 if (&(box->view->content->lines) == lines) // We are at the end if we have wrapped to the beginning.
1179 lines = NULL;
1180 else
1181 line = lines->line;
1182 // Figure out which line is our current line while we are here.
1183 if (box->view->Y + (box->view->cY - box->view->offsetY) == y)
1184 box->view->line = lines;
1185 }
1186 drawContentLine(box->view, y++, box->X, box->X + box->W, left, " ", line, right, current);
1187 }
1188 if (box->flags & BOX_BORDER)
1189 drawLine(y++, box->X, box->X + box->W, bchars[4], bchars[0], NULL, bchars[5], current);
1190 fflush(stdout);
1191}
1192
1193void drawBoxes(box *box)
1194{
1195 if (box->sub1) // If there's one sub box, there's always two.
1196 {
1197 drawBoxes(box->sub1);
1198 drawBoxes(box->sub2);
1199 }
1200 else
1201 drawBox(box);
1202}
1203
1204void calcBoxes(box *box)
1205{
1206 if (box->sub1) // If there's one sub box, there's always two.
1207 {
1208 box->sub1->X = box->X;
1209 box->sub1->Y = box->Y;
1210 box->sub1->W = box->W;
1211 box->sub1->H = box->H;
1212 box->sub2->X = box->X;
1213 box->sub2->Y = box->Y;
1214 box->sub2->W = box->W;
1215 box->sub2->H = box->H;
1216 if (box->flags & BOX_HSPLIT)
1217 {
1218 box->sub1->H *= box->split;
1219 box->sub2->H -= box->sub1->H;
1220 box->sub2->Y += box->sub1->H;
1221 }
1222 else
1223 {
1224 box->sub1->W *= box->split;
1225 box->sub2->W -= box->sub1->W;
1226 box->sub2->X += box->sub1->W;
1227 }
1228 sizeViewToBox(box->sub1, -1, -1, -1, -1);
1229 calcBoxes(box->sub1);
1230 sizeViewToBox(box->sub2, -1, -1, -1, -1);
1231 calcBoxes(box->sub2);
1232 }
1233 // Move the cursor to where it is, to check it's not now outside the box.
1234 moveCursorAbsolute(box->view, box->view->cX, box->view->cY, 0, 0);
1235
1236 // We could call drawBoxes() here, but this is recursive, and so is drawBoxes().
1237 // The combination might be deadly. Drawing the content of a box might be an expensive operation.
1238 // Later we might use a dirty box flag to deal with this, if it's not too much of a complication.
1239}
1240
1241void deleteBox(view *view)
1242{
1243 box *box = view->box;
1244
1245 if (box->parent)
1246 {
1247 struct _box *oldBox = box, *otherBox = box->parent->sub1;
1248
1249 if (otherBox == oldBox)
1250 otherBox = box->parent->sub2;
1251 if (currentBox->parent == box->parent)
1252 currentBox = box->parent;
1253 box = box->parent;
1254 box->X = box->sub1->X;
1255 box->Y = box->sub1->Y;
1256 if (box->flags & BOX_HSPLIT)
1257 box->H = box->sub1->H + box->sub2->H;
1258 else
1259 box->W = box->sub1->W + box->sub2->W;
1260 box->flags &= ~BOX_HSPLIT;
1261 // Move the other sub boxes contents up to this box.
1262 box->sub1 = otherBox->sub1;
1263 box->sub2 = otherBox->sub2;
1264 if (box->sub1)
1265 {
1266 box->sub1->parent = box;
1267 box->sub2->parent = box;
1268 box->flags = otherBox->flags;
1269 if (currentBox == box)
1270 currentBox = box->sub1;
1271 }
1272 else
1273 {
1274 if (!box->parent)
1275 box->flags &= ~BOX_BORDER;
1276 box->split = 1.0;
1277 }
1278 otherBox->sub1 = NULL;
1279 otherBox->sub2 = NULL;
1280 // Safe to free the boxes now that we have all their contents.
1281 freeBox(otherBox);
1282 freeBox(oldBox);
1283 }
1284 // Otherwise it must be a single full screen box. Never delete that one, unless we are quitting.
1285
1286 // Start the recursive recalculation of all the sub boxes.
1287 calcBoxes(box);
1288 drawBoxes(box);
1289}
1290
1291void cloneBox(struct _box *box, struct _box *sub)
1292{
1293 sub->parent = box;
1294 // Only a full screen box has no border.
1295 sub->flags |= BOX_BORDER;
1296 sub->view = xmalloc(sizeof(struct _view));
1297 // TODO - After this is more stable, should check if the memcpy() is simpler than - xzalloc() then copy a few things manually.
1298 // Might even be able to arrange the structure so we can memcpy just part of it, leaving the rest blank.
1299 memcpy(sub->view, box->view, sizeof(struct _view));
1300 sub->view->damage = NULL;
1301 sub->view->data = NULL;
1302 sub->view->output = NULL;
1303 sub->view->box = sub;
1304 if (box->view->prompt)
1305 sub->view->prompt = strdup(box->view->prompt);
1306}
1307
1308void splitBox(box *box, float split)
1309{
1310 uint16_t size;
1311 int otherBox = 0;
1312
1313 // First some sanity checks.
1314 if (0.0 > split)
1315 {
1316 // TODO - put this in the status line, or just silently fail. Also, better message. lol
1317 fprintf(stderr, "User is crazy.\n");
1318 return;
1319 }
1320 else if (1.0 <= split) // User meant to unsplit, and it may already be split.
1321 {
1322 // Actually, this means that the OTHER sub box gets deleted.
1323 if (box->parent)
1324 {
1325 if (box == box->parent->sub1)
1326 deleteBox(box->parent->sub2->view);
1327 else
1328 deleteBox(box->parent->sub1->view);
1329 }
1330 return;
1331 }
1332 else if (0.0 < split) // This is the normal case, so do nothing.
1333 {
1334 }
1335 else // User meant to delete this, zero split.
1336 {
1337 deleteBox(box->view);
1338 return;
1339 }
1340 if (box->flags & BOX_HSPLIT)
1341 size = box->H;
1342 else
1343 size = box->W;
1344 if (6 > size) // Is there room for 2 borders for each sub box and one character of content each?
1345 // TODO - also should check the contents minimum size.
1346 // No need to check the no border case, that's only for full screen.
1347 // People using terminals smaller than 6 characters get what they deserve.
1348 {
1349 // TODO - put this in the status line, or just silently fail.
1350 fprintf(stderr, "Box is too small to split.\n");
1351 return;
1352 }
1353
1354 // Note that a split box is actually three boxes. The parent, which is not drawn, and the two subs, which are.
1355 // Based on the assumption that there wont be lots of boxes, this keeps things simple.
1356 // It's possible that the box has already been split, and this is called just to update the split.
1357 box->split = split;
1358 if (NULL == box->sub1) // If not split already, do so.
1359 {
1360 box->sub1 = xzalloc(sizeof(struct _box));
1361 box->sub2 = xzalloc(sizeof(struct _box));
1362 cloneBox(box, box->sub1);
1363 cloneBox(box, box->sub2);
1364 if (box->flags & BOX_HSPLIT)
1365 {
1366 // Split the boxes in the middle of the content.
1367 box->sub2->view->offsetY += (box->H * box->split) - 2;
1368 // Figure out which sub box the cursor will be in, then update the cursor in the other box.
1369 if (box->sub1->view->cY < box->sub2->view->offsetY)
1370 box->sub2->view->cY = box->sub2->view->offsetY;
1371 else
1372 {
1373 box->sub1->view->cY = box->sub2->view->offsetY - 1;
1374 otherBox = 1;
1375 }
1376 }
1377 else
1378 {
1379 // Split the boxes in the middle of the content.
1380 box->sub2->view->offsetX += (box->W * box->split) - 2;
1381 // Figure out which sub box the cursor will be in, then update the cursor in the other box.
1382 if (box->sub1->view->cX < box->sub2->view->offsetX)
1383 box->sub2->view->cX = box->sub2->view->offsetX;
1384 else
1385 {
1386 box->sub1->view->cX = box->sub2->view->offsetX - 1;
1387 otherBox = 1;
1388 }
1389 }
1390 }
1391
1392 if ((currentBox == box) && (box->sub1))
1393 {
1394 if (otherBox)
1395 currentBox = box->sub2;
1396 else
1397 currentBox = box->sub1;
1398 }
1399
1400 // Start the recursive recalculation of all the sub boxes.
1401 calcBoxes(box);
1402 drawBoxes(box);
1403}
1404
1405// TODO - Might be better to just have a double linked list of boxes, and traverse that instead.
1406// Except that leaves a problem when deleting boxes, could end up with a blank space.
1407void switchBoxes(view *view)
1408{
1409 box *box = view->box;
1410
1411 // The assumption here is that box == currentBox.
1412 struct _box *oldBox = currentBox;
1413 struct _box *thisBox = box;
1414 int backingUp = 0;
1415
1416 // Depth first traversal.
1417 while ((oldBox == currentBox) && (thisBox->parent))
1418 {
1419 if (thisBox == thisBox->parent->sub1)
1420 {
1421 if (backingUp && (thisBox->parent))
1422 currentBox = thisBox->parent->sub2;
1423 else if (thisBox->sub1)
1424 currentBox = thisBox->sub1;
1425 else
1426 currentBox = thisBox->parent->sub2;
1427 }
1428 else if (thisBox == thisBox->parent->sub2)
1429 {
1430 thisBox = thisBox->parent;
1431 backingUp = 1;
1432 }
1433 }
1434
1435 // If we have not found the next box to move to, move back to the beginning.
1436 if (oldBox == currentBox)
1437 currentBox = rootBox;
1438
1439 // If we ended up on a parent box, go to it's first sub.
1440 while (currentBox->sub1)
1441 currentBox = currentBox->sub1;
1442
1443 // Just redraw them all.
1444 drawBoxes(rootBox);
1445}
1446
1447// TODO - It might be better to do away with this bunch of single line functions
1448// and map script commands directly to lower functions.
1449// How to deal with the various argument needs?
1450// Might be where we can re use the toybox argument stuff.
1451
1452void halveBoxHorizontally(view *view)
1453{
1454 view->box->flags |= BOX_HSPLIT;
1455 splitBox(view->box, 0.5);
1456}
1457
1458void halveBoxVertically(view *view)
1459{
1460 view->box->flags &= ~BOX_HSPLIT;
1461 splitBox(view->box, 0.5);
1462}
1463
1464void switchMode(view *view)
1465{
1466 currentBox->view->mode++;
1467 // Assumes that modes will always have a key mapping, which I think is a safe bet.
1468 if (NULL == currentBox->view->content->context->modes[currentBox->view->mode].keys)
1469 currentBox->view->mode = 0;
1470 commandMode = currentBox->view->content->context->modes[currentBox->view->mode].flags & 1;
1471}
1472
1473void leftChar(view *view)
1474{
1475 moveCursorRelative(view, -1, 0, 0, 0);
1476}
1477
1478void rightChar(view *view)
1479{
1480 moveCursorRelative(view, 1, 0, 0, 0);
1481}
1482
1483void upLine(view *view)
1484{
1485 moveCursorRelative(view, 0, -1, 0, 0);
1486}
1487
1488void downLine(view *view)
1489{
1490 moveCursorRelative(view, 0, 1, 0, 0);
1491}
1492
1493void upPage(view *view)
1494{
1495 moveCursorRelative(view, 0, 0 - (view->H - 1), 0, 0 - (view->H - 1));
1496}
1497
1498void downPage(view *view)
1499{
1500 moveCursorRelative(view, 0, view->H - 1, 0, view->H - 1);
1501}
1502
1503void endOfLine(view *view)
1504{
1505 moveCursorAbsolute(view, strlen(view->prompt) + view->oW, view->cY, 0, 0);
1506}
1507
1508void startOfLine(view *view)
1509{
1510 // TODO - add the advanced editing "smart home".
1511 moveCursorAbsolute(view, strlen(view->prompt), view->cY, 0, 0);
1512}
1513
1514void splitLine(view *view)
1515{
1516 // TODO - should move this into mooshLines().
1517 addLine(view->content, view->line, &(view->line->line[view->iX]), 0);
1518 view->line->line[view->iX] = '\0';
1519 moveCursorAbsolute(view, 0, view->cY + 1, 0, 0);
1520 if (view->box)
1521 drawBox(view->box);
1522}
1523
1524void deleteChar(view *view)
1525{
1526 // TODO - should move this into mooshLines().
1527 // If we are at the end of the line, then join this and the next line.
1528 if (view->oW == view->cX)
1529 {
1530 // Only if there IS a next line.
1531 if (&(view->content->lines) != view->line->next)
1532 {
1533 mooshStrings(view->line, view->line->next->line, view->iX, 1, !overWriteMode);
1534 view->line->next->line = NULL;
1535 freeLine(view->content, view->line->next);
1536 // TODO - should check if we are on the last page, then deal with scrolling.
1537 if (view->box)
1538 drawBox(view->box);
1539 }
1540 }
1541 else
1542 mooshStrings(view->line, NULL, view->iX, 1, !overWriteMode);
1543}
1544
1545void backSpaceChar(view *view)
1546{
1547 if (moveCursorRelative(view, -1, 0, 0, 0))
1548 deleteChar(view);
1549}
1550
1551void saveContent(view *view)
1552{
1553 saveFile(view->content);
1554}
1555
1556void executeLine(view *view)
1557{
1558 struct line *result = view->line;
1559
1560 // Don't bother doing much if there's nothing on this line.
1561 if (result->line[0])
1562 {
1563 doCommand(currentBox->view, result->line);
1564 // If we are not at the end of the history contents.
1565 if (&(view->content->lines) != result->next)
1566 {
1567 struct line *line = view->content->lines.prev;
1568
1569 // Remove the line first.
1570 result->next->prev = result->prev;
1571 result->prev->next = result->next;
1572 // Check if the last line is already blank, then remove it.
1573 if ('\0' == line->line[0])
1574 {
1575 freeLine(view->content, line);
1576 line = view->content->lines.prev;
1577 }
1578 // Then add it to the end.
1579 result->next = line->next;
1580 result->prev = line;
1581 line->next->prev = result;
1582 line->next = result;
1583 view->cY = view->content->lines.length - 1;
1584 }
1585 moveCursorAbsolute(view, 0, view->content->lines.length, 0, 0);
1586 // Make sure there is one blank line at the end.
1587 if ('\0' != view->line->line[0])
1588 {
1589 endOfLine(view);
1590 splitLine(view);
1591 }
1592 }
1593
1594 saveFile(view->content);
1595}
1596
1597void quit(view *view)
1598{
1599 handle_keys_quit();
1600}
1601
1602void nop(view *view)
1603{
1604 // 'tis a nop, don't actually do anything.
1605}
1606
1607
1608typedef void (*CSIhandler) (long extra, int *code, int count);
1609
1610struct CSI
1611{
1612 char *code;
1613 CSIhandler func;
1614};
1615
1616static void termSize(long extra, int *params, int count)
1617{
1618 struct _view *view = (struct _view *) extra; // Though we pretty much stomp on this straight away.
1619 int r = params[0], c = params[1];
1620
1621 // The defaults are 1, which get ignored by the heuristic below.
1622 // Check it's not an F3 key variation, coz some of them use the same CSI function code.
1623 // This is a heuristic, we are checking against an unusable terminal size.
1624 // TODO - Double check what the maximum F3 variations can be.
1625 if ((2 == count) && (8 < r) && (8 < c))
1626 {
1627 commandLine->Y = r;
1628 commandLine->W = c;
1629 rootBox->W = c;
1630 rootBox->H = r - 1;
1631 sizeViewToBox(rootBox, -1, -1, -1, -1);
1632 calcBoxes(rootBox);
1633 drawBoxes(rootBox);
1634
1635 // Move the cursor to where it is, to check it's not now outside the terminal window.
1636 moveCursorAbsolute(rootBox->view, rootBox->view->cX, rootBox->view->cY, 0, 0);
1637
1638 // We have no idea which is the current view now.
1639 if (commandMode) view = commandLine;
1640 else view = currentBox->view;
1641 updateLine(view);
1642 }
1643}
1644
1645struct CSI CSIcommands[] =
1646{
1647 {"R", termSize} // Parameters are cursor line and column. Note this may be sent at other times, not just during terminal resize.
1648};
1649
1650
1651// Callback for incoming sequences from the terminal.
1652static int handleEvent(long extra, struct keyevent *event)
1653{
1654 switch (event->type)
1655 {
1656 case HK_CSI :
1657 {
1658 int j;
1659
1660 for (j = 0; j < ARRAY_LEN(CSIcommands); j++)
1661 {
1662 if (strcmp(CSIcommands[j].code, event->sequence) == 0)
1663 {
1664 CSIcommands[j].func(extra, event->params, event->count);
1665 break;
1666 }
1667 }
1668 break;
1669 }
1670
1671 case HK_KEYS :
1672 {
1673 struct _view *view = (struct _view *) extra; // Though we pretty much stomp on this straight away.
1674 struct keyCommand *commands = currentBox->view->content->context->modes[currentBox->view->mode].keys;
1675 int j, l = strlen(event->sequence);
1676
1677 // Coz things might change out from under us, find the current view.
1678 if (commandMode) view = commandLine;
1679 else view = currentBox->view;
1680
1681 // Search for a key sequence bound to a command.
1682 for (j = 0; commands[j].key; j++)
1683 {
1684 if (strncmp(commands[j].key, event->sequence, l) == 0)
1685 {
1686 // If it's a partial match, keep accumulating them.
1687 if (strlen(commands[j].key) != l)
1688 return 0;
1689 else
1690 {
1691 doCommand(view, commands[j].command);
1692 return 1;
1693 }
1694 }
1695 }
1696
1697 // See if it's ordinary keys.
1698 // NOTE - with vi style ordinary keys can be commands,
1699 // but they would be found by the command check above first.
1700 if (!event->isTranslated)
1701 {
1702 // TODO - Should check for tabs to, and insert them.
1703 // Though better off having a function for that?
1704 mooshStrings(view->line, event->sequence, view->iX, 0, !overWriteMode);
1705 view->oW = formatLine(view, view->line->line, &(view->output));
1706 moveCursorRelative(view, strlen(event->sequence), 0, 0, 0);
1707 updateLine(view);
1708 }
1709 break;
1710 }
1711
1712 default : break;
1713 }
1714
1715 // Tell handle_keys to drop it, coz we dealt with it, or it's not one of ours.
1716 return 1;
1717}
1718
1719
1720// 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.
1721// Though most of the editors have their own variation.
1722// TODO - Maybe just use the joe one as default, it uses short names at least.
1723// Though vi is the only one in POSIX, so might be better to treat that one as the "standard" default.
1724// With some commands from others for stuff vi doesn't support.
1725struct function simpleEditCommands[] =
1726{
1727 {"backSpaceChar", "Back space last character.", 0, {backSpaceChar}},
1728 {"deleteBox", "Delete a box.", 0, {deleteBox}},
1729 {"deleteChar", "Delete current character.", 0, {deleteChar}},
1730 {"downLine", "Move cursor down one line.", 0, {downLine}},
1731 {"downPage", "Move cursor down one page.", 0, {downPage}},
1732 {"endOfLine", "Go to end of line.", 0, {endOfLine}},
1733 {"executeLine", "Execute a line as a script.", 0, {executeLine}},
1734 {"leftChar", "Move cursor left one character.", 0, {leftChar}},
1735 {"quit", "Quit the application.", 0, {quit}},
1736 {"rightChar", "Move cursor right one character.", 0, {rightChar}},
1737 {"save", "Save.", 0, {saveContent}},
1738 {"splitH", "Split box in half horizontally.", 0, {halveBoxHorizontally}},
1739 {"splitLine", "Split line at cursor.", 0, {splitLine}},
1740 {"splitV", "Split box in half vertically.", 0, {halveBoxVertically}},
1741 {"startOfLine", "Go to start of line.", 0, {startOfLine}},
1742 {"switchBoxes", "Switch to another box.", 0, {switchBoxes}},
1743 {"switchMode", "Switch between command and box.", 0, {switchMode}},
1744 {"upLine", "Move cursor up one line.", 0, {upLine}},
1745 {"upPage", "Move cursor up one page.", 0, {upPage}},
1746 {NULL, NULL, 0, {NULL}}
1747};
1748
1749// Construct a simple command line.
1750
1751// The key to command mappings.
1752// TODO - Should not move off the ends of the line to the next / previous line.
1753struct keyCommand simpleCommandKeys[] =
1754{
1755 {"BS", "backSpaceChar"},
1756 {"Del", "deleteChar"},
1757 {"Down", "downLine"},
1758 {"End", "endOfLine"},
1759 {"F10", "quit"},
1760 {"Home", "startOfLine"},
1761 {"Left", "leftChar"},
1762 {"Enter", "executeLine"},
1763 {"Return", "executeLine"},
1764 {"Right", "rightChar"},
1765 {"Esc", "switchMode"},
1766 {"Up", "upLine"},
1767 {NULL, NULL}
1768};
1769
1770
1771// Construct a simple emacs editor.
1772
1773// Mostly control keys, some meta keys.
1774// 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
1775// Ctrl-h is backspace / del. Pffft.
1776// Meta key is either Alt-keystroke, Esc keystroke, or an actual Meta-keystroke (do they still exist?).
1777// TODO - Alt and Meta not supported yet, so using Esc.
1778// Windows commands.
1779
1780// readline uses these same commands, and defaults to emacs keystrokes.
1781struct function simpleEmacsCommands[] =
1782{
1783 {"delete-backward-char", "Back space last character.", 0, {backSpaceChar}},
1784 {"delete-window", "Delete a box.", 0, {deleteBox}},
1785 {"delete-char", "Delete current character.", 0, {deleteChar}},
1786 {"next-line", "Move cursor down one line.", 0, {downLine}},
1787 {"scroll-up", "Move cursor down one page.", 0, {downPage}},
1788 {"end-of-line", "Go to end of line.", 0, {endOfLine}},
1789 {"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.
1790 {"backward-char", "Move cursor left one character.", 0, {leftChar}},
1791 {"save-buffers-kill-emacs", "Quit the application.", 0, {quit}}, // TODO - Does more than just quit.
1792 {"forward-char", "Move cursor right one character.", 0, {rightChar}},
1793 {"save-buffer", "Save.", 0, {saveContent}},
1794 {"split-window-horizontally", "Split box in half horizontally.", 0, {halveBoxHorizontally}}, // TODO - Making this one up for now, mg does not have it.
1795 {"newline", "Split line at cursor.", 0, {splitLine}},
1796 {"split-window-vertically", "Split box in half vertically.", 0, {halveBoxVertically}},
1797 {"beginning-of-line", "Go to start of line.", 0, {startOfLine}},
1798 {"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.
1799 {"execute-extended-command", "Switch between command and box.", 0, {switchMode}}, // Actually a one time invocation of the command line.
1800 {"previous-line", "Move cursor up one line.", 0, {upLine}},
1801 {"scroll-down", "Move cursor up one page.", 0, {upPage}},
1802 {NULL, NULL, 0, {NULL}}
1803};
1804
1805// The key to command mappings.
1806struct keyCommand simpleEmacsKeys[] =
1807{
1808 {"BS", "delete-backward-char"},
1809 {"Del", "delete-backward-char"},
1810 {"^D", "delete-char"},
1811 {"Down", "next-line"},
1812 {"^N", "next-line"},
1813 {"End", "end-of-line"},
1814 {"^E", "end-of-line"},
1815 {"^X^C", "save-buffers-kill-emacs"},
1816 {"^X^S", "save-buffer"},
1817 {"Home", "beginning-of-line"},
1818 {"^A", "beginning-of-line"},
1819 {"Left", "backward-char"},
1820 {"^B", "backward-char"},
1821 {"PgDn", "scroll-up"},
1822 {"^V", "scroll-up"},
1823 {"PgUp", "scroll-down"},
1824 {"Escv", "scroll-down"}, // M-v
1825 {"Enter", "newline"},
1826 {"Return", "newline"},
1827 {"Right", "forward-char"},
1828 {"^F", "forward-char"},
1829 {"Escx", "execute-extended-command"}, // M-x
1830 {"^X2", "split-window-vertically"},
1831 {"^XP", "other-window"},
1832 {"^X0", "delete-window"},
1833 {"Up", "previous-line"},
1834 {"^P", "previous-line"},
1835 {NULL, NULL}
1836};
1837
1838struct keyCommand simpleEmacsCommandKeys[] =
1839{
1840 {"Del", "delete-backwards-char"},
1841 {"^D", "delete-char"},
1842 {"Down", "next-line"},
1843 {"^N", "next-line"},
1844 {"End", "end-of-line"},
1845 {"^E", "end-of-line"},
1846 {"Home", "beginning-of-line"},
1847 {"^A", "beginning-of-line"},
1848 {"Left", "backward-char"},
1849 {"^B", "backward-char"},
1850 {"Right", "forward-char"},
1851 {"^F", "forward-char"},
1852 {"Up", "previous-line"},
1853 {"^P", "previous-line"},
1854 {"Enter", "accept-line"},
1855 {"Return", "accept-line"},
1856 {"Escx", "execute-extended-command"},
1857 {NULL, NULL}
1858};
1859
1860// An array of various modes.
1861struct mode simpleEmacsMode[] =
1862{
1863 {simpleEmacsKeys, NULL, NULL, 0},
1864 {simpleEmacsCommandKeys, NULL, NULL, 1},
1865 {NULL, NULL, NULL}
1866};
1867
1868// Put it all together into a simple editor context.
1869struct context simpleEmacs =
1870{
1871 simpleEmacsCommands,
1872 simpleEmacsMode,
1873 NULL,
1874 NULL,
1875 NULL
1876};
1877
1878
1879// Construct a simple joe / wordstar editor, using joe is the reference, seems to be the popular Unix variant.
1880// Esc x starts up the command line.
1881// Has multi control key combos. Mostly Ctrl-K, Ctrl-[ (Esc), (Ctrl-B, Ctrl-Q in wordstar and delphi), but might be others.
1882// Can't find a single list of command mappings for joe, gotta search all over. sigh
1883// Even the command line keystroke I stumbled on (Esc x) is not documented.
1884// Note that you don't have to let go of the Ctrl key for the second keystroke, but you can.
1885
1886// From http://joe-editor.sourceforge.net/list.html
1887// TODO - Some of these might be wrong. Just going by the inadequate joe docs for now.
1888struct function simpleJoeCommands[] =
1889{
1890 {"backs", "Back space last character.", 0, {backSpaceChar}},
1891 {"abort", "Delete a box.", 0, {deleteBox}}, // TODO - Should do quit if it's the last window.
1892 {"delch", "Delete current character.", 0, {deleteChar}},
1893 {"dnarw", "Move cursor down one line.", 0, {downLine}},
1894 {"pgdn", "Move cursor down one page.", 0, {downPage}},
1895 {"eol", "Go to end of line.", 0, {endOfLine}},
1896 {"ltarw", "Move cursor left one character.", 0, {leftChar}},
1897 {"killjoe", "Quit the application.", 0, {quit}},
1898 {"rtarw", "Move cursor right one character.", 0, {rightChar}},
1899 {"save", "Save.", 0, {saveContent}},
1900 {"splitw", "Split box in half horizontally.", 0, {halveBoxHorizontally}},
1901 {"open", "Split line at cursor.", 0, {splitLine}},
1902 {"bol", "Go to start of line.", 0, {startOfLine}},
1903 {"home", "Go to start of line.", 0, {startOfLine}},
1904 {"nextw", "Switch to another box.", 0, {switchBoxes}}, // This is "next window", there's also "previous window" which we don't support yet.
1905 {"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.
1906 {"uparw", "Move cursor up one line.", 0, {upLine}},
1907 {"pgup", "Move cursor up one page.", 0, {upPage}},
1908
1909 // Not an actual joe command.
1910 {"executeLine", "Execute a line as a script.", 0, {executeLine}}, // Perhaps this should be execmd?
1911 {NULL, NULL, 0, {NULL}}
1912};
1913
1914struct keyCommand simpleJoeKeys[] =
1915{
1916 {"BS", "backs"},
1917 {"^D", "delch"},
1918 {"Down", "dnarw"},
1919 {"^N", "dnarw"},
1920 {"^E", "eol"},
1921 {"^C", "killjoe"},
1922 {"^Kd", "save"},
1923 {"^K^D" "save"},
1924 {"^A", "bol"},
1925 {"Left", "ltarw"},
1926 {"^B", "ltarw"},
1927 {"^V", "pgdn"}, // Actually half a page.
1928 {"^U", "pgup"}, // Actually half a page.
1929 {"Enter", "open"},
1930 {"Return", "open"},
1931 {"Right", "rtarw"},
1932 {"^F", "rtarw"},
1933 {"Escx", "execmd"},
1934 {"Esc^X", "execmd"},
1935 {"^Ko", "splitw"},
1936 {"^K^O", "splitw"},
1937 {"^Kn", "nextw"},
1938 {"^K^N", "nextw"},
1939 {"^Kx", "killjoe"}, // TODO - Should ask if it should save if it's been modified. A good generic thing to do anyway.
1940 {"^K^X", "abort"}, // TODO - These two both close a window, and quit if that was the last window.
1941 {"Up", "uparw"},
1942 {"^P", "uparw"},
1943 {NULL, NULL}
1944};
1945
1946struct keyCommand simpleJoeCommandKeys[] =
1947{
1948 {"BS", "backs"},
1949 {"^D", "delch"},
1950 {"Down", "dnarw"},
1951 {"^N", "dnarw"},
1952 {"^E", "eol"},
1953 {"^A", "bol"},
1954 {"Left", "ltarw"},
1955 {"^B", "ltarw"},
1956 {"Right", "rtarw"},
1957 {"^F", "rtarw"},
1958 {"Escx", "execmd"},
1959 {"Esc^X", "execmd"},
1960 {"Up", "uparw"},
1961 {"^P", "uparw"},
1962 {"Enter", "executeLine"},
1963 {"Return", "executeLine"},
1964 {NULL, NULL}
1965};
1966
1967struct mode simpleJoeMode[] =
1968{
1969 {simpleJoeKeys, NULL, NULL, 0},
1970 {simpleJoeCommandKeys, NULL, NULL, 1},
1971 {NULL, NULL, NULL, 0}
1972};
1973
1974struct context simpleJoe =
1975{
1976 simpleJoeCommands,
1977 simpleJoeMode,
1978 NULL,
1979 NULL,
1980 NULL
1981};
1982
1983
1984// Simple more and / or less.
1985// '/' and '?' for search command mode. I think they both have some ex commands with the usual : command mode starter.
1986// No cursor movement, just scrolling.
1987// TODO - Put content into read only mode.
1988// TODO - actually implement read only mode where up and down one line do actual scrolling instead of cursor movement.
1989
1990struct keyCommand simpleLessKeys[] =
1991{
1992 {"Down", "downLine"},
1993 {"j", "downLine"},
1994 {"Enter", "downLine"},
1995 {"Return", "downLine"},
1996 {"End", "endOfLine"},
1997 {"q", "quit"},
1998 {":q", "quit"}, // TODO - A vi ism, should do ex command stuff instead.
1999 {"ZZ", "quit"},
2000 {"PgDn", "downPage"},
2001 {"f", "downPage"},
2002 {" ", "downPage"},
2003 {"^F", "downPage"},
2004 {"Left", "leftChar"},
2005 {"Right", "rightChar"},
2006 {"PgUp", "upPage"},
2007 {"b", "upPage"},
2008 {"^B", "upPage"},
2009 {"Up", "upLine"},
2010 {"k", "upLine"},
2011 {NULL, NULL}
2012};
2013
2014struct mode simpleLessMode[] =
2015{
2016 {simpleLessKeys, NULL, NULL, 0},
2017 {simpleCommandKeys, NULL, NULL, 1},
2018 {NULL, NULL, NULL}
2019};
2020
2021struct context simpleLess =
2022{
2023 simpleEditCommands,
2024 simpleLessMode,
2025 NULL,
2026 NULL,
2027 NULL
2028};
2029
2030struct keyCommand simpleMoreKeys[] =
2031{
2032 {"j", "downLine"},
2033 {"Enter", "downLine"},
2034 {"Return", "downLine"},
2035 {"q", "quit"},
2036 {":q", "quit"}, // See comments for "less".
2037 {"ZZ", "quit"},
2038 {"f", "downPage"},
2039 {" ", "downPage"},
2040 {"^F", "downPage"},
2041 {"b", "upPage"},
2042 {"^B", "upPage"},
2043 {"k", "upLine"},
2044 {NULL, NULL}
2045};
2046
2047struct mode simpleMoreMode[] =
2048{
2049 {simpleMoreKeys, NULL, NULL, 0},
2050 {simpleCommandKeys, NULL, NULL, 1},
2051 {NULL, NULL, NULL}
2052};
2053
2054struct context simpleMore =
2055{
2056 simpleEditCommands,
2057 simpleMoreMode,
2058 NULL,
2059 NULL,
2060 NULL
2061};
2062
2063
2064// Construct a simple mcedit / cool edit editor.
2065
2066struct keyCommand simpleMceditKeys[] =
2067{
2068 {"BS", "backSpaceChar"},
2069 {"Del", "deleteChar"},
2070 {"Down", "downLine"},
2071 {"End", "endOfLine"},
2072 {"F10", "quit"},
2073 {"Esc0", "quit"},
2074 {"F2", "save"},
2075 {"Esc2", "save"},
2076 {"Home", "startOfLine"},
2077 {"Left", "leftChar"},
2078 {"PgDn", "downPage"},
2079 {"PgUp", "upPage"},
2080 {"Enter", "splitLine"},
2081 {"Return", "splitLine"},
2082 {"Right", "rightChar"},
2083 {"Shift F2", "switchMode"}, // MC doesn't have a command mode.
2084 {"Esc:", "switchMode"}, // Sorta vi like, and coz tmux is screwing with the shift function keys somehow.
2085 {"Esc|", "splitV"}, // MC doesn't have a split window concept, so make these up to match tmux more or less.
2086 {"Esc-", "splitH"},
2087 {"Esco", "switchBoxes"},
2088 {"Escx", "deleteBox"},
2089 {"Up", "upLine"},
2090{"^C", "switchMode"}, // To test the signal stopper.
2091{"^D", "switchMode"}, // To test the signal stopper.
2092{"^Q", "switchMode"}, // To test the signal stopper.
2093{"^S", "switchMode"}, // To test the signal stopper.
2094{"^T", "switchMode"}, // To test the signal stopper.
2095{"^Z", "switchMode"}, // To test the signal stopper.
2096{"^\\", "switchMode"}, // To test the signal stopper.
2097{"F1", "switchMode"}, // To test various function keys.
2098{"F3", "switchMode"}, // To test various function keys.
2099{"F4", "switchMode"}, // To test various function keys.
2100{"F5", "switchMode"}, // To test various function keys.
2101{"F6", "switchMode"}, // To test various function keys.
2102{"F7", "switchMode"}, // To test various function keys.
2103{"F8", "switchMode"}, // To test various function keys.
2104{"F9", "switchMode"}, // To test various function keys.
2105 {NULL, NULL}
2106};
2107
2108struct mode simpleMceditMode[] =
2109{
2110 {simpleMceditKeys, NULL, NULL, 0},
2111 {simpleCommandKeys, NULL, NULL, 1},
2112 {NULL, NULL, NULL}
2113};
2114
2115struct context simpleMcedit =
2116{
2117 simpleEditCommands,
2118 simpleMceditMode,
2119 NULL,
2120 NULL,
2121 NULL
2122};
2123
2124
2125// Simple nano editor.
2126// Has key to function bindings, but no command line mode. Has "enter parameter on this line" mode for some commands.
2127// Control and meta keys, only singles, unlike emacs and joe.
2128// Can have multiple buffers, but no windows. Think I can skip that for simple editor.
2129
2130struct function simpleNanoCommands[] =
2131{
2132 {"backSpaceChar", "Back space last character.", 0, {backSpaceChar}},
2133 {"delete", "Delete current character.", 0, {deleteChar}},
2134 {"down", "Move cursor down one line.", 0, {downLine}},
2135 {"downPage", "Move cursor down one page.", 0, {downPage}},
2136 {"end", "Go to end of line.", 0, {endOfLine}},
2137 {"left", "Move cursor left one character.", 0, {leftChar}},
2138 {"exit", "Quit the application.", 0, {quit}},
2139 {"right", "Move cursor right one character.", 0, {rightChar}},
2140 {"writeout", "Save.", 0, {saveContent}},
2141 {"enter", "Split line at cursor.", 0, {splitLine}},
2142 {"home", "Go to start of line.", 0, {startOfLine}},
2143 {"up", "Move cursor up one line.", 0, {upLine}},
2144 {"upPage", "Move cursor up one page.", 0, {upPage}},
2145 {NULL, NULL, 0, {NULL}}
2146};
2147
2148
2149// 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.
2150struct keyCommand simpleNanoKeys[] =
2151{
2152// TODO - Delete key is ^H dammit. Find the alternate Esc sequence for Del.
2153// {"^H", "backSpaceChar"}, // ?
2154 {"BS", "backSpaceChar"},
2155 {"^D", "delete"},
2156 {"Del", "delete"},
2157 {"^N", "down"},
2158 {"Down", "down"},
2159 {"^E", "end"},
2160 {"End", "end"},
2161 {"^X", "exit"},
2162 {"F2", "exit"},
2163 {"^O", "writeout"},
2164 {"F3", "writeout"},
2165 {"^A", "home"},
2166 {"Home", "home"},
2167 {"^B", "left"},
2168 {"Left", "left"},
2169 {"^V", "downPage"}, // ?
2170 {"PgDn", "downPage"},
2171 {"^Y", "upPage"}, // ?
2172 {"PgUp", "upPage"},
2173 {"Enter", "enter"}, // TODO - Not sure if this is correct.
2174 {"Return", "enter"}, // TODO - Not sure if this is correct.
2175 {"^F", "right"},
2176 {"Right", "right"},
2177 {"^P", "up"},
2178 {"Up", "up"},
2179 {NULL, NULL}
2180};
2181
2182struct mode simpleNanoMode[] =
2183{
2184 {simpleNanoKeys, NULL, NULL, 0},
2185 {NULL, NULL, NULL}
2186};
2187
2188struct context simpleNano =
2189{
2190 simpleNanoCommands,
2191 simpleNanoMode,
2192 NULL,
2193 NULL,
2194 NULL
2195};
2196
2197
2198// Construct a simple vi editor.
2199// Only vi is not so simple. lol
2200// The "command line" modes are /, ?, :, and !,
2201// / is regex search.
2202// ? is regex search backwards.
2203// : is ex command mode.
2204// ! is replace text with output from shell command mode.
2205// Arrow keys do the right thing in "normal" mode, but not in insert mode.
2206// "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
2207// 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.
2208// Which is also the keyboard with the arrow keys marked on h, j, k, and l keys.
2209// Did I mention that vi is just a horrid historic relic that should have died long ago?
2210// Emacs looks to have the same problem, originally designed for an ancient keyboard that is nothing like what people actually use these days.
2211// "h", "j", "k", "l" move cursor, which is just random keys for dvorak users.
2212// ":" goes into ex command mode.
2213// ":q" deletes current window in vim.
2214// ":qa!" goes into ex mode and does some sort of quit command.
2215// The 'q' is short for quit, the ! is an optional argument to quit. No idea yet what the a is for, all windows?
2216// Del or "x" to delete a character. Del in insert mode.
2217// "X" to backspace. BS or Ctrl-H to backspace in insert mode.
2218// NOTE - Backspace in normal mode just moves left.
2219// Tab or Ctrl-I to insert a tab in insert mode.
2220// Return in normal mode goes to the start of the next line, or splits the line in insert mode.
2221// ":help" opens a window with help text.
2222// Vim window commands.
2223
2224// Vi needs extra variables and functions.
2225static int viTempExMode;
2226
2227void viMode(view *view)
2228{
2229 currentBox->view->mode = 0;
2230 commandMode = 0;
2231 viTempExMode = 0;
2232}
2233
2234void viInsertMode(view *view)
2235{
2236 currentBox->view->mode = 1;
2237 commandMode = 0;
2238}
2239
2240void viExMode(view *view)
2241{
2242 currentBox->view->mode = 2;
2243 commandMode = 1;
2244 // TODO - Should change this based on the event, : or Q.
2245 viTempExMode = 1;
2246 commandLine->prompt = xrealloc(commandLine->prompt, 2);
2247 strcpy(commandLine->prompt, ":");
2248}
2249
2250void viBackSpaceChar(view *view)
2251{
2252 if ((2 == currentBox->view->mode) && (0 == view->cX) && viTempExMode)
2253 viMode(view);
2254 else
2255 backSpaceChar(view);
2256}
2257
2258void viStartOfNextLine(view *view)
2259{
2260 startOfLine(view);
2261 downLine(view);
2262}
2263
2264struct function simpleViCommands[] =
2265{
2266 // These are actual ex commands.
2267 {"insert", "Switch to insert mode.", 0, {viInsertMode}},
2268 {"quit", "Quit the application.", 0, {quit}},
2269 {"visual", "Switch to visual mode.", 0, {viMode}},
2270 {"write", "Save.", 0, {saveContent}},
2271
2272 // These are not ex commands.
2273 {"backSpaceChar", "Back space last character.", 0, {viBackSpaceChar}},
2274 {"deleteBox", "Delete a box.", 0, {deleteBox}},
2275 {"deleteChar", "Delete current character.", 0, {deleteChar}},
2276 {"downLine", "Move cursor down one line.", 0, {downLine}},
2277 {"downPage", "Move cursor down one page.", 0, {downPage}},
2278 {"endOfLine", "Go to end of line.", 0, {endOfLine}},
2279 {"executeLine", "Execute a line as a script.", 0, {executeLine}},
2280 {"exMode", "Switch to ex mode.", 0, {viExMode}},
2281 {"leftChar", "Move cursor left one character.", 0, {leftChar}},
2282 {"rightChar", "Move cursor right one character.", 0, {rightChar}},
2283 {"splitH", "Split box in half horizontally.", 0, {halveBoxHorizontally}},
2284 {"splitLine", "Split line at cursor.", 0, {splitLine}},
2285 {"splitV", "Split box in half vertically.", 0, {halveBoxVertically}},
2286 {"startOfLine", "Go to start of line.", 0, {startOfLine}},
2287 {"startOfNLine", "Go to start of next line.", 0, {viStartOfNextLine}},
2288 {"switchBoxes", "Switch to another box.", 0, {switchBoxes}},
2289 {"upLine", "Move cursor up one line.", 0, {upLine}},
2290 {"upPage", "Move cursor up one page.", 0, {upPage}},
2291 {NULL, NULL, 0, {NULL}}
2292};
2293
2294struct keyCommand simpleViNormalKeys[] =
2295{
2296 {"BS", "leftChar"},
2297 {"X", "backSpaceChar"},
2298 {"Del", "deleteChar"},
2299 {"x", "deleteChar"},
2300 {"Down", "downLine"},
2301 {"j", "downLine"},
2302 {"End", "endOfLine"},
2303 {"Home", "startOfLine"},
2304 {"Left", "leftChar"},
2305 {"h", "leftChar"},
2306 {"PgDn", "downPage"},
2307 {"^F", "downPage"},
2308 {"PgUp", "upPage"},
2309 {"^B", "upPage"},
2310 {"Enter", "startOfNextLine"},
2311 {"Return", "startOfNextLine"},
2312 {"Right", "rightChar"},
2313 {"l", "rightChar"},
2314 {"i", "insert"},
2315 {":", "exMode"}, // This is the temporary ex mode that you can backspace out of. Or any command backs you out.
2316 {"Q", "exMode"}, // This is the ex mode you need to do the "visual" command to get out of.
2317 {"^Wv", "splitV"},
2318 {"^W^V", "splitV"},
2319 {"^Ws", "splitH"},
2320 {"^WS", "splitH"},
2321 {"^W^S", "splitH"},
2322 {"^Ww", "switchBoxes"},
2323 {"^W^W", "switchBoxes"},
2324 {"^Wq", "deleteBox"},
2325 {"^W^Q", "deleteBox"},
2326 {"Up", "upLine"},
2327 {"k", "upLine"},
2328 {NULL, NULL}
2329};
2330
2331struct keyCommand simpleViInsertKeys[] =
2332{
2333 {"BS", "backSpaceChar"},
2334 {"Del", "deleteChar"},
2335 {"Return", "splitLine"},
2336 {"Esc", "visual"},
2337 {"^C", "visual"},
2338 {NULL, NULL}
2339};
2340
2341struct keyCommand simpleExKeys[] =
2342{
2343 {"BS", "backSpaceChar"},
2344 {"Del", "deleteChar"},
2345 {"Down", "downLine"},
2346 {"End", "endOfLine"},
2347 {"Home", "startOfLine"},
2348 {"Left", "leftChar"},
2349 {"Enter", "executeLine"},
2350 {"Return", "executeLine"},
2351 {"Right", "rightChar"},
2352 {"Esc", "visual"},
2353 {"Up", "upLine"},
2354 {NULL, NULL}
2355};
2356
2357struct mode simpleViMode[] =
2358{
2359 {simpleViNormalKeys, NULL, NULL, 0},
2360 {simpleViInsertKeys, NULL, NULL, 0},
2361 {simpleExKeys, NULL, NULL, 1},
2362 {NULL, NULL, NULL}
2363};
2364
2365struct context simpleVi =
2366{
2367 simpleViCommands,
2368 simpleViMode,
2369 NULL,
2370 NULL,
2371 NULL
2372};
2373
2374
2375// TODO - simple sed editor? May be out of scope for "simple", so leave it until later?
2376// Probably entirely useless for "simple".
2377
2378
2379// TODO - have any unrecognised escape key sequence start up a new box (split one) to show the "show keys" content.
2380// That just adds each "Key is X" to the end of the content, and allows scrolling, as well as switching between other boxes.
2381
2382void boxes_main(void)
2383{
2384 struct context *context = &simpleMcedit; // The default is mcedit, coz that's what I use.
2385 struct termios termio, oldtermio;
2386 char *prompt = "Enter a command : ";
2387 unsigned W = 80, H = 24;
2388
2389 // For testing purposes, figure out which context we use. When this gets real, the toybox multiplexer will sort this out for us instead.
2390 if (toys.optflags & FLAG_m)
2391 {
2392 if (strcmp(TT.mode, "emacs") == 0)
2393 context = &simpleEmacs;
2394 else if (strcmp(TT.mode, "joe") == 0)
2395 context = &simpleJoe;
2396 else if (strcmp(TT.mode, "less") == 0)
2397 context = &simpleLess;
2398 else if (strcmp(TT.mode, "mcedit") == 0)
2399 context = &simpleMcedit;
2400 else if (strcmp(TT.mode, "more") == 0)
2401 context = &simpleMore;
2402 else if (strcmp(TT.mode, "nano") == 0)
2403 context = &simpleNano;
2404 else if (strcmp(TT.mode, "vi") == 0)
2405 context = &simpleVi;
2406 }
2407
2408 // 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.
2409 // It would STILL need the terminal size for output though. Perhaps just bitch and abort if it's not a tty?
2410 // 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.
2411
2412 // Grab the old terminal settings and save it.
2413 tcgetattr(0, &oldtermio);
2414 tcflush(0, TCIFLUSH);
2415 termio = oldtermio;
2416
2417 // Mould the terminal to our will.
2418 /*
2419 IUCLC (not in POSIX) Map uppercase characters to lowercase on input.
2420 IXON Enable XON/XOFF flow control on output.
2421 IXOFF Enable XON/XOFF flow control on input.
2422 IXANY (not in POSIX.1; XSI) Enable any character to restart output.
2423
2424 ECHO Echo input characters.
2425 ECHOE If ICANON is also set, the ERASE character erases the preceding input character, and WERASE erases the preceding word.
2426 ECHOK If ICANON is also set, the KILL character erases the current line.
2427 ECHONL If ICANON is also set, echo the NL character even if ECHO is not set.
2428 TOSTOP Send the SIGTTOU signal to the process group of a background process which tries to write to its controlling terminal.
2429 ICANON Enable canonical mode. This enables the special characters EOF, EOL, EOL2, ERASE, KILL, LNEXT, REPRINT, STATUS, and WERASE, and buffers by lines.
2430
2431 VTIME Timeout in deciseconds for non-canonical read.
2432 VMIN Minimum number of characters for non-canonical read.
2433
2434 raw mode turning off ICANON, IEXTEN, and ISIG kills most special key processing.
2435 termio.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
2436 termio.c_oflag &= ~OPOST;
2437 termio.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
2438 termio.c_cflag &= ~(CSIZE | PARENB);
2439 termio.c_cflag |= CS8;
2440
2441 IGNBRK ignore BREAK
2442 BRKINT complicated, bet in this context, sends BREAK as '\x00'
2443 PARMRK characters with parity or frame erors are sent as '\x00'
2444 ISTRIP strip 8th byte
2445 INLCR translate LF to CR in input
2446 IGLCR ignore CR
2447 OPOST enable implementation defined output processing
2448 ISIG generate signals on INTR (SIGINT on ^C), QUIT (SIGQUIT on ^\\), SUSP (SIGTSTP on ^Z), DSUSP (SIGTSTP on ^Y)
2449 IEXTEN enable implementation defined input processing, turns on some key -> signal -tuff
2450 CSIZE mask for character sizes, so in this case, we mask them all out
2451 PARENB enable parity
2452 CS8 8 bit characters
2453
2454 VEOF "sends" EOF on ^D, ICANON turns that on.
2455 VSTART restart output on ^Q, IXON turns that on.
2456 VSTATUS display status info and sends SIGINFO (STATUS) on ^T. Not in POSIX, not supported in Linux. ICANON turns that on.
2457 VSTOP stop output on ^S, IXON turns that on.
2458 */
2459 termio.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IUCLC | IXON | IXOFF | IXANY);
2460 termio.c_oflag &= ~OPOST;
2461 termio.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | TOSTOP | ICANON | ISIG | IEXTEN);
2462 termio.c_cflag &= ~(CSIZE | PARENB);
2463 termio.c_cflag |= CS8;
2464 termio.c_cc[VTIME]=0; // deciseconds.
2465 termio.c_cc[VMIN]=1;
2466 tcsetattr(0, TCSANOW, &termio);
2467
2468 terminal_size(&W, &H);
2469 if (toys.optflags & FLAG_w)
2470 W = TT.w;
2471 if (toys.optflags & FLAG_h)
2472 H = TT.h;
2473
2474 // 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.
2475 rootBox = addBox("root", context, toys.optargs[0], 0, 0, W, H - 1);
2476 currentBox = rootBox;
2477
2478 // Create the command line view, sharing the same context as the root. It will differentiate based on the view mode of the current box.
2479 // Also load the command line history as it's file.
2480 // 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?
2481 commandLine = addView("command", rootBox->view->content->context, ".boxes.history", 0, H, W, 1);
2482 // Add a prompt to it.
2483 commandLine->prompt = xrealloc(commandLine->prompt, strlen(prompt) + 1);
2484 strcpy(commandLine->prompt, prompt);
2485 // Move to the end of the history.
2486 moveCursorAbsolute(commandLine, 0, commandLine->content->lines.length, 0, 0);
2487
2488 // All the mouse tracking methods suck one way or another. sigh
2489 // http://rtfm.etla.org/xterm/ctlseq.html documents xterm stuff, near the bottom is the mouse stuff.
2490 // http://leonerds-code.blogspot.co.uk/2012/04/wide-mouse-support-in-libvterm.html is helpful.
2491 // Enable mouse (VT200 normal tracking mode, UTF8 encoding). The limit is 2015. Seems to only be in later xterms.
2492// fputs("\x1B[?1005h", stdout);
2493 // Enable mouse (VT340 locator reporting mode). In theory has no limit. Wont actually work though.
2494 // On the other hand, only allows for four buttons, so only half a mouse wheel.
2495 // 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".
2496// fputs("\x1B[1;2'z\x1B[1;3'{", stdout);
2497 // 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.
2498 // 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
2499// fputs("\x1B[?1000h", stdout);
2500// fflush(stdout);
2501
2502 calcBoxes(currentBox);
2503 drawBoxes(currentBox);
2504 // Do the first cursor update.
2505 updateLine(currentBox->view);
2506
2507 // Run the main loop.
2508 handle_keys((long) currentBox->view, handleEvent);
2509
2510 // TODO - Should remember to turn off mouse reporting when we leave.
2511
2512 // Restore the old terminal settings.
2513 tcsetattr(0, TCSANOW, &oldtermio);
2514
2515 puts("");
2516 fflush(stdout);
2517}
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
8USE_DUMBSH(NEWTOY(dumbsh, "", TOYFLAG_USR|TOYFLAG_BIN))
9
10config 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
22typedef void (*eventHandler) (void);
23
24struct keyCommand
25{
26 char *key;
27 eventHandler handler;
28};
29
30GLOBALS(
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.
39static 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.
52static 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
61static 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?
80static void doCommand()
81{
82 toybuf[0] = 0;
83 TT.x = 0;
84 TT.y++;
85 printf("\n");
86 fflush(stdout);
87 updateLine();
88}
89
90static void endOfLine()
91{
92 TT.x = strlen(toybuf);
93 updateLine();
94}
95
96static void leftChar()
97{
98 TT.x--;
99 updateLine();
100}
101
102static void nextHistory()
103{
104 TT.history = TT.history->next;
105 strcpy(toybuf, TT.history->data);
106 TT.x = strlen(toybuf);
107 updateLine();
108}
109
110static void prevHistory()
111{
112 TT.history = TT.history->prev;
113 strcpy(toybuf, TT.history->data);
114 TT.x = strlen(toybuf);
115 updateLine();
116}
117
118static void quit()
119{
120 handle_keys_quit();
121}
122
123static void rightChar()
124{
125 TT.x++;
126 updateLine();
127}
128
129static void startOfLine()
130{
131 TT.x = 0;
132 updateLine();
133}
134
135// The key to command mappings, Emacs style.
136static 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.
160static 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
235void 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
15struct 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.
32static 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
171static volatile sig_atomic_t sigWinch;
172static int stillRunning;
173
174static void handleSIGWINCH(int signalNumber)
175{
176 sigWinch = 1;
177}
178
179void 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
442void 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
6enum keyeventtype{
7 HK_CSI,
8 HK_KEYS,
9 HK_MOUSE,
10 HK_RAW
11};
12
13struct 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 */
72void handle_keys(long extra, int (*handle_event)(long extra, struct keyevent *event));
73
74
75/* Call this when you want handle_keys to return. */
76void 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
10USE_SHOWKEY(NEWTOY(showkey, "", TOYFLAG_USR|TOYFLAG_BIN))
11
12config 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
24typedef void (*eventHandler) (void);
25
26struct keyCommand
27{
28 char *key;
29 eventHandler handler;
30};
31
32GLOBALS(
33 unsigned h, w;
34 int x, y;
35)
36
37#define TT this.showkey
38
39
40static void quit()
41{
42 printf("Quitting.\r\n");
43 handle_keys_quit();
44}
45
46// The key to command mappings.
47static struct keyCommand simpleKeys[] =
48{
49 {"^C", quit}
50};
51
52// Callback for incoming sequences from the terminal.
53static 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
121void 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}