From 53bf6abdd50177da8b6dad36f487dcdac1b59176 Mon Sep 17 00:00:00 2001 From: Brian Holman Date: Mon, 9 Nov 2026 23:45:41 -0700 Subject: [PATCH] Import Ebitor 0.1.1 upstream source snapshot Original author: Pierre Sarrazin. Source: http://sarrazip.com/dev/ebitor-0.1.1.tar.gz Archive SHA-256: 6911a9d2ee80925622f1d82db1b77710a1f896865e63d29a04dc16489b150e83 --- Ebitor.c | 939 +++++++++++++++++++++++++++++++ Ebitor.h | 285 ++++++++++ Ebitor_private.h | 105 ++++ Makefile | 216 ++++++++ README.md | 150 +++++ Window.h | 36 ++ ebitdemo.c | 1041 +++++++++++++++++++++++++++++++++++ ebittest.c | 818 +++++++++++++++++++++++++++ findStringAndScrollToShow.c | 49 ++ gimeterm.c | 319 +++++++++++ gimeterm.h | 146 +++++ os9term.c | 296 ++++++++++ os9term.h | 111 ++++ processBackspace.c | 109 ++++ processPrintableChar.c | 110 ++++ scrollToShowLogicalOffset.c | 104 ++++ sg4term.c | 318 +++++++++++ sg4term.h | 95 ++++ smoldemo.c | 153 +++++ 19 files changed, 5400 insertions(+) create mode 100644 Ebitor.c create mode 100644 Ebitor.h create mode 100644 Ebitor_private.h create mode 100644 Makefile create mode 100644 README.md create mode 100644 Window.h create mode 100644 ebitdemo.c create mode 100644 ebittest.c create mode 100644 findStringAndScrollToShow.c create mode 100644 gimeterm.c create mode 100644 gimeterm.h create mode 100644 os9term.c create mode 100644 os9term.h create mode 100644 processBackspace.c create mode 100644 processPrintableChar.c create mode 100644 scrollToShowLogicalOffset.c create mode 100644 sg4term.c create mode 100644 sg4term.h create mode 100644 smoldemo.c diff --git a/Ebitor.c b/Ebitor.c new file mode 100644 index 0000000..ac94e6f --- /dev/null +++ b/Ebitor.c @@ -0,0 +1,939 @@ +/* Ebitor.c + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/* + This file uses the terms "terminal" and "window" interchangeably. +*/ + +#include "Ebitor_private.h" + + +enum +{ + MODE_COMMAND, + MODE_INSERTION, +}; + + +Ebitor Ebitor_instance; + + +void +Ebitor_init(char *bufferBegin, size_t bufferSize, + byte termWidth, byte termHeight, + ebitor_clear clear, + ebitor_locateFunc locate, + ebitor_getCursorPosFunc getCursorPos, + ebitor_printFunc print, + ebitor_printPrefixFunc printPrefix, + ebitor_clrtoeolFunc clrtoeol, + ebitor_scrollTerminalUpFunc scrollTerminalUp, + ebitor_scrollTerminalDownFunc scrollTerminalDown, + ebitor_waitKeyFunc waitKey) +{ + Ebitor *self = &Ebitor_instance; + self->termWidth = termWidth; + self->termHeight = termHeight; + self->bufferBegin = bufferBegin; + self->bufferEnd = bufferBegin + bufferSize; + self->bufferFilledSize = 0; + self->cursorOffset = 0; + self->savedCursorCol = 0; + self->savedCursorRow = 0; + self->mode = MODE_COMMAND; + self->insertBuffer.size = 0; + + self->clear = clear; + self->locate = locate; + self->getCursorPos = getCursorPos; + self->print = print; + self->printPrefix = printPrefix; + self->clrtoeol = clrtoeol; + self->scrollTerminalUp = scrollTerminalUp; + self->scrollTerminalDown = scrollTerminalDown; + self->waitKey = waitKey; +} + + +void +Ebitor_shutdown(void) +{ +} + + +Ebitor * +Ebitor_getInstance(void) +{ + return &Ebitor_instance; +} + + +void +Ebitor_setContentLength(size_t newLength) +{ + size_t max = Ebitor_instance.bufferEnd - Ebitor_instance.bufferBegin; + Ebitor_instance.bufferFilledSize = min(newLength, max); + + Ebitor_setLogicalCursorAtBeginning(); + + Ebitor_instance.mode = MODE_COMMAND; + Ebitor_instance.insertBuffer.size = 0; +} + + +size_t +Ebitor_getContentLength(void) +{ + return Ebitor_instance.bufferFilledSize; +} + + +// Move the contents of insert buffer to the cursor position in the edit buffer. +// Insert buffer ends up empty. +// Cursor offset updated to point to after the copied characters. +// +void +Ebitor_flushInsertBuffer(void) +{ + Ebitor *self = &Ebitor_instance; + if (self->insertBuffer.size == 0) + return; + + // Check if there is room in the edit buffer for the contents of the insert buffer. + // + size_t availRoom = self->bufferEnd - self->bufferBegin - self->bufferFilledSize; + if (self->insertBuffer.size > availRoom) + self->insertBuffer.size = availRoom; + + // Create a hole in the edit buffer where to copy the insert buffer. + // + memmove(self->bufferBegin + self->cursorOffset + self->insertBuffer.size, + self->bufferBegin + self->cursorOffset, + self->bufferFilledSize - self->cursorOffset); + + memcpy(self->bufferBegin + self->cursorOffset, self->insertBuffer.buffer, self->insertBuffer.size); + + self->bufferFilledSize += self->insertBuffer.size; + self->cursorOffset += self->insertBuffer.size; + self->insertBuffer.size = 0; +} + + +void +Ebitor_startCommandMode(void) +{ + Ebitor *self = &Ebitor_instance; + if (self->mode != MODE_COMMAND) + { + Ebitor_flushInsertBuffer(); + self->mode = MODE_COMMAND; + } +} + + +void +Ebitor_insertChar(char c) +{ + Ebitor *self = &Ebitor_instance; + if (self->mode == MODE_COMMAND) + { + // Go to insertion mode. + self->mode = MODE_INSERTION; + self->insertBuffer.buffer[0] = c; + self->insertBuffer.size = 1; + } + else // already in insertion mode + { + self->insertBuffer.buffer[self->insertBuffer.size++] = c; + + if (self->insertBuffer.size == INSERT_BUFFER_SIZE) // if full + { + Ebitor_flushInsertBuffer(); + assert(self->insertBuffer.size == 0); + } + } +} + + +// If no \r is found, returns the end of the filled part of the edit buffer. +// +size_t +Ebitor_findEOL(size_t startOffset) +{ + const Ebitor *self = &Ebitor_instance; + char *p = (char *) memchr(self->bufferBegin + startOffset, '\r', self->bufferFilledSize - startOffset); + return p ? p - self->bufferBegin : self->bufferFilledSize; +} + + +size_t +Ebitor_findSOL(size_t startOffset) +{ + const Ebitor *self = &Ebitor_instance; + char *p = self->bufferBegin + startOffset; + while (p > self->bufferBegin) // while possible to go back + { + --p; + if (*p == '\r') + return p + 1 - self->bufferBegin; + } + return p - self->bufferBegin; +} + + +size_t +Ebitor_findPreviousSOL(size_t solOffset) +{ + const Ebitor *self = &Ebitor_instance; + if (solOffset == 0) + return solOffset; + assert(self->bufferBegin[solOffset - 1] == '\r'); + return Ebitor_findSOL(solOffset - 1); +} + + +void +Ebitor_fillTerminalToBottom(size_t firstLogicalCharOffsetToPrint, byte firstRowToFill) +{ + const Ebitor *self = &Ebitor_instance; + //printf("(%u,%u;%u)", firstLogicalCharOffsetToPrint, firstRowToFill, self->bufferFilledSize); + assert(firstLogicalCharOffsetToPrint <= self->bufferFilledSize); + if (firstRowToFill >= self->termHeight) + return; // failsafe -- nothing to do + + self->locate(0, firstRowToFill); + + if (firstLogicalCharOffsetToPrint == self->bufferFilledSize) // if nothing to print + { + self->clrtoeol(); // erase a line that may have been merged up + return; + } + + // Reprint the rest of the window, while preserving the cursor position. + // The portion to print starts at self->cursorOffset and ends either at + // the end of the filled edit buffer, or at the bottom of the window. + // + const char *begin = self->bufferBegin + firstLogicalCharOffsetToPrint; + const char *end = self->bufferBegin + self->bufferFilledSize; + byte c = 0, r = firstRowToFill; + const char *p = begin; + for ( ; r < self->termHeight && p < end; ++p) + { + if (*p == '\r') + { + c = 0; + ++r; + } + else // printable char + { + ++c; + if (c == self->termWidth) + { + c = 0; + ++r; + } + } + } + // p points to the first char NOT to be printed. + + self->printPrefix(begin, p - begin); + + if (r < self->termHeight) + self->clrtoeol(); + if (r < self->termHeight - 1) + { + self->locate(0, r + 1); + self->clrtoeol(); + } +} + + +void +Ebitor_fillWindowFromHomeToRow(size_t firstLogicalCharOffsetToPrint, byte numRowsToFill) +{ + Ebitor *self = &Ebitor_instance; + if (numRowsToFill == 0) + return; + self->locate(0, 0); + size_t offset = firstLogicalCharOffsetToPrint; + for (;;) + { + size_t eolOffset = Ebitor_findEOL(offset); + while (eolOffset - offset >= self->termWidth) // if current row to be filled completely + { + self->printPrefix(self->bufferBegin + offset, self->termWidth); + if (--numRowsToFill == 0) + return; + offset += self->termWidth; + } + + if (offset != eolOffset) + self->printPrefix(self->bufferBegin + offset, eolOffset - offset); + self->print("\r"); + if (--numRowsToFill == 0) + return; + if (eolOffset == self->bufferFilledSize) // if EOF instead of \r + break; // go blank remaining rows to fill + + offset = eolOffset + 1; // pass \r + } + + for ( ; numRowsToFill--; ) + self->print("\r"); +} + + +void +Ebitor_setLogicalCursorAtBeginning(void) +{ + Ebitor_instance.cursorOffset = 0; + Ebitor_instance.savedCursorCol = 0; + Ebitor_instance.savedCursorRow = 0; +} + + +size_t +Ebitor_getLogicalCursorOffset(void) +{ + return Ebitor_instance.cursorOffset; +} + + +static void +Ebitor_refresh(byte cursorCol, byte cursorRow) +{ + Ebitor_instance.clear(); + + // Reprint the window starting at the logical offset that corresponds to + // the top-left corner of the terminal. + // + size_t homeOffset = Ebitor_getLogicalOffsetAtHome(cursorCol, cursorRow); + Ebitor_fillTerminalToBottom(homeOffset, 0); +} + + +static void +Ebitor_processLeftArrow(byte cursorCol, byte cursorRow) +{ + assert(Ebitor_instance.mode == MODE_COMMAND); + + if (Ebitor_instance.cursorOffset == 0) // if already at start of edit buffer + return; // nothing to do + + if (cursorCol > 0) // if not at leftmost window column + { + Ebitor_instance.locate(cursorCol - 1, cursorRow); + } + else + { + // Cursor at leftmost window column. + // If at start of logical line, go to end of previous logical line. + // Otherwise, scroll up if needed, then go to rightmost window column + // on previous window row. + // + size_t solOffset = Ebitor_findSOL(Ebitor_instance.cursorOffset); + if (solOffset == Ebitor_instance.cursorOffset) // if at start of logical line + { + size_t prevSOLOffset = Ebitor_findPreviousSOL(Ebitor_instance.cursorOffset); + assert(prevSOLOffset != Ebitor_instance.cursorOffset); // previous line found, because cursorOffset not 0 + size_t prevLineLen = solOffset - prevSOLOffset - 1; // minus one to exclude \r + byte lastRowLen = (byte) (prevLineLen % Ebitor_instance.termWidth); // e.g., if 37-char logical line on 32-column terminal, then 5 + if (cursorRow == 0) + { + // At top row of window. There is a line before the current one, b/c cursorOffset > 0. + // Scroll the window down one row. + // Print the last 'lastRowLen' chars of that line. Leave the cursor after these. + size_t offsetToPrint = Ebitor_instance.cursorOffset - 1 - lastRowLen; + Ebitor_instance.scrollTerminalDown(1); + Ebitor_instance.printPrefix(Ebitor_instance.bufferBegin + offsetToPrint, lastRowLen); + } + else + --cursorRow; + Ebitor_instance.locate(lastRowLen, cursorRow); + } + else // not at start of logical line + { + // Current logical line starts before cursorOffset. + if (cursorRow == 0) + { + // Cursor is home. Print full window row of chars from current logical line. + Ebitor_instance.scrollTerminalDown(1); + Ebitor_instance.printPrefix(Ebitor_instance.bufferBegin + (Ebitor_instance.cursorOffset - Ebitor_instance.termWidth), Ebitor_instance.termWidth); + } + else + --cursorRow; + Ebitor_instance.locate(Ebitor_instance.termWidth - 1, cursorRow); + } + } + --Ebitor_instance.cursorOffset; +} + + +static void +Ebitor_processRightArrow(byte cursorCol, byte cursorRow) +{ + assert(Ebitor_instance.mode == MODE_COMMAND); + + if (Ebitor_instance.cursorOffset == Ebitor_instance.bufferFilledSize) // if already at EOF + return; // nothing to do + + size_t eolOffset = Ebitor_findEOL(Ebitor_instance.cursorOffset); + if (Ebitor_instance.cursorOffset == eolOffset // if at end of logical line + || cursorCol + 1 == Ebitor_instance.termWidth) // or if at rightmost window column + { + if (cursorRow == Ebitor_instance.termHeight - 1) // if starting on last window row + { + Ebitor_instance.scrollTerminalUp(1); + Ebitor_instance.locate(0, cursorRow); + + // If the move still leaves the logical cursor in the current logical line, + // then print then the next row of the current logical line. + // Otherwise, print the first row of the next logical line. + // + if (Ebitor_instance.cursorOffset < eolOffset) + { + size_t nextCharOffset = Ebitor_instance.cursorOffset + 1; + size_t lineLenFromNextChar = eolOffset - nextCharOffset; + byte toPrint = (byte) min(lineLenFromNextChar, (size_t) Ebitor_instance.termWidth); + Ebitor_instance.printPrefix(Ebitor_instance.bufferBegin + nextCharOffset, toPrint); + } + else + { + size_t nextLineOffset = eolOffset + 1; // after the \r + size_t nextLineLen = Ebitor_findEOL(nextLineOffset) - nextLineOffset; + byte charsOnFirstRow = (byte) min(nextLineLen, (size_t) Ebitor_instance.termWidth); + Ebitor_instance.printPrefix(Ebitor_instance.bufferBegin + nextLineOffset, charsOnFirstRow); + } + } + else + ++cursorRow; + + cursorCol = 0; + } + else + ++cursorCol; // move cursor right + + assert(cursorRow < Ebitor_instance.termHeight); + Ebitor_instance.locate(cursorCol, cursorRow); + + ++Ebitor_instance.cursorOffset; + assert(Ebitor_instance.cursorOffset <= Ebitor_instance.bufferFilledSize); +} + + +// May change *cursorCol and *cursorRow. +// Does not change any fields of Ebitor_instance. +// +static void +Ebitor_scrollDownAndPrintRow(byte *cursorRow, size_t newOffsetToPrintFrom, size_t numCharsToPrint, BOOL affectTerminal) +{ + if (*cursorRow == 0) // if cursor is on top row of terminal + { + Ebitor_instance.scrollTerminalDown(1); // scroll terminal down to free top row + + if (affectTerminal) + { + // Print the previous logical line on the top terminal row, + // or a portion of that line if it is longer than a terminal row. + // + Ebitor_instance.locate(0, *cursorRow); + Ebitor_instance.printPrefix(Ebitor_instance.bufferBegin + newOffsetToPrintFrom, numCharsToPrint); + } + } + else + { + assert(*cursorRow > 0); + --*cursorRow; + } +} + + +static void +Ebitor_processUpArrow(byte cursorCol, byte cursorRow, BOOL affectTerminal) +{ + assert(Ebitor_instance.mode == MODE_COMMAND); + + // Do nothing if already on 1st logical line. + // + size_t solOffset = Ebitor_findSOL(Ebitor_instance.cursorOffset); + + // If the current logical line starts before the cursor row, go up in that logical line. + // + size_t newCursorOffset; + if (Ebitor_instance.cursorOffset - solOffset >= Ebitor_instance.termWidth) + { + // Current logical line starts before cursor row. + // Place cursor earlier in current logical line. + // + newCursorOffset = Ebitor_instance.cursorOffset - Ebitor_instance.termWidth; + + Ebitor_scrollDownAndPrintRow(&cursorRow, newCursorOffset, Ebitor_instance.termWidth, affectTerminal); + } + else + { + // Cursor is on first window row of current logical line. + // Place cursor on last window row of preceding logical line, if any. + // + if (solOffset == 0) + return; + + size_t prevSOLOffset = Ebitor_findPreviousSOL(solOffset); + assert(prevSOLOffset < solOffset); + size_t prevLineLen = solOffset - prevSOLOffset - 1; // exclude \r + byte charsOnLastRow = (byte) (prevLineLen % Ebitor_instance.termWidth); // after last char of previous line + size_t offsetOfLastRowOfPrevLine = solOffset - 1 - charsOnLastRow; + + Ebitor_scrollDownAndPrintRow(&cursorRow, offsetOfLastRowOfPrevLine, charsOnLastRow, affectTerminal); + + if (charsOnLastRow < cursorCol) // avoid putting cursor in empty space + cursorCol = charsOnLastRow; + + newCursorOffset = offsetOfLastRowOfPrevLine + cursorCol; + } + Ebitor_instance.cursorOffset = newCursorOffset; // move the logical cursor + Ebitor_instance.locate(cursorCol, cursorRow); +} + + +// May change *cursorCol and *cursorRow. +// Does not change any fields of Ebitor_instance. +// +static void +Ebitor_scrollUpAndPrintRow(byte *cursorCol, byte *cursorRow, size_t newOffsetToPrintFrom, byte numCharsToPrint, BOOL affectTerminal) +{ + if (*cursorRow == Ebitor_instance.termHeight - 1) // scroll if cursor on last window row + { + if (affectTerminal) + { + Ebitor_instance.scrollTerminalUp(1); + Ebitor_instance.locate(0, *cursorRow); + Ebitor_instance.printPrefix(Ebitor_instance.bufferBegin + newOffsetToPrintFrom, numCharsToPrint); + } + } + else + ++*cursorRow; + assert(*cursorRow < Ebitor_instance.termHeight); + + if (*cursorCol > numCharsToPrint) // avoid putting cursor in empty space + *cursorCol = numCharsToPrint; +} + + +static void +Ebitor_processDownArrow(byte cursorCol, byte cursorRow, BOOL affectTerminal) +{ + assert(Ebitor_instance.mode == MODE_COMMAND); + + size_t eolOffset = Ebitor_findEOL(Ebitor_instance.cursorOffset); + + // If the current logical line has characters beyond the current cursor row, + // move down this logical line. + // + size_t newCursorOffset; + if (cursorCol + (eolOffset - Ebitor_instance.cursorOffset) >= Ebitor_instance.termWidth) + { + const size_t newOffsetToPrintFrom = Ebitor_instance.cursorOffset - cursorCol + Ebitor_instance.termWidth; + const byte charsOnNewRow = (byte) min(eolOffset - newOffsetToPrintFrom, (size_t) Ebitor_instance.termWidth); + + Ebitor_scrollUpAndPrintRow(&cursorCol, &cursorRow, newOffsetToPrintFrom, charsOnNewRow, affectTerminal); + + newCursorOffset = min(Ebitor_instance.cursorOffset + Ebitor_instance.termWidth, eolOffset); + } + else if (eolOffset < Ebitor_instance.bufferFilledSize) // logical line ends on current window row, so if it has a \r: + { + assert(Ebitor_instance.bufferBegin[eolOffset] == '\r'); + const size_t newOffsetToPrintFrom = eolOffset + 1; // after the \r + assert(newOffsetToPrintFrom <= Ebitor_instance.bufferFilledSize); + const size_t nextLineLen = Ebitor_findEOL(newOffsetToPrintFrom) - newOffsetToPrintFrom; + const byte charsOnNewRow = (byte) min(nextLineLen, (size_t) Ebitor_instance.termWidth); + + Ebitor_scrollUpAndPrintRow(&cursorCol, &cursorRow, newOffsetToPrintFrom, charsOnNewRow, affectTerminal); + + newCursorOffset = newOffsetToPrintFrom + cursorCol; // move the logical cursor + } + else + return; + + Ebitor_instance.cursorOffset = newCursorOffset; + if (affectTerminal) + Ebitor_instance.locate(cursorCol, cursorRow); +} + + +void +Ebitor_processUpOrDownArrowsAndRefresh(BOOL isUpArrow, size_t numRepetitions) +{ + Ebitor_locateCursorAtSavedPosition(); + + byte cursorCol, cursorRow; + Ebitor_instance.getCursorPos(&cursorCol, &cursorRow); + + Ebitor_startCommandMode(); + + // Point to the right arrow processing function, depending on isUpArrow. + void (*processArrow)(byte cursorCol, byte cursorRow, BOOL affectTerminal) = isUpArrow ? Ebitor_processUpArrow : Ebitor_processDownArrow; + + for ( ; numRepetitions--; ) + (*processArrow)(cursorCol, cursorRow, FALSE); // do not affect terminal + + Ebitor_scrollToShowLogicalOffset(Ebitor_instance.cursorOffset, 0); + Ebitor_saveCursorPosition(); + + Ebitor_refresh(Ebitor_instance.savedCursorCol, Ebitor_instance.savedCursorRow); +} + + +// key: Value returned by a function of type ebitor_waitKeyFunc. +// +void +Ebitor_processKey(word key) +{ + byte cursorCol, cursorRow; + Ebitor_instance.getCursorPos(&cursorCol, &cursorRow); + + switch (key) + { + case '\b': // erase previous char + Ebitor_processBackspace(cursorCol, cursorRow); + break; + case '\r': + { + Ebitor_instance.clrtoeol(); + + if (cursorRow < Ebitor_instance.termHeight - 1) // if not on last window row + ++cursorRow; + else // on last window row + Ebitor_instance.scrollTerminalUp(1); + + Ebitor_fillTerminalToBottom(Ebitor_instance.cursorOffset, cursorRow); + Ebitor_instance.locate(0, cursorRow); + + Ebitor_insertChar('\r'); + } + break; + case ebitor_KEY_ARROW_LEFT: + // Go to command mode if not already in it. + // This flushes the insert buffer, if any. + // + Ebitor_startCommandMode(); + + Ebitor_processLeftArrow(cursorCol, cursorRow); + break; + case ebitor_KEY_ARROW_RIGHT: + Ebitor_startCommandMode(); + Ebitor_processRightArrow(cursorCol, cursorRow); + break; + case ebitor_KEY_ARROW_UP: + Ebitor_startCommandMode(); + Ebitor_processUpArrow(cursorCol, cursorRow, TRUE); + break; + case ebitor_KEY_ARROW_DOWN: + Ebitor_startCommandMode(); + Ebitor_processDownArrow(cursorCol, cursorRow, TRUE); + break; + default: + Ebitor_processPrintableChar(key, cursorCol, cursorRow); + } +} + + +void +Ebitor_locateCursorAtSavedPosition(void) +{ + Ebitor_instance.locate(Ebitor_instance.savedCursorCol, Ebitor_instance.savedCursorRow); +} + + +void +Ebitor_saveCursorPosition(void) +{ + Ebitor_instance.getCursorPos(&Ebitor_instance.savedCursorCol, &Ebitor_instance.savedCursorRow); +} + + +void +Ebitor_processEditing(BOOL startWithRefresh) +{ + if (startWithRefresh) + Ebitor_refresh(Ebitor_instance.savedCursorCol, Ebitor_instance.savedCursorRow); + + Ebitor_locateCursorAtSavedPosition(); + + for (;;) + { + assert(Ebitor_instance.cursorOffset <= Ebitor_instance.bufferFilledSize); + + word key = Ebitor_instance.waitKey(); + if (key == ebitor_KEY_ESCAPE) + break; + + Ebitor_processKey(key); + } + + Ebitor_startCommandMode(); // put inserted chars in edit buffer + + // Remember the cursor position for the next time this method is called. + // + Ebitor_saveCursorPosition(); +} + + +// Determines which logical offset is currently at position (0, 0) on the terminal, +// assuming that the current logical cursor is at terminal position (cursorCol, cursorRow). +// +size_t +Ebitor_getLogicalOffsetAtHome(byte cursorCol, byte cursorRow) +{ + Ebitor *self = &Ebitor_instance; + Ebitor_startCommandMode(); // put insert buffer into edit buffer, so that all the text is contiguous + + assert(self->cursorOffset >= cursorCol); + size_t offset = self->cursorOffset - cursorCol; // initialize at start of terminal row + //printf("[gLOAH(%u,%u):co=%u,o=%u]", cursorCol, cursorRow, self->cursorOffset, offset); + for (;;) // bring 'offset' back to the logical offset that is at (0, 0) on the terminal + { + //printf("(cr=%u,o=%u)", cursorRow, offset); + if (cursorRow == 0) + return offset; + if (offset == 0) + return 0; + //printf("(CHAR %u)", self->bufferBegin[offset - 1]); + if (self->bufferBegin[offset - 1] != '\r') + { + offset -= self->termWidth; // go back to start of terminal row + --cursorRow; + } + else // if offset is at the start of a logical line + { + //printf("(FOR)"); + for (;;) + { + size_t startOfLogicalLine = Ebitor_findSOL(offset - 1); // start of previous line + size_t logicalLineLen = offset - 1 - startOfLogicalLine; + //printf("(soll=%u,lll=%u)", startOfLogicalLine, logicalLineLen); + offset -= 1 + logicalLineLen % self->termWidth; // go back to \r, then back to start of row + --cursorRow; + for (;;) + { + if (cursorRow == 0) + return offset; + if (offset == startOfLogicalLine) + break; // reached start of logical line + + // In the current logical line, terminal location (0, cursorRow) is now preceded by + // a number of logical chars divisible by termWidth. + assert((offset - startOfLogicalLine) % self->termWidth == 0); + offset -= self->termWidth; + --cursorRow; + } + //printf("[cr=%u,o=%u]", cursorRow, offset); + assert(cursorRow > 0); + if (offset == 0) + return 0; + //printf("[%u]", self->bufferBegin[offset - 1]); + assert(self->bufferBegin[offset - 1] == '\r'); + } + } + } +} + + +void +Ebitor_getLogicalOffsetBelowWindow(size_t homeOffset, size_t *resultOffset, BOOL *isInWindow) +{ + Ebitor *self = &Ebitor_instance; + byte termRow = 0; + size_t offset = homeOffset; + byte numEditorLines = self->termHeight; + for (;;) + { + const size_t eolOffset = Ebitor_findEOL(offset); + while (eolOffset - offset >= self->termWidth) + { + offset += self->termWidth; + ++termRow; + if (termRow >= numEditorLines) // if off window + { + *resultOffset = offset; + *isInWindow = FALSE; + return; + } + } + if (eolOffset == self->bufferFilledSize) + { + *resultOffset = eolOffset; + *isInWindow = TRUE; + return; + } + assert(self->bufferBegin[eolOffset] == '\r'); + offset = eolOffset + 1; // pass '\r', which goes to next row + ++termRow; + if (termRow >= numEditorLines) // if off window + { + *resultOffset = offset; + *isInWindow = FALSE; + return; + } + } +} + + +char +Ebitor_isRegionVisible(size_t regionOffset, size_t regionLength, byte cursorCol, byte cursorRow, + size_t *homeOffset, size_t *firstOffWindowOffset) +{ + Ebitor *self = &Ebitor_instance; + //printf("[iRV(%u,%u,%u,%u): BFS=%u]", + // regionOffset, regionLength, cursorCol, cursorRow, self->bufferFilledSize); + assert(regionOffset + regionLength <= self->bufferFilledSize); + assert(self->insertBuffer.size == 0); + + *homeOffset = Ebitor_getLogicalOffsetAtHome(cursorCol, cursorRow); + if (regionOffset < *homeOffset) // if region is entirely or partly before the text that starts at home + return -1; // region is (entirely or partly) before displayed text + + // Get the offset of the first character that is below the bottom of the terminal. + // + BOOL isInWindow; + Ebitor_getLogicalOffsetBelowWindow(*homeOffset, firstOffWindowOffset, &isInWindow); + + if (!isInWindow && regionOffset + regionLength > *firstOffWindowOffset) + return +1; // region is (entirely or partly) after displayed text + + return 0; // region is entirely in the displayed text +} + + +size_t +Ebitor_countRowsToScrollDown(size_t logicalOffsetToShow, size_t homeOffset, + size_t *logicalOffsetAtStartOfTermRow) +{ + // Count the number of terminal rows from logicalOffsetToShow to homeOffset. + // This is how many rows we need to scroll the terminal down. + // + assert(logicalOffsetToShow < homeOffset); + + Ebitor *self = &Ebitor_instance; + size_t solOffset = Ebitor_findSOL(logicalOffsetToShow); + + // Bring logicalOffsetToShow back to the preceding logical position that is displayed + // at the start of a window row. + // We have: logicalOffsetToShow == solOffset + R * termWidth + C, where R >= 0 and C < termWidth. + // We replace logicalOffsetToShow with solOffset + R * termWidth. + // Example: A line has 67 chars and the terminal width is 32 + // We have logicalOffsetToShow - solOffset == 67. + // 67 % 32 == 3, so we bring logicalOffsetToShow to 64. + // + *logicalOffsetAtStartOfTermRow = logicalOffsetToShow - (logicalOffsetToShow - solOffset) % self->termWidth; + + size_t numTermRows = 0; + size_t offset = *logicalOffsetAtStartOfTermRow; + for (;;) + { + const size_t eolOffset = Ebitor_findEOL(offset); + while (eolOffset - offset >= self->termWidth) + { + offset += self->termWidth; + ++numTermRows; + if (offset == homeOffset) + return numTermRows; + } + offset = eolOffset + 1; // pass \r + ++numTermRows; + if (offset == homeOffset) + return numTermRows; + } +} + + +size_t +Ebitor_countRowsToScrollUp(size_t logicalOffsetToShow, size_t firstOffWindowOffset) +{ + Ebitor *self = &Ebitor_instance; + assert(firstOffWindowOffset <= logicalOffsetToShow); + assert((firstOffWindowOffset - Ebitor_findSOL(firstOffWindowOffset)) % self->termWidth == 0); + + size_t numTermRows = 1; + + size_t offset = firstOffWindowOffset; + for (;;) + { + assert((offset - Ebitor_findSOL(offset)) % self->termWidth == 0); + + if (offset == logicalOffsetToShow) // if target reached + return numTermRows; + + const size_t eolOffset = Ebitor_findEOL(offset); + + while (eolOffset - offset >= self->termWidth) // as long as term row at 'offset' is filled + { + if (logicalOffsetToShow - offset < self->termWidth) + return numTermRows; // logicalOffsetToShow is on current row + ++numTermRows; // logicalOffsetToShow is on next row or later + offset += self->termWidth; + } + + // Term row at 'offset' is not filled completely, so the current logical line ends on this row. + // + if (logicalOffsetToShow <= eolOffset) // if target logical position is on current row + return numTermRows; + offset = eolOffset; + if (offset == self->bufferFilledSize) // if EOF + return numTermRows; // can't scroll more than this + + ++offset; // pass the \r; now at position that would be at start of window row + ++numTermRows; + } +} + + +void +Ebitor_locateAndSavePos(byte col, byte row) +{ + Ebitor_instance.locate(col, row); + Ebitor_instance.savedCursorCol = col; + Ebitor_instance.savedCursorRow = row; +} + + +// startOfRowOffset: Logical offset of a character that is in column 0. +// Returns the logical offset of another character down the text that is also in column 0. +// If there are not enough rows, stops at the last row. +// +size_t +Ebitor_goDownRows(size_t startOfRowOffset, size_t numRows) +{ + size_t offset = startOfRowOffset; + for (;;) + { + size_t eolOffset = Ebitor_findEOL(offset); + while (eolOffset - offset >= Ebitor_instance.termWidth) // while terminal row filled + { + offset += Ebitor_instance.termWidth; + if (--numRows == 0) + return offset; + } + // EOL is on current row. + if (eolOffset == Ebitor_instance.bufferFilledSize) // if EOL is EOF + return offset; + offset = eolOffset + 1; // pass \r + // 'offset' is now at start of next logical line, which is displayed at column 0. + if (--numRows == 0) + return offset; + } +} diff --git a/Ebitor.h b/Ebitor.h new file mode 100644 index 0000000..8893218 --- /dev/null +++ b/Ebitor.h @@ -0,0 +1,285 @@ +/* Ebitor.h + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef _H_Ebitor +#define _H_Ebitor + +#ifdef _CMOC_VERSION_ /* If compiling with CMOC. */ +#include + +#else /* To compile with GCC (useful to get more warnings). */ +#include +#include +#include +typedef uint8_t byte; +typedef uint16_t word; +typedef uint8_t BOOL; +enum { FALSE, TRUE }; +void *memichr(const void *s, int c, size_t n); +int memicmp(const void *s1, const void *s2, size_t n); +#endif + + +// Control codes, >= 256. +// Characters in 32..126 and 128..255 are assumed to be printable. +// +enum +{ + ebitor_KEY_ARROW_LEFT = 256, + ebitor_KEY_ARROW_RIGHT, + ebitor_KEY_ARROW_UP, + ebitor_KEY_ARROW_DOWN, + ebitor_KEY_ESCAPE, +}; + + +struct Ebitor; + + +// Clear the entire terminal. +// Does not move the cursor. +// +typedef void (*ebitor_clear)(void); + +// Position the terminal's cursor. +// column, row: Start at 0. +// +typedef void (*ebitor_locateFunc)(byte column, byte row); + +// Obtains the current position of the terminal's cursor. +// *column, *row: Will start at 0. +// +typedef void (*ebitor_getCursorPosFunc)(byte *column, byte *row); + +// Prints an ASCIIZ to the terminal. +// Character '\r' does a carriage return and line feed AND clears +// the rest of the row it is applied to (with spaces). +// Returns FALSE if the printing reached the end of the terminal. +// In this case, the cursor can be assumed to be at the first +// position of the last row of the window. +// +typedef BOOL (*ebitor_printFunc)(const char *str); + +// Prints a given number of characters to the terminal. +// Character '\r' does a carriage return and line feed AND clears +// the rest of the row it is applied to (with spaces). +// No other control code is supported. +// Returns FALSE if the printing reached the end of the terminal. +// +typedef BOOL (*ebitor_printPrefixFunc)(const char *str, size_t prefixLength); + +// Clears the current terminal line from the cursor position to the end of the terminal line. +// Does not move the terminal's cursor. +// +typedef void (*ebitor_clrtoeolFunc)(void); + +// Moves the contents of the terminal up by the given number of rows. +// Fills the bottom row(s) of the terminal with spaces. +// Does not move the terminal's cursor. +// +typedef void (*ebitor_scrollTerminalUpFunc)(byte numRows); + +// Moves the contents of the terminal down by the given number of rows. +// Fills the top row(s) of the terminal with spaces. +// Does not move the terminal's cursor. +// +typedef void (*ebitor_scrollTerminalDownFunc)(byte numRows); + +// Blocks while waiting for a key press on the terminal. +// Returns a printable character, or a control character (e.g., '\b', '\r') or +// a control code (see the ebitor_KEY_* enum). +// +typedef word (*ebitor_waitKeyFunc)(void); + + +enum +{ + INSERT_BUFFER_SIZE = 64, // Must be >= 2. +}; + + +typedef struct InsertBuffer +{ + char buffer[INSERT_BUFFER_SIZE]; + size_t size; // prefix of buffer[] that is filled +} InsertBuffer; + + +typedef struct Ebitor +{ + byte termWidth; // number of columns of the terminal (all the columns used) + byte termHeight; // number of rows of the terminal (all the rows are used) + char *bufferBegin; + char *bufferEnd; + size_t bufferFilledSize; // prefix of [bufferBegin, bufferEnd) that is filled + size_t cursorOffset; // in [bufferBegin, bufferEnd); does not count the chars in insertBuffer + byte savedCursorCol; // cursor column when editing stopped + byte savedCursorRow; // cursor row when editing stopped + byte mode; // MODE_* enum value + InsertBuffer insertBuffer; + + // Terminal-specific functions. + + ebitor_clear clear; + ebitor_locateFunc locate; + ebitor_printFunc print; + ebitor_printPrefixFunc printPrefix; + ebitor_clrtoeolFunc clrtoeol; + ebitor_scrollTerminalUpFunc scrollTerminalUp; + ebitor_scrollTerminalDownFunc scrollTerminalDown; + ebitor_waitKeyFunc waitKey; + ebitor_getCursorPosFunc getCursorPos; + +} Ebitor; + + +// termWidth: Number of columns of the terminal (all the columns are used). +// termHeight: Number of rows of the terminal (all the rows are used). +// See the comments above concerning the behavior expected of the callbacks. +// +void Ebitor_init(char *bufferBegin, size_t bufferSize, + byte termWidth, byte termHeight, + ebitor_clear clear, + ebitor_locateFunc locate, + ebitor_getCursorPosFunc getCursorPos, + ebitor_printFunc print, + ebitor_printPrefixFunc printPrefix, + ebitor_clrtoeolFunc clrtoeol, + ebitor_scrollTerminalUpFunc scrollTerminalUp, + ebitor_scrollTerminalDownFunc scrollTerminalDown, + ebitor_waitKeyFunc waitKey); + + +// Return the address of the lone instance of struct Ebitor. +// Should be used only for self-testing code and/or debugging. +// +Ebitor *Ebitor_getInstance(void); + + +// Tells the editor how much text is currently in its buffer. +// Typically called after filling the buffer passed to Ebitor_init() +// from a file. +// Also puts the cursor at the beginning. +// newLength: Must not exceed the bufferSize parameter passed +// to Ebitor_init(). +// +void Ebitor_setContentLength(size_t newLength); + + +size_t Ebitor_getContentLength(void); + + +// Processes the user's keyboard commands to edit the text. +// Invokes the callbacks given to Ebitor_init(). +// Saves the terminal cursor position upon exiting. +// The next call will start by restoring the terminal cursor to the saved position. +// Other functions can affect the saved position, e.g., Ebitor_findStringAndScrollToShow(). +// startWithRefresh: Start by filling the terminal with what is currently supposed to appear, +// depending on the position of the logical cursor and of the terminal cursor. +// +void Ebitor_processEditing(BOOL startWithRefresh); + + +// Processes the given key as if it had been typed by the user. +// +// key: Must be a printable character or an ebitor_KEY_* value, but NOT ebitor_KEY_ESCAPE. +// +// Ebitor_locateCursorAtSavedPosition() must be called before calling this function; +// then, this function can be called one or more times; when this sequence of calls +// is done, Ebitor_saveCursorPosition() must be called. +// +void Ebitor_processKey(word key); + + +// Simulate a user pressing the up or down arrow multiple times, then refreshes the terminal. +// When the number of repetitions is large, this function is more efficient than calling +// Ebitor_processKey() multiple times, because the terminal would get updated with each call +// to Ebitor_processKey(). +// isUpArrow: TRUE to simulate an up arrow key, FALSE for a down arrow. +// numRepetitions: The number of times to repeat the specified arrow key. +// Allowed to be zero. +// +void Ebitor_processUpOrDownArrowsAndRefresh(BOOL isUpArrow, size_t numRepetitions); + + +// Remembers the current position of the cursor. +// The cursor can later be restored to that position by a call to Ebitor_locateCursorAtSavedPosition(). +// +void Ebitor_saveCursorPosition(void); + + +// Puts the cursor at the position saved by the most recent call to Ebitor_saveCursorPosition(). +// The latter must have been called at least once. +// +void Ebitor_locateCursorAtSavedPosition(void); + + +size_t Ebitor_getLogicalCursorOffset(void); + + +// Determines which logical offset is currently at position (0, 0) on the terminal. +// +size_t Ebitor_getLogicalOffsetAtHome(byte cursorCol, byte cursorRow); + + +// Also puts the terminal cursor at the home position. +// +void Ebitor_setLogicalCursorAtBeginning(void); + + +// Searches for the string in strSearchedFor and if found, scrolls the terminal and +// positions the cursor so that the the found string is visible. +// If the string is not found, the terminal is not scrolled and the cursor is not moved. +// startLogicalOffset: Position in the text where to start the search. +// strSearchedFor: Non empty, NUL-terminated. +// foundLogicalOffset: (Must not be null.) Receives the logical position where the string +// was found, if TRUE is returned. Not filled if FALSE is returned. +// Returns TRUE if found, FALSE if not. +// +BOOL Ebitor_findStringAndScrollToShow(size_t startLogicalOffset, const char *strSearchedFor, + size_t *foundLogicalOffset); + + +// Locates the terminal cursor at the terminal location equivalent to logicalOffsetToShow. +// Makes this terminal cursor the currently saved one. +// Scrolls enough to make sure that 'lengthToShow' characters from logicalOffsetToShow +// are visible in the terminal. +// lengthToShow is allowed to be zero. +// This saved position will be used by the next call to Ebitor_processEditing(). +// Puts the logical cursor at logicalOffsetToShow. +// Scrolls and/or redraws lines as necessary. +// +void Ebitor_scrollToShowLogicalOffset(size_t logicalOffsetToShow, size_t lengthToShow); + + +// Returns the offset of the start of the line that contains the given offset. +// +size_t Ebitor_findSOL(size_t startOffset); + + +// Returns the offset of the end-of-line delimiter of the line that contains the given offset. +// If the current line is the last one and has no such delimiter, then the length of the +// filled buffer is returned. +// +size_t Ebitor_findEOL(size_t startOffset); + + +void Ebitor_shutdown(void); + + +#endif /* _H_Ebitor */ diff --git a/Ebitor_private.h b/Ebitor_private.h new file mode 100644 index 0000000..d2cb203 --- /dev/null +++ b/Ebitor_private.h @@ -0,0 +1,105 @@ +/* Ebitor_private.h + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef _H_Ebitor_private +#define _H_Ebitor_private + +#include "Ebitor.h" + +#include + + +#define min(a, b) ((a) < (b) ? (a) : (b)) + + +extern Ebitor Ebitor_instance; + + +void Ebitor_startCommandMode(void); + + +// key: Must be a printable character in 32..255. +// +void Ebitor_processPrintableChar(word key, byte cursorCol, byte cursorRow); + + +// Prints the edit buffer starting from firstLogicalCharOffsetToPrint and stopping +// when the end of the edit buffer or the end of the window has been reached. +// The printing starts at column 0 of firstRowToFill. +// +void Ebitor_fillTerminalToBottom(size_t firstLogicalCharOffsetToPrint, byte firstRowToFill); + + +// Does not move the logical cursor. +// +void Ebitor_insertChar(char c); + + +// Determines if the region of the text at 'regionOffset' and of the given 'regionLength' +// is entirely visible in the terminal, assuming that the cursor offset is at (cursorCol, cursorRow) +// on the terminal. +// Assumes that the region specification is valid, i.e., it is within the filled buffer. +// Assumes that the insert buffer is empty. +// +// *homeOffset gets filled by Ebitor_getLogicalOffsetAtHome(). +// Returns -1 if region is (entirely or partly) before displayed text (*firstOffWindowOffset does NOT get filled). +// Returns +1 if region is (entirely or partly) after displayed text (*firstOffWindowOffset gets filled). +// Returns 0 if region is entirely in the displayed text (*firstOffWindowOffset gets filled). +// +char Ebitor_isRegionVisible(size_t regionOffset, size_t regionLength, byte cursorCol, byte cursorRow, + size_t *homeOffset, size_t *firstOffWindowOffset); + + +// firstOffWindowOffset: Must designate a position that would be displayed at the start of a window row. +// +size_t Ebitor_countRowsToScrollUp(size_t logicalOffsetToShow, size_t firstOffWindowOffset); + + +// Stores in *logicalOffsetAtStartOfTermRow the number rows by which the terminal +// must be scrolled down to show the given logical offset (logicalOffsetToShow) in the first row. +// homeOffset: Value obtained from Ebitor_getLogicalOffsetAtHome(). +// +size_t Ebitor_countRowsToScrollDown(size_t logicalOffsetToShow, size_t homeOffset, + size_t *logicalOffsetAtStartOfTermRow); + + +void Ebitor_processBackspace(byte cursorCol, byte cursorRow); + + +// solOffset: Must be the start of the edit buffer or be preceded by an EOL terminator. +// Returns solOffset itself if no previous line. +// +size_t Ebitor_findPreviousSOL(size_t solOffset); + + +// firstLogicalCharOffsetToPrint: Must designate a character that is to appear at the start of a terminal row. +// +void Ebitor_fillWindowFromHomeToRow(size_t firstLogicalCharOffsetToPrint, byte numRowsToFill); + + +// startOfRowOffset: Logical offset of a character that is in column 0. +// Returns the logical offset of another character down the text that is also in column 0. +// If there are not enough rows, stops at the last row. +// +size_t Ebitor_goDownRows(size_t startOfRowOffset, size_t numRows); + + +void Ebitor_locateAndSavePos(byte col, byte row); + + +#endif /* _H_Ebitor_private */ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..94a6ad4 --- /dev/null +++ b/Makefile @@ -0,0 +1,216 @@ +# By Pierre Sarrazin +# +# This file is in the public domain. +# +# To compile the demo program and the test program, do "make" or "make all". +# To make a DECB floppy disk image with those programs, do "make dsk". +# +# The OS-9 version needs the BControl library, available from the CMOC home page. +# Before building, create a symlink named 'bcontrol' that points to the +# BControl source code. +# Then to build, do "make TARGET=os9". +# To deploy to the OS-9 hard disk image designtaed by OS9_DSK, make sure that +# the "os9" command of the ToolShed package (version 2.2. or later) is in the path, +# then do "make TARGET=os9 deploy". + +PACKAGE = ebitor +VERSION = 0.1.1 + +TARGET = coco + +# Sources and headers of the library. +CORELIBSRC = \ + Ebitor.c \ + findStringAndScrollToShow.c \ + processPrintableChar.c \ + processBackspace.c \ + scrollToShowLogicalOffset.c +COCOLIBSRC = sg4term.c gimeterm.c +OS9LIBSRC = os9term.c +LIBSRC = $(CORELIBSRC) +CORELIBHEADERS = \ + Ebitor.h \ + Ebitor_private.h \ + Window.h +COCOLIBHEADERS = sg4term.h gimeterm.h +OS9LIBHEADERS = os9term.h +LIBHEADERS = $(CORELIBHEADERS) + +# Add platform-specific sources and headers. +ifeq "$(TARGET)" "coco" +LIBSRC += $(COCOLIBSRC) +LIBHEADERS += $(COCOLIBHEADERS) +else ifeq "$(TARGET)" "os9" +LIBSRC += $(OS9LIBSRC) +LIBHEADERS += $(OS9LIBHEADERS) +else ifeq "$(TARGET)" "usim" +LIBSRC += $(COCOLIBSRC) +LIBHEADERS += $(COCOLIBHEADERS) +endif + +STATICLIB = lib$(PACKAGE).a + +ifeq "$(TARGET)" "coco" +EXEEXT = .bin +else ifeq "$(TARGET)" "usim" +EXEEXT = .srec +else ifeq "$(TARGET)" "os9" +EXEEXT = +endif + +# Interactive demo program where the user can use the editor. +ifneq "$(TARGET)" "usim" +DEMOSRC = ebitdemo.c +DEMOBIN = ebitdemo$(EXEEXT) +endif + +ifeq "$(TARGET)" "coco" + +# Minimal interactive demo that only runs in 32x16 under DECB. +SMOLDEMOSRC = smoldemo.c +SMOLDEMOBIN = smoldemo$(EXEEXT) + +endif + +ifneq "$(TARGET)" "os9" + +# Non-interactive self-test suite (uses sg4term.c). +TESTSRC = ebittest.c +TESTBIN = ebittest$(EXEEXT) + +endif + +# List of sources and headers across all supported platforms. +DISTLIBSRC = $(CORELIBSRC) $(COCOLIBSRC) $(OS9LIBSRC) +DISTLIBHEADERS = $(CORELIBHEADERS) $(COCOLIBHEADERS) $(OS9LIBHEADERS) +DISTFILES = README.md Makefile $(DISTLIBHEADERS) $(DISTLIBSRC) $(DEMOSRC) $(SMOLDEMOSRC) $(TESTSRC) + + +DSK = $(PACKAGE)-$(VERSION)-$(TARGET).dsk + +# Compilation and linking flags. Left empty under OS-9. +# With no --org option, the DECB .bin entry point is $2800. +ifneq "$(TARGET)" "os9" +DEMOORG = --limit=7F00 +SMOLDEMOORG = --limit=7F00 +TESTORG = --limit=7F00 +endif +INTERMEDIATE = #--intermediate + +# Omit -DNDEBUG to enable the assert statements in the library. +NDEBUG = -DNDEBUG + +OPTIM = -fomit-frame-pointer +WARNINGS = -Wfor-condition-sizes #-Wgives-byte +WERROR = -Werror #-Wno-uncalled-static +STACKSPACE = 2048 +CFLAGS = --$(TARGET) $(NDEBUG) $(INTERMEDIATE) $(OPTIM) $(WARNINGS) $(WERROR) \ + -DVERSION=\"$(VERSION)\" --stack-space=$(STACKSPACE) +LDFLAGS = --$(TARGET) $(INTERMEDIATE) + + +DEMOOBJ = $(DEMOSRC:.c=.o) +SMOLDEMOOBJ = $(SMOLDEMOSRC:.c=.o) +TESTOBJ = $(TESTSRC:.c=.o) +LIBOBJ = $(LIBSRC:.c=.o) + +# Libraries possibly needed by this package. +ifeq "$(TARGET)" "os9" +BCONTROL_LIB = bcontrol +BCONTROL_LIB_DIR = bcontrol +DEMO_CFLAGS = -I $(BCONTROL_LIB_DIR) +DEMO_LDFLAGS = -L $(BCONTROL_LIB_DIR) -l$(BCONTROL_LIB) +endif + +# Tools. +CMOC = cmoc +LWAR = lwar +PERL = perl +TAR = tar +WRITECOCOFILE = writecocofile +INSTALL_LOADER = install-coco-boot-loader +XROAR = xroar + +all: $(DEMOBIN) $(SMOLDEMOBIN) $(TESTBIN) + +$(DEMOBIN): $(DEMOOBJ) $(STATICLIB) + $(CMOC) -o $(DEMOBIN) $(LDFLAGS) $(DEMOORG) $(DEMOOBJ) -L. -l$(PACKAGE) $(DEMO_LDFLAGS) + +ifeq "$(TARGET)" "coco" + +$(SMOLDEMOBIN): $(SMOLDEMOOBJ) $(STATICLIB) + $(CMOC) -o $(SMOLDEMOBIN) $(LDFLAGS) $(SMOLDEMOORG) $(SMOLDEMOOBJ) -L. -l$(PACKAGE) + +endif + +ifneq "$(TARGET)" "os9" + +$(TESTBIN): $(TESTOBJ) $(STATICLIB) + $(CMOC) -o $(TESTBIN) $(LDFLAGS) $(TESTORG) $(TESTOBJ) -L. -l$(PACKAGE) + +endif + +$(STATICLIB): $(LIBOBJ) + $(LWAR) --create $(STATICLIB) $(LIBOBJ) + +ifeq "$(TARGET)" "coco" + +$(DSK): dsk + +.PHONY: dsk +dsk: $(DEMOBIN) $(SMOLDEMOBIN) $(TESTBIN) + $(PERL) -e 'print chr(255) x (35*18*256)' > $(DSK) + $(WRITECOCOFILE) $(DSK) $(DEMOBIN) + $(WRITECOCOFILE) $(DSK) $(SMOLDEMOBIN) + $(WRITECOCOFILE) $(DSK) $(TESTBIN) + +endif + +ifeq "$(TARGET)" "os9" +OS9_DSK = 68sdc.vhd +OS9COPY = os9 copy +OS9ATTR = os9 attr -q + +.PHONY: deploy +deploy: $(DEMOBIN) + $(OS9COPY) $(DEMOBIN) $(OS9_DSK),CMDS -r + $(OS9ATTR) -epe $(OS9_DSK),CMDS/$(DEMOBIN) +endif + +%.o: %.c + $(CMOC) -c $(CFLAGS) $(DEMO_CFLAGS) -o $@ $< + +clean: + rm -f $(DEMOBIN) $(DEMOOBJ) \ + $(SMOLDEMOBIN) $(SMOLDEMOOBJ) \ + $(TESTBIN) $(TESTOBJ) \ + $(STATICLIB) $(LIBOBJ) + +distclean: clean + rm -f $(DEMOSRC:.c=.d) $(SMOLDEMOSRC:.c=.d) $(LIBSRC:.c=.d) + +.PHONY: dist distcheck +dist: + $(TAR) -czf $(PACKAGE)-$(VERSION).tar.gz --transform 's,^,$(PACKAGE)-$(VERSION)/,' $(DISTFILES) + +# To do a distcheck with TARGET=os9, also pass BCONTROL_LIB_DIR=FIXME. +# +distcheck: dist + mkdir ,distcheck + $(TAR) -C ,distcheck -xzf $(PACKAGE)-$(VERSION).tar.gz + $(MAKE) -C ,distcheck/$(PACKAGE)-$(VERSION) all dsk + rm -fr ,distcheck + @echo "SUCCESS: $(PACKAGE)-$(VERSION).tar.gz ready for distribution" + +# Automatic prerequisite generation. +%.d: %.c + $(CMOC) --deps-only $(CFLAGS) $(DEMO_CFLAGS) $< + +.PHONY: cleandeps +cleandeps: + rm -f $(DEMOSRC:.c=.d) $(SMOLDEMOSRC:.c=.d) $(TESTSRC:.c=.d) $(LIBSRC:.c=.d) + +include $(DEMOSRC:.c=.d) +include $(SMOLDEMOSRC:.c=.d) +include $(TESTSRC:.c=.d) +include $(LIBSRC:.c=.d) diff --git a/README.md b/README.md new file mode 100644 index 0000000..b0155e7 --- /dev/null +++ b/README.md @@ -0,0 +1,150 @@ +# Ebitor: A reusable text editor C library for 8-bit systems + +Ebitor is a C library that implements a bare bones text editor +that can be adapted to work in any terminal. It features text +search and can be extended by the client program. + +Copyright © 2021-2025 Pierre Sarrazin + +This code comes with ABSOLUTELY NO WARRANTY. + +It is recommended to make backups of any files whose contents +are subjected to this editor. + + +## License: GPLv3 + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . + +See file COPYING. + + +## Introduction + +This is NOT an editor application, it is only a **C library**. +It is intended for programmers who want to integrate a full-screen +editor into their own application. + +This library implements a bare bones editor: It has very few features. +More features can be implemented by the client program. They would +typically be invoked by the user by typing the escape key followed by +another key. For example, the Break key followed by A could be used to +put the cursor at the start of the current line. + + +## Features + +- Used as a library, not a program. +- Terminal functions are entirely provided by the client program. + This allows this editor to be used with any terminal type. +- CoCo 32x16, 40x25, 64x25, 80x25 terminal drivers provided. +- OS-9 40- and 80-column driver provided. + The 32-column terminal is not supported. + (The OS-9 version needs the BControl library, available from + the CMOC home page.) +- Does not require dynamic memory allocation. +- Folds lines that are longer than the terminal width. + Does not support non-folding with horizontal scrolling. +- Only one editor can be operated at a given time. +- Should be compiled with the CMOC compiler. + See . + The code assumes a 64k addressable space. +- The only controls provided are moving the cursor with the arrow + keys, and a backspace key to erase the previous character. + Other controls like page-up, page-down and string search must be + implemented by the client program. + The library offers function Ebitor_findStringAndScrollToShow() + to facilitate the latter. + + +## Building Ebitor + +In a Unix-like development environment, do `make` to compile +for the CoCo, or `make TARGET=os9` to compile for OS-9. + +See `Makefile` for details. + + +## Programming for Ebitor + +See `smoldemo.c` for a minimal example and `ebitdemo.c` for a +substantial one. To compile these demos, do `make`, then run +`smoldemo.bin` or `ebitdemo.bin` on a CoCo or an emulator. + +Either of these demos first #includes header files for one or +more terminal structs, e.g., `sgterm.h` for SG-4 mode (32x16), +`gimeterm.h` for the CoCo 3 text modes, or `os9term.h` for an +OS-9 40- or 80-character terminal. + +Then it #includes `Ebitor.h` to use the editor structs and functions. + +The demo's first step is to fill an ebitor_Window object that defines +the text window that the editor will use. Then it calls Ebitor's +`sg4term_init()` function, in the case of ,`smoldemo.c` to initialize +the 32x16 screen terminal. + +Then `Ebitor_init()` is called to initialize the editor. This call +receives several pointers to several functions that Ebitor will need, +e.g., clearing the terminal, locating the cursor, etc. In the case of +the 32x16 screen, `sg4term_clear` and `sg4term_locate` are passed. + +Then the demo enters its main editing loop. This loop must call +`Ebitor_processEditing()`. This function will operate until the user +presses the escape key, typically Break on a CoCo. + +Then the editing loop shows a prompt to ask the user what to do after +pressing the escape key. Both demos offer to quit the program or to +show a help page. `ebitdemo.c` also offers to find some text. + +If the user presses the escape key again instead of choosing one +of those options, the editing loop just goes back to the call to +`Ebitor_processEditing()`. + +When exiting the editor loop, `Ebitor_shutdown()` must be called. + + +## Porting to other environments + +`Ebitor_init()` accepts pointers to functions that handle the +terminal operations needed by the editor. Porting to a different +type of terminal mainly involves writing functions that fill the +same roles, and passing the addresses of those functions to +`Ebitor_init()`. + +A good starting point can be to make a copy of sg4term.h and +sg4term.c under new names, then reworking the code for the new +terminal type. + + +## Memory requirements + +The Ebitor library code should take about 5100 bytes in memory under DECB, +but about 5400 under OS-9. + +The SG4 (32x16) terminal code (sg4term.c) should take about 1300 bytes. + +The GIME (CoCo 3) terminal code (gimeterm.c) should take about 1300 bytes. + +The OS-9 terminal code should take about 1000 bytes. + +These sizes do not count: +* the text buffer in which the edited text is stored; +* the stack space needed during operation; +* the space that would be used if the assert() statements were enabled + by compiling without NDEBUG. + + +## Version history + +0.1.0 - 2027-07-27 - First public release. diff --git a/Window.h b/Window.h new file mode 100644 index 0000000..3dc4e8e --- /dev/null +++ b/Window.h @@ -0,0 +1,36 @@ +/* Window.h + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef _H_EbitorWindow +#define _H_EbitorWindow + +#include + + +typedef struct ebitor_Window +{ + byte width; + byte height; + byte leftCol; + byte topRow; + byte cursorCol; + byte cursorRow; +} ebitor_Window; + + +#endif /* _H_EbitorWindow */ diff --git a/ebitdemo.c b/ebitdemo.c new file mode 100644 index 0000000..a8aede2 --- /dev/null +++ b/ebitdemo.c @@ -0,0 +1,1041 @@ +/* ebitdemo.c - Demo of the Ebitor full screen text editor. + By Pierre Sarrazin + This file is in the public domain. + + The OS-9 version of this demo shows how to save the editor buffer to a file. +*/ + +#include "sg4term.h" /* 32x16 terminal to be used by the editor */ +#include "gimeterm.h" /* 40/64/80x25 terminal to be used by the editor */ +#include "Ebitor.h" /* the editor */ + +#include + +#ifdef OS9 + +#include "Keyboard.h" /* bcontrol */ +#include "os9term.h" + +#define ESCAPE_KEY_NAME "F1" /* See os9term_waitEditorKey() in os9term.c. */ + + +// Key codes. +enum +{ + KEY_CODE_UP_ARROW = 12, + KEY_CODE_DOWN_ARROW = 10, +}; + +Keyboard keyboard; + +// Keyboard_init() must have been called on 'keyboard'. +// +#define inkey() (Keyboard_poll(&keyboard)) + + +byte +waitKeyOS9(void *cookie) +{ + // A way to block while waiting, instead of polling repeatedly, would be good + // to save CPU time for other processes. + byte key; + do + key = inkey(); + while (key == 0); + return key; +} + + +// Returns a screen mode (32, 40, 80), or 0 upon failure to determine the terminal type. +// +byte +determineOS9ScreenMode(void) +{ + if (os9term_get32x16ScreenBuffer() != NULL) // if 32x16 + return 32; + byte screenTypeCode; + byte err = os9term_getGIMEScreenType(&screenTypeCode); + if (err != 0) + return 0; + return screenTypeCode * 40; +} + + +#else /* not OS9: */ + + +#define ESCAPE_KEY_NAME "BREAK" + + +// Key codes. +enum +{ + KEY_CODE_UP_ARROW = '^', + KEY_CODE_DOWN_ARROW = 10, +}; + + +#endif /* not OS9: */ + + +/////////////////////////////////////////////////////////////// + + +enum +{ + BASIC_TIMER_ADDRESS = 0x112, // incremented 60 times per second by Basic IRQ routine + BASIC_32X16_SCREEN = 0x0400, // address of 32x16 screen buffer + + // CoCo 3 only: + GIME_SCREEN_BLOCK = 0x36, + GIME_SCREEN_BUFFER = 0x6000, // in 64k addressable space; see setupCoCo3MMU() + GIME_SCREEN_VERT_OFFSET = GIME_SCREEN_BLOCK * 1024, // where screen is in 512k space (abs. addr. / 8) + GIME_EDITOR_BG_COLOR = 2, + DEFAULT_TEXT_ATTR = 3 * 8 + GIME_EDITOR_BG_COLOR, // foreground * 8 + background + INVERTED_TEXT_ATTR = 0 * 8 + 4, +}; + + +// Function pointers that depend on the screen mode. +// +static ebitor_clear clearFunc; +static ebitor_locateFunc locateFunc; +static ebitor_printFunc printFunc; +static ebitor_waitKeyFunc waitKeyFunc; +static ebitor_getCursorPosFunc getCursorPosFunc; +static void (*invertColorsFunc)(void); +static void (*eraseCurrentLineFunc)(void); + + +// Contains the edited text. +// +char textBuffer[600]; + + +typedef union WindowUnion +{ + #ifdef _COCO_BASIC_ + ebitor_Window sg4; + gimeterm_Window gime; + #elif defined(OS9) + ebitor_Window os9; + #endif +} WindowUnion; + + +#ifdef _COCO_BASIC_ + + +// Sets the screen mode to a CoCo 3 text screen, with 25 rows. +// Clears the screen to spaces of the background color specified by bgColor. +// numColumns: 40, 64, 80. +// bgColor: CLS color number 1..8 for the screen background. +// borderColor: 0..63 color number. +// +static void +setGimeHiResTextMode(byte numColumns, byte bgColor, byte borderColor) +{ + byte widthField; + switch (numColumns) + { + default: + case 40: widthField = 0x04; break; + case 64: widthField = 0x10; break; + case 80: widthField = 0x14; break; + } + * (byte *) 0xFF90 = 0x4C; // reset CoCo 2 compatible bit + * (byte *) 0xFF98 = 0x03; // text mode + * (byte *) 0xFF99 = 0x21 | widthField; // 200 lines per field, + // width specified by variable, + // 25 rows, + // color attributes enabled + * (byte *) 0xFF9A = borderColor; + * (word *) 0xFF9D = GIME_SCREEN_VERT_OFFSET; + + memset16(GIME_SCREEN_BUFFER, 0x2000 | (bgColor - 1), numColumns * (word) 25); +} + + +#endif /* _COCO_BASIC_ */ + + +// newStatus: Must be shorter than the terminal width. +// Does not move the terminal cursor. +// +static void +setStatus(const ebitor_Window *window, const char *newStatus) +{ + assert(getCursorPosFunc < 0xFF00); // check for corruption of data segment + + byte origCursorCol, origCursorRow; + (*getCursorPosFunc)(&origCursorCol, &origCursorRow); + + (*locateFunc)(0, window->height); // cursor deliberately on row below window + (*invertColorsFunc)(); + (*eraseCurrentLineFunc)(); // also puts cursor at start of line + (*printFunc)(newStatus); + (*invertColorsFunc)(); + + (*locateFunc)(origCursorCol, origCursorRow); +} + + +static void +showHelp(const ebitor_Window *window) +{ + assert(window); + assert(clearFunc); + assert(locateFunc); + assert(printFunc); + assert(waitKeyFunc); + (*clearFunc)(); + setStatus(window, "HELP PAGE"); + (*locateFunc)(0, 0); + (*printFunc)( + "BACKSPACE IS " + #ifdef OS9 + "CTRL+LEFT ARROW" + #else + "THE CLEAR KEY" + #endif + ".\r" + "\r" + "AFTER PRESSING " ESCAPE_KEY_NAME ":\r" + "\r" + "F: FIND SOME TEXT\r" + "N: FIND THE NEXT OCCURRENCE\r" + " OF THE SEARCHED TEXT\r" + "UP/DOWN ARROW: PAGE UP/DOWN\r" + #ifdef OS9 + "L: LOAD FROM A FILE\r" + "S: SAVE TO A FILE\r" + #endif + "Q: QUIT THIS EDITOR\r" + "H: SHOW THIS HELP PAGE\r" + "\r" + "PRESS A KEY TO CONTINUE: "); + (*waitKeyFunc)(); +} + + +// Lets the user type a single line, displayed in inverted colors. +// Returns an ASCIIZ in dest[]. +// The cursor is restored to its original position upon exit. +// +// fieldCol, fieldRow: Relative to the window (fieldRow allowed to be 1 row below window). +// maxLen: Maximum number of characters to accept; +// dest[] must have room for a subsequent NUL terminator. +// Returns TRUE if the user pressed Enter (then dest[] contains the entered ASCIIZ), +// or FALSE if the user pressed Break. +// +static BOOL +getLine(byte fieldCol, byte fieldRow, byte maxLen, char dest[]) +{ + byte origCursorCol, origCursorRow; + (*getCursorPosFunc)(&origCursorCol, &origCursorRow); + + // Print the initial contents of dest[] to the screen field. + // + (*invertColorsFunc)(); + (*locateFunc)(fieldCol, fieldRow); + (*printFunc)(dest); + + byte writer = (byte) strlen(dest); // offset to end of string + word key; + + for (;;) + { + key = (*waitKeyFunc)(); + if (key == ebitor_KEY_ESCAPE) + break; + if (key == '\r') // Enter + break; + switch (key) + { + case '\b': + if (writer == 0) + break; + --writer; + (*locateFunc)(fieldCol + writer, fieldRow); + (*printFunc)(" "); + (*locateFunc)(fieldCol + writer, fieldRow); + break; + default: + // Add character if printable and there is still room. + if (key < 128 && (byte) key > 32 && (byte) key != 127 && writer < maxLen) + { + char keyString[2] = { (char) key, '\0' }; + (*printFunc)(keyString); + dest[writer] = (char) key; + ++writer; + } + } + } + + (*invertColorsFunc)(); + (*locateFunc)(origCursorCol, origCursorRow); + + if (key == ebitor_KEY_ESCAPE) + return FALSE; + dest[writer] = '\0'; + return TRUE; +} + + +static size_t searchStartOffset; // position where handleFind() starts searching for string +static size_t foundLogicalOffset; // position where handleFind() last found its target string + +const char findPrompt[] = "FIND: "; +const char filenamePrompt[] = "FILENAME: "; + +enum +{ + MAX_WINDOW_WIDTH = 80, // of all screen modes supported by this demo + FIND_PROMPT_LEN = sizeof(findPrompt) - 1, + TARGET_STRING_MAX_LEN = MAX_WINDOW_WIDTH - FIND_PROMPT_LEN - 1, // leaves one column for the cursor + +#ifdef OS9 + + FILENAME_PROMPT_LEN = sizeof(filenamePrompt) - 1, + FILENAME_MAX_LEN = MAX_WINDOW_WIDTH - FILENAME_PROMPT_LEN - 1, // leaves one column for the cursor + +#endif +}; + + +// These buffers are global so that the previously entered string is remembered +// the next find Find or Save is used. +// These buffers are initialized to all NULs before main(). +// +static char strSearchedFor[TARGET_STRING_MAX_LEN + 1]; + +#ifdef OS9 + +static char filename[FILENAME_MAX_LEN + 1]; + +#endif + + +// Returns TRUE if this function set a status that should be left visible for the user. +// Reads findPrompt. +// Modifies searchStartOffset, strSearchedFor[]. +// +static BOOL +handleFind(const ebitor_Window *window, BOOL newFind) +{ + if (newFind) + { + setStatus(window, findPrompt); + if (!getLine(FIND_PROMPT_LEN, window->height, window->width - FIND_PROMPT_LEN - 1, strSearchedFor)) + return FALSE; + searchStartOffset = Ebitor_getLogicalCursorOffset(); + } + else + { + size_t curOffset = Ebitor_getLogicalCursorOffset(); + if (curOffset == foundLogicalOffset) // if cursor did not move since last find + searchStartOffset = foundLogicalOffset + 1; // start "next find" after current find + else + searchStartOffset = curOffset; // cursor moved, so find "next" from new cursor pos + } + + BOOL found = Ebitor_findStringAndScrollToShow(searchStartOffset, strSearchedFor, &foundLogicalOffset); + if (found) + { + setStatus(window, "FOUND"); + return TRUE; + } + + setStatus(window, "NOT FOUND"); + return TRUE; +} + + +#ifdef OS9 + + +byte +getOpenFileSize(unsigned char fd, unsigned long *sizeInBytes) +{ + unsigned long tmp; + unsigned char errorCode; + asm + { + pshs u,y ; protect data segment pointer (Y) and frame pointer (U) against OS-9 call; + ; cannot refer to local C vars when U modified + + lda :fd ; path number + ldb #2 ; function code 2 + os9 $8D ; I$GetStt + bcs @error + clrb +@error + tfr u,y ; save low word of file size in Y; free up U + ldu 2,s ; restore ability to refer to C local vars + stx :tmp[0] ; store high word of file size in local C var + sty :tmp[2] ; store low word + stb :errorCode + + puls y,u ; restore Y, U already restored (discards the 4 bytes pushed) + } + if (errorCode == 0) // if success + *sizeInBytes = tmp; + return errorCode; +} + + +// filePath: Must end with '\r'. +// Returns an error code upon failure, 0 upon success. +// *errorPhase receives: +// 1 if error happened on file open; +// 2 on reading; +// 3 on closing; +// 4 if the file size could not be obtained; +// 5 if the file is too large for maxBufferLength. +// *numBytesRead receives the number of bytes effectively read, upon success. +// *fileSizeInBytes receives the file size upon success and error codes 2 to 5. +// +byte +loadFileToBuffer(const char *filePath, void *buffer, size_t maxBufferLength, + unsigned long *fileSizeInBytes, byte *errorPhase, size_t *numBytesRead) +{ + unsigned char fd, errorCode; + + // Open the file in read mode. + asm + { + lda #$01 ; A = read mode + ldx :filePath + os9 $84 ; I$Open + bcs @error + clrb + sta :fd +@error + stb :errorCode + } + + if (errorCode != 0) // if open failed + { + *errorPhase = 1; + return errorCode; + } + + errorCode = getOpenFileSize(fd, fileSizeInBytes); + if (errorCode != 0) + { + *errorPhase = 4; + return errorCode; + } + + if (*fileSizeInBytes > maxBufferLength) + { + *errorPhase = 5; + return 207; // hack: return E$MemFul + } + + // Load bytes from the file to the buffer. + *numBytesRead = 0; + asm + { + lda :fd ; path number + ldx :buffer ; address where to store the bytes + pshs y ; save global data ptr; cannot refer to globals for now + ldy :maxBufferLength ; number of bytes to read + os9 $89 ; I$Read + bcs @error + clrb + sty [:numBytesRead] ; store in *numBytesRead +@error + stb :errorCode + puls y ; restore global data ptr; can refer to globals again + } + + if (errorCode != 0) + { + *errorPhase = 2; + // Do not return because we need to close the file. + } + + unsigned char closeErrorCode; + asm + { + lda :fd ; path number + os9 $8F ; I$Close + bcs @error + clrb +@error + stb :closeErrorCode + } + + if (errorCode != 0) // if read error + return errorCode; + if (closeErrorCode != 0) + { + *errorPhase = 3; + return closeErrorCode; + } + + *errorPhase = 0; // success + return 0; +} + + +// Calls setStatus() before returning. +// +static void +loadFromFile(const ebitor_Window *window) +{ + setStatus(window, filenamePrompt); + + if (!getLine(FILENAME_PROMPT_LEN, window->height, window->width - FILENAME_PROMPT_LEN - 1, filename)) + { + setStatus(window, "TEXT NOT LOADED"); + return; + } + + size_t filenameLen = strlen(filename); + filename[filenameLen] = '\r'; // terminator required by OS-9 I$Open + byte errorPhase; + unsigned long fileSizeInBytes; + size_t numBytesRead; + byte errorCode = loadFileToBuffer(filename, textBuffer, sizeof(textBuffer) - 1, + &fileSizeInBytes, &errorPhase, &numBytesRead); + + filename[filenameLen] = '\0'; // restore terminator (required by next call to getLine()) + + char status[MAX_WINDOW_WIDTH]; + + if (errorCode != 0) + { + if (errorPhase == 4) + sprintf(status, "FAILED TO GET FILE SIZE"); + else if (errorPhase == 5) + sprintf(status, "FILE TOO BIG (%lu VS MAX %u)", fileSizeInBytes, sizeof(textBuffer) - 1); + else + sprintf(status, "ERROR #%u WHEN %sING [%lu]", + errorCode, + errorPhase == 1 ? "OPEN" : (errorPhase == 2 ? "READ" : "CLOS"), + fileSizeInBytes); + } + else + { + sprintf(status, "READ ALL %u CHARACTERS", numBytesRead); + + // Tell the editor that it now has text. + Ebitor_setContentLength(numBytesRead); + } + + setStatus(window, status); +} + + +// filePath: Must end with '\r'. +// Returns an error code upon failure, 0 upon success. +// *errorPhase receives: +// 1 if error happened on file creation; +// 2 on reading; +// 3 on closing. +// *numBytesWritten receives the number of bytes effectively written, upon success. +// +byte +createFileFromBuffer(const char *filePath, const void *buffer, size_t bufferLength, byte *errorPhase, size_t *numBytesWritten) +{ + unsigned char fd, errorCode; + asm + { + ldd #$0203 ; A = write mode; B = readable, writable, sharable + ldx :filePath + os9 $83 ; I$Create + bcs @error + clrb + sta :fd +@error + stb :errorCode + } + + if (errorCode != 0) + { + *errorPhase = 1; + return errorCode; + } + + *numBytesWritten = 0; + asm + { + lda :fd ; path number + ldx :buffer ; address of bytes to write + pshs y ; save global data ptr; cannot refer to globals for now + ldy :bufferLength ; number of bytes to write + os9 $8A ; I$Write + bcs @error + clrb + sty [:numBytesWritten] ; store in *numBytesWritten +@error + stb :errorCode + puls y ; restore global data ptr; can refer to globals again + } + + if (errorCode != 0) + { + *errorPhase = 2; + // Do not return because we need to close the file. + } + + unsigned char closeErrorCode; + asm + { + lda :fd ; path number + os9 $8F ; I$Close + bcs @error + clrb +@error + stb :closeErrorCode + } + + if (errorCode != 0) // if write error + return errorCode; + if (closeErrorCode != 0) + { + *errorPhase = 3; + return closeErrorCode; + } + + *errorPhase = 0; // success + return 0; +} + + +// Calls setStatus() before returning. +// +static void +saveToFile(const ebitor_Window *window) +{ + setStatus(window, filenamePrompt); + + if (!getLine(FILENAME_PROMPT_LEN, window->height, window->width - FILENAME_PROMPT_LEN - 1, filename)) + { + setStatus(window, "TEXT NOT SAVED"); + return; + } + + //FIXME: Check if file already exists, prompt for overwrite. + + setStatus(window, "SAVING..."); + + size_t saveFilenameLen = strlen(filename); + filename[saveFilenameLen] = '\r'; // terminator required by OS-9 I$Create + byte errorPhase; + size_t numBytesWritten; + byte errorCode = createFileFromBuffer(filename, textBuffer, Ebitor_getContentLength(), &errorPhase, &numBytesWritten); + + filename[saveFilenameLen] = '\0'; // restore terminator (required by next call to getLine()) + + char status[MAX_WINDOW_WIDTH]; + + if (errorCode != 0) + sprintf(status, "SAVE FAILED: ERROR #%u WHEN %sING", + errorCode, + errorPhase == 1 ? "CREAT" : (errorPhase == 2 ? "WRIT" : "CLOS")); + else if (numBytesWritten != Ebitor_getContentLength()) + sprintf(status, "FAILED: WROTE %u of %u", numBytesWritten, Ebitor_getContentLength()); + else + sprintf(status, "WROTE ALL %u CHARACTERS", numBytesWritten); + + setStatus(window, status); +} + + +#endif /* OS9 */ + + +#ifdef _COCO_BASIC_ + + +static byte +inkey1(void *cookie) +{ + return inkey(); +} + + +#ifndef NDEBUG /* Condition need to avoid warning on failedAssertHandler_gime() not getting called. */ + +static void +failedAssertHandler_gime(const char *file, int lineno, const char *condition) +{ + char temp[256]; + sprintf(temp, "[ASSERT FAILED at %s:%d: %s]", file, lineno, condition); + gimeterm_locate(0, 0); + gimeterm_print(temp); + for (;;) + ; +} + +#endif + + +#endif + + +// screenMode: Must be 32, 40, 64 or 80. +// window: Pointer to an object that gets filled with the definition of +// the text window. +// Must be the appropriate ebitor_Window field of *windowUnion. +// Returns TRUE upon success. +// Fills globals, locateFunc, getCursorPosFunc, etc. +// +static BOOL +initEbitor(byte screenMode, WindowUnion *windowUnion, ebitor_Window *window) +{ + window->cursorCol = window->cursorRow = 0; + + // Specify a window for the editor. + // Excludes the status line, which this demo renders below this window. + // + #ifdef _COCO_BASIC_ + byte numRows = screenMode == 32 ? 16 : 25; + // A border is left unused, to show that the sg4 and gime drivers + // can use a subwindow of the screen. + window->width = screenMode - 2; + window->height = numRows - 3; + window->leftCol = 1; + window->topRow = 1; + + if (screenMode != 32) + { + if (!isCoCo3) + { + printf("MODE %u NOT SUPPORTED ON A COCO 1 OR 2\n", screenMode); + return FALSE; + } + windowUnion->gime.textAttribute = DEFAULT_TEXT_ATTR; + windowUnion->gime.invertedTextAttribute = INVERTED_TEXT_ATTR; + } + + switch (screenMode) + { + case 32: + width(32); // by SECB + cls(3); + sg4term_init((char *) BASIC_32X16_SCREEN, window, + inkey1, NULL, (word *) BASIC_TIMER_ADDRESS); + + Ebitor_init(textBuffer, sizeof(textBuffer), + window->width, window->height, + clearFunc = sg4term_clear, + locateFunc = sg4term_locate, + getCursorPosFunc = sg4term_getCursorPos, + printFunc = sg4term_print, + sg4term_printPrefix, + sg4term_clrtoeol, + sg4term_scrollWindowUp, + sg4term_scrollWindowDown, + waitKeyFunc = sg4term_waitEditorKey); + invertColorsFunc = sg4term_invertColors; + eraseCurrentLineFunc = sg4term_eraseCurrentLine; + return TRUE; + + case 40: + case 64: + case 80: + setGimeHiResTextMode(screenMode, 8, 7); + gimeterm_init(GIME_SCREEN_BUFFER, screenMode, &windowUnion->gime, + inkey1, NULL, (word *) BASIC_TIMER_ADDRESS); + + _SetFailedAssertHandler(failedAssertHandler_gime); + + Ebitor_init(textBuffer, sizeof(textBuffer), + window->width, window->height, + clearFunc = gimeterm_clear, + locateFunc = gimeterm_locate, + getCursorPosFunc = gimeterm_getCursorPos, + printFunc = gimeterm_print, + gimeterm_printPrefix, + gimeterm_clrtoeol, + gimeterm_scrollWindowUp, + gimeterm_scrollWindowDown, + waitKeyFunc = gimeterm_waitEditorKey); + invertColorsFunc = gimeterm_invertColors; + eraseCurrentLineFunc = gimeterm_eraseCurrentLine; + return TRUE; + + default: + printf("UNSUPPORTED SCREEN MODE %u\n", screenMode); + return FALSE; + } + + #elif defined(OS9) + + window->width = screenMode; + window->height = 24; + window->leftCol = 0; + window->topRow = 0; + + byte err = os9term_init(window->width, window->height, + window->leftCol, window->topRow, + waitKeyOS9, NULL); + if (err != 0) + { + printf("Failed to initialize support for this terminal: error #%u.\n", err); + return FALSE; + } + + Ebitor_init(textBuffer, sizeof(textBuffer), + window->width, window->height, + clearFunc = os9term_clear, + locateFunc = os9term_locate, + getCursorPosFunc = os9term_getCursorPos, + printFunc = os9term_print, + os9term_printPrefix, + os9term_clrtoeol, + os9term_scrollWindowUp, + os9term_scrollWindowDown, + waitKeyFunc = os9term_waitEditorKey); + invertColorsFunc = os9term_invertColors; + eraseCurrentLineFunc = os9term_eraseCurrentLine; + + return TRUE; + + #endif +} + + +// Does not animate a cursor. +// +byte +waitUpperCaseKey(void) +{ + byte key; + while ((key = (byte) toupper(inkey())) == 0) + ; + return key; +} + + +BOOL +askConfirmation(const ebitor_Window *window) +{ + setStatus(window, "REALLY QUIT? (Y/N)"); + byte key = waitUpperCaseKey(); + return key == 'Y'; +} + + +BOOL +work(byte screenMode) +{ + Ebitor *editor = Ebitor_getInstance(); + + WindowUnion windowUnion; + + ebitor_Window *window = + #ifdef _COCO_BASIC_ + (screenMode == 32 ? &windowUnion.sg4 : &windowUnion.gime.window) + #elif defined(OS9) + &windowUnion.os9 + #endif + ; + + if (!initEbitor(screenMode, &windowUnion, window)) + return FALSE; + + // Main editing loop. + // + for (BOOL refresh = TRUE, resetStatus = TRUE; ; ) + { + if (resetStatus) + setStatus(window, "PRESS " ESCAPE_KEY_NAME " FOR MENU"); + else + resetStatus = TRUE; + + Ebitor_processEditing(refresh); + + refresh = FALSE; + + setStatus(window, "F=FIND, Q=QUIT, H=HELP"); + byte key = waitUpperCaseKey(); + if (key == 3) // "escape" key + continue; // back to processing + if (key == 'Q') + { + if (askConfirmation(window)) + break; // quit + continue; // back to processing + } + switch ((char) key) + { + case KEY_CODE_UP_ARROW: + Ebitor_processUpOrDownArrowsAndRefresh(TRUE, window->height); + break; + case KEY_CODE_DOWN_ARROW: + Ebitor_processUpOrDownArrowsAndRefresh(FALSE, window->height); + break; + case 'F': + resetStatus = ! handleFind(window, TRUE); + break; + case 'N': + resetStatus = ! handleFind(window, FALSE); + break; + #ifdef OS9 + case 'L': + loadFromFile(window); + refresh = TRUE; + resetStatus = FALSE; + break; + case 'S': + saveToFile(window); + resetStatus = FALSE; + break; + #endif + case 'H': + showHelp(window); + refresh = TRUE; + break; + } + } + + Ebitor_shutdown(); + return TRUE; +} + + +#ifdef _COCO_BASIC_ + + +void +delay(unsigned ticks) +{ + for (unsigned limit = getTimer() + ticks; getTimer() != limit; ) + ; +} + + +// Returns 32, 40, 64, 80. +// +byte +chooseScreenMode(void) +{ + printf("[3] 32X16\n" + "[4] 40X25\n" + "[6] 64X25\n" + "[8] 80X25\n" + "MODE? "); + for (;;) + { + byte screenMode; + word key = waitkey(TRUE); + switch (key) + { + case '3': screenMode = 32; break; + case '4': screenMode = 40; break; + case '6': screenMode = 64; break; + case '8': screenMode = 80; break; + default: key = 0; + } + if (key == 0) // if invalid response + continue; + printf("%c\n", (char) key); + delay(30); + return screenMode; + } +} + + +static void *originalS; + + +BOOL +setupCoCo3MMU(void) +{ + /* + Assume that PCLEAR 1 has been done before executing this program. + S is assumed to be in $7Fxx. + Save S in a global. + Put S at the end of the graphics page. + At $6000 (GIME_SCREEN_BUFFER), map in an 8k MMU page that will contain the GIME text screen. + (This will preserve the page that contains the Basic stack space.) + Run the editor. + When it ends, map the original MMU page at $6000, restoring the Basic stack space. + Load S from the global. + Quit the program. + */ + disableInterrupts(); + asm + { + sts :originalS ; uses U register to refer to C local variable + lds <$BC ; GRPRAM: Start of graphics page + leas 1536,s ; skip 1 PMODE page (assuming PCLEAR 1) + ldb #GIME_SCREEN_BLOCK ; block used by SECB to store 40/80-column screen + stb $FFA3 ; bank at $6000 + } + enableInterrupts(); + + byte screenMode = chooseScreenMode(); + BOOL success = work(screenMode); + + disableInterrupts(); + asm + { + ldb #$3B ; block that is normally mapped at $6000 + stb $FFA3 ; bank at $6000 + lds :originalS ; uses U register to refer to C local variable + } + enableInterrupts(); + + width(32); + return success; +} + + +#endif /* _COCO_BASIC_ */ + + +int +main() +{ + BOOL success = FALSE; + + #ifdef OS9 + // This reference to OS9RawTerminal_init() helps prove that the bcontrol library + // was compiled with TARGET=os9. + // If it was compiled for the wrong target platform, then building this program + // will fail with this linking error: + // External symbol _OS9RawTerminal_init not found in ebitdemo.o:code + // + assert(OS9RawTerminal_init != NULL); + + //printf("main: %s %s\n", __DATE__, __TIME__); + Keyboard_init(&keyboard); + + byte screenMode = determineOS9ScreenMode(); + if (screenMode != 40 && screenMode != 80) + { + printf("Error: This terminal type is\n" + "not supported by this editor.\n"); + return FALSE; + } + + success = work(screenMode); + + #else + initCoCoSupport(); // initializes 'isCoCo3' + width(32); + rgb(); + + if (isCoCo3) + success = setupCoCo3MMU(); // calls work() + else + success = work(32); + + #endif + + #ifdef _COCO_BASIC_ + cls(255); + #elif defined(OS9) + if (success) // don't clear screen upon error, b/c error msg has just been printed + putchar(12); // clear whole screen + Keyboard_shutdown(&keyboard); + #endif + + return 0; // returning 1 on OS-9 causes "Unconditional Abort" error message +} diff --git a/ebittest.c b/ebittest.c new file mode 100644 index 0000000..07e85cf --- /dev/null +++ b/ebittest.c @@ -0,0 +1,818 @@ +/* ebittest.c + + This file is in the public domain. +*/ + +#undef NDEBUG /* enable asserts */ + +#include "sg4term.h" +#include "Ebitor_private.h" + + +/////////////////////////////////////////////////////////////// + + +static const char *predefinedKeyPresses = ""; + + +static byte +readPredefinedKeyOrKeyboard(void) +{ + if (*predefinedKeyPresses != '\0') + return *predefinedKeyPresses++; + return 0; // not supposed to be reached +} + + +static const ebitor_Window testWindow = { 32, 15, 0, 0, 0, 0 }; + + +static size_t currentTestIndex; + + +static byte +inkey1(void *cookie) +{ + byte code = readPredefinedKeyOrKeyboard(); + return code; +} + + +// Declarations of private functions used by the self tests. +// +// char Ebitor_isRegionVisible(size_t regionOffset, size_t regionLength, byte cursorCol, byte cursorRow, +// size_t *homeOffset, size_t *firstOffScreenOffset); +// size_t Ebitor_countRowsToScrollUp(size_t logicalOffsetToShow, size_t firstOffScreenOffset); +// size_t Ebitor_countRowsToScrollDown(size_t logicalOffsetToShow, size_t homeOffset, size_t *logicalOffsetAtStartOfTermRow); + + +static char textBuffer[600]; + + +static const char *initContents = "" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ01234\r" + "L0\r" + "L1\r" + "L2\r" + "L3\r" + "L4\r" + "L5\r" + "L6\r" + "L7\r" + "L8\r" + "L9\r" + "L10\r" + "L11\r" + "L12\r" + "L13\r" + "L14ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz\r" + "L15\r" + "L16\r" + "L17\r" + ; + + +// Uses initContents. Fills textBuffer. Calls Ebitor_setContentLength(). +// +static void +setRepeatedTestContent(size_t numRepetitions) +{ + size_t initContentLength = strlen(initContents); + assert(initContentLength < sizeof(textBuffer) / numRepetitions); + char *dest = textBuffer; + for (size_t i = numRepetitions; i--; dest += initContentLength) + memcpy(dest, initContents, initContentLength); + Ebitor_setContentLength(initContentLength * numRepetitions); +} + + +//: Tested: Ebitor_setContentLength +// +static void +setTestContent(void) +{ + setRepeatedTestContent(1); +} + + +static void +test_scrollWindowUp(void) +{ + Ebitor *editor = Ebitor_getInstance(); + setTestContent(); + + // Show the text. + predefinedKeyPresses = "\x03"; + Ebitor_processEditing(TRUE); + + char text[3]; + sg4term_getChars(0, 14, text, sizeof(text)); + assert(memcmp(text, "L13", sizeof(text)) == 0); + + sg4term_scrollWindowUp(1); + + sg4term_getChars(0, 13, text, sizeof(text)); + assert(memcmp(text, "L13", sizeof(text)) == 0); // L13 moved one row up + sg4term_getChars(0, 14, text, sizeof(text)); + assert(memcmp(text, " ", sizeof(text)) == 0); // bottom row cleared +} + + +static void +test_scrollWindowDown(void) +{ + Ebitor *editor = Ebitor_getInstance(); + setTestContent(); + + // Show the text. + predefinedKeyPresses = "\x03"; + Ebitor_processEditing(TRUE); + + char text[3]; + sg4term_getChars(0, 0, text, sizeof(text)); + assert(memcmp(text, "ABC", sizeof(text)) == 0); + + sg4term_scrollWindowDown(1); + + sg4term_getChars(0, 1, text, sizeof(text)); + assert(memcmp(text, "ABC", sizeof(text)) == 0); // ABC moved one row down + sg4term_getChars(0, 0, text, sizeof(text)); + assert(memcmp(text, " ", sizeof(text)) == 0); // top row cleared +} + + +//: Tested: Ebitor_isRegionVisible +//: Tested: Ebitor_countRowsToScrollUp +// +static void +test_countRowsToScrollUp(void) +{ + Ebitor *editor = Ebitor_getInstance(); + setTestContent(); + + size_t homeOffset = 0xFEDC, firstOffScreenOffset = 0xEDCB; // dummy values to be overwritten + + // Check that a substring near the end of the text is not displayed. + // + char *p = strstr(editor->bufferBegin, "L16\r"); + assert(p); + size_t regionOffset = p - editor->bufferBegin; + printf("[regionOffset=%u]", regionOffset); + char code = Ebitor_isRegionVisible(regionOffset, 3, editor->savedCursorCol, editor->savedCursorRow, + &homeOffset, &firstOffScreenOffset); + printf("[C=%d,H=%u,F=%u]", code, homeOffset, firstOffScreenOffset); + assert(code == 1); // substring comes after the displayed text + assert(homeOffset == 0); // top of screen shows top of text + size_t expectedFirstOffScreenOffset = strstr(editor->bufferBegin, "L14ABC") - editor->bufferBegin; + assert(firstOffScreenOffset == expectedFirstOffScreenOffset); + + // Test that a character not at the start of a terminal row can be scrolled up to. + // + size_t logicalOffsetToShow = regionOffset + 1; + size_t numTermRows = Ebitor_countRowsToScrollUp(logicalOffsetToShow, firstOffScreenOffset); + printf("[N=%u]", numTermRows); + assert(numTermRows == 5); +} + + +//: Tested: Ebitor_isRegionVisible +//: Tested: Ebitor_countRowsToScrollDown +// +static void +test_countRowsToScrollDown(void) +{ + Ebitor *editor = Ebitor_getInstance(); + setTestContent(); + + // Show the text and move the cursor below the initially displayed text. + predefinedKeyPresses = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\x03"; + Ebitor_processEditing(TRUE); + + // Cursor is at bottom left of editable area. + assert(editor->savedCursorCol == 0); + assert(editor->savedCursorRow == 14); + + // Logical cursor is at end of text. + assert(editor->cursorOffset == editor->bufferFilledSize); + + size_t homeOffset = 0, firstOffScreenOffset = 0xFEDC; + + // Check that a substring near the beginning of the text is not displayed. + // + char *p = strstr(editor->bufferBegin, "L2\r"); + assert(p); + size_t regionOffset = p - editor->bufferBegin; + printf("[regionOffset=%u]", regionOffset); + char code = Ebitor_isRegionVisible(regionOffset, 2, editor->savedCursorCol, editor->savedCursorRow, + &homeOffset, &firstOffScreenOffset); + printf("[C=%d,H=%u,F=%u]", code, homeOffset, firstOffScreenOffset); + assert(code == -1); // substring comes before the displayed text + assert(homeOffset == strstr(editor->bufferBegin, "L6\r") - editor->bufferBegin); + assert(firstOffScreenOffset == 0xFEDC); // dummy value not touched + + size_t logicalOffsetToShow = regionOffset + 1; + size_t logicalOffsetAtStartOfTermRow = 0; + size_t numTermRows = Ebitor_countRowsToScrollDown(logicalOffsetToShow, homeOffset, &logicalOffsetAtStartOfTermRow); + printf("[N=%u,A=%u]", numTermRows, logicalOffsetAtStartOfTermRow); + assert(numTermRows == 4); + assert(logicalOffsetAtStartOfTermRow == regionOffset); // b/c regionOffset is at start of line ("L2") +} + + +//: Tested: Ebitor_scrollToShowLogicalOffset +//: Tested: Ebitor_getLogicalOffsetAtHome +//: Tested: Ebitor_isRegionVisible +// +static void +test_scrollToShowLogicalOffset(void) +{ + Ebitor *editor = Ebitor_getInstance(); + setTestContent(); + + // Initial screen shows top of text. + // Target a line that is below the screen. + // + char *p = strstr(editor->bufferBegin, "L16\r"); + assert(p); + size_t offsetInLine = 1; + size_t regionOffset = p - editor->bufferBegin + offsetInLine; + size_t regionLen = 2; + //printf("[regionOffset=%u]", regionOffset); + + // Show the text. + predefinedKeyPresses = "\x03"; + Ebitor_processEditing(TRUE); + + Ebitor_scrollToShowLogicalOffset(regionOffset, regionLen); + + byte cursorCol, cursorRow; + editor->getCursorPos(&cursorCol, &cursorRow); + //printf("[%u,%u]", cursorCol, cursorRow); + assert(cursorCol == offsetInLine); + assert(cursorRow == editor->termHeight - 1); // last window row + + size_t h = Ebitor_getLogicalOffsetAtHome(cursorCol, cursorRow); + //printf("[HO=%u]", h); + assert(h == strstr(editor->bufferBegin, "L4\r") - editor->bufferBegin); + + size_t homeOffset = 0xFFFF, firstOffScreenOffset = 0xFFFF; + char code = Ebitor_isRegionVisible(regionOffset, regionLen, cursorCol, cursorRow, + &homeOffset, &firstOffScreenOffset); + //printf("[%d,%u,%u]", code, homeOffset, firstOffScreenOffset); + assert(code == 0); // region now visible + assert(homeOffset == h); + assert(firstOffScreenOffset == strstr(editor->bufferBegin, "L17\r") - editor->bufferBegin); + + // Check that terminal contents got scrolled up. + char text[3]; + sg4term_getChars(0, 7, text, sizeof(text)); + assert(memcmp(text, "L11", sizeof(text)) == 0); + + // Now scroll up to a line that is currently above the displayed text. + // + regionOffset = strstr(editor->bufferBegin, "L2\r") - editor->bufferBegin + offsetInLine; + regionLen = 1; // just the "2" + //printf("[regionOffset=%u]", regionOffset); + code = Ebitor_isRegionVisible(regionOffset, regionLen, cursorCol, cursorRow, + &homeOffset, &firstOffScreenOffset); + //printf("[%d,%u,%u]", code, homeOffset, firstOffScreenOffset); + assert(code == -1); // "L2" line is above the displayed text + assert(homeOffset == h); + assert(firstOffScreenOffset == strstr(editor->bufferBegin, "L17\r") - editor->bufferBegin); + + Ebitor_scrollToShowLogicalOffset(regionOffset, regionLen); + + editor->getCursorPos(&cursorCol, &cursorRow); + //printf("[%u,%u]", cursorCol, cursorRow); + assert(cursorCol == offsetInLine); + assert(cursorRow == 0); + + homeOffset = 0xFFFF, firstOffScreenOffset = 0xFFFF; + code = Ebitor_isRegionVisible(regionOffset, regionLen, cursorCol, cursorRow, + &homeOffset, &firstOffScreenOffset); + //printf("[%d,%u,%u]", code, homeOffset, firstOffScreenOffset); + assert(code == 0); // region now visible + assert(homeOffset == regionOffset - offsetInLine); + assert(firstOffScreenOffset == strstr(editor->bufferBegin, "L15\r") - editor->bufferBegin); + + // Check that terminal contents got scrolled down. + sg4term_getChars(0, 7, text, sizeof(text)); + assert(memcmp(text, "L9 ", sizeof(text)) == 0); +} + + +//: Tested: Ebitor_findStringAndScrollToShow +// +static void +test_findStringAndScrollToShow(void) +{ + Ebitor *editor = Ebitor_getInstance(); + setTestContent(); + + // Show the text. + predefinedKeyPresses = "\x03"; + Ebitor_processEditing(TRUE); + + BOOL found; + size_t foundLogicalOffset; + + // Search for a string below the displayed text. + + found = Ebitor_findStringAndScrollToShow(0, "l16", &foundLogicalOffset); + assert(found); + + char text[3]; + sg4term_getChars(0, 14, text, sizeof(text)); + assert(memcmp(text, "L16", sizeof(text)) == 0); + + byte cursorCol, cursorRow; + editor->getCursorPos(&cursorCol, &cursorRow); + assert(cursorCol == 0 && cursorRow == 14); + assert(memcmp(editor->bufferBegin + editor->cursorOffset, "L16\r", 4) == 0); + + // Search for a string above the displayed text. + + found = Ebitor_findStringAndScrollToShow(0, "l2", &foundLogicalOffset); + assert(found); + + sg4term_getChars(0, 0, text, sizeof(text)); + assert(memcmp(text, "L2 ", sizeof(text)) == 0); + + editor->getCursorPos(&cursorCol, &cursorRow); + assert(cursorCol == 0 && cursorRow == 0); + assert(memcmp(editor->bufferBegin + editor->cursorOffset, "L2\r", 3) == 0); + + // Search for a string already in the displayed text. + found = Ebitor_findStringAndScrollToShow(0, "678", &foundLogicalOffset); + assert(found); + + sg4term_getChars(3, 13, text, sizeof(text)); + assert(memcmp(text, "678", sizeof(text)) == 0); + assert(memcmp(editor->bufferBegin + editor->cursorOffset, "678", 3) == 0); + + // Search for a string that is not in the text. + + found = Ebitor_findStringAndScrollToShow(0, "ABSENT", &foundLogicalOffset); + assert(!found); + + sg4term_getChars(3, 13, text, sizeof(text)); + assert(memcmp(text, "678", sizeof(text)) == 0); + + editor->getCursorPos(&cursorCol, &cursorRow); + assert(cursorCol == 3 && cursorRow == 13); + assert(memcmp(editor->bufferBegin + editor->cursorOffset, "678", 3) == 0); + + size_t homeOffset = Ebitor_getLogicalOffsetAtHome(cursorCol, cursorRow); + //printf("[homeOffset=%u]", homeOffset); + assert(homeOffset == strlen("ABCDEFGHIJKLMNOPQRSTUVWXYZ01234\r" "L0\r" "L1\r")); + + // Search for a string that appears more than once. + size_t numOccurrences = 0; + size_t startLogicalOffset = 0; + for (;;) + { + found = Ebitor_findStringAndScrollToShow(startLogicalOffset, "L1", &foundLogicalOffset); + //printf("[%d,%u]", found, foundLogicalOffset); waitkey(1); + if (!found) + break; + assert(startLogicalOffset <= foundLogicalOffset); + assert(foundLogicalOffset <= editor->bufferFilledSize - 2); + ++numOccurrences; + assert(numOccurrences <= 9); + + editor->getCursorPos(&cursorCol, &cursorRow); + assert(memcmp(editor->bufferBegin + editor->cursorOffset, "L1", 2) == 0); + + // Try to find another occurrence. + startLogicalOffset = foundLogicalOffset + 1; + } + assert(numOccurrences == 9); +} + + +//: Tested: Ebitor_findStringAndScrollToShow +//: Tested: Ebitor_processEditing +// +static void +test_findDisplayedLineAfterScrollDown(void) +{ + Ebitor *editor = Ebitor_getInstance(); + setTestContent(); + + // Show the text. + predefinedKeyPresses = "\x03"; + Ebitor_processEditing(TRUE); + + assert(editor->savedCursorCol == 0 && editor->savedCursorRow == 0); + + // Find "L3", which is displayed. + // + size_t foundLogicalOffset = 0xFFFF; + BOOL found = Ebitor_findStringAndScrollToShow(0, "L3", &foundLogicalOffset); + assert(found); + assert(foundLogicalOffset == 41); + assert(editor->cursorOffset == 41); + + byte cursorCol, cursorRow; + sg4term_getCursorPos(&cursorCol, &cursorRow); + assert(cursorCol == 0); + assert(cursorRow == 4); + + assert(editor->savedCursorCol == 0 && editor->savedCursorRow == 4); + + // Go down enough to screen window up one row. + // FALSE means no refresh, to check that Ebitor_findStringAndScrollToShow() + // did NOT scroll the window. + // + predefinedKeyPresses = "\n\n\n\n\n\n\n\n\n\n\n\x03"; + Ebitor_processEditing(FALSE); + + assert(editor->savedCursorCol == 0 && editor->savedCursorRow == testWindow.height - 1); + + char text[3]; + sg4term_getChars(0, testWindow.height - 1, text, sizeof(text)); + assert(memcmp(text, "L14", sizeof(text)) == 0); + + // Find "L3" again and check that the screen has not scrolled. + // + found = Ebitor_findStringAndScrollToShow(0, "L3", &foundLogicalOffset); + assert(found); + assert(foundLogicalOffset == 41); + assert(editor->cursorOffset == 41); + + sg4term_getCursorPos(&cursorCol, &cursorRow); + assert(cursorCol == 0); + assert(cursorRow == 3); + + assert(editor->savedCursorCol == 0 && editor->savedCursorRow == 3); + + sg4term_getChars(0, testWindow.height - 1, text, sizeof(text)); + assert(memcmp(text, "L14", sizeof(text)) == 0); + + // Process nothing, but check that the screen has been redisplayed correctly. + // + predefinedKeyPresses = "\x03"; + Ebitor_processEditing(TRUE); + + sg4term_getChars(0, testWindow.height - 1, text, sizeof(text)); + assert(memcmp(text, "L14", sizeof(text)) == 0); +} + + +//: Tested: Ebitor_processUpOrDownArrowsAndRefresh +// +static void +test_goPageUpOnEmptyBuffer(void) +{ + Ebitor *editor = Ebitor_getInstance(); + predefinedKeyPresses = "\x03"; + Ebitor_processEditing(TRUE); + + // Page up: + Ebitor_processUpOrDownArrowsAndRefresh(TRUE, testWindow.height); +} + + +//: Tested: Ebitor_processUpOrDownArrowsAndRefresh +// +static void +test_goPageUpOnSingleLine(void) +{ + Ebitor *editor = Ebitor_getInstance(); + predefinedKeyPresses = "\r\x03"; + Ebitor_processEditing(TRUE); + + // Page up: + Ebitor_processUpOrDownArrowsAndRefresh(TRUE, testWindow.height); +} + + +//: Tested: Ebitor_scrollToShowLogicalOffset +// +static void +test_goTwoPagesUp(void) +{ + Ebitor *editor = Ebitor_getInstance(); + setRepeatedTestContent(2); + + // Show the text. + predefinedKeyPresses = + "\n\n\n\n\n\n\n\n\n\n" // go to bottom of text (scrolls down 2 pages) + "\n\n\n\n\n\n\n\n\n\n" + "\n\n\n\n\n\n\n\n\n\n" + "\n\n\n\n\n\n\n\n\n\n" + "\n\n" + "\x03"; + Ebitor_processEditing(TRUE); + + // Go back up to the first "L2" line. + size_t targetOffset = 32 + 3 + 3; + Ebitor_scrollToShowLogicalOffset(targetOffset, 2); + + assert(editor->cursorOffset == targetOffset); + assert(editor->savedCursorCol == 0 && editor->savedCursorRow == 0); +} + + +//: Tested: Ebitor_scrollToShowLogicalOffset +// +static void +test_goTwoPagesDown(void) +{ + Ebitor *editor = Ebitor_getInstance(); + setRepeatedTestContent(2); + + // Show the text. + predefinedKeyPresses = "\x03"; + Ebitor_processEditing(TRUE); + + // Scroll down to the second "L13" line. + // + const char *target = strstr(textBuffer, "L11\r"); + assert(target); + target = strstr(target + 1, "L11\r"); + assert(target); + + size_t targetOffset = target - textBuffer; + Ebitor_scrollToShowLogicalOffset(targetOffset, 3); + + assert(editor->cursorOffset == targetOffset); + assert(editor->savedCursorCol == 0 && editor->savedCursorRow == testWindow.height - 1); + + // Check that the scrolling was correct. + // + char text[3]; + sg4term_getChars(0, testWindow.height - 1, text, sizeof(text)); + assert(memcmp(text, "L11", sizeof(text)) == 0); + sg4term_getChars(0, 2, text, sizeof(text)); + assert(memcmp(text, "ABC", sizeof(text)) == 0); +} + + +// Checks that the terminal cursor goes down when the user presses the down arrow key. +// +static void +test_goOneRowDown(void) +{ + setRepeatedTestContent(2); + + // Show the text. + predefinedKeyPresses = "\x03"; + Ebitor_processEditing(TRUE); + + // Down arrow, then return from Ebitor_processEditing(). + predefinedKeyPresses = "\x0A\x03"; + Ebitor_processEditing(FALSE); + + // Check that cursor went down one row. + byte column, row; + sg4term_getCursorPos(&column, &row); + assert(column == 0); + assert(row == 1); + + // Check that logical offset is at start of 2nd logical line. + assert(Ebitor_getLogicalCursorOffset() == strstr(textBuffer, "\r") + 1 - textBuffer); +} + + +//: Tested: Ebitor_setContentLength +//: Tested: Ebitor_processEditing +// +static void +test_bufferFill(void) +{ + Ebitor *editor = Ebitor_getInstance(); + + // Fill textBuffer (with letters) almost to the limit. + // + size_t filledSize = sizeof(textBuffer) - 5; + for (size_t i = 0; i < filledSize; ++i) + textBuffer[i] = 'A' + (char) (i % 26); + Ebitor_setContentLength(filledSize); + + assert(editor->bufferFilledSize == sizeof(textBuffer) - 5); + + // Interactively add too many chars. + // + predefinedKeyPresses = "12345678\x03"; + Ebitor_processEditing(TRUE); + + assert(editor->bufferFilledSize == sizeof(textBuffer)); // no room for "678" + + char text[7]; + sg4term_getChars(0, 0, text, sizeof(text)); + assert(memcmp(text, "12345AB", sizeof(text)) == 0); + + // Backspace. + // + predefinedKeyPresses = "\f\x03"; + Ebitor_processEditing(FALSE); + + assert(editor->bufferFilledSize == sizeof(textBuffer) - 1); + + sg4term_getChars(0, 0, text, sizeof(text)); + assert(memcmp(text, "1234ABC", sizeof(text)) == 0); + + // Backspace too much. + // + predefinedKeyPresses = "\f\f\f\f\f\f\f\x03"; + Ebitor_processEditing(FALSE); + + assert(editor->bufferFilledSize == sizeof(textBuffer) - 5); + + sg4term_getChars(0, 0, text, sizeof(text)); + assert(memcmp(text, "ABCDEFG", sizeof(text)) == 0); +} + + +// Tests a fix made in Ebitor_processPrintableChar() on 2025-01-09 +// re: not calling Ebitor_fillTerminalToBottom() with firstRowToFill +// equal to Ebitor_instance.termHeight. +// In this test, the last visible row has 1 character less than the +// terminal width, then the user adds a character to the start of +// that row. +// +//: Tested: Ebitor_setContentLength +//: Tested: Ebitor_processEditing +// +static void +test_addCharToLastVisibleRowWithAlmostFullLine(void) +{ + Ebitor *editor = Ebitor_getInstance(); + + // Fill textBuffer (with letters) almost to the limit. + // + strcpy(textBuffer, + "L0\r" + "L1\r" + "L2\r" + "L3\r" + "L4\r" + "L5\r" + "L6\r" + "L7\r" + "L8\r" + "L9\r" + "L10\r" + "L11\r" + "L12\r" + "L13\r" + "L14--+----1----+----2----+----3\r" // last visible row, initially; 1 char short of filling row + "L15\r"); + Ebitor_setContentLength(strlen(textBuffer)); + + // Interactively add a char at start of last visible row. + // + predefinedKeyPresses = + "\n\n\n\n\n\n\n\n\n\n\n\n\n\n" // go from row 0 to row 14 + "*" // add printable char + "\x03" // return from Ebitor_processEditing() + ; + Ebitor_processEditing(TRUE); + + // Check content of last 3 visible rows. + // + char text[32 * 3 + 1]; + sg4term_getChars(0, testWindow.height - 3, text, sizeof(text) - 1); + text[32 * 3] = '\0'; + + assert(strcmp(text, + "L13 " + "*L14--+----1----+----2----+----3" + " ") == 0); + + // 2 down arrows, then check that L15 appears. + // + predefinedKeyPresses = "\n\n\x03"; + Ebitor_processEditing(FALSE); + sg4term_getChars(0, testWindow.height - 3, text, sizeof(text) - 1); + assert(strcmp(text, + "*L14--+----1----+----2----+----3" + " " + "L15 ") == 0); +} + + +#ifdef USIM +char screenBuffer[512]; +word timer; +#define TIMER_ADDRESS (&timer) +#else /* CoCo: */ +char *screenBuffer = (char *) 0x0400; +#define TIMER_ADDRESS ((word *) 0x112) +#endif + + +// screenMode: 32, 40, 64, 80. +// +static void +initEbitor(byte screenMode, const ebitor_Window *window) +{ + Ebitor *editor = Ebitor_getInstance(); + + word irqServiceRoutineAddress = * (word *) 0xFFF8; + BOOL isCoCo3 = (irqServiceRoutineAddress == 0xFEF7); + + if (screenMode != 32 && !isCoCo3) + { + printf("MODE %u IS ONLY SUPPORTED ON\nA COCO 3.\n", screenMode); + return; + } + + switch (screenMode) + { + case 32: + #ifdef _COCO_BASIC_ + width(32); // by SECB + cls(3); + #endif + sg4term_init(screenBuffer, window, inkey1, NULL, TIMER_ADDRESS); + + Ebitor_init(textBuffer, sizeof(textBuffer), + window->width, window->height, + sg4term_clear, + sg4term_locate, + sg4term_getCursorPos, + sg4term_print, + sg4term_printPrefix, + sg4term_clrtoeol, + sg4term_scrollWindowUp, + sg4term_scrollWindowDown, + sg4term_waitEditorKey); + break; + + default: + assert(0); + } +} + + +typedef void (*TestFunction)(void); + + +static void +runTest(TestFunction testFunc) +{ + byte screenMode = 32; + #ifdef _COCO_BASIC_ + width(32); + locate(0, 0); + #endif + initEbitor(screenMode, &testWindow); + testFunc(); + Ebitor_shutdown(); +} + + +TestFunction tests[] = +{ + test_scrollWindowUp, + test_scrollWindowDown, + test_countRowsToScrollUp, + test_countRowsToScrollDown, + test_scrollToShowLogicalOffset, + test_findStringAndScrollToShow, + test_findDisplayedLineAfterScrollDown, + test_goPageUpOnEmptyBuffer, + test_goPageUpOnSingleLine, + test_goTwoPagesUp, + test_goTwoPagesDown, + test_bufferFill, + test_goOneRowDown, + test_addCharToLastVisibleRowWithAlmostFullLine, +}; + + +static void +runSelfTests(void) +{ + size_t numTests = sizeof(tests) / sizeof(tests[0]); + for (currentTestIndex = 0; currentTestIndex < numTests; ++currentTestIndex) + runTest(tests[currentTestIndex]); + #ifdef _COCO_BASIC_ + cls(255); + #endif + printf("\n* RAN %u TEST(S) *\n", numTests); +} + + +static void +failedAssertHandler(const char *file, int lineno, const char *condition) +{ + printf("[***FAILED ASSERT IN TEST #%u: %s:%d: %s]", + currentTestIndex, file, lineno, condition); + for (;;) + ; +} + + +int +main() +{ + #ifdef _COCO_BASIC_ + rgb(); + #endif + _SetFailedAssertHandler(failedAssertHandler); + runSelfTests(); + return 0; +} diff --git a/findStringAndScrollToShow.c b/findStringAndScrollToShow.c new file mode 100644 index 0000000..d26639f --- /dev/null +++ b/findStringAndScrollToShow.c @@ -0,0 +1,49 @@ +/* findStringAndScrollToShow.c + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "Ebitor_private.h" + + +BOOL +Ebitor_findStringAndScrollToShow(size_t startLogicalOffset, const char *strSearchedFor, + size_t *foundLogicalOffset) +{ + Ebitor *self = &Ebitor_instance; + Ebitor_startCommandMode(); // put insert buffer into edit buffer, so that all the text is contiguous + + size_t lenStrSearchedFor = strlen(strSearchedFor); + if (lenStrSearchedFor == 0 || startLogicalOffset >= self->bufferFilledSize) + return FALSE; + + const char * const bufferEnd = self->bufferBegin + self->bufferFilledSize; + const char *startPtr = self->bufferBegin + startLogicalOffset; + const char *foundPtr; + do + { + foundPtr = (char *) memichr(startPtr, strSearchedFor[0], bufferEnd - startPtr); + if (!foundPtr) + return FALSE; + if (memicmp(foundPtr + 1, strSearchedFor + 1, lenStrSearchedFor - 1) == 0) + break; + startPtr = foundPtr + 1; + } while (startPtr < bufferEnd); + + *foundLogicalOffset = foundPtr - self->bufferBegin; + Ebitor_scrollToShowLogicalOffset(*foundLogicalOffset, lenStrSearchedFor); + return TRUE; +} diff --git a/gimeterm.c b/gimeterm.c new file mode 100644 index 0000000..6ce0934 --- /dev/null +++ b/gimeterm.c @@ -0,0 +1,319 @@ +/* gimeterm.c - CoCo 3 GIME hardware text mode terminal functions. + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "gimeterm.h" + +#include "Ebitor.h" + + +struct Ebitor; + + +static byte gimeterm_width, gimeterm_height; // max 80x24 +static byte gimeterm_winLeftCol, gimeterm_winTopRow; // 0..79, 0..24 +static word *gimeterm_screenBuffer; // address of 40/64/80x24/25 screen buffer +static byte gimeterm_screenColumns; // 40, 64 or 80 (regardless of gimeterm_width) +static byte gimeterm_cursorCol, gimeterm_cursorRow; // lower than gimeterm_width, gimeterm_cursorRow +static byte (*gimeterm_inkeyFuncPtr)(void *cookie); // returns 0 if no key pressed +static void *gimeterm_inkeyFuncCookie; // passed to gimeterm_inkeyFuncPtr +static word *gimeterm_timerPtr; // points to a word that gets incremented 60 times per second +static byte gimeterm_textAttribute; +static byte gimeterm_invertedTextAttribute; + + +static word * +getPosInWindow(byte col, byte row) +{ + return gimeterm_screenBuffer + ((word) (gimeterm_winTopRow + row) * gimeterm_screenColumns + gimeterm_winLeftCol + col); +} + + +#define getCursorAddress() (getPosInWindow(gimeterm_cursorCol, gimeterm_cursorRow)) + + +static void +gimeterm_clearRowsAt(word *rowStartDest, byte numRows) +{ + word w = 0x2000 | gimeterm_textAttribute; + for (byte i = numRows; i--; rowStartDest += gimeterm_screenColumns) // for each window row to clear + memset16(rowStartDest, w, gimeterm_width); +} + + +void +gimeterm_clear(void) +{ + gimeterm_clearRowsAt(getPosInWindow(0, 0), gimeterm_height); +} + + +void +gimeterm_init(void *screenBuffer, byte screenMode, const gimeterm_Window *window, + byte (*inkeyFuncPtr)(void *), void *inkeyFuncCookie, + word *timerPtr) +{ + gimeterm_screenBuffer = (word *) screenBuffer; + gimeterm_screenColumns = screenMode; + gimeterm_inkeyFuncPtr = inkeyFuncPtr; + gimeterm_inkeyFuncCookie = inkeyFuncCookie; + gimeterm_timerPtr = timerPtr; + gimeterm_setWindow(window); +} + + +void +gimeterm_setWindow(const gimeterm_Window *window) +{ + gimeterm_width = window->window.width; + gimeterm_height = window->window.height; + gimeterm_winLeftCol = window->window.leftCol; + gimeterm_winTopRow = window->window.topRow; + gimeterm_cursorCol = window->window.cursorCol; + gimeterm_cursorRow = window->window.cursorRow; + gimeterm_textAttribute = window->textAttribute; + gimeterm_invertedTextAttribute = window->invertedTextAttribute; +} + + +void +gimeterm_getWindow(gimeterm_Window *dest) +{ + dest->window.width = gimeterm_width; + dest->window.height = gimeterm_height; + dest->window.leftCol = gimeterm_winLeftCol; + dest->window.topRow = gimeterm_winTopRow; + dest->window.cursorCol = gimeterm_cursorCol; + dest->window.cursorRow = gimeterm_cursorRow; + dest->textAttribute = gimeterm_textAttribute; + dest->invertedTextAttribute = gimeterm_invertedTextAttribute; +} + + +void +gimeterm_locate(byte column, byte row) +{ + gimeterm_cursorCol = column; + gimeterm_cursorRow = row; +} + + +void +gimeterm_getCursorPos(byte *column, byte *row) +{ + *column = gimeterm_cursorCol; + *row = gimeterm_cursorRow; +} + + +BOOL +gimeterm_newline(void) +{ + gimeterm_cursorCol = 0; // back to start of window row + if (++gimeterm_cursorRow >= gimeterm_height) + { + --gimeterm_cursorRow; + gimeterm_cursorCol = 0; // back to start of last row (avoid writing outside window) + return FALSE; // reached end of window + } + return TRUE; +} + + +BOOL +gimeterm_putchar(int c) +{ + word *cursor = getCursorAddress(); + if (c == '\r') + { + word w = 0x2000 | gimeterm_textAttribute; + for ( ; gimeterm_cursorCol < gimeterm_width; ++gimeterm_cursorCol) + *cursor++ = w; + return gimeterm_newline(); + } + + ((byte *) cursor)[0] = (byte) c; + ((byte *) cursor)[1] = gimeterm_textAttribute; + if (++gimeterm_cursorCol >= gimeterm_width) // if past end of window row + return gimeterm_newline(); + + return TRUE; +} + + +BOOL +gimeterm_print(const char *str) +{ + for ( ; *str; ++str) + if (!gimeterm_putchar(*str)) + return FALSE; // reached end of window + return TRUE; +} + + +BOOL +gimeterm_printPrefix(const char *str, size_t prefixLength) +{ + for (size_t i = 0; i < prefixLength; ++i) + if (!gimeterm_putchar(str[i])) + return FALSE; // reached end of window + return TRUE; +} + +// Use inverted colors for the next print operations. +// +void +gimeterm_invertColors(void) +{ + byte temp = gimeterm_textAttribute; + gimeterm_textAttribute = gimeterm_invertedTextAttribute; + gimeterm_invertedTextAttribute = temp; +} + + +// Does not move the cursor. +// +void +gimeterm_clrtoeol(void) +{ + memset16(getCursorAddress(), 0x2000 | gimeterm_textAttribute, gimeterm_width - gimeterm_cursorCol); +} + + +void +gimeterm_scrollWindowUp(byte numRows) +{ + if (numRows == 0) + return; + + word *rowStartDest = getPosInWindow(0, 0); // top window row + const word *rowStartSrc = rowStartDest + ((word) numRows * gimeterm_screenColumns); + + size_t bytesPerWindowRow = gimeterm_width << 1; + for (byte i = gimeterm_height - numRows; i--; rowStartSrc += gimeterm_screenColumns, rowStartDest += gimeterm_screenColumns) // for each window row to scroll + memcpy(rowStartDest, rowStartSrc, bytesPerWindowRow); + gimeterm_clearRowsAt(rowStartDest, numRows); +} + + +void +gimeterm_scrollWindowDown(byte numRows) +{ + if (numRows == 0) + return; + + word *rowStartDest = getPosInWindow(0, gimeterm_height - 1); // bottom window row + const word *rowStartSrc = rowStartDest - ((word) numRows * gimeterm_screenColumns); + + size_t bytesPerWindowRow = gimeterm_width << 1; + for (byte i = gimeterm_height - numRows; i--; rowStartSrc -= gimeterm_screenColumns, rowStartDest -= gimeterm_screenColumns) // for each window row to scroll + memmove(rowStartDest, rowStartSrc, bytesPerWindowRow); + const word w = 0x2000 | gimeterm_textAttribute; + for (byte i = numRows; i--; rowStartDest -= gimeterm_screenColumns) // for each window row to clear + memset16(rowStartDest, w, gimeterm_width); +} + + +void +gimeterm_eraseCurrentLine(void) +{ + memset16(getPosInWindow(0, gimeterm_cursorRow), 0x2000 | gimeterm_textAttribute, gimeterm_width); + gimeterm_cursorCol = 0; +} + + +// Animates a cursor using the timerPtr passed to gimeterm_init(). +// Uses the inkeyFuncPtr and inkeyFuncCookie passed to gimeterm_init() to poll the keyboard. +// attributeByte: Address of a GIME 40/80-column screen attribute byte. +// cursorAttribute: Byte to put at *attributeByte to animate the cursor. +// Returns the key pressed, without interpretation. +// +static byte +gimeterm_waitKeyAtPosition(byte *attributeByte, byte cursorAttribute) +{ + byte origByteOnScreen = *attributeByte; + + // Wait for key with animated cursor. + byte key; + for (word startTime = *gimeterm_timerPtr; ; ) + { + key = (*gimeterm_inkeyFuncPtr)(gimeterm_inkeyFuncCookie); + if (key) + break; + *attributeByte = (((*gimeterm_timerPtr - startTime) & 0x38) == 0x38 ? origByteOnScreen : cursorAttribute); + } + + *attributeByte = origByteOnScreen; + return key; +} + + +byte +gimeterm_waitKey(void) +{ + byte *cursor = (byte *) getCursorAddress() + 1; // point to attribute byte + return gimeterm_waitKeyAtPosition(cursor, gimeterm_invertedTextAttribute); +} + + +word +gimeterm_waitEditorKey(void) +{ + for (;;) + { + byte key = gimeterm_waitKey(); + + switch (key) + { + case 3: // Break + return ebitor_KEY_ESCAPE; + case 8: // left arrow + return ebitor_KEY_ARROW_LEFT; + case 9: // right arrow + return ebitor_KEY_ARROW_RIGHT; + case '^': // up arrow + return ebitor_KEY_ARROW_UP; + case 10: // down arrow + return ebitor_KEY_ARROW_DOWN; + case 12: // Clear used as backspace + return '\b'; // backspace + case 13: // Enter + return '\r'; + default: + if (key >= ' ' && key != 127) + return key; + } + } +} + + +byte +gimeterm_setTextAttribute(byte newAttribute) +{ + byte orig = gimeterm_textAttribute; + gimeterm_textAttribute = newAttribute; + return orig; +} + + +byte +gimeterm_setInvertedTextAttribute(byte newAttribute) +{ + byte orig = gimeterm_invertedTextAttribute; + gimeterm_invertedTextAttribute = newAttribute; + return orig; +} diff --git a/gimeterm.h b/gimeterm.h new file mode 100644 index 0000000..7c46230 --- /dev/null +++ b/gimeterm.h @@ -0,0 +1,146 @@ +/* gimeterm.h - CoCo 3 GIME hardware text mode terminal functions. + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/* + These functions implement a terminal compliant with the specs in Ebitor.h. + + Each screen cell is a character byte followed by an attribute byte, + i.e., 2 bytes per screen character. +*/ + +#ifndef _H_gimeterm +#define _H_gimeterm + +#include "Window.h" + + +typedef struct gimeterm_Window +{ + ebitor_Window window; + + // Default text attribute used by functions that put characters on the screen. + // See gimeterm_setTextAttribute(). + // + byte textAttribute; + + // Attribute to use to show characters with inverted colors. + // See gimeterm_setInvertedTextAttribute(). + // + byte invertedTextAttribute; + +} gimeterm_Window; + + +// Defines a window in a GIME hardware text screen. +// Does NOT clear the window. +// Does NOT change the video mode. +// +// screenBuffer: Address of the screen. +// screenMode: 40, 64 or 80. +// window: Initial window in the given screen. +// inkeyFuncPtr: Must return 0 (and not block) if no key pressed. +// inkeyFuncCookie: Will be passed to inkeyFuncPtr. +// timerPtr: Address of an unsigned 16-bit integer that gets incremented 60 times per second. +// +void gimeterm_init(void *screenBuffer, byte screenMode, + const gimeterm_Window *window, + byte (*inkeyFuncPtr)(void *cookie), void *inkeyFuncCookie, + word *timerPtr); + +// Changes the current window. +// +void gimeterm_setWindow(const gimeterm_Window *state); + +// Copies the state of the current window into the designated object. +// +void gimeterm_getWindow(gimeterm_Window *dest); + +// Fills the window defined by gimeterm_init() with spaces and the 'textAttribute' +// passed to gimeterm_init(). +// Does not move the cursor. +// +void gimeterm_clear(void); + +// column, row: Coordinates relative to the window defined by gimeterm_init(). +// Does not check if the parameters are valid. +// This may be useful to write outside the window, as long as no carriage return is written. +// +void gimeterm_locate(byte column, byte row); + +// column, row: Receive coordinates relative to the window defined by gimeterm_init(). +// +void gimeterm_getCursorPos(byte *column, byte *row); + +// CAUTION: This function does NOT scroll when it reaches the end of the window. +// Character 13 does a carriage return and line feed AND clears +// the rest of the row it is applied to (with spaces and gimeterm_textAttribute). +// No other control code is supported. +// +// Returns FALSE if the cursor has fallen off the bottom of the window. +// The caller should scroll the window up and reposition the cursor. +// +BOOL gimeterm_putchar(int c); + +// Returns FALSE the string could not be printed entirely because the printing reached end of window. +// +BOOL gimeterm_print(const char *str); + +// Returns FALSE the string could not be printed entirely because the printing reached end of window. +// +BOOL gimeterm_printPrefix(const char *str, size_t prefixLength); + +// Returns FALSE if the cursor has fallen off the bottom of the window. +// The caller should scroll the window up and reposition the cursor. +// +BOOL gimeterm_newline(void); + +// Use inverted colors for the next print operations. +// +void gimeterm_invertColors(void); + +void gimeterm_clrtoeol(void); +void gimeterm_scrollWindowUp(byte numRows); +void gimeterm_scrollWindowDown(byte numRows); + +// Fills the line where the cursor is with spaces and puts the cursor at the start of this line. +// +void gimeterm_eraseCurrentLine(void); + +// Animates a cursor while waiting. +// Returns an ASCII code or an ebitor_KEY_* code. +// +word gimeterm_waitEditorKey(void); + + +// The following functions are not part of the Ebitor terminal function set. + + +byte gimeterm_waitKey(void); + + +// Returns the attribute used up to now. +// +byte gimeterm_setTextAttribute(byte newAttribute); + + +// Returns the inverted text attribute used up to now. +// +byte gimeterm_setInvertedTextAttribute(byte newAttribute); + + +#endif /* _H_gimeterm */ diff --git a/os9term.c b/os9term.c new file mode 100644 index 0000000..d857a34 --- /dev/null +++ b/os9term.c @@ -0,0 +1,296 @@ +/* os9term.c - OS-9 terminal functions. + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "os9term.h" + +#include "Ebitor_private.h" + + +struct Ebitor; + + +static byte os9term_width, os9term_height; +static byte os9term_winLeftCol, os9term_winTopRow; +static byte os9term_cursorCol, os9term_cursorRow; // lower than os9term_winLeftCol, os9term_winTopRow +static byte (*os9term_waitKeyFuncPtr)(void *cookie); // blocks until key available +static void *os9term_waitKeyFuncCookie; // argument passed to sg4term_inkeyFuncPtr + + +// Changes the OS-9 terminal's working area. +// Sends the CWArea sequence to standard output. +// Source: "NitrOS-9 EOU Level 2 Windowing System Manual". +// Only works in 40- and 80-column modes. +// This puts the OS-9 terminal cursor at the home position of the window. +// +static void +setWorkingAreaExtraHeight(byte increment) +{ + byte buf[] = { 0x1B, 0x25, os9term_winLeftCol, os9term_winTopRow, os9term_width, os9term_height + increment }; + putstr((char *) buf, sizeof(buf)); +} + + +void +os9term_clear(void) +{ + byte c, r; + os9term_getCursorPos(&c, &r); + + // Tell OS-9 to work in a window that only contains the text editing area, not the status line. + // This way, the status line does not get cleared. + setWorkingAreaExtraHeight(0); + + putchar(12); + + // Restore the OS-9 window that includes the status line. + setWorkingAreaExtraHeight(1); + + os9term_locate(c, r); +} + + +asm byte * +os9term_get32x16ScreenBuffer(void) +{ + asm + { + pshs y ; protect global variable segment pointer + lda #1 ; path number + ldb #$1C ; SS.AlfaS (Return Alfa Display Status) + os9 $8D ; I$GetStt + bcs @error + tfr x,d ; return screen buffer address in D + bra @done +@error + clra ; return 0 in D + clrb +@done + puls y + } +} + + +asm byte +os9term_getGIMEScreenType(byte *screenTypeCode) +{ + asm + { + lda #1 ; path number + ldb #$93 ; SS.ScTyp: Returns the type of a screen to a calling program + os9 $8D ; I$GetStt + bcs @error + clrb + sta [2,s] ; put code in *screenTypeCode +@error + ; Error code returned in B, as per CMOC calling convention. + } +} + + +byte +os9term_init(byte width, byte height, + byte winLeftCol, byte winTopRow, + byte (*waitKeyFuncPtr)(void *), void *waitKeyFuncCookie) +{ + os9term_width = width; + os9term_height = height; + os9term_winLeftCol = winLeftCol; + os9term_winTopRow = winTopRow; + os9term_cursorCol = 0; + os9term_cursorRow = 0; + os9term_waitKeyFuncPtr = waitKeyFuncPtr; + os9term_waitKeyFuncCookie = waitKeyFuncCookie; + + return 0; // success +} + + +void +os9term_locate(byte column, byte row) +{ + char str[] = { 2, 32 + column, 32 + row }; + putstr(str, sizeof(str)); + os9term_cursorCol = column; + os9term_cursorRow = row; +} + + +void +os9term_getCursorPos(byte *column, byte *row) +{ + *column = os9term_cursorCol; + *row = os9term_cursorRow; +} + + +// Character 13 does a carriage return and line feed AND clears +// the rest of the row it is applied to (with spaces). +// No other control code is supported. +// Updates os9term_cursorCol and os9term_cursorRow. +// +static BOOL +os9term_putchar(int c) //FIXME: Does not check against window height. Should return FALSE. See gimeterm.c. +{ + if (c == '\r') + { + os9term_cursorCol = 0; + ++os9term_cursorRow; + putchar(4); // clears to end of line + } + else + { + ++os9term_cursorCol; + if (os9term_cursorCol >= os9term_width) + { + os9term_cursorCol = 0; + if (os9term_cursorRow < os9term_height - 1) + ++os9term_cursorRow; + } + } + + putchar((char) c); + return TRUE; +} + + +BOOL +os9term_print(const char *str) +{ + for ( ; *str; ++str) + if (!os9term_putchar(*str)) + return FALSE; // reached end of window + return TRUE; +} + + +BOOL +os9term_printPrefix(const char *str, size_t prefixLength) +{ + for (size_t i = 0; i < prefixLength; ++i) + if (!os9term_putchar(str[i])) + return FALSE; // reached end of window + return TRUE; +} + + +void +os9term_invertColors(void) +{ + // Not supported. +} + + +// Does not move the cursor. +// +void +os9term_clrtoeol(void) +{ + for (byte c = os9term_cursorCol; c < os9term_width; ++c) + putchar(' '); +} + + +void +os9term_scrollWindowUp(byte numRows) +{ + if (numRows == 0) + return; + + // Tell OS-9 to work in a window that only contains the text editing area, not the status line. + // This way, the status line does not get scrolled up. + setWorkingAreaExtraHeight(0); + + // Move cursor to bottom row if not already on that row. + char goBottom[] = { 2, 32, (32 - 1) + os9term_height }; + putstr(goBottom, sizeof(goBottom)); + + for ( ; numRows--; ) + putchar(10); // cursor down + + // Restore the OS-9 window that includes the status line. + setWorkingAreaExtraHeight(1); + + // Restore original cursor position. + char restore[] = { 2, 32 + os9term_cursorCol, 32 + os9term_cursorRow }; + putstr(restore, sizeof(restore)); +} + + +void +os9term_scrollWindowDown(byte numRows) +{ + if (numRows == 0) + return; + + // Tell OS-9 to work in a window that only contains the text editing area, not the status line. + // This way, the status line does not get scrolled down. + // This puts the OS-9 cursor at the home position. + setWorkingAreaExtraHeight(0); + + for ( ; numRows--; ) + putstr("\x1F\x30", 2); // insert line, scroll the following lines down + + // Restore the OS-9 window that includes the status line. + setWorkingAreaExtraHeight(1); + + // Restore original cursor position. + char restore[] = { 2, 32 + os9term_cursorCol, 32 + os9term_cursorRow }; + putstr(restore, sizeof(restore)); +} + + +void +os9term_eraseCurrentLine(void) +{ + putchar(3); +} + + +word +os9term_waitEditorKey(void) +{ + for (;;) + { + byte key = (*os9term_waitKeyFuncPtr)(os9term_waitKeyFuncCookie); + + switch (key) + { + case 177: // F1 + // N.B.: If 'key' is 123 when pressing F1, it may be because + // the BControl library has been compiled for DECB + // instead of OS-9. In that case, recompile it by + // passing TARGET=os9 to make. + return ebitor_KEY_ESCAPE; + case 8: // left arrow + return ebitor_KEY_ARROW_LEFT; + case 9: // right arrow + return ebitor_KEY_ARROW_RIGHT; + case 12: // up arrow + return ebitor_KEY_ARROW_UP; + case 10: // down arrow + return ebitor_KEY_ARROW_DOWN; + case 16: // Ctrl-Left + return '\b'; // backspace + case 13: // Enter + return '\r'; + default: + if (key >= ' ' && key != 127) // if not control char (127 = Delete) + return key; + } + } +} diff --git a/os9term.h b/os9term.h new file mode 100644 index 0000000..e2005f6 --- /dev/null +++ b/os9term.h @@ -0,0 +1,111 @@ +/* os9term.h - OS-9 terminal functions. + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/* + These functions implement a terminal compliant with the specs in Ebitor.h. +*/ + +#ifndef _H_os9term +#define _H_os9term + +#include "Window.h" + + +// Returns the address of the 32x16 screen buffer is standard out +// is current in that mode. Otherwise, returns NULL. +// +byte *os9term_get32x16ScreenBuffer(void); + + +// Returns an OS-9 error code upon failure, or 0 upon success +// (*screenTypeCode is then 1, 2 or 5..8). +// Suitable to be called when the terminal uses a GIME mode. +// Returns error code 208 when run in a 32x16 terminal. +// +byte os9term_getGIMEScreenType(byte *screenTypeCode); + + +// Defines a window in an OS-9 terminal. +// +// Assumes that there is an extra row below the designated window. +// For example, on a 40x25 screen, the window would be (40, 24, 0, 0), +// and the 25th row would be the status line. +// +// Does NOT clear the window (see os9term_clear()). +// +// width, height: Dimensions in characters of the window. +// winLeftCol, winTopRow: Zero-based coordinates of the top left of the window. +// waitKeyFuncPtr: Pointer to a function that waits until a key is pressed and +// returns its ASCII code, e.g., 65 for 'A', 12 for the up arrow. +// waitKeyFuncCookie: Value to be passed to (*waitKeyFuncPtr)(). +// +// Returns 0 upon success, or an error code upon failure: +// 1: Terminal type not supported (e.g., the current terminal is 32x16). +// 2: Failed to determine is the screen is a GIME text screen. +// 3: The screen is in a GIME mode but not in a 40- or 80-column mode. +// +byte os9term_init(byte width, byte height, + byte winLeftCol, byte winTopRow, + byte (*waitKeyFuncPtr)(void *), void *waitKeyFuncCookie); + +// Must be called before leaving the process. +// +void os9term_shutdown(void); + + +// Fills the window defined by os9term_init() with spaces. +// Does not move the cursor. +// +void os9term_clear(void); + +// column, row: Coordinates relative to the window defined by os9term_init(). +// Does not check if the parameters are valid. +// This may be useful to write outside the window, as long as no carriage return is written. +// +void os9term_locate(byte column, byte row); + +// column, row: Receive coordinates relative to the window defined by os9term_init(). +// +void os9term_getCursorPos(byte *column, byte *row); + +// Returns FALSE the string could not be printed entirely because the printing reached end of window. +// +BOOL os9term_print(const char *str); + +// Returns FALSE the string could not be printed entirely because the printing reached end of window. +// +BOOL os9term_printPrefix(const char *str, size_t prefixLength); + +// Use inverted colors for the next print operations. +// +void os9term_invertColors(void); + +void os9term_clrtoeol(void); +void os9term_scrollWindowUp(byte numRows); +void os9term_scrollWindowDown(byte numRows); + +// Fills the line where the cursor is with spaces and puts the cursor at the start of this line. +// +void os9term_eraseCurrentLine(void); + +// Returns an ASCII code or an ebitor_KEY_* code. +// +word os9term_waitEditorKey(void); + + +#endif /* _H_os9term */ diff --git a/processBackspace.c b/processBackspace.c new file mode 100644 index 0000000..9597dc5 --- /dev/null +++ b/processBackspace.c @@ -0,0 +1,109 @@ +/* processBackspace.c + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "Ebitor_private.h" + + +void +Ebitor_processBackspace(byte cursorCol, byte cursorRow) +{ + Ebitor_startCommandMode(); + + // This check must be done after Ebitor_startCommandMode(), which can update cursorOffset + if (Ebitor_instance.cursorOffset == 0) // if at start of edit buffer + return; // nothing to do + + size_t solOffset = Ebitor_findSOL(Ebitor_instance.cursorOffset); + size_t eolOffset = Ebitor_findEOL(Ebitor_instance.cursorOffset); + + // E.g.: ...ABCDEF..............FOOBAR + // ^ ^ ^ ^bufferFilledSize + // | | `eolOffset + // | `cursorOffset + // `solOffset + + // Print rest of line at preceding position. + // + BOOL erasingPrevCR = (cursorCol == 0); + if (!erasingPrevCR) + { + --cursorCol; + } + else // at column 0: + { + if (Ebitor_instance.cursorOffset == solOffset) // if at start of logical line + { + // About to erase previous line's terminator. + assert(Ebitor_instance.bufferBegin[solOffset - 1] == '\r'); // b/c cursorOffset > 0, there must be a line before + + size_t prevSOLOffset = Ebitor_findPreviousSOL(solOffset); + assert(prevSOLOffset < solOffset); + size_t prevLineLen = solOffset - prevSOLOffset - 1; // exclude \r + cursorCol = (byte) (prevLineLen % Ebitor_instance.termWidth); // after last char of previous line + if (cursorRow == 0) + { + Ebitor_instance.scrollTerminalDown(1); + Ebitor_instance.printPrefix(Ebitor_instance.bufferBegin + (solOffset - 1 - prevLineLen), prevLineLen); + } + else + --cursorRow; + } + else // inside a logical line: + { + cursorCol = Ebitor_instance.termWidth - 1; + if (cursorRow == 0) + { + Ebitor_instance.scrollTerminalDown(1); + Ebitor_instance.printPrefix(Ebitor_instance.bufferBegin + (Ebitor_instance.cursorOffset - Ebitor_instance.termWidth), Ebitor_instance.termWidth); + } + else + --cursorRow; + } + } + assert(cursorRow < Ebitor_instance.termHeight); + Ebitor_instance.locate(cursorCol, cursorRow); + char *cursorPtr = Ebitor_instance.bufferBegin + Ebitor_instance.cursorOffset; + assert(Ebitor_instance.cursorOffset <= eolOffset); + size_t numCharsToPrint = eolOffset - Ebitor_instance.cursorOffset; + if (Ebitor_instance.printPrefix(cursorPtr, numCharsToPrint)) + { + // We have not reached the end of the window. + + Ebitor_instance.clrtoeol(); // erase last char of logical line + + if (erasingPrevCR) + { + // Print the lines that follow the cursor row. + // This will make a new line visible at the bottom, if the text is long enough. + // TODO: This might be optimized by only writing the bottom row. + // + size_t firstLogicalCharOffsetToPrint = (eolOffset == Ebitor_instance.bufferFilledSize ? eolOffset : eolOffset + 1); + + byte dummy, r; + Ebitor_instance.getCursorPos(&dummy, &r); + + Ebitor_fillTerminalToBottom(firstLogicalCharOffsetToPrint, r + 1); + } + } + + Ebitor_instance.locate(cursorCol, cursorRow); + + memmove(cursorPtr - 1, cursorPtr, Ebitor_instance.bufferFilledSize - Ebitor_instance.cursorOffset); + --Ebitor_instance.cursorOffset; + --Ebitor_instance.bufferFilledSize; +} diff --git a/processPrintableChar.c b/processPrintableChar.c new file mode 100644 index 0000000..c01ded0 --- /dev/null +++ b/processPrintableChar.c @@ -0,0 +1,110 @@ +/* processPrintableChar.c + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "Ebitor_private.h" + + +void +Ebitor_processPrintableChar(word key, byte cursorCol, byte cursorRow) +{ + if (key < 256) + { + // Reject if no room in edit buffer. + // + if (Ebitor_instance.bufferFilledSize + Ebitor_instance.insertBuffer.size + 1 > Ebitor_instance.bufferEnd - Ebitor_instance.bufferBegin) + return; + + size_t eolOffset = Ebitor_findEOL(Ebitor_instance.cursorOffset); + // eolOffset either designates a \r, or the end of the filled edit buffer. + + // If the character is about to be printed on the last row, check if scrolling up is needed. + // Count the number of times a printable character will be printed in the last window column + // plus the number of carriage returns that will be printed, when printing the rest of the + // affected line. + // If a scroll is done, the cursor is moved one row up. + // + if (cursorRow == Ebitor_instance.termHeight - 1) + { + BOOL needScroll = FALSE; + byte col = cursorCol; + ++col; // cursor position after printing 'key' + if (col == Ebitor_instance.termWidth) // if past last column + needScroll = TRUE; + const char *p = Ebitor_instance.bufferBegin + Ebitor_instance.cursorOffset; + const char *end = Ebitor_instance.bufferBegin + eolOffset; + //locate(0, 8); printf("[%u,%u]", Ebitor_instance.cursorOffset, eolOffset); + for ( ; p < end; ++p) + { + if (*p == '\r') + { + col = 0; + needScroll = TRUE; + } + else // *p is printable + { + ++col; + if (col == Ebitor_instance.termWidth) + needScroll = TRUE; + } + } + if (needScroll) + { + Ebitor_instance.scrollTerminalUp(1); + --cursorRow; + assert(cursorRow >= 0); + assert(cursorRow < Ebitor_instance.termHeight); + Ebitor_instance.locate(cursorCol, cursorRow); + } + } + + // Print the character just typed. + // + char c = (char) key; + Ebitor_instance.printPrefix(&c, 1); + + // Reprint the rest of the line, if any, while preserving the new cursor position. + // + size_t lenRest = eolOffset - Ebitor_instance.cursorOffset; + if (lenRest > 0) + { + Ebitor_instance.getCursorPos(&cursorCol, &cursorRow); + assert(cursorRow < Ebitor_instance.termHeight); + if (Ebitor_instance.printPrefix(Ebitor_instance.bufferBegin + Ebitor_instance.cursorOffset, lenRest)) + { + // We did not reach the end of the window. + + byte afterPrintCol, afterPrintRow; + Ebitor_instance.getCursorPos(&afterPrintCol, &afterPrintRow); + if (afterPrintCol == 0) // if printing ends at column 0 + { + Ebitor_instance.print("\r"); // show an empty row + if (eolOffset < Ebitor_instance.bufferFilledSize // if something after current EOL + && afterPrintRow + 1 < Ebitor_instance.termHeight) // and there is room in the terminal window + Ebitor_fillTerminalToBottom(eolOffset + 1, afterPrintRow + 1); + } + } + Ebitor_instance.locate(cursorCol, cursorRow); + } + + // Ebitor_instance.cursorOffset is not incremented here b/c 'c' is only + // added to the insert buffer. When the latter will be moved + // to the edit buffer, Ebitor_instance.cursorOffset will be incremented. + // + Ebitor_insertChar(c); + } +} diff --git a/scrollToShowLogicalOffset.c b/scrollToShowLogicalOffset.c new file mode 100644 index 0000000..914ac2f --- /dev/null +++ b/scrollToShowLogicalOffset.c @@ -0,0 +1,104 @@ +/* scrollToShowLogicalOffset.c + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "Ebitor_private.h" + + +void +Ebitor_scrollToShowLogicalOffset(size_t logicalOffsetToShow, size_t lengthToShow) +{ + Ebitor *self = &Ebitor_instance; + byte cursorCol = self->savedCursorCol, cursorRow = self->savedCursorRow; + + size_t homeOffset, firstOffWindowOffset; + char code = Ebitor_isRegionVisible(logicalOffsetToShow, lengthToShow, cursorCol, cursorRow, + &homeOffset, &firstOffWindowOffset); + //printf("(%u,%u,%u->CODE=%d,HO=%u,F=%u)", + // logicalOffsetToShow, cursorCol, cursorRow, code, homeOffset, firstOffWindowOffset); + if (code < 0) // if region to show is before displayed text + { + size_t logicalOffsetAtStartOfTermRow; + size_t numTermRows = Ebitor_countRowsToScrollDown(logicalOffsetToShow, homeOffset, &logicalOffsetAtStartOfTermRow); + assert(numTermRows > 0); + if (numTermRows < self->termHeight) // if NOT scrolling all current rows off + { + assert(logicalOffsetAtStartOfTermRow <= logicalOffsetToShow); + assert(logicalOffsetToShow - logicalOffsetAtStartOfTermRow < self->termWidth); + self->scrollTerminalDown((byte) numTermRows); + } + else // redraw whole window + numTermRows = self->termHeight; + + Ebitor_fillWindowFromHomeToRow(logicalOffsetAtStartOfTermRow, (byte) numTermRows); + + byte cursorCol = (byte) (logicalOffsetToShow - logicalOffsetAtStartOfTermRow); + Ebitor_locateAndSavePos(cursorCol, 0); + } + else if (code > 0) // region to show is after displayed text + { + size_t numTermRows = Ebitor_countRowsToScrollUp(logicalOffsetToShow, firstOffWindowOffset); + assert(numTermRows > 0); + if (numTermRows < self->termHeight) // if NOT scrolling all current rows off + { + self->scrollTerminalUp((byte) numTermRows); + Ebitor_fillTerminalToBottom(firstOffWindowOffset, self->termHeight - (byte) numTermRows); + } + else // redraw whole window + { + size_t newHomeOffset = Ebitor_goDownRows(homeOffset, numTermRows); + assert(newHomeOffset <= self->bufferFilledSize); + Ebitor_fillWindowFromHomeToRow(newHomeOffset, self->termHeight); + } + + size_t solOffset = Ebitor_findSOL(logicalOffsetToShow); + byte cursorCol = (byte) ((logicalOffsetToShow - solOffset) % self->termWidth); + Ebitor_locateAndSavePos(cursorCol, self->termHeight - 1); + } + else // code == 0: region is complete in displayed text + { + // Locate the cursor at logicalOffsetToShow. + byte cursorCol = 0, cursorRow = 0; // position of homeOffset + size_t offset = homeOffset; + for (;;) + { + // Here, offset is in column 0 of the terminal. + // + size_t eolOffset = Ebitor_findEOL(offset); + if (logicalOffsetToShow <= eolOffset) // if target position is on current logical line + { + cursorCol = (byte) ((logicalOffsetToShow - offset) % self->termWidth); + cursorRow += (byte) ((logicalOffsetToShow - offset) / self->termWidth); + // No overflow possible b/c we know logicalOffsetToShow is on window + + assert(cursorRow < self->termHeight); + Ebitor_locateAndSavePos(cursorCol, cursorRow); + break; + } + + assert(eolOffset < self->bufferFilledSize); // b/c logicalOffsetToShow is after eolOffset + size_t numRowsInLine = (eolOffset - offset) / self->termWidth + 1; + assert(cursorRow + numRowsInLine < self->termHeight); + // No overflow possible b/c we know logicalOffsetToShow is on window + + offset = eolOffset + 1; // go to char after \r; this char is at column 0 + cursorRow += (byte) numRowsInLine; + } + } + + self->cursorOffset = logicalOffsetToShow; +} diff --git a/sg4term.c b/sg4term.c new file mode 100644 index 0000000..807f171 --- /dev/null +++ b/sg4term.c @@ -0,0 +1,318 @@ +/* sg4term.c - CoCo 32x16 SG4 mode (6847) terminal functions. + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "sg4term.h" + +#include "Ebitor_private.h" + + +enum +{ + sg4term_SPACE_CODE = 0x60, +}; + + +struct Ebitor; + + +static byte sg4term_width, sg4term_height; // max 32x16 +static byte sg4term_winLeftCol, sg4term_winTopRow; // 0..31, 0..15 +static char *sg4term_screenBuffer; // address of 32x16 screen buffer +static byte sg4term_cursorCol, sg4term_cursorRow; // lower than sg4term_winLeftCol, sg4term_winTopRow +static byte (*sg4term_inkeyFuncPtr)(void *cookie); // returns 0 if no key pressed +static void *sg4term_inkeyFuncCookie; // argument passed to sg4term_inkeyFuncPtr +static word *sg4term_timerPtr; // points to a word that gets incremented 60 times per second +static char sg4term_attributeInversionFlag; + + +static char * +getPosInWindow(byte col, byte row) +{ + return sg4term_screenBuffer + ((word) (sg4term_winTopRow + row) << 5) + (sg4term_winLeftCol + col); +} + + +#define getCursorAddress() (getPosInWindow(sg4term_cursorCol, sg4term_cursorRow)) + + +static void +sg4term_clearRowsAt(char *rowStartDest, byte numRows) +{ + char value = sg4term_SPACE_CODE ^ sg4term_attributeInversionFlag; + for (byte i = numRows; i--; rowStartDest += 32) // for each window row to clear + memset(rowStartDest, value, sg4term_width); +} + + +void +sg4term_clear(void) +{ + sg4term_clearRowsAt(getPosInWindow(0, 0), sg4term_height); +} + + +void +sg4term_init(char *screenBuffer, const ebitor_Window *window, + byte (*inkeyFuncPtr)(void *), void *inkeyFuncCookie, word *timerPtr) +{ + sg4term_screenBuffer = screenBuffer; + sg4term_width = window->width; + sg4term_height = window->height; + sg4term_winLeftCol = window->leftCol; + sg4term_winTopRow = window->topRow; + sg4term_cursorCol = window->cursorCol; + sg4term_cursorRow = window->cursorRow; + sg4term_inkeyFuncPtr = inkeyFuncPtr; + sg4term_inkeyFuncCookie = inkeyFuncCookie; + sg4term_timerPtr = timerPtr; + sg4term_attributeInversionFlag = 0; +} + + +void +sg4term_locate(byte column, byte row) +{ + sg4term_cursorCol = column; + sg4term_cursorRow = row; +} + + +void +sg4term_getCursorPos(byte *column, byte *row) +{ + *column = sg4term_cursorCol; + *row = sg4term_cursorRow; +} + + +static BOOL +sg4term_newline(void) +{ + sg4term_cursorCol = 0; // back to start of window row + if (++sg4term_cursorRow >= sg4term_height) + { + --sg4term_cursorRow; + sg4term_cursorCol = 0; // back to start of last row (avoid writing outside window) + return FALSE; // reached end of window + } + return TRUE; +} + + +asm char +sg4term_convertASCIIToScreenByte(char c) +{ + asm + { + ldb 3,s // low byte of 'c' (big endian) + cmpb #64 + blo @typo // typographical char + cmpb #96 + blo @done // upper-case letter + cmpb #128 + bhs @done // graphical char + subb #96 // lower-case letter + bra @store +@typo + addb #64 +@store + stb 3,s +@done + } +} + + +// CAUTION: This function does NOT scroll when it reaches the end of the window. +// Character 13 does a carriage return and line feed AND clears +// the rest of the row it is applied to (with spaces). +// No other control code is supported. +// +static BOOL +sg4term_putchar(int c) +{ + char *cursor = getCursorAddress(); + if (c == '\r') + { + char charToWrite = sg4term_SPACE_CODE ^ sg4term_attributeInversionFlag; + for ( ; sg4term_cursorCol < sg4term_width; ++sg4term_cursorCol) + *cursor++ = charToWrite; + return sg4term_newline(); + } + + *cursor++ = sg4term_convertASCIIToScreenByte((char) c) ^ sg4term_attributeInversionFlag; + if (++sg4term_cursorCol >= sg4term_width) // if past end of window row + return sg4term_newline(); + + return TRUE; +} + + +BOOL +sg4term_print(const char *str) +{ + for ( ; *str; ++str) + if (!sg4term_putchar(*str)) + return FALSE; // reached end of window + return TRUE; +} + + +BOOL +sg4term_printPrefix(const char *str, size_t prefixLength) +{ + for (size_t i = 0; i < prefixLength; ++i) + if (!sg4term_putchar(str[i])) + return FALSE; // reached end of window + return TRUE; +} + + +void +sg4term_invertColors(void) +{ + sg4term_attributeInversionFlag ^= 0x40; +} + + +// Does not move the cursor. +// +void +sg4term_clrtoeol(void) +{ + memset(getCursorAddress(), sg4term_SPACE_CODE ^ sg4term_attributeInversionFlag, sg4term_width - sg4term_cursorCol); +} + + +void +sg4term_scrollWindowUp(byte numRows) +{ + if (numRows == 0) + return; + + char *rowStartDest = getPosInWindow(0, 0); // top window row + const char *rowStartSrc = rowStartDest + ((word) numRows << 5); + + for (byte i = sg4term_height - numRows; i--; rowStartSrc += 32, rowStartDest += 32) // for each window row to scroll + memmove(rowStartDest, rowStartSrc, sg4term_width); + sg4term_clearRowsAt(rowStartDest, numRows); +} + + +void +sg4term_scrollWindowDown(byte numRows) +{ + if (numRows == 0) + return; + + char *rowStartDest = getPosInWindow(0, sg4term_height - 1); // bottom window row + const char *rowStartSrc = rowStartDest - ((word) numRows << 5); + + for (byte i = sg4term_height - numRows; i--; rowStartSrc -= 32, rowStartDest -= 32) // for each window row to scroll + memmove(rowStartDest, rowStartSrc, sg4term_width); + byte c = sg4term_SPACE_CODE ^ sg4term_attributeInversionFlag; + for (byte i = numRows; i--; rowStartDest -= 32) // for each window row to clear + memset(rowStartDest, c, sg4term_width); +} + + +void +sg4term_eraseCurrentLine(void) +{ + memset(getPosInWindow(0, sg4term_cursorRow), sg4term_SPACE_CODE ^ sg4term_attributeInversionFlag, sg4term_width); + sg4term_cursorCol = 0; +} + + +word +sg4term_waitEditorKey(void) +{ + char *cursor = getCursorAddress(); + for (;;) + { + byte origByteOnScreen = *cursor; + + // Wait for key with animated cursor if sg4term_timerPtr is not null. + // Otherwise, wait for key with inverted character at cursor. + byte key; + if (sg4term_timerPtr == NULL) + { + *cursor = origByteOnScreen ^ 0x40; + do + key = (*sg4term_inkeyFuncPtr)(sg4term_inkeyFuncCookie); + while (key == 0); + } + else + { + for (word startTime = *sg4term_timerPtr; ; ) + { + key = (*sg4term_inkeyFuncPtr)(sg4term_inkeyFuncCookie); + if (key) + break; + *cursor = origByteOnScreen ^ (((*sg4term_timerPtr - startTime) & 0x38) == 0x38 ? 0x00 : 0x40); + } + } + + *cursor = origByteOnScreen; + + switch (key) + { + case 3: // Break + return ebitor_KEY_ESCAPE; + case 8: // left arrow + return ebitor_KEY_ARROW_LEFT; + case 9: // right arrow + return ebitor_KEY_ARROW_RIGHT; + case '^': // up arrow + return ebitor_KEY_ARROW_UP; + case 10: // down arrow + return ebitor_KEY_ARROW_DOWN; + case 12: // Clear used as backspace + return '\b'; // backspace + case 13: // Enter + return '\r'; + default: + if (key >= ' ' && key != 127) + return key; + } + } +} + + +static char +sg4term_convertScreenByteToASCII(char b) +{ + if ((byte) b >= 128) + return 0; // 128..255: no equivalent in ASCII + if (b < 32) + return b + 96; + if (b < 64) // 32..63 + return 0; // no equivalent in ASCII + if (b < 96) // 64..95 + return b; + return b - 64; // 96..127 +} + + +void +sg4term_getChars(byte column, byte row, char *dest, size_t len) +{ + assert(column < sg4term_width && row < sg4term_height); + const char *p = getPosInWindow(column, row); + for (size_t i = len; i--; ) + *dest++ = sg4term_convertScreenByteToASCII(*p++); +} diff --git a/sg4term.h b/sg4term.h new file mode 100644 index 0000000..7d4ebed --- /dev/null +++ b/sg4term.h @@ -0,0 +1,95 @@ +/* sg4term.h - CoCo 32x16 SG4 mode (6847) terminal functions. + + Copyright (C) 2021-2025 Pierre Sarrazin + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/* + These functions implement a terminal compliant with the specs in Ebitor.h + in a sub-window of a CoCo 32x16 screen (SG4 mode). +*/ + +#ifndef _H_sg4term +#define _H_sg4term + +#include "Window.h" + + +// Defines a window in a 6847 screen in 32x16 (SG4) mode. +// Does NOT clear the window. +// screenBuffer: Address of the 32x16 screen. +// width: 2..32. +// height: 2..16. +// winLeftCol: 0..30. +// winTopRow: 0..14. +// inkeyFuncPtr: Must return 0 (and not block) if no key pressed. +// inkeyFuncCookie: Will be passed to inkeyFuncPtr. +// timerPtr: Address of an unsigned 16-bit integer that gets incremented 60 times per second. +// If NULL, the cursor will not be animated. +// +void sg4term_init(char *screenBuffer, const ebitor_Window *window, + byte (*inkeyFuncPtr)(void *cookie), void *inkeyFuncCookie, word *timerPtr); + + +// Fills the window defined by sg4term_init() with spaces. +// +void sg4term_clear(void); + +// column, row: Coordinates relative to the window defined by sg4term_init(). +// Does not check if the parameters are valid. +// This may be useful to write outside the window, as long as no carriage return is written. +// +void sg4term_locate(byte column, byte row); + +// column, row: Receive coordinates relative to the window defined by sg4term_init(). +// +void sg4term_getCursorPos(byte *column, byte *row); + +// Returns FALSE the string could not be printed entirely because the printing reached end of window. +// +BOOL sg4term_print(const char *str); + +// Returns FALSE the string could not be printed entirely because the printing reached end of window. +// +BOOL sg4term_printPrefix(const char *str, size_t prefixLength); + +// Use inverted colors for the next print operations. +// +void sg4term_invertColors(void); + +void sg4term_clrtoeol(void); +void sg4term_scrollWindowUp(byte numRows); +void sg4term_scrollWindowDown(byte numRows); + +// Fills the line where the cursor is with spaces and puts the cursor at the start of this line. +// +void sg4term_eraseCurrentLine(void); + +// Animates a cursor while waiting. +// Returns an ASCII code or an ebitor_KEY_* code. +// +word sg4term_waitEditorKey(void); + +// Converts an ASCII code to a 6847 SG4 character code. +// Negative codes (graphics characters) are returned unmodified. +// +char sg4term_convertASCIIToScreenByte(char c); + +// Returns ASCII codes in dest[0..len-1]. Does nothing if len is 0. +// +void sg4term_getChars(byte column, byte row, char *dest, size_t len); + + +#endif /* _H_sg4term */ diff --git a/smoldemo.c b/smoldemo.c new file mode 100644 index 0000000..f230f19 --- /dev/null +++ b/smoldemo.c @@ -0,0 +1,153 @@ +/* smoldemo.c - Minimal demo of the Ebitor full screen text editor. + By Pierre Sarrazin + This file is in the public domain. +*/ + +#include "sg4term.h" /* 32x16 terminal to be used by the editor */ +#include "Ebitor.h" /* the editor */ + +#include + + +/////////////////////////////////////////////////////////////// + + +enum +{ + BASIC_TIMER_ADDRESS = 0x112, // incremented 60 times per second by Basic IRQ routine + BASIC_32X16_SCREEN = 0x0400, // address of 32x16 screen buffer +}; + + +// Contains the edited text. +// +char textBuffer[600]; + + +// newStatus: Must be shorter than the terminal width. +// Does not move the terminal cursor. +// +static void +setStatus(const ebitor_Window *window, const char *newStatus) +{ + byte origCursorCol, origCursorRow; + sg4term_getCursorPos(&origCursorCol, &origCursorRow); + + sg4term_locate(0, window->height); // cursor deliberately on row below window + sg4term_invertColors(); + sg4term_eraseCurrentLine(); // also puts cursor at start of line + sg4term_print(newStatus); + sg4term_invertColors(); + + sg4term_locate(origCursorCol, origCursorRow); +} + + +static void +showHelp(const ebitor_Window *window) +{ + sg4term_clear(); + setStatus(window, "HELP PAGE"); + sg4term_locate(0, 0); + sg4term_print( + "BACKSPACE IS THE CLEAR KEY.\r" + "\r" + "COMMANDS AFTER PRESSING BREAK:" + "\r" + "Q: QUIT THIS EDITOR\r" + "H: SHOW THIS HELP PAGE\r" + "\r" + "PRESS A KEY TO CONTINUE: "); + sg4term_waitEditorKey(); +} + + +static byte +inkey1(void *cookie) +{ + return inkey(); +} + + +// Does not animate a cursor. +// +byte +waitUpperCaseKey(void) +{ + byte key; + while ((key = (byte) toupper(inkey())) == 0) + ; + return key; +} + + +int +main() +{ + width(32); // on a CoCo 3, switches to 32x16 if not already in that mode + rgb(); // on a CoCo 3, resets the palette in case it is not at the default + + ebitor_Window window; + + window.cursorCol = window.cursorRow = 0; + + // Specify a window for the editor. + // A border is left unused, to show that the sg4 driver + // can use a subwindow of the screen. + // Excludes the status line, which this demo renders below this window. + window.width = 32 - 2; + window.height = 16 - 3; + window.leftCol = 1; + window.topRow = 1; + + width(32); // by SECB + cls(3); + sg4term_init((char *) BASIC_32X16_SCREEN, &window, + inkey1, NULL, (word *) BASIC_TIMER_ADDRESS); + + Ebitor_init(textBuffer, sizeof(textBuffer), + window.width, window.height, + sg4term_clear, + sg4term_locate, + sg4term_getCursorPos, + sg4term_print, + sg4term_printPrefix, + sg4term_clrtoeol, + sg4term_scrollWindowUp, + sg4term_scrollWindowDown, + sg4term_waitEditorKey); + + // Main editing loop. + // + for (BOOL refresh = TRUE, resetStatus = TRUE; ; ) + { + if (resetStatus) + setStatus(&window, "PRESS BREAK FOR MENU"); + else + resetStatus = TRUE; + + Ebitor_processEditing(refresh); + + refresh = FALSE; + + setStatus(&window, "Q=QUIT, H=HELP"); + byte key = waitUpperCaseKey(); + if (key == 3) // if break key + continue; // back to processing + if (key == 'Q') + break; // quit + switch ((char) key) + { + case 'H': + showHelp(&window); + refresh = TRUE; + break; + } + } + + Ebitor_shutdown(); + + cls(255); // equivalent to Basic's CLS command without an argument + printf("FINAL TEXT:\n\n%s\n", textBuffer); + return 0; +}