diff --git a/src/Makefile.am b/src/Makefile.am index c97290a..2d4f7bd 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -338,22 +338,10 @@ EXTRA_DIST += \ include/wx_strings.h \ include/xml_io.h \ widgets/missing_strings.c \ - widgets/Fl_Text_Buffer_mod_1_1.cxx \ - widgets/Fl_Text_Buffer_mod_1_3.cxx \ - widgets/Fl_Text_Display_mod_1_1.cxx \ - widgets/Fl_Text_Display_mod_1_3.cxx \ - widgets/Fl_Text_Editor_mod_1_1.cxx \ - widgets/Fl_Text_Editor_mod_1_3.cxx \ - include/Fl_Text_Buffer_mod.H \ - include/Fl_Text_Buffer_mod_1_1.H \ - include/Fl_Text_Buffer_mod_1_3.H \ - include/Fl_Text_Display_mod.H \ - include/Fl_Text_Display_mod_1_1.H \ - include/Fl_Text_Display_mod_1_3.H \ - include/Fl_Text_Editor_mod.H \ - include/Fl_Text_Editor_mod_1_1.H \ - include/Fl_Text_Editor_mod_1_3.H \ include/FTextView.h \ + include/Fl_Text_Buffer_mod.H \ + include/Fl_Text_Display_mod.H \ + include/Fl_Text_Editor_mod.H \ include/blank.h \ include/csv.h \ include/missing_strings.h \ diff --git a/src/include/FTextView.h b/src/include/FTextView.h index 4d5dad0..f595973 100644 --- a/src/include/FTextView.h +++ b/src/include/FTextView.h @@ -4,24 +4,21 @@ // Copyright (C) 2007-2009 // Stelios Bounanos, M0GLD // -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ +// This file is part of FLAMP. // -// This file is part of flmsg -// -// flrig is free software; you can redistribute it and/or modify +// This 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. // -// flrig is distributed in the hope that it will be useful, +// This software 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 FTextView_H_ @@ -46,8 +43,8 @@ public: // CLICK_START: same as first clickable style // NATTR: number of styles (last style + 1) enum TEXT_ATTR { RECV, XMIT, CTRL, SKIP, ALTR, - CLICK_START, QSY = CLICK_START, /* FOO, BAR, ..., */ - NATTR }; + CLICK_START, QSY = CLICK_START, /* FOO, BAR, ..., */ + NATTR }; FTextBase(int x, int y, int w, int h, const char *l = 0); virtual ~FTextBase() { delete tbuf; delete sbuf; } @@ -80,7 +77,7 @@ public: protected: void set_style(int attr, Fl_Font f, int s, Fl_Color c, - int set = SET_FONT | SET_SIZE | SET_COLOR); + int set = SET_FONT | SET_SIZE | SET_COLOR); int readFile(const char* fn = 0); void saveFile(void); char* get_word(int x, int y, const char* nwchars = "", bool ontext = true); @@ -109,7 +106,7 @@ protected: int max_lines; bool scroll_hint; bool restore_wrap; -// bool wrap_restore; + // bool wrap_restore; private: int oldw, oldh, olds; @@ -123,7 +120,7 @@ class FTextView : public FTextBase { public: FTextView(int x, int y, int w, int h, const char *l = 0); - ~FTextView() { } + ~FTextView() { } virtual int handle(int event); @@ -136,7 +133,7 @@ protected: virtual void handle_context_menu(void); virtual void menu_cb(size_t item); static void changed_cb(int pos, int nins, int ndel, int nsty, - const char *dtext, void *arg); + const char *dtext, void *arg); void change_keybindings(void); private: @@ -171,7 +168,7 @@ protected: virtual void handle_context_menu(void); virtual void menu_cb(size_t item); static void changed_cb(int pos, int nins, int ndel, int nsty, - const char *dtext, void *arg); + const char *dtext, void *arg); private: FTextEdit(); diff --git a/src/include/Fl_Text_Buffer_mod.H b/src/include/Fl_Text_Buffer_mod.H index 56f7e52..1a84b2a 100644 --- a/src/include/Fl_Text_Buffer_mod.H +++ b/src/include/Fl_Text_Buffer_mod.H @@ -1,27 +1,788 @@ -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ + // -// This file is part of flmsg +// "$Id: Fl_Text_Buffer_mod.H 8148 2010-12-31 22:38:03Z matt $" // -// flrig 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. +// Header file for Fl_Text_Buffer_mod class. // -// flrig is distributed in the hope that it will be useful, +// Copyright 2001-2010 by Bill Spitzak and others. +// Original code Copyright Mark Edel. Permission to distribute under +// the LGPL for the FLTK library granted by Mark Edel. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Library General Public +// License as published by the Free Software Foundation; either +// version 2 of the License, or (at your option) any later version. +// +// This library 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. +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Library 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 . -// ---------------------------------------------------------------------------- +// You should have received a copy of the GNU Library General Public +// License along with this library; if not, write to the +// +// Free Software Foundation, Inc. +// 51 Franklin Street, Fifth Floor +// Boston, MA 02110-1301 USA. +// +// Please report all bugs and problems on the following page: +// +// http://www.fltk.org/str.php +// + +/* \file + Fl_Text_Buffer_mod, Fl_Text_Selection_mod widget . */ + +#ifndef Fl_Text_Buffer_mod_H +#define Fl_Text_Buffer_mod_H #include -#if FLMSG_FLTK_API_MINOR < 3 -# include "Fl_Text_Buffer_mod_1_1.H" +#undef ASSERT_UTF8 + +#ifdef ASSERT_UTF8 +# include +# define IS_UTF8_ALIGNED(a) if (a && *a) assert(fl_utf8len(*(a))>0); +# define IS_UTF8_ALIGNED2(a, b) if (b>=0 && blength()) assert(fl_utf8len(a->byte_at(b))>0); #else -# include "Fl_Text_Buffer_mod_1_3.H" +# define IS_UTF8_ALIGNED(a) +# define IS_UTF8_ALIGNED2(a, b) #endif + + +/* + "character size" is the size of a UTF-8 character in bytes + "character width" is the width of a Unicode character in pixels + "column" was orginally defined as a character offset from the left margin. + It was identical to the byte offset. In UTF-8, we have neither a byte offset + nor truly fixed width fonts (*). Column could be a pixel value multiplied with + an average character width (which is a bearable approximation). + + * in Unicode, there are no fixed width fonts! Even if the ASCII characters may + happen to be all the same width in pixels, chinese charcaters surely are not. + There are plenty of exceptions, like ligatures, that make special handling of + "fixed" character widths a nightmare. I decided to remove all references to + fixed fonts and see "columns" as a multiple of the average width of a + character in the main font. + - Matthias + */ + + +/* Maximum length in characters of a tab or control character expansion + of a single buffer character */ +#define FL_TEXT_MAX_EXP_CHAR_LEN 20 + +#include + + +/** + \class Fl_Text_Selection_mod + \brief This is an internal class for Fl_Text_Buffer_mod to manage text selections. + This class works correctly with utf-8 strings assuming that the parameters + for all calls are on character boundaries. + */ +class FL_EXPORT Fl_Text_Selection_mod { + friend class Fl_Text_Buffer_mod; + +public: + + /** + \brief Set the selection range. + \param start byte offset to first selected character + \param end byte offset pointing after last selected character + */ + void set(int start, int end); + + /** + \brief Updates a selection afer text was modified. + Updates an individual selection for changes in the corresponding text + \param pos byte offset into text buffer at which the change occured + \param nDeleted number of bytes deleted from the buffer + \param nInserted number of bytes inserted into the buffer + */ + void update(int pos, int nDeleted, int nInserted); + + /** + \brief Return the byte offset to the first selected character. + \return byte offset + */ + int start() const { return mStart; } + + /** + \brief Return the byte ofsset to the character after the last selected character. + \return byte offset + */ + int end() const { return mEnd; } + + /** + \brief Returns true if any text is selected. + \return a non-zero number if any text has been selected, or 0 + if no text is selected. + */ + bool selected() const { return mSelected; } + + /** + \brief Modify the 'selected' flag. + \param b new flag + */ + void selected(bool b) { mSelected = b; } + + /** + Return true if position \p pos with indentation \p dispIndex is in + the Fl_Text_Selection_mod. + */ + int includes(int pos) const; + + /** + \brief Return the positions of this selection. + \param start retrun byte offset to first selected character + \param end retrun byte offset pointing after last selected character + \return true if selected + */ + int position(int* start, int* end) const; + +protected: + + int mStart; ///< byte offset to the first selected character + int mEnd; ///< byte offset to the character after the last selected character + bool mSelected; ///< this flag is set if any text is selected +}; + + +typedef void (*Fl_Text_Modify_Cb)(int pos, int nInserted, int nDeleted, +int nRestyled, const char* deletedText, +void* cbArg); + + +typedef void (*Fl_Text_Predelete_Cb)(int pos, int nDeleted, void* cbArg); + + +/** + \brief This class manages unicode displayed in one or more Fl_Text_Display_mod widgets. + + All text in Fl_Text_Buffer_modmust be encoded in UTF-8. All indices used in the + function calls must be aligned to the start of a UTF-8 sequence. All indices + and pointers returned will be aligned. All functions that return a single + character will return that in an unsiged int in UCS-4 encoding. + + The Fl_Text_Buffer_mod class is used by the Fl_Text_Display_mod + and Fl_Text_Editor_mod to manage complex text data and is based upon the + excellent NEdit text editor engine - see http://www.nedit.org/. + */ +class FL_EXPORT Fl_Text_Buffer_mod { +public: + + /** + Create an empty text buffer of a pre-determined size. + \param requestedSize use this to avoid unnecessary re-allocation + if you know exactly how much the buffer will need to hold + \param preferredGapSize Initial size for the buffer gap (empty space + in the buffer where text might be inserted + if the user is typing sequential chars) + */ + Fl_Text_Buffer_mod(int requestedSize = 0, int preferredGapSize = 1024); + + /** + Frees a text buffer + */ + ~Fl_Text_Buffer_mod(); + + /** + \brief Returns the number of bytes in the buffer. + \return size of text in bytes + */ + int length() const { return mLength; } + + /** + \brief Get a copy of the entire contents of the text buffer. + Memory is allocated to contain the returned string, which the caller + must free. + \return newly allocated text buffer - must be free'd, text is utf8 + */ + char* text() const; + + /** + Replaces the entire contents of the text buffer. + \param text Text must be valid utf8. + */ + void text(const char* text); + + /** + \brief Get a copy of a part of the text buffer. + Return a copy of the text between \p start and \p end character positions + from text buffer \p buf. Positions start at 0, and the range does not + include the character pointed to by \p end. + When you are done with the text, free it using the free() function. + \param start byte offset to first character + \param end byte offset after last character in range + \return newly allocated text buffer - must be free'd, text is utf8 + */ + char* text_range(int start, int end) const; + + /** + Returns the character at the specified position pos in the buffer. + Positions start at 0 + \param pos byte offset into buffer, pos must be at acharacter boundary + \return Unicode UCS-4 encoded character + */ + unsigned int char_at(int pos) const; + + /** + Returns the raw byte at the specified position pos in the buffer. + Positions start at 0 + \param pos byte offset into buffer + \return unencoded raw byte + */ + char byte_at(int pos) const; + + /** + Convert a byte offset in buffer into a memory address. + \param pos byte offset into buffer + \return byte offset converted to a memory address + */ + const char *address(int pos) const + { return (pos < mGapStart) ? mBuf+pos : mBuf+pos+mGapEnd-mGapStart; } + + /** + Convert a byte offset in buffer into a memory address. + \param pos byte offset into buffer + \return byte offset converted to a memory address + */ + char *address(int pos) + { return (pos < mGapStart) ? mBuf+pos : mBuf+pos+mGapEnd-mGapStart; } + + /** + Inserts null-terminated string \p text at position \p pos. + \param pos insertion position as byte offset (must be utf-8 character aligned) + \param text utf-8 encoded and nul terminated text + */ + void insert(int pos, const char* text); + + /** + Appends the text string to the end of the buffer. + \param t utf-8 encoded and nul terminated text + */ + void append(const char* t) { insert(length(), t); } + + /** + Deletes a range of characters in the buffer. + \param start byte offset to first character to be removed + \param end byte offset to charcatre after last character to be removed + */ + void remove(int start, int end); + + /** + Deletes the characters between \p start and \p end, and inserts the null-terminated string \p text in their place in the buffer. + \param start byte offset to first character to be removed and new insert position + \param end byte offset to charcatre after last character to be removed + \param text utf-8 encoded and nul terminated text + */ + void replace(int start, int end, const char *text); + + /** + Copies text from one buffer to this one. + \param fromBuf source text buffer may be the same as this + \param fromStart byte offset into buffer + \param fromEnd byte offset into buffer + \param toPos destination byte offset into buffer + */ + void copy(Fl_Text_Buffer_mod* fromBuf, int fromStart, int fromEnd, int toPos); + + /** + Undo text modification according to the undo variables or insert text + from the undo buffer + */ + int undo(int *cp=0); + + /** + Lets the undo system know if we can undo changes + */ + void canUndo(char flag=1); + + /** + Inserts a file at the specified position. Returns 0 on success, + non-zero on error (strerror() contains reason). 1 indicates open + for read failed (no data loaded). 2 indicates error occurred + while reading data (data was partially loaded). + File can be UTF-8 or CP1252-encoded. + If the input file is not UTF-8-encoded, the Fl_Text_Buffer_mod widget will contain + UTF-8-transcoded data. By default, the message Fl_Text_Buffer_mod::file_encoding_warning_message + will warn the user about this. + \see input_file_was_transcoded and transcoding_warning_action. + */ + int insertfile(const char *file, int pos, int buflen = 128*1024); + + /** + Appends the named file to the end of the buffer. See also insertfile(). + */ + int appendfile(const char *file, int buflen = 128*1024) + { return insertfile(file, length(), buflen); } + + /** + Loads a text file into the buffer. See also insertfile(). + */ + int loadfile(const char *file, int buflen = 128*1024) + { select(0, length()); remove_selection(); return appendfile(file, buflen); } + + /** + Writes the specified portions of the file to a file. Returns 0 on success, non-zero + on error (strerror() contains reason). 1 indicates open for write failed + (no data saved). 2 indicates error occurred while writing data + (data was partially saved). + */ + int outputfile(const char *file, int start, int end, int buflen = 128*1024); + + /** + Saves a text file from the current buffer + */ + int savefile(const char *file, int buflen = 128*1024) + { return outputfile(file, 0, length(), buflen); } + + /** + Gets the tab width. + */ + int tab_distance() const { return mTabDist; } + + /** + Set the hardware tab distance (width) used by all displays for this buffer, + and used in computing offsets for rectangular selection operations. + */ + void tab_distance(int tabDist); + + /** + Selects a range of characters in the buffer. + */ + void select(int start, int end); + + /** + Returns a non 0 value if text has been selected, 0 otherwise + */ + int selected() const { return mPrimary.selected(); } + + /** + Cancels any previous selection on the primary text selection object + */ + void unselect(); + + /** + Gets the selection position + */ + int selection_position(int* start, int* end); + + /** + Returns the currently selected text. When you are done with + the text, free it using the free() function. + */ + char* selection_text(); + + /** + Removes the text in the primary selection. + */ + void remove_selection(); + + /** + Replaces the text in the primary selection. + */ + void replace_selection(const char* text); + + /** + Selects a range of characters in the secondary selection. + */ + void secondary_select(int start, int end); + + /** + Returns a non 0 value if text has been selected in the secondary + text selection, 0 otherwise + */ + int secondary_selected() { return mSecondary.selected(); } + + /** + Clears any selection in the secondary text selection object. + */ + void secondary_unselect(); + + /** + Returns the current selection in the secondary text selection object. + */ + int secondary_selection_position(int* start, int* end); + + /** + Returns the text in the secondary selection. When you are + done with the text, free it using the free() function. + */ + char* secondary_selection_text(); + + /** + Removes the text from the buffer corresponding to the secondary text selection object. + */ + void remove_secondary_selection(); + + /** + Replaces the text from the buffer corresponding to the secondary + text selection object with the new string \p text. + */ + void replace_secondary_selection(const char* text); + + /** + Highlights the specified text within the buffer. + */ + void highlight(int start, int end); + + /** + Returns the highlighted text. When you are done with the + text, free it using the free() function. + */ + int highlight() { return mHighlight.selected(); } + + /** + Unhighlights text in the buffer. + */ + void unhighlight(); + + /** + Highlights the specified text between \p start and \p end within the buffer. + */ + int highlight_position(int* start, int* end); + + /** + Returns the highlighted text. When you are done with the + text, free it using the free() function. + */ + char* highlight_text(); + + /** + Adds a callback function that is called whenever the text buffer is + modified. The callback function is declared as follows: + + \code + typedef void (*Fl_Text_Modify_Cb)(int pos, int nInserted, int nDeleted, + int nRestyled, const char* deletedText, + void* cbArg); + \endcode + */ + void add_modify_callback(Fl_Text_Modify_Cb bufModifiedCB, void* cbArg); + + /** + Removes a modify callback. + */ + void remove_modify_callback(Fl_Text_Modify_Cb bufModifiedCB, void* cbArg); + + /** + Calls all modify callbacks that have been registered using + the add_modify_callback() + method. + */ + void call_modify_callbacks() { call_modify_callbacks(0, 0, 0, 0, 0); } + + /** + Adds a callback routine to be called before text is deleted from the buffer. + */ + void add_predelete_callback(Fl_Text_Predelete_Cb bufPredelCB, void* cbArg); + + /** + Removes a callback routine \p bufPreDeleteCB associated with argument \p cbArg + to be called before text is deleted from the buffer. + */ + void remove_predelete_callback(Fl_Text_Predelete_Cb predelCB, void* cbArg); + + /** + Calls the stored pre-delete callback procedure(s) for this buffer to update + the changed area(s) on the screen and any other listeners. + */ + void call_predelete_callbacks() { call_predelete_callbacks(0, 0); } + + /** + Returns the text from the entire line containing the specified + character position. When you are done with the text, free it + using the free() function. + \param pos byte index into buffer + \return copy of utf8 text, must be free'd + */ + char* line_text(int pos) const; + + /** + Returns the position of the start of the line containing position \p pos. + \param pos byte index into buffer + \return byte offset to line start + */ + int line_start(int pos) const; + + /** + Finds and returns the position of the end of the line containing position \p pos + (which is either a pointer to the newline character ending the line, + or a pointer to one character beyond the end of the buffer) + \param pos byte index into buffer + \return byte offset to line end + */ + int line_end(int pos) const; + + /** + Returns the position corresponding to the start of the word + \param pos byte index into buffer + \return byte offset to word start + */ + int word_start(int pos) const; + + /** + Returns the position corresponding to the end of the word. + \param pos byte index into buffer + \return byte offset to word end + */ + int word_end(int pos) const; + + /** + Count the number of displayed characters between buffer position + \p lineStartPos and \p targetPos. (displayed characters are the characters + shown on the screen to represent characters in the buffer, where tabs and + control characters are expanded) + */ + int count_displayed_characters(int lineStartPos, int targetPos) const; + + /** + Count forward from buffer position \p startPos in displayed characters + (displayed characters are the characters shown on the screen to represent + characters in the buffer, where tabs and control characters are expanded) + \param lineStartPos byte offset into buffer + \param nChars number of bytes that are sent to the display + \return byte offset in input after all output bytes are sent + */ + int skip_displayed_characters(int lineStartPos, int nChars); + + /** + Counts the number of newlines between \p startPos and \p endPos in buffer. + The character at position \p endPos is not counted. + */ + int count_lines(int startPos, int endPos) const; + + /** + Finds the first character of the line \p nLines forward from \p startPos + in the buffer and returns its position + */ + int skip_lines(int startPos, int nLines); + + /** + Finds and returns the position of the first character of the line \p nLines backwards + from \p startPos (not counting the character pointed to by \p startpos if + that is a newline) in the buffer. \p nLines == 0 means find the beginning of the line + */ + int rewind_lines(int startPos, int nLines); + + /** + Finds the next occurrence of the specified character. + Search forwards in buffer for character \p searchChar, starting + with the character \p startPos, and returning the result in \p foundPos + returns 1 if found, 0 if not. (The difference between this and + BufSearchForward is that it's optimized for single characters. The + overall performance of the text widget is dependent on its ability to + count lines quickly, hence searching for a single character: newline) + \param startPos byte offset to start position + \param searchChar UCS-4 character that we want to find + \param foundPos byte offset where the character was found + \return 1 if found, 0 if not + */ + int findchar_forward(int startPos, unsigned searchChar, int* foundPos) const; + + /** + Search backwards in buffer \p buf for character \p searchChar, starting + with the character BEFORE \p startPos, returning the result in \p foundPos + returns 1 if found, 0 if not. (The difference between this and + BufSearchBackward is that it's optimized for single characters. The + overall performance of the text widget is dependent on its ability to + count lines quickly, hence searching for a single character: newline) + \param startPos byte offset to start position + \param searchChar UCS-4 character that we want to find + \param foundPos byte offset where the character was found + \return 1 if found, 0 if not + */ + int findchar_backward(int startPos, unsigned int searchChar, int* foundPos) const; + + /** + Search forwards in buffer for string \p searchString, starting with the + character \p startPos, and returning the result in \p foundPos + returns 1 if found, 0 if not. + \param startPos byte offset to start position + \param searchString utf8 string that we want to find + \param foundPos byte offset where the string was found + \param matchCase if set, match character case + \return 1 if found, 0 if not + */ + int search_forward(int startPos, const char* searchString, int* foundPos, + int matchCase = 0) const; + + /** + Search backwards in buffer for string searchCharssearchString, starting with the + character BEFORE \p startPos, returning the result in \p foundPos + returns 1 if found, 0 if not. + \param startPos byte offset to start position + \param searchString utf8 string that we want to find + \param foundPos byte offset where the string was found + \param matchCase if set, match character case + \return 1 if found, 0 if not + */ + int search_backward(int startPos, const char* searchString, int* foundPos, + int matchCase = 0) const; + + int findchars_forward(int startPos, const char* searchChars, int* foundPos); + int findchars_backward(int startPos, const char* searchChars, int* foundPos); + + /** + Returns the primary selection. + */ + const Fl_Text_Selection_mod* primary_selection() const { return &mPrimary; } + + /** + Returns the primary selection. + */ + Fl_Text_Selection_mod* primary_selection() { return &mPrimary; } + + /** + Returns the secondary selection. + */ + const Fl_Text_Selection_mod* secondary_selection() const { return &mSecondary; } + + /** + Returns the current highlight selection. + */ + const Fl_Text_Selection_mod* highlight_selection() const { return &mHighlight; } + + /** + Returns the index of the previous character. + \param ix index to the current char + */ + int prev_char(int ix) const; + int prev_char_clipped(int ix) const; + + /** + Returns the index of the next character. + \param ix index to the current char + */ + int next_char(int ix) const; + int next_char_clipped(int ix) const; + + /** + Align an index into the buffer to the current or previous utf8 boundary. + */ + int utf8_align(int) const; + + /** + \brief true iff the loaded file has been transcoded to UTF-8 + */ + int input_file_was_transcoded; + + /** This message may be displayed using the fl_alert() function when a file + which was not UTF-8 encoded is input. + */ + static const char* file_encoding_warning_message; + + /** + \brief Pointer to a function called after reading a non UTF-8 encoded file. + + This function is called after reading a file if the file content + was transcoded to UTF-8. Its default implementation calls fl_alert() + with the text of \ref file_encoding_warning_message. No warning message is + displayed if this pointer is set to NULL. Use \ref input_file_was_transcoded + to be informed if file input required transcoding to UTF-8. + */ + void (*transcoding_warning_action)(Fl_Text_Buffer_mod*); + +protected: + + /** + Calls the stored modify callback procedure(s) for this buffer to update the + changed area(s) on the screen and any other listeners. + */ + void call_modify_callbacks(int pos, int nDeleted, int nInserted, + int nRestyled, const char* deletedText) const; + + /** + Calls the stored pre-delete callback procedure(s) for this buffer to update + the changed area(s) on the screen and any other listeners. + */ + void call_predelete_callbacks(int pos, int nDeleted) const; + + /** + Internal (non-redisplaying) version of BufInsert. Returns the length of + text inserted (this is just strlen(\p text), however this calculation can be + expensive and the length will be required by any caller who will continue + on to call redisplay). \p pos must be contiguous with the existing text in + the buffer (i.e. not past the end). + \return the number of bytes inserted + */ + int insert_(int pos, const char* text); + + /** + Internal (non-redisplaying) version of BufRemove. Removes the contents + of the buffer between start and end (and moves the gap to the site of + the delete). + */ + void remove_(int start, int end); + + /** + Calls the stored redisplay procedure(s) for this buffer to update the + screen for a change in a selection. + */ + void redisplay_selection(Fl_Text_Selection_mod* oldSelection, + Fl_Text_Selection_mod* newSelection) const; + + /** + Move the gap to start at a new position. + */ + void move_gap(int pos); + + /** + Reallocates the text storage in the buffer to have a gap starting at \p newGapStart + and a gap size of \p newGapLen, preserving the buffer's current contents. + */ + void reallocate_with_gap(int newGapStart, int newGapLen); + + char* selection_text_(Fl_Text_Selection_mod* sel) const; + + /** + Removes the text from the buffer corresponding to \p sel. + */ + void remove_selection_(Fl_Text_Selection_mod* sel); + + /** + Replaces the \p text in selection \p sel. + */ + void replace_selection_(Fl_Text_Selection_mod* sel, const char* text); + + /** + Updates all of the selections in the buffer for changes in the buffer's text + */ + void update_selections(int pos, int nDeleted, int nInserted); + + Fl_Text_Selection_mod mPrimary; /**< highlighted areas */ + Fl_Text_Selection_mod mSecondary; /**< highlighted areas */ + Fl_Text_Selection_mod mHighlight; /**< highlighted areas */ + int mLength; /**< length of the text in the buffer (the length + of the buffer itself must be calculated: + gapEnd - gapStart + length) */ + char* mBuf; /**< allocated memory where the text is stored */ + int mGapStart; /**< points to the first character of the gap */ + int mGapEnd; /**< points to the first char after the gap */ + // The hardware tab distance used by all displays for this buffer, + // and used in computing offsets for rectangular selection operations. + int mTabDist; /**< equiv. number of characters in a tab */ + int mNModifyProcs; /**< number of modify-redisplay procs attached */ + Fl_Text_Modify_Cb *mModifyProcs;/**< procedures to call when buffer is + modified to redisplay contents */ + void** mCbArgs; /**< caller arguments for modifyProcs above */ + int mNPredeleteProcs; /**< number of pre-delete procs attached */ + Fl_Text_Predelete_Cb *mPredeleteProcs; /**< procedure to call before text is deleted + from the buffer; at most one is supported. */ + void **mPredeleteCbArgs; /**< caller argument for pre-delete proc above */ + int mCursorPosHint; /**< hint for reasonable cursor position after + a buffer modification operation */ + char mCanUndo; /**< if this buffer is used for attributes, it must + not do any undo calls */ + int mPreferredGapSize; /**< the default allocation for the text gap is 1024 + bytes and should only be increased if frequent + and large changes in buffer size are expected */ +}; + +#endif + +// +// End of "$Id: Fl_Text_Buffer_mod.H 8148 2010-12-31 22:38:03Z matt $". +// diff --git a/src/include/Fl_Text_Buffer_mod_1_1.H b/src/include/Fl_Text_Buffer_mod_1_1.H deleted file mode 100644 index 72a5f5c..0000000 --- a/src/include/Fl_Text_Buffer_mod_1_1.H +++ /dev/null @@ -1,262 +0,0 @@ -// -// "$Id: Fl_Text_Buffer.H 6010 2008-01-04 20:31:52Z matt $" -// -// Header file for Fl_Text_Buffer class. -// -// Copyright 2001-2005 by Bill Spitzak and others. -// Original code Copyright Mark Edel. Permission to distribute under -// the LGPL for the FLTK library granted by Mark Edel. -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ -// -// This file is part of flmsg -// -// flrig 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. -// -// flrig 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 FL_TEXT_BUFFER_H -#define FL_TEXT_BUFFER_H - -/* Maximum length in characters of a tab or control character expansion - of a single buffer character */ -#define FL_TEXT_MAX_EXP_CHAR_LEN 20 - -#include - -class FL_EXPORT Fl_Text_Selection { - friend class Fl_Text_Buffer_mod; - - public: - void set(int start, int end); - void set_rectangular(int start, int end, int rectStart, int rectEnd); - void update(int pos, int nDeleted, int nInserted); - char rectangular() { return mRectangular; } - int start() { return mStart; } - int end() { return mEnd; } - int rect_start() { return mRectStart; } - int rect_end() { return mRectEnd; } - char selected() { return mSelected; } - void selected(char b) { mSelected = b; } - int includes(int pos, int lineStartPos, int dispIndex); - int position(int* start, int* end); - int position(int* start, int* end, int* isRect, int* rectStart, int* rectEnd); - - - protected: - char mSelected; - char mRectangular; - int mStart; - int mEnd; - int mRectStart; - int mRectEnd; -}; - -typedef void (*Fl_Text_Modify_Cb)(int pos, int nInserted, int nDeleted, - int nRestyled, const char* deletedText, - void* cbArg); -typedef void (*Fl_Text_Predelete_Cb)(int pos, int nDeleted, void* cbArg); - -class FL_EXPORT Fl_Text_Buffer_mod { - public: - Fl_Text_Buffer_mod(int requestedSize = 0); - ~Fl_Text_Buffer_mod(); - - int length() { return mLength; } - char* text(); - void text(const char* text); - char* text_range(int start, int end); - char character(int pos); - char* text_in_rectangle(int start, int end, int rectStart, int rectEnd); - void insert(int pos, const char* text); - void append(const char* t) { insert(length(), t); } - void remove(int start, int end); - void replace(int start, int end, const char *text); - void copy(Fl_Text_Buffer_mod* fromBuf, int fromStart, int fromEnd, int toPos); - int undo(int *cp=0); - void canUndo(char flag=1); - int insertfile(const char *file, int pos, int buflen = 128*1024); - int appendfile(const char *file, int buflen = 128*1024) - { return insertfile(file, length(), buflen); } - int loadfile(const char *file, int buflen = 128*1024) - { select(0, length()); remove_selection(); return appendfile(file, buflen); } - int outputfile(const char *file, int start, int end, int buflen = 128*1024); - int savefile(const char *file, int buflen = 128*1024) - { return outputfile(file, 0, length(), buflen); } - - void insert_column(int column, int startPos, const char* text, - int* charsInserted, int* charsDeleted); - - void replace_rectangular(int start, int end, int rectStart, int rectEnd, - const char* text); - - void overlay_rectangular(int startPos, int rectStart, int rectEnd, - const char* text, int* charsInserted, - int* charsDeleted); - - void remove_rectangular(int start, int end, int rectStart, int rectEnd); - void clear_rectangular(int start, int end, int rectStart, int rectEnd); - int tab_distance() { return mTabDist; } - void tab_distance(int tabDist); - void select(int start, int end); - int selected() { return mPrimary.selected(); } - void unselect(); - void select_rectangular(int start, int end, int rectStart, int rectEnd); - int selection_position(int* start, int* end); - - int selection_position(int* start, int* end, int* isRect, int* rectStart, - int* rectEnd); - - char* selection_text(); - void remove_selection(); - void replace_selection(const char* text); - void secondary_select(int start, int end); - int secondary_selected() { return mSecondary.selected(); } - void secondary_unselect(); - - void secondary_select_rectangular(int start, int end, int rectStart, - int rectEnd); - - int secondary_selection_position(int* start, int* end); - int secondary_selection_position(int* start, int* end, int* isRect, - int* rectStart, int* rectEnd); - - char* secondary_selection_text(); - void remove_secondary_selection(); - void replace_secondary_selection(const char* text); - void highlight(int start, int end); - int highlight() { return mHighlight.selected(); } - void unhighlight(); - void highlight_rectangular(int start, int end, int rectStart, int rectEnd); - - int highlight_position(int* start, int* end); - int highlight_position(int* start, int* end, int* isRect, int* rectStart, - int* rectEnd); - - char* highlight_text(); - void add_modify_callback(Fl_Text_Modify_Cb bufModifiedCB, void* cbArg); - void remove_modify_callback(Fl_Text_Modify_Cb bufModifiedCB, void* cbArg); - - void call_modify_callbacks() { call_modify_callbacks(0, 0, 0, 0, 0); } - - void add_predelete_callback(Fl_Text_Predelete_Cb bufPredelCB, void* cbArg); - void remove_predelete_callback(Fl_Text_Predelete_Cb predelCB, void* cbArg); - - void call_predelete_callbacks() { call_predelete_callbacks(0, 0); } - - char* line_text(int pos); - int line_start(int pos); - int line_end(int pos); - int word_start(int pos); - int word_end(int pos); - int expand_character(int pos, int indent, char *outStr); - - static int expand_character(char c, int indent, char* outStr, int tabDist, - char nullSubsChar); - - static int character_width(char c, int indent, int tabDist, char nullSubsChar); - int count_displayed_characters(int lineStartPos, int targetPos); - int skip_displayed_characters(int lineStartPos, int nChars); - int count_lines(int startPos, int endPos); - int skip_lines(int startPos, int nLines); - int rewind_lines(int startPos, int nLines); - int findchar_forward(int startPos, char searchChar, int* foundPos); - int findchar_backward(int startPos, char searchChar, int* foundPos); - int findchars_forward(int startPos, const char* searchChars, int* foundPos); - int findchars_backward(int startPos, const char* searchChars, int* foundPos); - - int search_forward(int startPos, const char* searchString, int* foundPos, - int matchCase = 0); - - int search_backward(int startPos, const char* searchString, int* foundPos, - int matchCase = 0); - - int substitute_null_characters(char* string, int length); - void unsubstitute_null_characters(char* string); - char null_substitution_character() { return mNullSubsChar; } - Fl_Text_Selection* primary_selection() { return &mPrimary; } - Fl_Text_Selection* secondary_selection() { return &mSecondary; } - Fl_Text_Selection* highlight_selection() { return &mHighlight; } - - protected: - void call_modify_callbacks(int pos, int nDeleted, int nInserted, - int nRestyled, const char* deletedText); - void call_predelete_callbacks(int pos, int nDeleted); - - int insert_(int pos, const char* text); - void remove_(int start, int end); - - void remove_rectangular_(int start, int end, int rectStart, int rectEnd, - int* replaceLen, int* endPos); - - void insert_column_(int column, int startPos, const char* insText, - int* nDeleted, int* nInserted, int* endPos); - - void overlay_rectangular_(int startPos, int rectStart, int rectEnd, - const char* insText, int* nDeleted, - int* nInserted, int* endPos); - - void redisplay_selection(Fl_Text_Selection* oldSelection, - Fl_Text_Selection* newSelection); - - void move_gap(int pos); - void reallocate_with_gap(int newGapStart, int newGapLen); - char* selection_text_(Fl_Text_Selection* sel); - void remove_selection_(Fl_Text_Selection* sel); - void replace_selection_(Fl_Text_Selection* sel, const char* text); - - void rectangular_selection_boundaries(int lineStartPos, int rectStart, - int rectEnd, int* selStart, - int* selEnd); - - void update_selections(int pos, int nDeleted, int nInserted); - - Fl_Text_Selection mPrimary; /* highlighted areas */ - Fl_Text_Selection mSecondary; - Fl_Text_Selection mHighlight; - int mLength; /* length of the text in the buffer (the length - of the buffer itself must be calculated: - gapEnd - gapStart + length) */ - char* mBuf; /* allocated memory where the text is stored */ - int mGapStart; /* points to the first character of the gap */ - int mGapEnd; /* points to the first char after the gap */ - // The hardware tab distance used by all displays for this buffer, - // and used in computing offsets for rectangular selection operations. - int mTabDist; /* equiv. number of characters in a tab */ - int mUseTabs; /* True if buffer routines are allowed to use - tabs for padding in rectangular operations */ - int mNModifyProcs; /* number of modify-redisplay procs attached */ - Fl_Text_Modify_Cb* /* procedures to call when buffer is */ - mNodifyProcs; /* modified to redisplay contents */ - void** mCbArgs; /* caller arguments for modifyProcs above */ - int mNPredeleteProcs; /* number of pre-delete procs attached */ - Fl_Text_Predelete_Cb* /* procedure to call before text is deleted */ - mPredeleteProcs; /* from the buffer; at most one is supported. */ - void **mPredeleteCbArgs; /* caller argument for pre-delete proc above */ - int mCursorPosHint; /* hint for reasonable cursor position after - a buffer modification operation */ - char mNullSubsChar; /* NEdit is based on C null-terminated strings, - so ascii-nul characters must be substituted - with something else. This is the else, but - of course, things get quite messy when you - use it */ - char mCanUndo; /* if this buffer is used for attributes, it must - not do any undo calls */ -}; - -#endif - -// -// End of "$Id: Fl_Text_Buffer.H 6010 2008-01-04 20:31:52Z matt $". -// diff --git a/src/include/Fl_Text_Buffer_mod_1_3.H b/src/include/Fl_Text_Buffer_mod_1_3.H deleted file mode 100644 index 395ce8a..0000000 --- a/src/include/Fl_Text_Buffer_mod_1_3.H +++ /dev/null @@ -1,783 +0,0 @@ -// -// "$Id: Fl_Text_Buffer_mod.H 8148 2010-12-31 22:38:03Z matt $" -// -// Header file for Fl_Text_Buffer_mod class. -// -// Copyright 2001-2010 by Bill Spitzak and others. -// Original code Copyright Mark Edel. Permission to distribute under -// the LGPL for the FLTK library granted by Mark Edel. -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ -// -// This file is part of flmsg -// -// flrig 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. -// -// flrig 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 . -// ---------------------------------------------------------------------------- - -/* \file - Fl_Text_Buffer_mod, Fl_Text_Selection_mod widget . */ - -#ifndef Fl_Text_Buffer_mod_H -#define Fl_Text_Buffer_mod_H - - -#undef ASSERT_UTF8 - -#ifdef ASSERT_UTF8 -# include -# define IS_UTF8_ALIGNED(a) if (a && *a) assert(fl_utf8len(*(a))>0); -# define IS_UTF8_ALIGNED2(a, b) if (b>=0 && blength()) assert(fl_utf8len(a->byte_at(b))>0); -#else -# define IS_UTF8_ALIGNED(a) -# define IS_UTF8_ALIGNED2(a, b) -#endif - - -/* - "character size" is the size of a UTF-8 character in bytes - "character width" is the width of a Unicode character in pixels - "column" was orginally defined as a character offset from the left margin. - It was identical to the byte offset. In UTF-8, we have neither a byte offset - nor truly fixed width fonts (*). Column could be a pixel value multiplied with - an average character width (which is a bearable approximation). - - * in Unicode, there are no fixed width fonts! Even if the ASCII characters may - happen to be all the same width in pixels, chinese charcaters surely are not. - There are plenty of exceptions, like ligatures, that make special handling of - "fixed" character widths a nightmare. I decided to remove all references to - fixed fonts and see "columns" as a multiple of the average width of a - character in the main font. - - Matthias - */ - - -/* Maximum length in characters of a tab or control character expansion - of a single buffer character */ -#define FL_TEXT_MAX_EXP_CHAR_LEN 20 - -#include - - -/** - \class Fl_Text_Selection_mod - \brief This is an internal class for Fl_Text_Buffer_mod to manage text selections. - This class works correctly with utf-8 strings assuming that the parameters - for all calls are on character boundaries. - */ -class FL_EXPORT Fl_Text_Selection_mod { - friend class Fl_Text_Buffer_mod; - -public: - - /** - \brief Set the selection range. - \param start byte offset to first selected character - \param end byte offset pointing after last selected character - */ - void set(int start, int end); - - /** - \brief Updates a selection afer text was modified. - Updates an individual selection for changes in the corresponding text - \param pos byte offset into text buffer at which the change occured - \param nDeleted number of bytes deleted from the buffer - \param nInserted number of bytes inserted into the buffer - */ - void update(int pos, int nDeleted, int nInserted); - - /** - \brief Return the byte offset to the first selected character. - \return byte offset - */ - int start() const { return mStart; } - - /** - \brief Return the byte ofsset to the character after the last selected character. - \return byte offset - */ - int end() const { return mEnd; } - - /** - \brief Returns true if any text is selected. - \return a non-zero number if any text has been selected, or 0 - if no text is selected. - */ - bool selected() const { return mSelected; } - - /** - \brief Modify the 'selected' flag. - \param b new flag - */ - void selected(bool b) { mSelected = b; } - - /** - Return true if position \p pos with indentation \p dispIndex is in - the Fl_Text_Selection_mod. - */ - int includes(int pos) const; - - /** - \brief Return the positions of this selection. - \param start retrun byte offset to first selected character - \param end retrun byte offset pointing after last selected character - \return true if selected - */ - int position(int* start, int* end) const; - -protected: - - int mStart; ///< byte offset to the first selected character - int mEnd; ///< byte offset to the character after the last selected character - bool mSelected; ///< this flag is set if any text is selected -}; - - -typedef void (*Fl_Text_Modify_Cb)(int pos, int nInserted, int nDeleted, - int nRestyled, const char* deletedText, - void* cbArg); - - -typedef void (*Fl_Text_Predelete_Cb)(int pos, int nDeleted, void* cbArg); - - -/** - \brief This class manages unicode displayed in one or more Fl_Text_Display_mod widgets. - - All text in Fl_Text_Buffer_modmust be encoded in UTF-8. All indices used in the - function calls must be aligned to the start of a UTF-8 sequence. All indices - and pointers returned will be aligned. All functions that return a single - character will return that in an unsiged int in UCS-4 encoding. - - The Fl_Text_Buffer_mod class is used by the Fl_Text_Display_mod - and Fl_Text_Editor_mod to manage complex text data and is based upon the - excellent NEdit text editor engine - see http://www.nedit.org/. - */ -class FL_EXPORT Fl_Text_Buffer_mod { -public: - - /** - Create an empty text buffer of a pre-determined size. - \param requestedSize use this to avoid unnecessary re-allocation - if you know exactly how much the buffer will need to hold - \param preferredGapSize Initial size for the buffer gap (empty space - in the buffer where text might be inserted - if the user is typing sequential chars) - */ - Fl_Text_Buffer_mod(int requestedSize = 0, int preferredGapSize = 1024); - - /** - Frees a text buffer - */ - ~Fl_Text_Buffer_mod(); - - /** - \brief Returns the number of bytes in the buffer. - \return size of text in bytes - */ - int length() const { return mLength; } - - /** - \brief Get a copy of the entire contents of the text buffer. - Memory is allocated to contain the returned string, which the caller - must free. - \return newly allocated text buffer - must be free'd, text is utf8 - */ - char* text() const; - - /** - Replaces the entire contents of the text buffer. - \param text Text must be valid utf8. - */ - void text(const char* text); - - /** - \brief Get a copy of a part of the text buffer. - Return a copy of the text between \p start and \p end character positions - from text buffer \p buf. Positions start at 0, and the range does not - include the character pointed to by \p end. - When you are done with the text, free it using the free() function. - \param start byte offset to first character - \param end byte offset after last character in range - \return newly allocated text buffer - must be free'd, text is utf8 - */ - char* text_range(int start, int end) const; - - /** - Returns the character at the specified position pos in the buffer. - Positions start at 0 - \param pos byte offset into buffer, pos must be at acharacter boundary - \return Unicode UCS-4 encoded character - */ - unsigned int char_at(int pos) const; - - /** - Returns the raw byte at the specified position pos in the buffer. - Positions start at 0 - \param pos byte offset into buffer - \return unencoded raw byte - */ - char byte_at(int pos) const; - - /** - Convert a byte offset in buffer into a memory address. - \param pos byte offset into buffer - \return byte offset converted to a memory address - */ - const char *address(int pos) const - { return (pos < mGapStart) ? mBuf+pos : mBuf+pos+mGapEnd-mGapStart; } - - /** - Convert a byte offset in buffer into a memory address. - \param pos byte offset into buffer - \return byte offset converted to a memory address - */ - char *address(int pos) - { return (pos < mGapStart) ? mBuf+pos : mBuf+pos+mGapEnd-mGapStart; } - - /** - Inserts null-terminated string \p text at position \p pos. - \param pos insertion position as byte offset (must be utf-8 character aligned) - \param text utf-8 encoded and nul terminated text - */ - void insert(int pos, const char* text); - - /** - Appends the text string to the end of the buffer. - \param t utf-8 encoded and nul terminated text - */ - void append(const char* t) { insert(length(), t); } - - /** - Deletes a range of characters in the buffer. - \param start byte offset to first character to be removed - \param end byte offset to charcatre after last character to be removed - */ - void remove(int start, int end); - - /** - Deletes the characters between \p start and \p end, and inserts the null-terminated string \p text in their place in the buffer. - \param start byte offset to first character to be removed and new insert position - \param end byte offset to charcatre after last character to be removed - \param text utf-8 encoded and nul terminated text - */ - void replace(int start, int end, const char *text); - - /** - Copies text from one buffer to this one. - \param fromBuf source text buffer may be the same as this - \param fromStart byte offset into buffer - \param fromEnd byte offset into buffer - \param toPos destination byte offset into buffer - */ - void copy(Fl_Text_Buffer_mod* fromBuf, int fromStart, int fromEnd, int toPos); - - /** - Undo text modification according to the undo variables or insert text - from the undo buffer - */ - int undo(int *cp=0); - - /** - Lets the undo system know if we can undo changes - */ - void canUndo(char flag=1); - - /** - Inserts a file at the specified position. Returns 0 on success, - non-zero on error (strerror() contains reason). 1 indicates open - for read failed (no data loaded). 2 indicates error occurred - while reading data (data was partially loaded). - File can be UTF-8 or CP1252-encoded. - If the input file is not UTF-8-encoded, the Fl_Text_Buffer_mod widget will contain - UTF-8-transcoded data. By default, the message Fl_Text_Buffer_mod::file_encoding_warning_message - will warn the user about this. - \see input_file_was_transcoded and transcoding_warning_action. - */ - int insertfile(const char *file, int pos, int buflen = 128*1024); - - /** - Appends the named file to the end of the buffer. See also insertfile(). - */ - int appendfile(const char *file, int buflen = 128*1024) - { return insertfile(file, length(), buflen); } - - /** - Loads a text file into the buffer. See also insertfile(). - */ - int loadfile(const char *file, int buflen = 128*1024) - { select(0, length()); remove_selection(); return appendfile(file, buflen); } - - /** - Writes the specified portions of the file to a file. Returns 0 on success, non-zero - on error (strerror() contains reason). 1 indicates open for write failed - (no data saved). 2 indicates error occurred while writing data - (data was partially saved). - */ - int outputfile(const char *file, int start, int end, int buflen = 128*1024); - - /** - Saves a text file from the current buffer - */ - int savefile(const char *file, int buflen = 128*1024) - { return outputfile(file, 0, length(), buflen); } - - /** - Gets the tab width. - */ - int tab_distance() const { return mTabDist; } - - /** - Set the hardware tab distance (width) used by all displays for this buffer, - and used in computing offsets for rectangular selection operations. - */ - void tab_distance(int tabDist); - - /** - Selects a range of characters in the buffer. - */ - void select(int start, int end); - - /** - Returns a non 0 value if text has been selected, 0 otherwise - */ - int selected() const { return mPrimary.selected(); } - - /** - Cancels any previous selection on the primary text selection object - */ - void unselect(); - - /** - Gets the selection position - */ - int selection_position(int* start, int* end); - - /** - Returns the currently selected text. When you are done with - the text, free it using the free() function. - */ - char* selection_text(); - - /** - Removes the text in the primary selection. - */ - void remove_selection(); - - /** - Replaces the text in the primary selection. - */ - void replace_selection(const char* text); - - /** - Selects a range of characters in the secondary selection. - */ - void secondary_select(int start, int end); - - /** - Returns a non 0 value if text has been selected in the secondary - text selection, 0 otherwise - */ - int secondary_selected() { return mSecondary.selected(); } - - /** - Clears any selection in the secondary text selection object. - */ - void secondary_unselect(); - - /** - Returns the current selection in the secondary text selection object. - */ - int secondary_selection_position(int* start, int* end); - - /** - Returns the text in the secondary selection. When you are - done with the text, free it using the free() function. - */ - char* secondary_selection_text(); - - /** - Removes the text from the buffer corresponding to the secondary text selection object. - */ - void remove_secondary_selection(); - - /** - Replaces the text from the buffer corresponding to the secondary - text selection object with the new string \p text. - */ - void replace_secondary_selection(const char* text); - - /** - Highlights the specified text within the buffer. - */ - void highlight(int start, int end); - - /** - Returns the highlighted text. When you are done with the - text, free it using the free() function. - */ - int highlight() { return mHighlight.selected(); } - - /** - Unhighlights text in the buffer. - */ - void unhighlight(); - - /** - Highlights the specified text between \p start and \p end within the buffer. - */ - int highlight_position(int* start, int* end); - - /** - Returns the highlighted text. When you are done with the - text, free it using the free() function. - */ - char* highlight_text(); - - /** - Adds a callback function that is called whenever the text buffer is - modified. The callback function is declared as follows: - - \code - typedef void (*Fl_Text_Modify_Cb)(int pos, int nInserted, int nDeleted, - int nRestyled, const char* deletedText, - void* cbArg); - \endcode - */ - void add_modify_callback(Fl_Text_Modify_Cb bufModifiedCB, void* cbArg); - - /** - Removes a modify callback. - */ - void remove_modify_callback(Fl_Text_Modify_Cb bufModifiedCB, void* cbArg); - - /** - Calls all modify callbacks that have been registered using - the add_modify_callback() - method. - */ - void call_modify_callbacks() { call_modify_callbacks(0, 0, 0, 0, 0); } - - /** - Adds a callback routine to be called before text is deleted from the buffer. - */ - void add_predelete_callback(Fl_Text_Predelete_Cb bufPredelCB, void* cbArg); - - /** - Removes a callback routine \p bufPreDeleteCB associated with argument \p cbArg - to be called before text is deleted from the buffer. - */ - void remove_predelete_callback(Fl_Text_Predelete_Cb predelCB, void* cbArg); - - /** - Calls the stored pre-delete callback procedure(s) for this buffer to update - the changed area(s) on the screen and any other listeners. - */ - void call_predelete_callbacks() { call_predelete_callbacks(0, 0); } - - /** - Returns the text from the entire line containing the specified - character position. When you are done with the text, free it - using the free() function. - \param pos byte index into buffer - \return copy of utf8 text, must be free'd - */ - char* line_text(int pos) const; - - /** - Returns the position of the start of the line containing position \p pos. - \param pos byte index into buffer - \return byte offset to line start - */ - int line_start(int pos) const; - - /** - Finds and returns the position of the end of the line containing position \p pos - (which is either a pointer to the newline character ending the line, - or a pointer to one character beyond the end of the buffer) - \param pos byte index into buffer - \return byte offset to line end - */ - int line_end(int pos) const; - - /** - Returns the position corresponding to the start of the word - \param pos byte index into buffer - \return byte offset to word start - */ - int word_start(int pos) const; - - /** - Returns the position corresponding to the end of the word. - \param pos byte index into buffer - \return byte offset to word end - */ - int word_end(int pos) const; - - /** - Count the number of displayed characters between buffer position - \p lineStartPos and \p targetPos. (displayed characters are the characters - shown on the screen to represent characters in the buffer, where tabs and - control characters are expanded) - */ - int count_displayed_characters(int lineStartPos, int targetPos) const; - - /** - Count forward from buffer position \p startPos in displayed characters - (displayed characters are the characters shown on the screen to represent - characters in the buffer, where tabs and control characters are expanded) - \param lineStartPos byte offset into buffer - \param nChars number of bytes that are sent to the display - \return byte offset in input after all output bytes are sent - */ - int skip_displayed_characters(int lineStartPos, int nChars); - - /** - Counts the number of newlines between \p startPos and \p endPos in buffer. - The character at position \p endPos is not counted. - */ - int count_lines(int startPos, int endPos) const; - - /** - Finds the first character of the line \p nLines forward from \p startPos - in the buffer and returns its position - */ - int skip_lines(int startPos, int nLines); - - /** - Finds and returns the position of the first character of the line \p nLines backwards - from \p startPos (not counting the character pointed to by \p startpos if - that is a newline) in the buffer. \p nLines == 0 means find the beginning of the line - */ - int rewind_lines(int startPos, int nLines); - - /** - Finds the next occurrence of the specified character. - Search forwards in buffer for character \p searchChar, starting - with the character \p startPos, and returning the result in \p foundPos - returns 1 if found, 0 if not. (The difference between this and - BufSearchForward is that it's optimized for single characters. The - overall performance of the text widget is dependent on its ability to - count lines quickly, hence searching for a single character: newline) - \param startPos byte offset to start position - \param searchChar UCS-4 character that we want to find - \param foundPos byte offset where the character was found - \return 1 if found, 0 if not - */ - int findchar_forward(int startPos, unsigned searchChar, int* foundPos) const; - - /** - Search backwards in buffer \p buf for character \p searchChar, starting - with the character BEFORE \p startPos, returning the result in \p foundPos - returns 1 if found, 0 if not. (The difference between this and - BufSearchBackward is that it's optimized for single characters. The - overall performance of the text widget is dependent on its ability to - count lines quickly, hence searching for a single character: newline) - \param startPos byte offset to start position - \param searchChar UCS-4 character that we want to find - \param foundPos byte offset where the character was found - \return 1 if found, 0 if not - */ - int findchar_backward(int startPos, unsigned int searchChar, int* foundPos) const; - - /** - Search forwards in buffer for string \p searchString, starting with the - character \p startPos, and returning the result in \p foundPos - returns 1 if found, 0 if not. - \param startPos byte offset to start position - \param searchString utf8 string that we want to find - \param foundPos byte offset where the string was found - \param matchCase if set, match character case - \return 1 if found, 0 if not - */ - int search_forward(int startPos, const char* searchString, int* foundPos, - int matchCase = 0) const; - - /** - Search backwards in buffer for string searchCharssearchString, starting with the - character BEFORE \p startPos, returning the result in \p foundPos - returns 1 if found, 0 if not. - \param startPos byte offset to start position - \param searchString utf8 string that we want to find - \param foundPos byte offset where the string was found - \param matchCase if set, match character case - \return 1 if found, 0 if not - */ - int search_backward(int startPos, const char* searchString, int* foundPos, - int matchCase = 0) const; - - int findchars_forward(int startPos, const char* searchChars, int* foundPos); - int findchars_backward(int startPos, const char* searchChars, int* foundPos); - - /** - Returns the primary selection. - */ - const Fl_Text_Selection_mod* primary_selection() const { return &mPrimary; } - - /** - Returns the primary selection. - */ - Fl_Text_Selection_mod* primary_selection() { return &mPrimary; } - - /** - Returns the secondary selection. - */ - const Fl_Text_Selection_mod* secondary_selection() const { return &mSecondary; } - - /** - Returns the current highlight selection. - */ - const Fl_Text_Selection_mod* highlight_selection() const { return &mHighlight; } - - /** - Returns the index of the previous character. - \param ix index to the current char - */ - int prev_char(int ix) const; - int prev_char_clipped(int ix) const; - - /** - Returns the index of the next character. - \param ix index to the current char - */ - int next_char(int ix) const; - int next_char_clipped(int ix) const; - - /** - Align an index into the buffer to the current or previous utf8 boundary. - */ - int utf8_align(int) const; - - /** - \brief true iff the loaded file has been transcoded to UTF-8 - */ - int input_file_was_transcoded; - - /** This message may be displayed using the fl_alert() function when a file - which was not UTF-8 encoded is input. - */ - static const char* file_encoding_warning_message; - - /** - \brief Pointer to a function called after reading a non UTF-8 encoded file. - - This function is called after reading a file if the file content - was transcoded to UTF-8. Its default implementation calls fl_alert() - with the text of \ref file_encoding_warning_message. No warning message is - displayed if this pointer is set to NULL. Use \ref input_file_was_transcoded - to be informed if file input required transcoding to UTF-8. - */ - void (*transcoding_warning_action)(Fl_Text_Buffer_mod*); - -protected: - - /** - Calls the stored modify callback procedure(s) for this buffer to update the - changed area(s) on the screen and any other listeners. - */ - void call_modify_callbacks(int pos, int nDeleted, int nInserted, - int nRestyled, const char* deletedText) const; - - /** - Calls the stored pre-delete callback procedure(s) for this buffer to update - the changed area(s) on the screen and any other listeners. - */ - void call_predelete_callbacks(int pos, int nDeleted) const; - - /** - Internal (non-redisplaying) version of BufInsert. Returns the length of - text inserted (this is just strlen(\p text), however this calculation can be - expensive and the length will be required by any caller who will continue - on to call redisplay). \p pos must be contiguous with the existing text in - the buffer (i.e. not past the end). - \return the number of bytes inserted - */ - int insert_(int pos, const char* text); - - /** - Internal (non-redisplaying) version of BufRemove. Removes the contents - of the buffer between start and end (and moves the gap to the site of - the delete). - */ - void remove_(int start, int end); - - /** - Calls the stored redisplay procedure(s) for this buffer to update the - screen for a change in a selection. - */ - void redisplay_selection(Fl_Text_Selection_mod* oldSelection, - Fl_Text_Selection_mod* newSelection) const; - - /** - Move the gap to start at a new position. - */ - void move_gap(int pos); - - /** - Reallocates the text storage in the buffer to have a gap starting at \p newGapStart - and a gap size of \p newGapLen, preserving the buffer's current contents. - */ - void reallocate_with_gap(int newGapStart, int newGapLen); - - char* selection_text_(Fl_Text_Selection_mod* sel) const; - - /** - Removes the text from the buffer corresponding to \p sel. - */ - void remove_selection_(Fl_Text_Selection_mod* sel); - - /** - Replaces the \p text in selection \p sel. - */ - void replace_selection_(Fl_Text_Selection_mod* sel, const char* text); - - /** - Updates all of the selections in the buffer for changes in the buffer's text - */ - void update_selections(int pos, int nDeleted, int nInserted); - - Fl_Text_Selection_mod mPrimary; /**< highlighted areas */ - Fl_Text_Selection_mod mSecondary; /**< highlighted areas */ - Fl_Text_Selection_mod mHighlight; /**< highlighted areas */ - int mLength; /**< length of the text in the buffer (the length - of the buffer itself must be calculated: - gapEnd - gapStart + length) */ - char* mBuf; /**< allocated memory where the text is stored */ - int mGapStart; /**< points to the first character of the gap */ - int mGapEnd; /**< points to the first char after the gap */ - // The hardware tab distance used by all displays for this buffer, - // and used in computing offsets for rectangular selection operations. - int mTabDist; /**< equiv. number of characters in a tab */ - int mNModifyProcs; /**< number of modify-redisplay procs attached */ - Fl_Text_Modify_Cb *mModifyProcs;/**< procedures to call when buffer is - modified to redisplay contents */ - void** mCbArgs; /**< caller arguments for modifyProcs above */ - int mNPredeleteProcs; /**< number of pre-delete procs attached */ - Fl_Text_Predelete_Cb *mPredeleteProcs; /**< procedure to call before text is deleted - from the buffer; at most one is supported. */ - void **mPredeleteCbArgs; /**< caller argument for pre-delete proc above */ - int mCursorPosHint; /**< hint for reasonable cursor position after - a buffer modification operation */ - char mCanUndo; /**< if this buffer is used for attributes, it must - not do any undo calls */ - int mPreferredGapSize; /**< the default allocation for the text gap is 1024 - bytes and should only be increased if frequent - and large changes in buffer size are expected */ -}; - -#endif - -// -// End of "$Id: Fl_Text_Buffer_mod.H 8148 2010-12-31 22:38:03Z matt $". -// diff --git a/src/include/Fl_Text_Display_mod.H b/src/include/Fl_Text_Display_mod.H index 9e74c40..a1ce1f7 100644 --- a/src/include/Fl_Text_Display_mod.H +++ b/src/include/Fl_Text_Display_mod.H @@ -1,27 +1,496 @@ -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ // -// This file is part of flmsg +// "$Id: Fl_Text_Display_mod.H 8306 2011-01-24 17:04:22Z matt $" // -// flrig 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. +// Header file for Fl_Text_Display_mod class. // -// flrig is distributed in the hope that it will be useful, +// Copyright 2001-2010 by Bill Spitzak and others. +// Original code Copyright Mark Edel. Permission to distribute under +// the LGPL for the FLTK library granted by Mark Edel. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Library General Public +// License as published by the Free Software Foundation; either +// version 2 of the License, or (at your option) any later version. +// +// This library 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. +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Library 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 . -// ---------------------------------------------------------------------------- +// You should have received a copy of the GNU Library General Public +// License along with this library; if not, write to the +// +// Free Software Foundation, Inc. +// 51 Franklin Street, Fifth Floor +// Boston, MA 02110-1301 USA. +// +// Please report all bugs and problems on the following page: +// +// http://www.fltk.org/str.php +// + +/* \file + Fl_Text_Display_mod widget . */ + +#ifndef Fl_Text_Display_mod_H +#define Fl_Text_Display_mod_H + +#include + +#include +#include +#include +#include +#include "Fl_Text_Buffer_mod.H" #include -#if FLMSG_FLTK_API_MINOR < 3 -# include "Fl_Text_Display_mod_1_1.H" -#else -# include "Fl_Text_Display_mod_1_3.H" +/** + \brief Rich text display widget. + + This is the FLTK text display widget. It allows the user to view multiple lines + of text and supports highlighting and scrolling. The buffer that is displayed + in the widget is managed by the Fl_Text_Buffer_mod class. A single Text Buffer + can be displayed by multiple Text Displays. + */ +class FL_EXPORT Fl_Text_Display_mod: public Fl_Group { + +public: + + /** + text display cursor shapes enumeration + */ + enum { + NORMAL_CURSOR, /**< I-beam */ + CARET_CURSOR, /**< caret under the text */ + DIM_CURSOR, /**< dim I-beam */ + BLOCK_CURSOR, /**< unfille box under the current character */ + HEAVY_CURSOR /**< thick I-beam */ + }; + + /** + the character position is the left edge of a character, whereas + the cursor is thought to be between the centers of two consecutive + characters. + */ + enum { + CURSOR_POS, + CHARACTER_POS + }; + + /** + drag types - they match Fl::event_clicks() so that single clicking to + start a collection selects by character, double clicking selects by + word and triple clicking selects by line. + */ + enum { + DRAG_NONE = -2, + DRAG_START_DND = -1, + DRAG_CHAR = 0, + DRAG_WORD = 1, + DRAG_LINE = 2 + }; + + /** + wrap types - used in wrap_mode() + */ + enum { + WRAP_NONE, /**< don't wrap text at all */ + WRAP_AT_COLUMN, /**< wrap text at the given text column */ + WRAP_AT_PIXEL, /**< wrap text at a pixel position */ + WRAP_AT_BOUNDS /**< wrap text so that it fits into the widget width */ + }; + + friend void fl_text_drag_me(int pos, Fl_Text_Display_mod* d); + + typedef void (*Unfinished_Style_Cb)(int, void *); + + /** + This structure associates the color, font, andsize of a string to draw + with an attribute mask matching attr + */ + struct Style_Table_Entry { + Fl_Color color; + Fl_Font font; + Fl_Fontsize size; + unsigned attr; + }; + + Fl_Text_Display_mod(int X, int Y, int W, int H, const char *l = 0); + ~Fl_Text_Display_mod(); + + virtual int handle(int e); + + void buffer(Fl_Text_Buffer_mod* buf); + + /** + Sets the current text buffer associated with the text widget. + Multiple text widgets can be associated with the same text buffer. + \param buf new text buffer + */ + void buffer(Fl_Text_Buffer_mod& buf) { buffer(&buf); } + + /** + Gets the current text buffer associated with the text widget. + Multiple text widgets can be associated with the same text buffer. + \return current text buffer + */ + Fl_Text_Buffer_mod* buffer() const { return mBuffer; } + + void redisplay_range(int start, int end); + void scroll(int topLineNum, int horizOffset); + void insert(const char* text); + void overstrike(const char* text); + void insert_position(int newPos); + + /** + Gets the position of the text insertion cursor for text display. + \return insert position index into text buffer + */ + int insert_position() const { return mCursorPos; } + int position_to_xy(int pos, int* x, int* y) const; + + int in_selection(int x, int y) const; + void show_insert_position(); + + int move_right(); + int move_left(); + int move_up(); + int move_down(); + int count_lines(int start, int end, bool start_pos_is_line_start) const; + int line_start(int pos) const; + int line_end(int startPos, bool startPosIsLineStart) const; + int skip_lines(int startPos, int nLines, bool startPosIsLineStart); + int rewind_lines(int startPos, int nLines); + void next_word(void); + void previous_word(void); + + void show_cursor(int b = 1); + + /** + Hides the text cursor. + */ + void hide_cursor() { show_cursor(0); } + + void cursor_style(int style); + + /** + Gets the text cursor color. + \return cursor color + */ + Fl_Color cursor_color() const {return mCursor_color;} + + /** + Sets the text cursor color. + \param n new cursor color + */ + void cursor_color(Fl_Color n) {mCursor_color = n;} + + /** + Gets the width/height of the scrollbars. + /return width of scrollbars + */ + int scrollbar_width() const { return scrollbar_width_; } + + /** + Sets the width/height of the scrollbars. + \param W width of scrollbars + */ + void scrollbar_width(int W) { scrollbar_width_ = W; } + + /** + Gets the scrollbar alignment type. + \return scrollbar alignment + */ + Fl_Align scrollbar_align() const { return scrollbar_align_; } + + /** + Sets the scrollbar alignment type. + \param a new scrollbar alignment + */ + void scrollbar_align(Fl_Align a) { scrollbar_align_ = a; } + + /** + Moves the insert position to the beginning of the current word. + \param pos start calculation at this index + \return beginning of the words + */ + int word_start(int pos) const { return buffer()->word_start(pos); } + + /** + Moves the insert position to the end of the current word. + \param pos start calculation at this index + \return index of first character after the end of the word + */ + int word_end(int pos) const { return buffer()->word_end(pos); } + + + void highlight_data(Fl_Text_Buffer_mod *styleBuffer, + const Style_Table_Entry *styleTable, + int nStyles, char unfinishedStyle, + Unfinished_Style_Cb unfinishedHighlightCB, + void *cbArg); + + int position_style(int lineStartPos, int lineLen, int lineIndex) const; + + /** + \todo FIXME : get set methods pointing on shortcut_ + have no effects as shortcut_ is unused in this class and derived! + \return the current shortcut key + */ + int shortcut() const {return shortcut_;} + + /** + \todo FIXME : get set methods pointing on shortcut_ + have no effects as shortcut_ is unused in this class and derived! + \param s the new shortcut key + */ + void shortcut(int s) {shortcut_ = s;} + + /** + Gets the default font used when drawing text in the widget. + \return current text font face unless overridden by a style + */ + Fl_Font textfont() const {return textfont_;} + + /** + Sets the default font used when drawing text in the widget. + \param s default text font face + */ + void textfont(Fl_Font s) {textfont_ = s; mColumnScale = 0;} + + /** + Gets the default size of text in the widget. + \return current text height unless overridden by a style + */ + Fl_Fontsize textsize() const {return textsize_;} + + /** + Sets the default size of text in the widget. + \param s new text size + */ + void textsize(Fl_Fontsize s) {textsize_ = s; mColumnScale = 0;} + + /** + Gets the default color of text in the widget. + \return text color unless overridden by a style + */ + Fl_Color textcolor() const {return textcolor_;} + + /** + Sets the default color of text in the widget. + \param n new text color + */ + void textcolor(Fl_Color n) {textcolor_ = n;} + + int wrapped_column(int row, int column) const; + int wrapped_row(int row) const; + void wrap_mode(int wrap, int wrap_margin); + + virtual void resize(int X, int Y, int W, int H); + + /** + Convert an x pixel position into a column number. + \param x number of pixels from the left margin + \return an approximate column number based on the main font + */ + double x_to_col(double x) const; + + /** + Convert a column number into an x pixel position. + \param col an approximate column number based on the main font + \return number of pixels from the left margin to the left of an + average sized character + */ + double col_to_x(double col) const; + +protected: + // Most (all?) of this stuff should only be called from resize() or + // draw(). + // Anything with "vline" indicates thats it deals with currently + // visible lines. + + virtual void draw(); + void draw_text(int X, int Y, int W, int H); + void draw_range(int start, int end); + void draw_cursor(int, int); + + void draw_string(int style, int x, int y, int toX, const char *string, + int nChars) const; + + void draw_vline(int visLineNum, int leftClip, int rightClip, + int leftCharIndex, int rightCharIndex); + + int find_x(const char *s, int len, int style, int x) const; + + enum { + DRAW_LINE, + FIND_INDEX, + FIND_INDEX_FROM_ZERO, + GET_WIDTH + }; + + int handle_vline(int mode, + int lineStart, int lineLen, int leftChar, int rightChar, + int topClip, int bottomClip, + int leftClip, int rightClip) const; + + void draw_line_numbers(bool clearAll); + + void clear_rect(int style, int x, int y, int width, int height) const; + void display_insert(); + + void offset_line_starts(int newTopLineNum); + + void calc_line_starts(int startLine, int endLine); + + void update_line_starts(int pos, int charsInserted, int charsDeleted, + int linesInserted, int linesDeleted, int *scrolled); + + void calc_last_char(); + + int position_to_line( int pos, int* lineNum ) const; + double string_width(const char* string, int length, int style) const; + + static void scroll_timer_cb(void*); + + static void buffer_predelete_cb(int pos, int nDeleted, void* cbArg); + static void buffer_modified_cb(int pos, int nInserted, int nDeleted, + int nRestyled, const char* deletedText, + void* cbArg); + + static void h_scrollbar_cb(Fl_Scrollbar* w, Fl_Text_Display_mod* d); + static void v_scrollbar_cb( Fl_Scrollbar* w, Fl_Text_Display_mod* d); + void update_v_scrollbar(); + void update_h_scrollbar(); + int measure_vline(int visLineNum) const; + int longest_vline() const; + int empty_vlines() const; + int vline_length(int visLineNum) const; + int xy_to_position(int x, int y, int PosType = CHARACTER_POS) const; + + void xy_to_rowcol(int x, int y, int* row, int* column, + int PosType = CHARACTER_POS) const; + void maintain_absolute_top_line_number(int state); + int get_absolute_top_line_number() const; + void absolute_top_line_number(int oldFirstChar); + int maintaining_absolute_top_line_number() const; + void reset_absolute_top_line_number(); + int position_to_linecol(int pos, int* lineNum, int* column) const; + int scroll_(int topLineNum, int horizOffset); + + void extend_range_for_styles(int* start, int* end); + + void find_wrap_range(const char *deletedText, int pos, int nInserted, + int nDeleted, int *modRangeStart, int *modRangeEnd, + int *linesInserted, int *linesDeleted); + void measure_deleted_lines(int pos, int nDeleted); + void wrapped_line_counter(Fl_Text_Buffer_mod *buf, int startPos, int maxPos, + int maxLines, bool startPosIsLineStart, + int styleBufOffset, int *retPos, int *retLines, + int *retLineStart, int *retLineEnd, + bool countLastLineMissingNewLine = true) const; + void find_line_end(int pos, bool start_pos_is_text_start, int *lineEnd, + int *nextLineStart) const; + double measure_proportional_character(const char *s, int colNum, int pos) const; + int wrap_uses_character(int lineEndPos) const; + + static const int DEFAULT_TOP_MARGIN; + static const int DEFAULT_BOTTOM_MARGIN; + static const int DEFAULT_LEFT_MARGIN; + static const int DEFAULT_RIGHT_MARGIN; + int TOP_MARGIN, BOTTOM_MARGIN, LEFT_MARGIN, RIGHT_MARGIN; + + int damage_range1_start, damage_range1_end; + int damage_range2_start, damage_range2_end; + int mCursorPos; + int mCursorOn; + int mCursorOldY; /* Y pos. of cursor for blanking */ + int mCursorToHint; /* Tells the buffer modified callback + where to move the cursor, to reduce + the number of redraw calls */ + int mCursorStyle; /* One of enum cursorStyles above */ + int mCursorPreferredXPos; /* Pixel position for vert. cursor movement */ + int mNVisibleLines; /* # of visible (displayed) lines */ + int mNBufferLines; /* # of newlines in the buffer */ + Fl_Text_Buffer_mod* mBuffer; /* Contains text to be displayed */ + Fl_Text_Buffer_mod* mStyleBuffer; /* Optional parallel buffer containing + color and font information */ + int mFirstChar, mLastChar; /* Buffer positions of first and last + displayed character (lastChar points + either to a newline or one character + beyond the end of the buffer) */ + int mContinuousWrap; /* Wrap long lines when displaying */ + int mFastDisplay; /* force continuous wrap and insertion of eol characters + used in FTextRX */ + std::string s_text; /* current contents of line text buffer */ + std::string s_style; /* current contents of line stype buffer */ + int mWrapMarginPix; /* Margin in # of pixels for + wrapping in continuousWrap mode */ + int* mLineStarts; + int mTopLineNum; /* Line number of top displayed line + of file (first line of file is 1) */ + int mAbsTopLineNum; /* In continuous wrap mode, the line + number of the top line if the text + were not wrapped (note that this is + only maintained as needed). */ + int mNeedAbsTopLineNum; /* Externally settable flag to continue + maintaining absTopLineNum even if + it isn't needed for line # display */ + int mHorizOffset; /* Horizontal scroll pos. in pixels */ + int mTopLineNumHint; /* Line number of top displayed line + of file (first line of file is 1) */ + int mHorizOffsetHint; /* Horizontal scroll pos. in pixels */ + int mNStyles; /* Number of entries in styleTable */ + const Style_Table_Entry *mStyleTable; /* Table of fonts and colors for + coloring/syntax-highlighting */ + char mUnfinishedStyle; /* Style buffer entry which triggers + on-the-fly reparsing of region */ + Unfinished_Style_Cb mUnfinishedHighlightCB; /* Callback to parse "unfinished" */ + /* regions */ + void* mHighlightCBArg; /* Arg to unfinishedHighlightCB */ + + int mMaxsize; + + int mSuppressResync; /* Suppress resynchronization of line + starts during buffer updates */ + int mNLinesDeleted; /* Number of lines deleted during + buffer modification (only used + when resynchronization is suppressed) */ + int mModifyingTabDistance; /* Whether tab distance is being + modified */ + + mutable double mColumnScale; /* Width in pixels of an average character. This + value is calculated as needed (lazy eval); it + needs to be mutable so that it can be calculated + within a method marked as "const" */ + + Fl_Color mCursor_color; + + Fl_Scrollbar* mHScrollBar; + Fl_Scrollbar* mVScrollBar; + int scrollbar_width_; + Fl_Align scrollbar_align_; + int dragPos, dragType, dragging; + int display_insert_position_hint; + struct { int x, y, w, h; } text_area; + + int shortcut_; + + Fl_Font textfont_; + Fl_Fontsize textsize_; + Fl_Color textcolor_; + + // The following are not presently used from the original NEdit code, + // but are being put here so that future versions of Fl_Text_Display_mod + // can implement line numbers without breaking binary compatibility. + + /* Line number margin and width */ + int mLineNumLeft, mLineNumWidth; +}; + #endif + +// +// End of "$Id: Fl_Text_Display_mod.H 8306 2011-01-24 17:04:22Z matt $". +// diff --git a/src/include/Fl_Text_Display_mod_1_1.H b/src/include/Fl_Text_Display_mod_1_1.H deleted file mode 100644 index 80392da..0000000 --- a/src/include/Fl_Text_Display_mod_1_1.H +++ /dev/null @@ -1,303 +0,0 @@ -// -// "$Id: Fl_Text_Display.H 4502 2005-08-10 23:11:51Z matt $" -// -// Header file for Fl_Text_Display class. -// -// Copyright 2001-2005 by Bill Spitzak and others. -// Original code Copyright Mark Edel. Permission to distribute under -// the LGPL for the FLTK library granted by Mark Edel. -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ -// -// This file is part of flmsg -// -// flrig 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. -// -// flrig 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 FL_TEXT_DISPLAY_MOD_H -#define FL_TEXT_DISPLAY_MOD_H - -#include -#include -#include -#include -#include "Fl_Text_Buffer_mod.H" - -class Fl_Text_Display_mod: public Fl_Group { - public: - enum { - NORMAL_CURSOR, CARET_CURSOR, DIM_CURSOR, - BLOCK_CURSOR, HEAVY_CURSOR - }; - - enum { - CURSOR_POS, CHARACTER_POS - }; - - // drag types- they match Fl::event_clicks() so that single clicking to - // start a collection selects by character, double clicking selects by - // word and triple clicking selects by line. - enum { - DRAG_CHAR = 0, DRAG_WORD = 1, DRAG_LINE = 2 - }; - friend void fl_text_drag_me(int pos, Fl_Text_Display_mod* d); - - typedef void (*Unfinished_Style_Cb)(int, void *); - - // style attributes - currently not implemented! - enum { - ATTR_NONE = 0, - ATTR_UNDERLINE = 1, - ATTR_HIDDEN = 2 - }; - - struct Style_Table_Entry { - Fl_Color color; - Fl_Font font; - int size; - unsigned attr; - }; - - Fl_Text_Display_mod(int X, int Y, int W, int H, const char *l = 0); - ~Fl_Text_Display_mod(); - - virtual int handle(int e); - void buffer(Fl_Text_Buffer_mod* buf); - void buffer(Fl_Text_Buffer_mod& buf) { buffer(&buf); } - Fl_Text_Buffer_mod* buffer() { return mBuffer; } - void redisplay_range(int start, int end); - void scroll(int topLineNum, int horizOffset); - void insert(const char* text); - void overstrike(const char* text); - void insert_position(int newPos); - int insert_position() { return mCursorPos; } - int in_selection(int x, int y); - void show_insert_position(); - int move_right(); - int move_left(); - int move_up(); - int move_down(); - int count_lines(int start, int end, bool start_pos_is_line_start); - int line_start(int pos); - int line_end(int pos, bool start_pos_is_line_start); - int skip_lines(int startPos, int nLines, bool startPosIsLineStart); - int rewind_lines(int startPos, int nLines); - void next_word(void); - void previous_word(void); - void show_cursor(int b = 1); - void hide_cursor() { show_cursor(0); } - void cursor_style(int style); - Fl_Color cursor_color() const {return mCursor_color;} - void cursor_color(Fl_Color n) {mCursor_color = n;} - int scrollbar_width() { return scrollbar_width_; } - Fl_Align scrollbar_align() { return scrollbar_align_; } - void scrollbar_width(int W) { scrollbar_width_ = W; } - void scrollbar_align(Fl_Align a) { scrollbar_align_ = a; } - int word_start(int pos) { return buffer()->word_start(pos); } - int word_end(int pos) { return buffer()->word_end(pos); } - - - void highlight_data(Fl_Text_Buffer_mod *styleBuffer, - const Style_Table_Entry *styleTable, - int nStyles, char unfinishedStyle, - Unfinished_Style_Cb unfinishedHighlightCB, - void *cbArg); - - int position_style(int lineStartPos, int lineLen, int lineIndex, - int dispIndex); - - Fl_Font textfont() const {return textfont_;} - void textfont(Fl_Font f) {textfont_ = f;} - uchar textsize() const {return textsize_;} - void textsize(uchar s) {textsize_ = s;} - Fl_Color textcolor() const {return (Fl_Color)textcolor_;} - void textcolor(unsigned n) {textcolor_ = n;} - - int wrapped_column(int row, int column); - int wrapped_row(int row); - void wrap_mode(int wrap, int wrap_margin); - - virtual void resize(int X, int Y, int W, int H); - - protected: - // Most (all?) of this stuff should only be called from resize() or - // draw(). - // Anything with "vline" indicates thats it deals with currently - // visible lines. - - virtual void draw(); - void draw_text(int X, int Y, int W, int H); - void draw_range(int start, int end); - void draw_cursor(int, int); - - void draw_string(int style, int x, int y, int toX, const char *string, - int nChars); - - void draw_vline(int visLineNum, int leftClip, int rightClip, - int leftCharIndex, int rightCharIndex); - - void draw_line_numbers(bool clearAll); - - void clear_rect(int style, int x, int y, int width, int height); - void display_insert(); - - void offset_line_starts(int newTopLineNum); - - void calc_line_starts(int startLine, int endLine); - - void update_line_starts(int pos, int charsInserted, int charsDeleted, - int linesInserted, int linesDeleted, int *scrolled); - - void calc_last_char(); - - int position_to_line( size_t pos, int* lineNum);//int pos, int* lineNum ); - int string_width(const char* string, int length, int style); - - static void scroll_timer_cb(void*); - - static void buffer_predelete_cb(int pos, int nDeleted, void* cbArg); - static void buffer_modified_cb(int pos, int nInserted, int nDeleted, - int nRestyled, const char* deletedText, - void* cbArg); - - static void h_scrollbar_cb(Fl_Scrollbar* w, Fl_Text_Display_mod* d); - static void v_scrollbar_cb( Fl_Scrollbar* w, Fl_Text_Display_mod* d); - void update_v_scrollbar(); - void update_h_scrollbar(); - int measure_vline(int visLineNum); - int longest_vline(); - int empty_vlines(); - int vline_length(int visLineNum); - int xy_to_position(int x, int y, int PosType = CHARACTER_POS); - - void xy_to_rowcol(int x, int y, int* row, int* column, - int PosType = CHARACTER_POS); - - int position_to_xy(int pos, int* x, int* y); - void maintain_absolute_top_line_number(int state); - int get_absolute_top_line_number(); - void absolute_top_line_number(int oldFirstChar); - int maintaining_absolute_top_line_number(); - void reset_absolute_top_line_number(); - int position_to_linecol(int pos, int* lineNum, int* column); - void scroll_(int topLineNum, int horizOffset); - - void extend_range_for_styles(int* start, int* end); - - void find_wrap_range(const char *deletedText, int pos, int nInserted, - int nDeleted, int *modRangeStart, int *modRangeEnd, - int *linesInserted, int *linesDeleted); - void measure_deleted_lines(int pos, int nDeleted); - void wrapped_line_counter(Fl_Text_Buffer_mod *buf, int startPos, int maxPos, - int maxLines, bool startPosIsLineStart, - int styleBufOffset, int *retPos, int *retLines, - int *retLineStart, int *retLineEnd, - bool countLastLineMissingNewLine = true); - void find_line_end(int pos, bool start_pos_is_line_start, int *lineEnd, - int *nextLineStart); - int measure_proportional_character(char c, int colNum, int pos); - int wrap_uses_character(int lineEndPos); - int range_touches_selection(Fl_Text_Selection *sel, int rangeStart, - int rangeEnd); - - static const int DEFAULT_TOP_MARGIN; - static const int DEFAULT_BOTTOM_MARGIN; - static const int DEFAULT_LEFT_MARGIN; - static const int DEFAULT_RIGHT_MARGIN; - int TOP_MARGIN, BOTTOM_MARGIN, LEFT_MARGIN, RIGHT_MARGIN; - - int damage_range1_start, damage_range1_end; - int damage_range2_start, damage_range2_end; - int mCursorPos; - int mCursorOn; - int mCursorOldY; /* Y pos. of cursor for blanking */ - int mCursorToHint; /* Tells the buffer modified callback - where to move the cursor, to reduce - the number of redraw calls */ - int mCursorStyle; /* One of enum cursorStyles above */ - int mCursorPreferredCol; /* Column for vert. cursor movement */ - int mNVisibleLines; /* # of visible (displayed) lines */ - int mNBufferLines; /* # of newlines in the buffer */ - Fl_Text_Buffer_mod* mBuffer; /* Contains text to be displayed */ - Fl_Text_Buffer_mod* mStyleBuffer; /* Optional parallel buffer containing - color and font information */ - int mFirstChar, mLastChar; /* Buffer positions of first and last - displayed character (lastChar points - either to a newline or one character - beyond the end of the buffer) */ - int mContinuousWrap; /* Wrap long lines when displaying */ - int mWrapMargin; /* Margin in # of char positions for - wrapping in continuousWrap mode */ - int* mLineStarts; - int mTopLineNum; /* Line number of top displayed line - of file (first line of file is 1) */ - int mAbsTopLineNum; /* In continuous wrap mode, the line - number of the top line if the text - were not wrapped (note that this is - only maintained as needed). */ - int mNeedAbsTopLineNum; /* Externally settable flag to continue - maintaining absTopLineNum even if - it isn't needed for line # display */ - int mHorizOffset; /* Horizontal scroll pos. in pixels */ - int mTopLineNumHint; /* Line number of top displayed line - of file (first line of file is 1) */ - int mHorizOffsetHint; /* Horizontal scroll pos. in pixels */ - int mNStyles; /* Number of entries in styleTable */ - const Style_Table_Entry *mStyleTable; /* Table of fonts and colors for - coloring/syntax-highlighting */ - char mUnfinishedStyle; /* Style buffer entry which triggers - on-the-fly reparsing of region */ - Unfinished_Style_Cb mUnfinishedHighlightCB; /* Callback to parse "unfinished" */ - /* regions */ - void* mHighlightCBArg; /* Arg to unfinishedHighlightCB */ - - int mMaxsize; - - int mFixedFontWidth; /* Font width if all current fonts are - fixed and match in width, else -1 */ - int mSuppressResync; /* Suppress resynchronization of line - starts during buffer updates */ - int mNLinesDeleted; /* Number of lines deleted during - buffer modification (only used - when resynchronization is suppressed) */ - int mModifyingTabDistance; /* Whether tab distance is being - modified */ - - Fl_Color mCursor_color; - - Fl_Scrollbar* mHScrollBar; - Fl_Scrollbar* mVScrollBar; - int scrollbar_width_; - Fl_Align scrollbar_align_; - int dragPos, dragType, dragging; - int display_insert_position_hint; - struct { int x, y, w, h; } text_area; - - Fl_Font textfont_; - uchar textsize_; - unsigned textcolor_; - - // The following are not presently used from the original NEdit code, - // but are being put here so that future versions of Fl_Text_Display - // can implement line numbers without breaking binary compatibility. - int mLineNumLeft, mLineNumWidth; - /* Line number margin and width */ -}; - -#endif - -// -// End of "$Id: Fl_Text_Display.H 4502 2005-08-10 23:11:51Z matt $". -// diff --git a/src/include/Fl_Text_Display_mod_1_3.H b/src/include/Fl_Text_Display_mod_1_3.H deleted file mode 100644 index 7df067d..0000000 --- a/src/include/Fl_Text_Display_mod_1_3.H +++ /dev/null @@ -1,491 +0,0 @@ -// -// "$Id: Fl_Text_Display_mod.H 8306 2011-01-24 17:04:22Z matt $" -// -// Header file for Fl_Text_Display_mod class. -// -// Copyright 2001-2010 by Bill Spitzak and others. -// Original code Copyright Mark Edel. Permission to distribute under -// the LGPL for the FLTK library granted by Mark Edel. -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ -// -// This file is part of flmsg -// -// flrig 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. -// -// flrig 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 . -// ---------------------------------------------------------------------------- - -/* \file - Fl_Text_Display_mod widget . */ - -#ifndef Fl_Text_Display_mod_H -#define Fl_Text_Display_mod_H - -#include - -#include -#include -#include -#include -#include "Fl_Text_Buffer_mod.H" - -/** - \brief Rich text display widget. - - This is the FLTK text display widget. It allows the user to view multiple lines - of text and supports highlighting and scrolling. The buffer that is displayed - in the widget is managed by the Fl_Text_Buffer_mod class. A single Text Buffer - can be displayed by multiple Text Displays. - */ -class FL_EXPORT Fl_Text_Display_mod: public Fl_Group { - -public: - - /** - text display cursor shapes enumeration - */ - enum { - NORMAL_CURSOR, /**< I-beam */ - CARET_CURSOR, /**< caret under the text */ - DIM_CURSOR, /**< dim I-beam */ - BLOCK_CURSOR, /**< unfille box under the current character */ - HEAVY_CURSOR /**< thick I-beam */ - }; - - /** - the character position is the left edge of a character, whereas - the cursor is thought to be between the centers of two consecutive - characters. - */ - enum { - CURSOR_POS, - CHARACTER_POS - }; - - /** - drag types - they match Fl::event_clicks() so that single clicking to - start a collection selects by character, double clicking selects by - word and triple clicking selects by line. - */ - enum { - DRAG_NONE = -2, - DRAG_START_DND = -1, - DRAG_CHAR = 0, - DRAG_WORD = 1, - DRAG_LINE = 2 - }; - - /** - wrap types - used in wrap_mode() - */ - enum { - WRAP_NONE, /**< don't wrap text at all */ - WRAP_AT_COLUMN, /**< wrap text at the given text column */ - WRAP_AT_PIXEL, /**< wrap text at a pixel position */ - WRAP_AT_BOUNDS /**< wrap text so that it fits into the widget width */ - }; - - friend void fl_text_drag_me(int pos, Fl_Text_Display_mod* d); - - typedef void (*Unfinished_Style_Cb)(int, void *); - - /** - This structure associates the color, font, andsize of a string to draw - with an attribute mask matching attr - */ - struct Style_Table_Entry { - Fl_Color color; - Fl_Font font; - Fl_Fontsize size; - unsigned attr; - }; - - Fl_Text_Display_mod(int X, int Y, int W, int H, const char *l = 0); - ~Fl_Text_Display_mod(); - - virtual int handle(int e); - - void buffer(Fl_Text_Buffer_mod* buf); - - /** - Sets the current text buffer associated with the text widget. - Multiple text widgets can be associated with the same text buffer. - \param buf new text buffer - */ - void buffer(Fl_Text_Buffer_mod& buf) { buffer(&buf); } - - /** - Gets the current text buffer associated with the text widget. - Multiple text widgets can be associated with the same text buffer. - \return current text buffer - */ - Fl_Text_Buffer_mod* buffer() const { return mBuffer; } - - void redisplay_range(int start, int end); - void scroll(int topLineNum, int horizOffset); - void insert(const char* text); - void overstrike(const char* text); - void insert_position(int newPos); - - /** - Gets the position of the text insertion cursor for text display. - \return insert position index into text buffer - */ - int insert_position() const { return mCursorPos; } - int position_to_xy(int pos, int* x, int* y) const; - - int in_selection(int x, int y) const; - void show_insert_position(); - - int move_right(); - int move_left(); - int move_up(); - int move_down(); - int count_lines(int start, int end, bool start_pos_is_line_start) const; - int line_start(int pos) const; - int line_end(int startPos, bool startPosIsLineStart) const; - int skip_lines(int startPos, int nLines, bool startPosIsLineStart); - int rewind_lines(int startPos, int nLines); - void next_word(void); - void previous_word(void); - - void show_cursor(int b = 1); - - /** - Hides the text cursor. - */ - void hide_cursor() { show_cursor(0); } - - void cursor_style(int style); - - /** - Gets the text cursor color. - \return cursor color - */ - Fl_Color cursor_color() const {return mCursor_color;} - - /** - Sets the text cursor color. - \param n new cursor color - */ - void cursor_color(Fl_Color n) {mCursor_color = n;} - - /** - Gets the width/height of the scrollbars. - /return width of scrollbars - */ - int scrollbar_width() const { return scrollbar_width_; } - - /** - Sets the width/height of the scrollbars. - \param W width of scrollbars - */ - void scrollbar_width(int W) { scrollbar_width_ = W; } - - /** - Gets the scrollbar alignment type. - \return scrollbar alignment - */ - Fl_Align scrollbar_align() const { return scrollbar_align_; } - - /** - Sets the scrollbar alignment type. - \param a new scrollbar alignment - */ - void scrollbar_align(Fl_Align a) { scrollbar_align_ = a; } - - /** - Moves the insert position to the beginning of the current word. - \param pos start calculation at this index - \return beginning of the words - */ - int word_start(int pos) const { return buffer()->word_start(pos); } - - /** - Moves the insert position to the end of the current word. - \param pos start calculation at this index - \return index of first character after the end of the word - */ - int word_end(int pos) const { return buffer()->word_end(pos); } - - - void highlight_data(Fl_Text_Buffer_mod *styleBuffer, - const Style_Table_Entry *styleTable, - int nStyles, char unfinishedStyle, - Unfinished_Style_Cb unfinishedHighlightCB, - void *cbArg); - - int position_style(int lineStartPos, int lineLen, int lineIndex) const; - - /** - \todo FIXME : get set methods pointing on shortcut_ - have no effects as shortcut_ is unused in this class and derived! - \return the current shortcut key - */ - int shortcut() const {return shortcut_;} - - /** - \todo FIXME : get set methods pointing on shortcut_ - have no effects as shortcut_ is unused in this class and derived! - \param s the new shortcut key - */ - void shortcut(int s) {shortcut_ = s;} - - /** - Gets the default font used when drawing text in the widget. - \return current text font face unless overridden by a style - */ - Fl_Font textfont() const {return textfont_;} - - /** - Sets the default font used when drawing text in the widget. - \param s default text font face - */ - void textfont(Fl_Font s) {textfont_ = s; mColumnScale = 0;} - - /** - Gets the default size of text in the widget. - \return current text height unless overridden by a style - */ - Fl_Fontsize textsize() const {return textsize_;} - - /** - Sets the default size of text in the widget. - \param s new text size - */ - void textsize(Fl_Fontsize s) {textsize_ = s; mColumnScale = 0;} - - /** - Gets the default color of text in the widget. - \return text color unless overridden by a style - */ - Fl_Color textcolor() const {return textcolor_;} - - /** - Sets the default color of text in the widget. - \param n new text color - */ - void textcolor(Fl_Color n) {textcolor_ = n;} - - int wrapped_column(int row, int column) const; - int wrapped_row(int row) const; - void wrap_mode(int wrap, int wrap_margin); - - virtual void resize(int X, int Y, int W, int H); - - /** - Convert an x pixel position into a column number. - \param x number of pixels from the left margin - \return an approximate column number based on the main font - */ - double x_to_col(double x) const; - - /** - Convert a column number into an x pixel position. - \param col an approximate column number based on the main font - \return number of pixels from the left margin to the left of an - average sized character - */ - double col_to_x(double col) const; - -protected: - // Most (all?) of this stuff should only be called from resize() or - // draw(). - // Anything with "vline" indicates thats it deals with currently - // visible lines. - - virtual void draw(); - void draw_text(int X, int Y, int W, int H); - void draw_range(int start, int end); - void draw_cursor(int, int); - - void draw_string(int style, int x, int y, int toX, const char *string, - int nChars) const; - - void draw_vline(int visLineNum, int leftClip, int rightClip, - int leftCharIndex, int rightCharIndex); - - int find_x(const char *s, int len, int style, int x) const; - - enum { - DRAW_LINE, - FIND_INDEX, - FIND_INDEX_FROM_ZERO, - GET_WIDTH - }; - - int handle_vline(int mode, - int lineStart, int lineLen, int leftChar, int rightChar, - int topClip, int bottomClip, - int leftClip, int rightClip) const; - - void draw_line_numbers(bool clearAll); - - void clear_rect(int style, int x, int y, int width, int height) const; - void display_insert(); - - void offset_line_starts(int newTopLineNum); - - void calc_line_starts(int startLine, int endLine); - - void update_line_starts(int pos, int charsInserted, int charsDeleted, - int linesInserted, int linesDeleted, int *scrolled); - - void calc_last_char(); - - int position_to_line( int pos, int* lineNum ) const; - double string_width(const char* string, int length, int style) const; - - static void scroll_timer_cb(void*); - - static void buffer_predelete_cb(int pos, int nDeleted, void* cbArg); - static void buffer_modified_cb(int pos, int nInserted, int nDeleted, - int nRestyled, const char* deletedText, - void* cbArg); - - static void h_scrollbar_cb(Fl_Scrollbar* w, Fl_Text_Display_mod* d); - static void v_scrollbar_cb( Fl_Scrollbar* w, Fl_Text_Display_mod* d); - void update_v_scrollbar(); - void update_h_scrollbar(); - int measure_vline(int visLineNum) const; - int longest_vline() const; - int empty_vlines() const; - int vline_length(int visLineNum) const; - int xy_to_position(int x, int y, int PosType = CHARACTER_POS) const; - - void xy_to_rowcol(int x, int y, int* row, int* column, - int PosType = CHARACTER_POS) const; - void maintain_absolute_top_line_number(int state); - int get_absolute_top_line_number() const; - void absolute_top_line_number(int oldFirstChar); - int maintaining_absolute_top_line_number() const; - void reset_absolute_top_line_number(); - int position_to_linecol(int pos, int* lineNum, int* column) const; - int scroll_(int topLineNum, int horizOffset); - - void extend_range_for_styles(int* start, int* end); - - void find_wrap_range(const char *deletedText, int pos, int nInserted, - int nDeleted, int *modRangeStart, int *modRangeEnd, - int *linesInserted, int *linesDeleted); - void measure_deleted_lines(int pos, int nDeleted); - void wrapped_line_counter(Fl_Text_Buffer_mod *buf, int startPos, int maxPos, - int maxLines, bool startPosIsLineStart, - int styleBufOffset, int *retPos, int *retLines, - int *retLineStart, int *retLineEnd, - bool countLastLineMissingNewLine = true) const; - void find_line_end(int pos, bool start_pos_is_text_start, int *lineEnd, - int *nextLineStart) const; - double measure_proportional_character(const char *s, int colNum, int pos) const; - int wrap_uses_character(int lineEndPos) const; - - static const int DEFAULT_TOP_MARGIN; - static const int DEFAULT_BOTTOM_MARGIN; - static const int DEFAULT_LEFT_MARGIN; - static const int DEFAULT_RIGHT_MARGIN; - int TOP_MARGIN, BOTTOM_MARGIN, LEFT_MARGIN, RIGHT_MARGIN; - - int damage_range1_start, damage_range1_end; - int damage_range2_start, damage_range2_end; - int mCursorPos; - int mCursorOn; - int mCursorOldY; /* Y pos. of cursor for blanking */ - int mCursorToHint; /* Tells the buffer modified callback - where to move the cursor, to reduce - the number of redraw calls */ - int mCursorStyle; /* One of enum cursorStyles above */ - int mCursorPreferredXPos; /* Pixel position for vert. cursor movement */ - int mNVisibleLines; /* # of visible (displayed) lines */ - int mNBufferLines; /* # of newlines in the buffer */ - Fl_Text_Buffer_mod* mBuffer; /* Contains text to be displayed */ - Fl_Text_Buffer_mod* mStyleBuffer; /* Optional parallel buffer containing - color and font information */ - int mFirstChar, mLastChar; /* Buffer positions of first and last - displayed character (lastChar points - either to a newline or one character - beyond the end of the buffer) */ - int mContinuousWrap; /* Wrap long lines when displaying */ - int mFastDisplay; /* force continuous wrap and insertion of eol characters - used in FTextRX */ - std::string s_text; /* current contents of line text buffer */ - std::string s_style; /* current contents of line stype buffer */ - int mWrapMarginPix; /* Margin in # of pixels for - wrapping in continuousWrap mode */ - int* mLineStarts; - int mTopLineNum; /* Line number of top displayed line - of file (first line of file is 1) */ - int mAbsTopLineNum; /* In continuous wrap mode, the line - number of the top line if the text - were not wrapped (note that this is - only maintained as needed). */ - int mNeedAbsTopLineNum; /* Externally settable flag to continue - maintaining absTopLineNum even if - it isn't needed for line # display */ - int mHorizOffset; /* Horizontal scroll pos. in pixels */ - int mTopLineNumHint; /* Line number of top displayed line - of file (first line of file is 1) */ - int mHorizOffsetHint; /* Horizontal scroll pos. in pixels */ - int mNStyles; /* Number of entries in styleTable */ - const Style_Table_Entry *mStyleTable; /* Table of fonts and colors for - coloring/syntax-highlighting */ - char mUnfinishedStyle; /* Style buffer entry which triggers - on-the-fly reparsing of region */ - Unfinished_Style_Cb mUnfinishedHighlightCB; /* Callback to parse "unfinished" */ - /* regions */ - void* mHighlightCBArg; /* Arg to unfinishedHighlightCB */ - - int mMaxsize; - - int mSuppressResync; /* Suppress resynchronization of line - starts during buffer updates */ - int mNLinesDeleted; /* Number of lines deleted during - buffer modification (only used - when resynchronization is suppressed) */ - int mModifyingTabDistance; /* Whether tab distance is being - modified */ - - mutable double mColumnScale; /* Width in pixels of an average character. This - value is calculated as needed (lazy eval); it - needs to be mutable so that it can be calculated - within a method marked as "const" */ - - Fl_Color mCursor_color; - - Fl_Scrollbar* mHScrollBar; - Fl_Scrollbar* mVScrollBar; - int scrollbar_width_; - Fl_Align scrollbar_align_; - int dragPos, dragType, dragging; - int display_insert_position_hint; - struct { int x, y, w, h; } text_area; - - int shortcut_; - - Fl_Font textfont_; - Fl_Fontsize textsize_; - Fl_Color textcolor_; - - // The following are not presently used from the original NEdit code, - // but are being put here so that future versions of Fl_Text_Display_mod - // can implement line numbers without breaking binary compatibility. - - /* Line number margin and width */ - int mLineNumLeft, mLineNumWidth; -}; - -#endif - -// -// End of "$Id: Fl_Text_Display_mod.H 8306 2011-01-24 17:04:22Z matt $". -// diff --git a/src/include/Fl_Text_Editor_mod.H b/src/include/Fl_Text_Editor_mod.H index 6bef513..f80620f 100644 --- a/src/include/Fl_Text_Editor_mod.H +++ b/src/include/Fl_Text_Editor_mod.H @@ -1,27 +1,145 @@ -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ // -// This file is part of flmsg +// "$Id: Fl_Text_Editor_mod.H 7903 2010-11-28 21:06:39Z matt $" // -// flrig 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. +// Header file for Fl_Text_Editor_mod class. // -// flrig is distributed in the hope that it will be useful, +// Copyright 2001-2010 by Bill Spitzak and others. +// Original code Copyright Mark Edel. Permission to distribute under +// the LGPL for the FLTK library granted by Mark Edel. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Library General Public +// License as published by the Free Software Foundation; either +// version 2 of the License, or (at your option) any later version. +// +// This library 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. +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Library 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 . -// ---------------------------------------------------------------------------- +// You should have received a copy of the GNU Library General Public +// License along with this library; if not, write to the +// +// Free Software Foundation, Inc. +// 51 Franklin Street, Fifth Floor +// Boston, MA 02110-1301 USA. +// +// Please report all bugs and problems on the following page: +// +// http://www.fltk.org/str.php +// + +/* \file + Fl_Text_Editor_mod widget . */ + + +#ifndef Fl_Text_Editor_mod_H +#define Fl_Text_Editor_mod_H + +#include "Fl_Text_Display_mod.H" #include -#if FLMSG_FLTK_API_MINOR < 3 -# include "Fl_Text_Editor_mod_1_1.H" -#else -# include "Fl_Text_Editor_mod_1_3.H" +// key will match in any state +#define Fl_Text_Editor_mod_ANY_STATE (-1L) + +/** + This is the FLTK text editor widget. It allows the user to + edit multiple lines of text and supports highlighting and + scrolling. The buffer that is displayed in the widget is managed + by the Fl_Text_Buffer_mod + class. + */ +class FL_EXPORT Fl_Text_Editor_mod : public Fl_Text_Display_mod { +public: + /** Key function binding callback type */ + typedef int (*Key_Func)(int key, Fl_Text_Editor_mod* editor); + + /** Simple linked list associating a key/state to a function */ + struct Key_Binding { + int key; ///< the key pressed + int state; ///< the state of key modifiers + Key_Func function; ///< associated function + Key_Binding* next; ///< next key binding in the list + }; + + Fl_Text_Editor_mod(int X, int Y, int W, int H, const char* l = 0); + ~Fl_Text_Editor_mod() { remove_all_key_bindings(); } + virtual int handle(int e); + /** + Sets the current insert mode; if non-zero, new text + is inserted before the current cursor position. Otherwise, new + text replaces text at the current cursor position. + */ + void insert_mode(int b) { insert_mode_ = b; } + /** + Gets the current insert mode; if non-zero, new text + is inserted before the current cursor position. Otherwise, new + text replaces text at the current cursor position. + */ + int insert_mode() { return insert_mode_; } + + void add_key_binding(int key, int state, Key_Func f, Key_Binding** list); + /** Adds a key of state "state" with the function "function" */ + void add_key_binding(int key, int state, Key_Func f) + { add_key_binding(key, state, f, &key_bindings); } + void remove_key_binding(int key, int state, Key_Binding** list); + /** Removes the key binding associated with the key "key" of state "state". */ + void remove_key_binding(int key, int state) + { remove_key_binding(key, state, &key_bindings); } + void remove_all_key_bindings(Key_Binding** list); + /** Removes all of the key bindings associated with the text editor or list. */ + void remove_all_key_bindings() { remove_all_key_bindings(&key_bindings); } + void add_default_key_bindings(Key_Binding** list); + Key_Func bound_key_function(int key, int state, Key_Binding* list); + /** Returns the function associated with a key binding. */ + Key_Func bound_key_function(int key, int state) + { return bound_key_function(key, state, key_bindings); } + /** Sets the default key function for unassigned keys. */ + void default_key_function(Key_Func f) { default_key_function_ = f; } + + // functions for the built in default bindings + static int kf_default(int c, Fl_Text_Editor_mod* e); + static int kf_ignore(int c, Fl_Text_Editor_mod* e); + static int kf_backspace(int c, Fl_Text_Editor_mod* e); + static int kf_enter(int c, Fl_Text_Editor_mod* e); + static int kf_move(int c, Fl_Text_Editor_mod* e); + static int kf_shift_move(int c, Fl_Text_Editor_mod* e); + static int kf_ctrl_move(int c, Fl_Text_Editor_mod* e); + static int kf_c_s_move(int c, Fl_Text_Editor_mod* e); + static int kf_meta_move(int c, Fl_Text_Editor_mod* e); + static int kf_m_s_move(int c, Fl_Text_Editor_mod* e); + static int kf_home(int, Fl_Text_Editor_mod* e); + static int kf_end(int c, Fl_Text_Editor_mod* e); + static int kf_left(int c, Fl_Text_Editor_mod* e); + static int kf_up(int c, Fl_Text_Editor_mod* e); + static int kf_right(int c, Fl_Text_Editor_mod* e); + static int kf_down(int c, Fl_Text_Editor_mod* e); + static int kf_page_up(int c, Fl_Text_Editor_mod* e); + static int kf_page_down(int c, Fl_Text_Editor_mod* e); + static int kf_insert(int c, Fl_Text_Editor_mod* e); + static int kf_delete(int c, Fl_Text_Editor_mod* e); + static int kf_copy(int c, Fl_Text_Editor_mod* e); + static int kf_cut(int c, Fl_Text_Editor_mod* e); + static int kf_paste(int c, Fl_Text_Editor_mod* e); + static int kf_select_all(int c, Fl_Text_Editor_mod* e); + static int kf_undo(int c, Fl_Text_Editor_mod* e); + +protected: + int handle_key(); + void maybe_do_callback(); + +#ifndef FL_DOXYGEN + int insert_mode_; + Key_Binding* key_bindings; + static Key_Binding* global_key_bindings; + Key_Func default_key_function_; #endif +}; + +#endif + +// +// End of "$Id: Fl_Text_Editor_mod.H 7903 2010-11-28 21:06:39Z matt $". +// + diff --git a/src/include/Fl_Text_Editor_mod_1_1.H b/src/include/Fl_Text_Editor_mod_1_1.H deleted file mode 100644 index 39eac48..0000000 --- a/src/include/Fl_Text_Editor_mod_1_1.H +++ /dev/null @@ -1,108 +0,0 @@ -// -// "$Id: Fl_Text_Editor.H 4288 2005-04-16 00:13:17Z mike $" -// -// Header file for Fl_Text_Editor class. -// -// Copyright 2001-2005 by Bill Spitzak and others. -// Original code Copyright Mark Edel. Permission to distribute under -// the LGPL for the FLTK library granted by Mark Edel. -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ -// -// This file is part of flmsg -// -// flrig 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. -// -// flrig 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 FL_TEXT_EDITOR_MOD_H -#define FL_TEXT_EDITOR_MOD_H - -#include "Fl_Text_Display_mod.H" - -// key will match in any state -#define FL_TEXT_EDITOR_ANY_STATE (-1L) - -class Fl_Text_Editor_mod : public Fl_Text_Display_mod { - public: - typedef int (*Key_Func)(int key, Fl_Text_Editor_mod* editor); - - struct Key_Binding { - int key; - int state; - Key_Func function; - Key_Binding* next; - }; - - Fl_Text_Editor_mod(int X, int Y, int W, int H, const char* l = 0); - ~Fl_Text_Editor_mod() { remove_all_key_bindings(); } - virtual int handle(int e); - void insert_mode(int b) { insert_mode_ = b; } - int insert_mode() { return insert_mode_; } - - void add_key_binding(int key, int state, Key_Func f, Key_Binding** list); - void add_key_binding(int key, int state, Key_Func f) - { add_key_binding(key, state, f, &key_bindings); } - void remove_key_binding(int key, int state, Key_Binding** list); - void remove_key_binding(int key, int state) - { remove_key_binding(key, state, &key_bindings); } - void remove_all_key_bindings(Key_Binding** list); - void remove_all_key_bindings() { remove_all_key_bindings(&key_bindings); } - void add_default_key_bindings(Key_Binding** list); - Key_Func bound_key_function(int key, int state, Key_Binding* list); - Key_Func bound_key_function(int key, int state) - { return bound_key_function(key, state, key_bindings); } - void default_key_function(Key_Func f) { default_key_function_ = f; } - - // functions for the built in default bindings - static int kf_default(int c, Fl_Text_Editor_mod* e); - static int kf_ignore(int c, Fl_Text_Editor_mod* e); - static int kf_backspace(int c, Fl_Text_Editor_mod* e); - static int kf_enter(int c, Fl_Text_Editor_mod* e); - static int kf_move(int c, Fl_Text_Editor_mod* e); - static int kf_shift_move(int c, Fl_Text_Editor_mod* e); - static int kf_ctrl_move(int c, Fl_Text_Editor_mod* e); - static int kf_c_s_move(int c, Fl_Text_Editor_mod* e); - static int kf_home(int, Fl_Text_Editor_mod* e); - static int kf_end(int c, Fl_Text_Editor_mod* e); - static int kf_left(int c, Fl_Text_Editor_mod* e); - static int kf_up(int c, Fl_Text_Editor_mod* e); - static int kf_right(int c, Fl_Text_Editor_mod* e); - static int kf_down(int c, Fl_Text_Editor_mod* e); - static int kf_page_up(int c, Fl_Text_Editor_mod* e); - static int kf_page_down(int c, Fl_Text_Editor_mod* e); - static int kf_insert(int c, Fl_Text_Editor_mod* e); - static int kf_delete(int c, Fl_Text_Editor_mod* e); - static int kf_copy(int c, Fl_Text_Editor_mod* e); - static int kf_cut(int c, Fl_Text_Editor_mod* e); - static int kf_paste(int c, Fl_Text_Editor_mod* e); - static int kf_select_all(int c, Fl_Text_Editor_mod* e); - static int kf_undo(int c, Fl_Text_Editor_mod* e); - - protected: - int handle_key(); - void maybe_do_callback(); - - int insert_mode_; - Key_Binding* key_bindings; - static Key_Binding* global_key_bindings; - Key_Func default_key_function_; -}; - -#endif - -// -// End of "$Id: Fl_Text_Editor.H 4288 2005-04-16 00:13:17Z mike $". -// - diff --git a/src/include/Fl_Text_Editor_mod_1_3.H b/src/include/Fl_Text_Editor_mod_1_3.H deleted file mode 100644 index c44687d..0000000 --- a/src/include/Fl_Text_Editor_mod_1_3.H +++ /dev/null @@ -1,141 +0,0 @@ -// -// "$Id: Fl_Text_Editor_mod.H 7903 2010-11-28 21:06:39Z matt $" -// -// Header file for Fl_Text_Editor_mod class. -// -// Copyright 2001-2010 by Bill Spitzak and others. -// Original code Copyright Mark Edel. Permission to distribute under -// the LGPL for the FLTK library granted by Mark Edel. -// -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ -// -// This file is part of flmsg -// -// flrig 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. -// -// flrig 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 . -// ---------------------------------------------------------------------------- - -/* \file - Fl_Text_Editor_mod widget . */ - - -#ifndef Fl_Text_Editor_mod_H -#define Fl_Text_Editor_mod_H - -#include "Fl_Text_Display_mod.H" - -// key will match in any state -#define Fl_Text_Editor_mod_ANY_STATE (-1L) - -/** - This is the FLTK text editor widget. It allows the user to - edit multiple lines of text and supports highlighting and - scrolling. The buffer that is displayed in the widget is managed - by the Fl_Text_Buffer_mod - class. -*/ -class FL_EXPORT Fl_Text_Editor_mod : public Fl_Text_Display_mod { - public: - /** Key function binding callback type */ - typedef int (*Key_Func)(int key, Fl_Text_Editor_mod* editor); - - /** Simple linked list associating a key/state to a function */ - struct Key_Binding { - int key; ///< the key pressed - int state; ///< the state of key modifiers - Key_Func function; ///< associated function - Key_Binding* next; ///< next key binding in the list - }; - - Fl_Text_Editor_mod(int X, int Y, int W, int H, const char* l = 0); - ~Fl_Text_Editor_mod() { remove_all_key_bindings(); } - virtual int handle(int e); - /** - Sets the current insert mode; if non-zero, new text - is inserted before the current cursor position. Otherwise, new - text replaces text at the current cursor position. - */ - void insert_mode(int b) { insert_mode_ = b; } - /** - Gets the current insert mode; if non-zero, new text - is inserted before the current cursor position. Otherwise, new - text replaces text at the current cursor position. - */ - int insert_mode() { return insert_mode_; } - - void add_key_binding(int key, int state, Key_Func f, Key_Binding** list); - /** Adds a key of state "state" with the function "function" */ - void add_key_binding(int key, int state, Key_Func f) - { add_key_binding(key, state, f, &key_bindings); } - void remove_key_binding(int key, int state, Key_Binding** list); - /** Removes the key binding associated with the key "key" of state "state". */ - void remove_key_binding(int key, int state) - { remove_key_binding(key, state, &key_bindings); } - void remove_all_key_bindings(Key_Binding** list); - /** Removes all of the key bindings associated with the text editor or list. */ - void remove_all_key_bindings() { remove_all_key_bindings(&key_bindings); } - void add_default_key_bindings(Key_Binding** list); - Key_Func bound_key_function(int key, int state, Key_Binding* list); - /** Returns the function associated with a key binding. */ - Key_Func bound_key_function(int key, int state) - { return bound_key_function(key, state, key_bindings); } - /** Sets the default key function for unassigned keys. */ - void default_key_function(Key_Func f) { default_key_function_ = f; } - - // functions for the built in default bindings - static int kf_default(int c, Fl_Text_Editor_mod* e); - static int kf_ignore(int c, Fl_Text_Editor_mod* e); - static int kf_backspace(int c, Fl_Text_Editor_mod* e); - static int kf_enter(int c, Fl_Text_Editor_mod* e); - static int kf_move(int c, Fl_Text_Editor_mod* e); - static int kf_shift_move(int c, Fl_Text_Editor_mod* e); - static int kf_ctrl_move(int c, Fl_Text_Editor_mod* e); - static int kf_c_s_move(int c, Fl_Text_Editor_mod* e); - static int kf_meta_move(int c, Fl_Text_Editor_mod* e); - static int kf_m_s_move(int c, Fl_Text_Editor_mod* e); - static int kf_home(int, Fl_Text_Editor_mod* e); - static int kf_end(int c, Fl_Text_Editor_mod* e); - static int kf_left(int c, Fl_Text_Editor_mod* e); - static int kf_up(int c, Fl_Text_Editor_mod* e); - static int kf_right(int c, Fl_Text_Editor_mod* e); - static int kf_down(int c, Fl_Text_Editor_mod* e); - static int kf_page_up(int c, Fl_Text_Editor_mod* e); - static int kf_page_down(int c, Fl_Text_Editor_mod* e); - static int kf_insert(int c, Fl_Text_Editor_mod* e); - static int kf_delete(int c, Fl_Text_Editor_mod* e); - static int kf_copy(int c, Fl_Text_Editor_mod* e); - static int kf_cut(int c, Fl_Text_Editor_mod* e); - static int kf_paste(int c, Fl_Text_Editor_mod* e); - static int kf_select_all(int c, Fl_Text_Editor_mod* e); - static int kf_undo(int c, Fl_Text_Editor_mod* e); - - protected: - int handle_key(); - void maybe_do_callback(); - -#ifndef FL_DOXYGEN - int insert_mode_; - Key_Binding* key_bindings; - static Key_Binding* global_key_bindings; - Key_Func default_key_function_; -#endif -}; - -#endif - -// -// End of "$Id: Fl_Text_Editor_mod.H 7903 2010-11-28 21:06:39Z matt $". -// - diff --git a/src/include/flinput2.h b/src/include/flinput2.h index cdd4ed5..2ea33f7 100644 --- a/src/include/flinput2.h +++ b/src/include/flinput2.h @@ -2,14 +2,14 @@ // Copyright (C) 2014 // David Freese, W1HKJ // -// This file is part of flmsg +// This file is part of fldigi // -// flrig is free software; you can redistribute it and/or modify +// fldigi 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. // -// flrig is distributed in the hope that it will be useful, +// fldigi 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. @@ -23,11 +23,27 @@ #include +#include "config.h" + class Fl_Input2 : public Fl_Input { +private: + int ascii_cnt; // restart the numeric keypad entries. + int ascii_chr; // character value of ASCII > 0x80 + int handle_key_ascii(int key); + char *utf8text; + int utf8cnt; + public: Fl_Input2(int x, int y, int w, int h, const char* l = 0); int handle(int event); + +#if FLMSG_FLTK_API_MINOR > 3 + int position() { return Fl_Input::insert_position(); } + int position(int p, int m) { return Fl_Input::insert_position(p, m); } + int position(int p) { return Fl_Input::insert_position(p, p); } +#endif + }; #endif // FL_INPUT2_ diff --git a/src/widgets/FTextView.cxx b/src/widgets/FTextView.cxx index a60754d..aba28c0 100644 --- a/src/widgets/FTextView.cxx +++ b/src/widgets/FTextView.cxx @@ -7,7 +7,7 @@ // Copyright (C) 2008-2009 // Dave Freese, W1HKJ // -// This file is part of flmsg. +// This file is part of FLAMP. // // This is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by @@ -27,7 +27,6 @@ #include #include -#include #include #include #include @@ -54,6 +53,7 @@ #include "debug.h" + /// FTextBase constructor. /// Word wrapping is enabled by default at column 80, but see \c reset_wrap_col. /// @param x @@ -62,15 +62,9 @@ /// @param h /// @param l -#if flmsg_FLTK_API_MAJOR == 1 && flmsg_FLTK_API_MINOR < 3 -FTextBase::FTextBase(int x, int y, int w, int h, const char *l) -: Fl_Text_Editor_mod(x, y, w, h, l), -wrap(true), wrap_col(80), max_lines(0), scroll_hint(false) -#else FTextBase::FTextBase(int x, int y, int w, int h, const char *l) : Fl_Text_Editor_mod(x, y, w, h, l), wrap(WRAP_AT_BOUNDS), wrap_col(80), max_lines(0), scroll_hint(false) -#endif { oldw = oldh = olds = -1; oldf = (Fl_Font)-1; @@ -149,15 +143,9 @@ void FTextBase::add(unsigned char c, int attr) void FTextBase::set_word_wrap(bool b) { -#if flmsg_FLTK_API_MAJOR == 1 && flmsg_FLTK_API_MINOR < 3 - if ((wrap = b)) wrap_mode(true, 0); - else wrap_mode(false, 0); - show_insert_position(); -#else if ((wrap = b)) wrap_mode(WRAP_AT_BOUNDS, 0); else wrap_mode(WRAP_NONE, 0); show_insert_position(); -#endif } void FTextBase::setFont(Fl_Font f, int attr) @@ -207,7 +195,6 @@ void FTextBase::resize(int X, int Y, int W, int H) if (need_wrap_reset) reset_wrap_col(); -#if flmsg_FLTK_API_MAJOR == 1 && flmsg_FLTK_API_MINOR == 3 TOP_MARGIN = DEFAULT_TOP_MARGIN; int r = H - Fl::box_dh(box()) - TOP_MARGIN - BOTTOM_MARGIN; if (mHScrollBar->visible()) @@ -217,16 +204,7 @@ void FTextBase::resize(int X, int Y, int W, int H) //printf("H %d, textsize %d, lines %d, extra %d\n", r, msize, r / msize, r % msize); if (r %= msize) TOP_MARGIN += r; -#else - if (need_margin_reset && textsize() > 0) { - TOP_MARGIN = DEFAULT_TOP_MARGIN; - int r = H - Fl::box_dh(box()) - TOP_MARGIN - BOTTOM_MARGIN; - if (mHScrollBar->visible()) - r -= scrollbar_width(); - if (r %= textsize()) - TOP_MARGIN += r; - } -#endif + if (scroll_hint) { mTopLineNumHint = mNBufferLines; mHorizOffsetHint = 0; @@ -911,7 +889,7 @@ void FTextEdit::changed_cb(int pos, int nins, int ndel, int nsty, const char *dt } else if (nsty > 0) // restyled, e.g. selected, text return e->buffer_modified_cb(pos, nins, ndel, nsty, dtext, e); - + // No changes, e.g., a paste with an empty clipboard. return; } @@ -933,9 +911,9 @@ void FTextEdit::changed_cb(int pos, int nins, int ndel, int nsty, const char *dt } else if (ndel > 0) e->sbuf->remove(pos, pos + ndel); - + e->sbuf->select(pos, pos + nins - ndel); - + e->buffer_modified_cb(pos, nins, ndel, nsty, dtext, e); // We may need to scroll if the text was inserted by the // add() methods, e.g. by a macro diff --git a/src/widgets/Fl_Text_Buffer_mod.cxx b/src/widgets/Fl_Text_Buffer_mod.cxx index c5aaa70..355d422 100644 --- a/src/widgets/Fl_Text_Buffer_mod.cxx +++ b/src/widgets/Fl_Text_Buffer_mod.cxx @@ -1,27 +1,1855 @@ -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ // -// This file is part of flmsg +// "$Id: Fl_Text_Buffer_mod.cxx 8040 2010-12-15 17:38:39Z manolo $" // -// flrig 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. +// Copyright 2001-2010 by Bill Spitzak and others. +// Original code Copyright Mark Edel. Permission to distribute under +// the LGPL for the FLTK library granted by Mark Edel. // -// flrig is distributed in the hope that it will be useful, +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Library General Public +// License as published by the Free Software Foundation; either +// version 2 of the License, or (at your option) any later version. +// +// This library 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. +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Library 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 . -// ---------------------------------------------------------------------------- +// You should have received a copy of the GNU Library General Public +// License along with this library; if not, write to the +// +// Free Software Foundation, Inc. +// 51 Franklin Street, Fifth Floor +// Boston, MA 02110-1301 USA. +// +// Please report all bugs and problems on the following page: +// +// http://www.fltk.org/str.php +// + +#include +#include +#include +#include "missing_strings.h" +#include +#include +#include +#include "Fl_Text_Buffer_mod.H" #include -#if FLMSG_FLTK_API_MINOR < 3 -# include "Fl_Text_Buffer_mod_1_1.cxx" -#else -# include "Fl_Text_Buffer_mod_1_3.cxx" +#if FLCLUSTER_FLTK_API_MAJOR == 1 && FLCLUSTER_FLTK_API_MINOR < 3 +# error "FLTK versions less then 1.3 are no longer supported" #endif + +/* + This file is based on a port of NEdit to FLTK many years ago. NEdit at that + point was already stretched beyond the task it was designed for which explains + why the source code is sometimes pretty convoluted. It still is a very useful + widget for FLTK, and we are thankful that the nedit team allowed us to + integrate their code. + + With the introduction of Unicode and UTF-8, Fl_Text_... has to go into a whole + new generation of code. Originally designed for monospaced fonts only, many + features make less sense in the multibyte and multiwidth world of UTF-8. + + Columns are a good example. There is simply no such thing. The new Fl_Text_... + widget converts columns to pixels by multiplying them with the average + character width for a given font. + + Rectangular selections were rarely used (if at all) and make little sense when + using variable width fonts. They have been removed. + + Using multiple spaces to emulate tab stops has been replaced by pixel counting + routines. They are slower, but give the expected result for proportional fonts. + + And constantly recalculating character widths is just much too expensive. Lines + of text are now subdivided into blocks of text which are measured at once + instead of individual characters. + */ + + +#ifndef min + +static int max(int i1, int i2) +{ + return i1 >= i2 ? i1 : i2; +} + +static int min(int i1, int i2) +{ + return i1 <= i2 ? i1 : i2; +} + +#endif + + +static char *undobuffer; +static int undobufferlength; +static Fl_Text_Buffer_mod *undowidget; +static int undoat; // points after insertion +static int undocut; // number of characters deleted there +static int undoinsert; // number of characters inserted +static int undoyankcut; // length of valid contents of buffer, even if undocut=0 + +/* + Resize the undo buffer to match at least the requested size. + */ +static void undobuffersize(int n) +{ + if (n > undobufferlength) { + if (undobuffer) { + do { + undobufferlength *= 2; + } while (undobufferlength < n); + undobuffer = (char *) realloc(undobuffer, undobufferlength); + } else { + undobufferlength = n + 9; + undobuffer = (char *) malloc(undobufferlength); + } + } +} + +static void def_transcoding_warning_action(Fl_Text_Buffer_mod *text) +{ + fl_alert("%s", text->file_encoding_warning_message); +} + +/* + Initialize all variables. + */ +Fl_Text_Buffer_mod::Fl_Text_Buffer_mod(int requestedSize, int preferredGapSize) +{ + mLength = 0; + mPreferredGapSize = preferredGapSize; + mBuf = (char *) malloc(requestedSize + mPreferredGapSize); + mGapStart = 0; + mGapEnd = mPreferredGapSize; + mTabDist = 8; + mPrimary.mSelected = 0; + mPrimary.mStart = mPrimary.mEnd = 0; + mSecondary.mSelected = 0; + mSecondary.mStart = mSecondary.mEnd = 0; + mHighlight.mSelected = 0; + mHighlight.mStart = mHighlight.mEnd = 0; + mModifyProcs = NULL; + mCbArgs = NULL; + mNModifyProcs = 0; + mNPredeleteProcs = 0; + mPredeleteProcs = NULL; + mPredeleteCbArgs = NULL; + mCursorPosHint = 0; + mCanUndo = 1; + input_file_was_transcoded = 0; + transcoding_warning_action = def_transcoding_warning_action; +} + + +/* + Free all resources. + */ +Fl_Text_Buffer_mod::~Fl_Text_Buffer_mod() +{ + free(mBuf); + if (mNModifyProcs != 0) { + delete[]mModifyProcs; + delete[]mCbArgs; + } + if (mNPredeleteProcs != 0) { + delete[]mPredeleteProcs; + delete[]mPredeleteCbArgs; + } +} + + +/* + This function copies verbose whatever is in front and after the gap into a + single buffer. + */ +char *Fl_Text_Buffer_mod::text() const { + char *t = (char *) malloc(mLength + 1); + memcpy(t, mBuf, mGapStart); + memcpy(t+mGapStart, mBuf+mGapEnd, mLength - mGapStart); + t[mLength] = '\0'; + return t; +} + + +/* + Set the text buffer to a new string. + */ +void Fl_Text_Buffer_mod::text(const char *t) +{ + IS_UTF8_ALIGNED(t) + + call_predelete_callbacks(0, length()); + + /* Save information for redisplay, and get rid of the old buffer */ + const char *deletedText = text(); + int deletedLength = mLength; + free((void *) mBuf); + + /* Start a new buffer with a gap of mPreferredGapSize at the end */ + int insertedLength = strlen(t); + mBuf = (char *) malloc(insertedLength + mPreferredGapSize); + mLength = insertedLength; + mGapStart = insertedLength; + mGapEnd = mGapStart + mPreferredGapSize; + memcpy(mBuf, t, insertedLength); + + /* Zero all of the existing selections */ + update_selections(0, deletedLength, 0); + + /* Call the saved display routine(s) to update the screen */ + call_modify_callbacks(0, deletedLength, insertedLength, 0, deletedText); + free((void *) deletedText); +} + + +/* + Creates a range of text to a new buffer and copies verbose from around the gap. + */ +char *Fl_Text_Buffer_mod::text_range(int start, int end) const { + IS_UTF8_ALIGNED2(this, (start)) + IS_UTF8_ALIGNED2(this, (end)) + + char *s = NULL; + + /* Make sure start and end are ok, and allocate memory for returned string. + If start is bad, return "", if end is bad, adjust it. */ + if (start < 0 || start > mLength) + { + s = (char *) malloc(1); + s[0] = '\0'; + return s; + } + if (end < start) { + int temp = start; + start = end; + end = temp; + } + if (end > mLength) + end = mLength; + int copiedLength = end - start; + s = (char *) malloc(copiedLength + 1); + + /* Copy the text from the buffer to the returned string */ + if (end <= mGapStart) { + memcpy(s, mBuf + start, copiedLength); + } else if (start >= mGapStart) { + memcpy(s, mBuf + start + (mGapEnd - mGapStart), copiedLength); + } else { + int part1Length = mGapStart - start; + memcpy(s, mBuf + start, part1Length); + memcpy(s + part1Length, mBuf + mGapEnd, copiedLength - part1Length); + } + s[copiedLength] = '\0'; + return s; +} + +/* + Return a UCS-4 character at the given index. + Pos must be at a character boundary. + */ +unsigned int Fl_Text_Buffer_mod::char_at(int pos) const { + if (pos < 0 || pos >= mLength) + return '\0'; + + IS_UTF8_ALIGNED2(this, (pos)) + + const char *src = address(pos); + return fl_utf8decode(src, 0, 0); +} + + +/* + Return the raw byte at the given index. + This function ignores all unicode encoding. + */ +char Fl_Text_Buffer_mod::byte_at(int pos) const { + if (pos < 0 || pos >= mLength) + return '\0'; + const char *src = address(pos); + return *src; +} + + +/* + Insert some text at the given index. + Pos must be at a character boundary. + */ +void Fl_Text_Buffer_mod::insert(int pos, const char *text) +{ + IS_UTF8_ALIGNED2(this, (pos)) + IS_UTF8_ALIGNED(text) + + /* check if there is actually any text */ + if (!text || !*text) + return; + + /* if pos is not contiguous to existing text, make it */ + if (pos > mLength) + pos = mLength; + if (pos < 0) + pos = 0; + + /* Even if nothing is deleted, we must call these callbacks */ + call_predelete_callbacks(pos, 0); + + /* insert and redisplay */ + int nInserted = insert_(pos, text); + mCursorPosHint = pos + nInserted; + IS_UTF8_ALIGNED2(this, (mCursorPosHint)) + call_modify_callbacks(pos, 0, nInserted, 0, NULL); +} + + +/* + Replace a range of text with new text. + Start and end must be at a character boundary. + */ +void Fl_Text_Buffer_mod::replace(int start, int end, const char *text) +{ + // Range check... + if (!text) + return; + if (start < 0) + start = 0; + if (end > mLength) + end = mLength; + + IS_UTF8_ALIGNED2(this, (start)) + IS_UTF8_ALIGNED2(this, (end)) + IS_UTF8_ALIGNED(text) + + call_predelete_callbacks(start, end - start); + const char *deletedText = text_range(start, end); + remove_(start, end); + int nInserted = insert_(start, text); + mCursorPosHint = start + nInserted; + call_modify_callbacks(start, end - start, nInserted, 0, deletedText); + free((void *) deletedText); +} + + +/* + Remove a range of text. + Start and End must be at a character boundary. + */ +void Fl_Text_Buffer_mod::remove(int start, int end) +{ + /* Make sure the arguments make sense */ + if (start > end) { + int temp = start; + start = end; + end = temp; + } + if (start > mLength) + start = mLength; + if (start < 0) + start = 0; + if (end > mLength) + end = mLength; + if (end < 0) + end = 0; + + IS_UTF8_ALIGNED2(this, (start)) + IS_UTF8_ALIGNED2(this, (end)) + + if (start == end) + return; + + call_predelete_callbacks(start, end - start); + /* Remove and redisplay */ + const char *deletedText = text_range(start, end); + remove_(start, end); + mCursorPosHint = start; + call_modify_callbacks(start, end - start, 0, 0, deletedText); + free((void *) deletedText); +} + + +/* + Copy a range of text from another text buffer. + fromStart, fromEnd, and toPos must be at a character boundary. + */ +void Fl_Text_Buffer_mod::copy(Fl_Text_Buffer_mod * fromBuf, int fromStart, + int fromEnd, int toPos) +{ + IS_UTF8_ALIGNED2(fromBuf, fromStart) + IS_UTF8_ALIGNED2(fromBuf, fromEnd) + IS_UTF8_ALIGNED2(this, (toPos)) + + int copiedLength = fromEnd - fromStart; + + /* Prepare the buffer to receive the new text. If the new text fits in + the current buffer, just move the gap (if necessary) to where + the text should be inserted. If the new text is too large, reallocate + the buffer with a gap large enough to accomodate the new text and a + gap of mPreferredGapSize */ + if (copiedLength > mGapEnd - mGapStart) + reallocate_with_gap(toPos, copiedLength + mPreferredGapSize); + else if (toPos != mGapStart) + move_gap(toPos); + + /* Insert the new text (toPos now corresponds to the start of the gap) */ + if (fromEnd <= fromBuf->mGapStart) { + memcpy(&mBuf[toPos], &fromBuf->mBuf[fromStart], copiedLength); + } else if (fromStart >= fromBuf->mGapStart) { + memcpy(&mBuf[toPos], + &fromBuf->mBuf[fromStart + (fromBuf->mGapEnd - fromBuf->mGapStart)], + copiedLength); + } else { + int part1Length = fromBuf->mGapStart - fromStart; + memcpy(&mBuf[toPos], &fromBuf->mBuf[fromStart], part1Length); + memcpy(&mBuf[toPos + part1Length], + &fromBuf->mBuf[fromBuf->mGapEnd], copiedLength - part1Length); + } + mGapStart += copiedLength; + mLength += copiedLength; + update_selections(toPos, 0, copiedLength); +} + + +/* + Take the previous changes and undo them. Return the previous + cursor position in cursorPos. Returns 1 if the undo was applied. + CursorPos will be at a character boundary. + */ +int Fl_Text_Buffer_mod::undo(int *cursorPos) +{ + if (undowidget != this || (!undocut && !undoinsert && !mCanUndo)) + return 0; + + int ilen = undocut; + int xlen = undoinsert; + int b = undoat - xlen; + + if (xlen && undoyankcut && !ilen) { + ilen = undoyankcut; + } + + if (xlen && ilen) { + undobuffersize(ilen + 1); + undobuffer[ilen] = 0; + char *tmp = strdup(undobuffer); + replace(b, undoat, tmp); + if (cursorPos) + *cursorPos = mCursorPosHint; + free(tmp); + } else if (xlen) { + remove(b, undoat); + if (cursorPos) + *cursorPos = mCursorPosHint; + } else if (ilen) { + undobuffersize(ilen + 1); + undobuffer[ilen] = 0; + insert(undoat, undobuffer); + if (cursorPos) + *cursorPos = mCursorPosHint; + undoyankcut = 0; + } + + return 1; +} + + +/* + Set a flag if undo function will work. + */ +void Fl_Text_Buffer_mod::canUndo(char flag) +{ + mCanUndo = flag; + // disabling undo also clears the last undo operation! + if (!mCanUndo && undowidget==this) + undowidget = 0; +} + + +/* + Change the tab width. This will cause a couple of callbacks and a complete + redisplay. + Matt: I am not entirely sure why we need to trigger callbacks because + tabs are only a graphical hint, not changing any text at all, but I leave + this in here for back compatibility. + */ +void Fl_Text_Buffer_mod::tab_distance(int tabDist) +{ + /* First call the pre-delete callbacks with the previous tab setting + still active. */ + call_predelete_callbacks(0, mLength); + + /* Change the tab setting */ + mTabDist = tabDist; + + /* Force any display routines to redisplay everything (unfortunately, + this means copying the whole buffer contents to provide "deletedText" */ + const char *deletedText = text(); + call_modify_callbacks(0, mLength, mLength, 0, deletedText); + free((void *) deletedText); +} + + +/* + Select a range of text. + Start and End must be at a character boundary. + */ +void Fl_Text_Buffer_mod::select(int start, int end) +{ + IS_UTF8_ALIGNED2(this, (start)) + IS_UTF8_ALIGNED2(this, (end)) + + Fl_Text_Selection_mod oldSelection = mPrimary; + + mPrimary.set(start, end); + redisplay_selection(&oldSelection, &mPrimary); +} + + +/* + Clear the primary selection. + */ +void Fl_Text_Buffer_mod::unselect() +{ + Fl_Text_Selection_mod oldSelection = mPrimary; + + mPrimary.mSelected = 0; + redisplay_selection(&oldSelection, &mPrimary); +} + + +/* + Return the primary selection range. + */ +int Fl_Text_Buffer_mod::selection_position(int *start, int *end) +{ + return mPrimary.position(start, end); +} + + +/* + Return a copy of the selected text. + */ +char *Fl_Text_Buffer_mod::selection_text() +{ + return selection_text_(&mPrimary); +} + + +/* + Remove the selected text. + */ +void Fl_Text_Buffer_mod::remove_selection() +{ + remove_selection_(&mPrimary); +} + + +/* + Replace the selected text. + */ +void Fl_Text_Buffer_mod::replace_selection(const char *text) +{ + replace_selection_(&mPrimary, text); +} + + +/* + Select text. + Start and End must be at a character boundary. + */ +void Fl_Text_Buffer_mod::secondary_select(int start, int end) +{ + Fl_Text_Selection_mod oldSelection = mSecondary; + + mSecondary.set(start, end); + redisplay_selection(&oldSelection, &mSecondary); +} + + +/* + Deselect text. + */ +void Fl_Text_Buffer_mod::secondary_unselect() +{ + Fl_Text_Selection_mod oldSelection = mSecondary; + + mSecondary.mSelected = 0; + redisplay_selection(&oldSelection, &mSecondary); +} + + +/* + Return the selected range. + */ +int Fl_Text_Buffer_mod::secondary_selection_position(int *start, int *end) +{ + return mSecondary.position(start, end); +} + + +/* + Return a copy of the text in this selection. + */ +char *Fl_Text_Buffer_mod::secondary_selection_text() +{ + return selection_text_(&mSecondary); +} + + +/* + Remove the selected text. + */ +void Fl_Text_Buffer_mod::remove_secondary_selection() +{ + remove_selection_(&mSecondary); +} + + +/* + Replace selected text. + */ +void Fl_Text_Buffer_mod::replace_secondary_selection(const char *text) +{ + replace_selection_(&mSecondary, text); +} + + +/* + Highlight a range of text. + Start and End must be at a character boundary. + */ +void Fl_Text_Buffer_mod::highlight(int start, int end) +{ + Fl_Text_Selection_mod oldSelection = mHighlight; + + mHighlight.set(start, end); + redisplay_selection(&oldSelection, &mHighlight); +} + + +/* + Remove text highlighting. + */ +void Fl_Text_Buffer_mod::unhighlight() +{ + Fl_Text_Selection_mod oldSelection = mHighlight; + + mHighlight.mSelected = 0; + redisplay_selection(&oldSelection, &mHighlight); +} + + +/* + Return position of highlight. + */ +int Fl_Text_Buffer_mod::highlight_position(int *start, int *end) +{ + return mHighlight.position(start, end); +} + + +/* + Return a copy of highlighted text. + */ +char *Fl_Text_Buffer_mod::highlight_text() +{ + return selection_text_(&mHighlight); +} + + +/* + Add a callback that is called whenever text is modified. + */ +void Fl_Text_Buffer_mod::add_modify_callback(Fl_Text_Modify_Cb bufModifiedCB, + void *cbArg) +{ + Fl_Text_Modify_Cb *newModifyProcs = + new Fl_Text_Modify_Cb[mNModifyProcs + 1]; + void **newCBArgs = new void *[mNModifyProcs + 1]; + for (int i = 0; i < mNModifyProcs; i++) { + newModifyProcs[i + 1] = mModifyProcs[i]; + newCBArgs[i + 1] = mCbArgs[i]; + } + if (mNModifyProcs != 0) { + delete[]mModifyProcs; + delete[]mCbArgs; + } + newModifyProcs[0] = bufModifiedCB; + newCBArgs[0] = cbArg; + mNModifyProcs++; + mModifyProcs = newModifyProcs; + mCbArgs = newCBArgs; +} + + +/* + Remove a callback. + */ +void Fl_Text_Buffer_mod::remove_modify_callback(Fl_Text_Modify_Cb bufModifiedCB, + void *cbArg) +{ + int i, toRemove = -1; + + /* find the matching callback to remove */ + for (i = 0; i < mNModifyProcs; i++) { + if (mModifyProcs[i] == bufModifiedCB && mCbArgs[i] == cbArg) { + toRemove = i; + break; + } + } + if (toRemove == -1) { + Fl::error + ("Fl_Text_Buffer_mod::remove_modify_callback(): Can't find modify CB to remove"); + return; + } + + /* Allocate new lists for remaining callback procs and args (if + any are left) */ + mNModifyProcs--; + if (mNModifyProcs == 0) { + mNModifyProcs = 0; + delete[]mModifyProcs; + mModifyProcs = NULL; + delete[]mCbArgs; + mCbArgs = NULL; + return; + } + Fl_Text_Modify_Cb *newModifyProcs = new Fl_Text_Modify_Cb[mNModifyProcs]; + void **newCBArgs = new void *[mNModifyProcs]; + + /* copy out the remaining members and free the old lists */ + for (i = 0; i < toRemove; i++) { + newModifyProcs[i] = mModifyProcs[i]; + newCBArgs[i] = mCbArgs[i]; + } + for (; i < mNModifyProcs; i++) { + newModifyProcs[i] = mModifyProcs[i + 1]; + newCBArgs[i] = mCbArgs[i + 1]; + } + delete[]mModifyProcs; + delete[]mCbArgs; + mModifyProcs = newModifyProcs; + mCbArgs = newCBArgs; +} + + +/* + Add a callback that is called before deleting text. + */ +void Fl_Text_Buffer_mod::add_predelete_callback(Fl_Text_Predelete_Cb bufPreDeleteCB, + void *cbArg) +{ + Fl_Text_Predelete_Cb *newPreDeleteProcs = + new Fl_Text_Predelete_Cb[mNPredeleteProcs + 1]; + void **newCBArgs = new void *[mNPredeleteProcs + 1]; + for (int i = 0; i < mNPredeleteProcs; i++) { + newPreDeleteProcs[i + 1] = mPredeleteProcs[i]; + newCBArgs[i + 1] = mPredeleteCbArgs[i]; + } + if (mNPredeleteProcs != 0) { + delete[]mPredeleteProcs; + delete[]mPredeleteCbArgs; + } + newPreDeleteProcs[0] = bufPreDeleteCB; + newCBArgs[0] = cbArg; + mNPredeleteProcs++; + mPredeleteProcs = newPreDeleteProcs; + mPredeleteCbArgs = newCBArgs; +} + + +/* + Remove a callback. + */ +void Fl_Text_Buffer_mod::remove_predelete_callback(Fl_Text_Predelete_Cb bufPreDeleteCB, void *cbArg) +{ + int i, toRemove = -1; + /* find the matching callback to remove */ + for (i = 0; i < mNPredeleteProcs; i++) { + if (mPredeleteProcs[i] == bufPreDeleteCB && + mPredeleteCbArgs[i] == cbArg) { + toRemove = i; + break; + } + } + if (toRemove == -1) { + Fl::error + ("Fl_Text_Buffer_mod::remove_predelete_callback(): Can't find pre-delete CB to remove"); + return; + } + + /* Allocate new lists for remaining callback procs and args (if + any are left) */ + mNPredeleteProcs--; + if (mNPredeleteProcs == 0) { + mNPredeleteProcs = 0; + delete[]mPredeleteProcs; + mPredeleteProcs = NULL; + delete[]mPredeleteCbArgs; + mPredeleteCbArgs = NULL; + return; + } + Fl_Text_Predelete_Cb *newPreDeleteProcs = + new Fl_Text_Predelete_Cb[mNPredeleteProcs]; + void **newCBArgs = new void *[mNPredeleteProcs]; + + /* copy out the remaining members and free the old lists */ + for (i = 0; i < toRemove; i++) { + newPreDeleteProcs[i] = mPredeleteProcs[i]; + newCBArgs[i] = mPredeleteCbArgs[i]; + } + for (; i < mNPredeleteProcs; i++) { + newPreDeleteProcs[i] = mPredeleteProcs[i + 1]; + newCBArgs[i] = mPredeleteCbArgs[i + 1]; + } + delete[]mPredeleteProcs; + delete[]mPredeleteCbArgs; + mPredeleteProcs = newPreDeleteProcs; + mPredeleteCbArgs = newCBArgs; +} + + +/* + Return a copy of the line that contains a given index. + Pos must be at a character boundary. + */ +char *Fl_Text_Buffer_mod::line_text(int pos) const { + return text_range(line_start(pos), line_end(pos)); +} + + +/* + Find the beginning of the line. + */ +int Fl_Text_Buffer_mod::line_start(int pos) const +{ + if (!findchar_backward(pos, '\n', &pos)) + return 0; + return pos + 1; +} + + +/* + Find the end of the line. + */ +int Fl_Text_Buffer_mod::line_end(int pos) const { + if (!findchar_forward(pos, '\n', &pos)) + pos = mLength; + return pos; +} + + +/* + Find the beginning of a word. + NOT UNICODE SAFE. + */ +int Fl_Text_Buffer_mod::word_start(int pos) const { + // FIXME: character is ucs-4 + while (pos>0 && (isalnum(char_at(pos)) || char_at(pos) == '_')) { + pos = prev_char(pos); + } + // FIXME: character is ucs-4 + if (!(isalnum(char_at(pos)) || char_at(pos) == '_')) + pos = next_char(pos); + return pos; +} + +/* + ** Search backwards in buffer for characters in "searchChars", starting + ** with the character BEFORE "startPos", returning the result in "foundPos" + ** returns 1 if found, 0 if not. + */ +int Fl_Text_Buffer_mod::findchars_backward( int startPos, const char *searchChars, + int *foundPos ) { + int pos = startPos; + const char *c; + char ch = 0; + + if ( startPos == 0 ) { + *foundPos = 0; + return 0; + } + while ( pos > 0 ) { + ch = char_at(pos); + for ( c = searchChars; *c != '\0'; c++ ) { + if ( ch == *c ) { + *foundPos = pos; + return 1; + } + } + pos = prev_char(pos); + } + *foundPos = 0; + return 0; +} + + +/* + Find the end of a word. + NOT UNICODE SAFE. + */ +int Fl_Text_Buffer_mod::word_end(int pos) const { + // FIXME: character is ucs-4 + while (pos < length() && (isalnum(char_at(pos)) || char_at(pos) == '_')) + { + pos = next_char(pos); + } + return pos; +} + +/* + ** Search forwards in buffer for characters in "searchChars", starting + ** with the character "startPos", and returning the result in "foundPos" + ** returns 1 if found, 0 if not. + */ +int Fl_Text_Buffer_mod::findchars_forward( int startPos, const char *searchChars, + int *foundPos ) { + int pos = startPos; + const char *c; + char ch = 0; + + while ( pos < length() ) { + ch = char_at(pos); + for ( c = searchChars; *c != '\0'; c++ ) { + if ( ch == *c ) { + *foundPos = pos; + return 1; + } + } + pos = next_char(pos); + } + *foundPos = length(); + return 0; +} + + +/* + Count the number of characters between two positions. + */ +int Fl_Text_Buffer_mod::count_displayed_characters(int lineStartPos, + int targetPos) const +{ + IS_UTF8_ALIGNED2(this, (lineStartPos)) + IS_UTF8_ALIGNED2(this, (targetPos)) + + int charCount = 0; + + int pos = lineStartPos; + while (pos < targetPos) { + pos = next_char(pos); + charCount++; + } + return charCount; +} + + +/* + Skip ahead a number of characters from a given index. + This function breaks early if it encounters a newline character. + */ +int Fl_Text_Buffer_mod::skip_displayed_characters(int lineStartPos, int nChars) +{ + IS_UTF8_ALIGNED2(this, (lineStartPos)) + + int pos = lineStartPos; + + for (int charCount = 0; charCount < nChars && pos < mLength; charCount++) { + unsigned int c = char_at(pos); + if (c == '\n') + return pos; + pos = next_char(pos); + } + return pos; +} + + +/* + Count the number of newline characters between start and end. + startPos and endPos must be at a character boundary. + This function is optimized for speed by not using UTF-8 calls. + */ +int Fl_Text_Buffer_mod::count_lines(int startPos, int endPos) const { + IS_UTF8_ALIGNED2(this, (startPos)) + IS_UTF8_ALIGNED2(this, (endPos)) + + int gapLen = mGapEnd - mGapStart; + int lineCount = 0; + + int pos = startPos; + while (pos < mGapStart) + { + if (pos == endPos) + return lineCount; + if (mBuf[pos++] == '\n') + lineCount++; + } + while (pos < mLength) { + if (pos == endPos) + return lineCount; + if (mBuf[pos++ + gapLen] == '\n') + lineCount++; + } + return lineCount; +} + + +/* + Skip to the first character, n lines ahead. + StartPos must be at a character boundary. + This function is optimized for speed by not using UTF-8 calls. + */ +int Fl_Text_Buffer_mod::skip_lines(int startPos, int nLines) +{ + IS_UTF8_ALIGNED2(this, (startPos)) + + if (nLines == 0) + return startPos; + + int gapLen = mGapEnd - mGapStart; + int pos = startPos; + int lineCount = 0; + while (pos < mGapStart) { + if (mBuf[pos++] == '\n') { + lineCount++; + if (lineCount == nLines) { + IS_UTF8_ALIGNED2(this, (pos)) + return pos; + } + } + } + while (pos < mLength) { + if (mBuf[pos++ + gapLen] == '\n') { + lineCount++; + if (lineCount >= nLines) { + IS_UTF8_ALIGNED2(this, (pos)) + return pos; + } + } + } + IS_UTF8_ALIGNED2(this, (pos)) + return pos; +} + + +/* + Skip to the first character, n lines back. + StartPos must be at a character boundary. + This function is optimized for speed by not using UTF-8 calls. + */ +int Fl_Text_Buffer_mod::rewind_lines(int startPos, int nLines) +{ + IS_UTF8_ALIGNED2(this, (startPos)) + + int pos = startPos - 1; + if (pos <= 0) + return 0; + + int gapLen = mGapEnd - mGapStart; + int lineCount = -1; + while (pos >= mGapStart) { + if (mBuf[pos + gapLen] == '\n') { + if (++lineCount >= nLines) { + IS_UTF8_ALIGNED2(this, (pos+1)) + return pos + 1; + } + } + pos--; + } + while (pos >= 0) { + if (mBuf[pos] == '\n') { + if (++lineCount >= nLines) { + IS_UTF8_ALIGNED2(this, (pos+1)) + return pos + 1; + } + } + pos--; + } + return 0; +} + + +/* + Find a matching string in the buffer. + */ +int Fl_Text_Buffer_mod::search_forward(int startPos, const char *searchString, + int *foundPos, int matchCase) const +{ + IS_UTF8_ALIGNED2(this, (startPos)) + IS_UTF8_ALIGNED(searchString) + + if (!searchString) + return 0; + int bp; + const char *sp; + if (matchCase) { + while (startPos < length()) { + bp = startPos; + sp = searchString; + for (;;) { + char c = *sp; + // we reached the end of the "needle", so we found the string! + if (!c) { + *foundPos = startPos; + return 1; + } + int l = fl_utf8len1(c); + if (memcmp(sp, address(bp), l)) + break; + sp += l; bp += l; + } + startPos = next_char(startPos); + } + } else { + while (startPos < length()) { + bp = startPos; + sp = searchString; + for (;;) { + // we reached the end of the "needle", so we found the string! + if (!*sp) { + *foundPos = startPos; + return 1; + } + int l; + unsigned int b = char_at(bp); + unsigned int s = fl_utf8decode(sp, 0, &l); + if (fl_tolower(b)!=fl_tolower(s)) + break; + sp += l; + bp = next_char(bp); + } + startPos = next_char(startPos); + } + } + return 0; +} + +int Fl_Text_Buffer_mod::search_backward(int startPos, const char *searchString, + int *foundPos, int matchCase) const +{ + IS_UTF8_ALIGNED2(this, (startPos)) + IS_UTF8_ALIGNED(searchString) + + if (!searchString) + return 0; + int bp; + const char *sp; + if (matchCase) { + while (startPos >= 0) { + bp = startPos; + sp = searchString; + for (;;) { + char c = *sp; + // we reached the end of the "needle", so we found the string! + if (!c) { + *foundPos = startPos; + return 1; + } + int l = fl_utf8len1(c); + if (memcmp(sp, address(bp), l)) + break; + sp += l; bp += l; + } + startPos = prev_char(startPos); + } + } else { + while (startPos >= 0) { + bp = startPos; + sp = searchString; + for (;;) { + // we reached the end of the "needle", so we found the string! + if (!*sp) { + *foundPos = startPos; + return 1; + } + int l; + unsigned int b = char_at(bp); + unsigned int s = fl_utf8decode(sp, 0, &l); + if (fl_tolower(b)!=fl_tolower(s)) + break; + sp += l; + bp = next_char(bp); + } + startPos = prev_char(startPos); + } + } + return 0; +} + + + +/* + Insert a string into the buffer. + Pos must be at a character boundary. Text must be a correct UTF-8 string. + */ +int Fl_Text_Buffer_mod::insert_(int pos, const char *text) +{ + if (!text || !*text) + return 0; + + int insertedLength = strlen(text); + + /* Prepare the buffer to receive the new text. If the new text fits in + the current buffer, just move the gap (if necessary) to where + the text should be inserted. If the new text is too large, reallocate + the buffer with a gap large enough to accomodate the new text and a + gap of mPreferredGapSize */ + if (insertedLength > mGapEnd - mGapStart) + reallocate_with_gap(pos, insertedLength + mPreferredGapSize); + else if (pos != mGapStart) + move_gap(pos); + + /* Insert the new text (pos now corresponds to the start of the gap) */ + memcpy(&mBuf[pos], text, insertedLength); + mGapStart += insertedLength; + mLength += insertedLength; + update_selections(pos, 0, insertedLength); + + if (mCanUndo) { + if (undowidget == this && undoat == pos && undoinsert) { + undoinsert += insertedLength; + } else { + undoinsert = insertedLength; + undoyankcut = (undoat == pos) ? undocut : 0; + } + undoat = pos + insertedLength; + undocut = 0; + undowidget = this; + } + + return insertedLength; +} + + +/* + Remove a string from the buffer. + Unicode safe. Start and end must be at a character boundary. + */ +void Fl_Text_Buffer_mod::remove_(int start, int end) +{ + /* if the gap is not contiguous to the area to remove, move it there */ + + if (mCanUndo) { + if (undowidget == this && undoat == end && undocut) { + undobuffersize(undocut + end - start + 1); + memmove(undobuffer + end - start, undobuffer, undocut); + undocut += end - start; + } else { + undocut = end - start; + undobuffersize(undocut); + } + undoat = start; + undoinsert = 0; + undoyankcut = 0; + undowidget = this; + } + + if (start > mGapStart) { + if (mCanUndo) + memcpy(undobuffer, mBuf + (mGapEnd - mGapStart) + start, + end - start); + move_gap(start); + } else if (end < mGapStart) { + if (mCanUndo) + memcpy(undobuffer, mBuf + start, end - start); + move_gap(end); + } else { + int prelen = mGapStart - start; + if (mCanUndo) { + memcpy(undobuffer, mBuf + start, prelen); + memcpy(undobuffer + prelen, mBuf + mGapEnd, end - start - prelen); + } + } + + /* expand the gap to encompass the deleted characters */ + mGapEnd += end - mGapStart; + mGapStart -= mGapStart - start; + + /* update the length */ + mLength -= end - start; + + /* fix up any selections which might be affected by the change */ + update_selections(start, end - start, 0); +} + + +/* + simple setter. + Unicode safe. Start and end must be at a character boundary. + */ +void Fl_Text_Selection_mod::set(int startpos, int endpos) +{ + mSelected = startpos != endpos; + mStart = min(startpos, endpos); + mEnd = max(startpos, endpos); +} + + +/* + simple getter. + Unicode safe. Start and end will be at a character boundary. + */ +int Fl_Text_Selection_mod::position(int *startpos, int *endpos) const { + if (!mSelected) + return 0; + *startpos = mStart; + *endpos = mEnd; + + return 1; +} + + +/* + Return if a position is inside the selected area. + Unicode safe. Pos must be at a character boundary. + */ +int Fl_Text_Selection_mod::includes(int pos) const { + return (selected() && pos >= start() && pos < end() ); +} + + +/* + Return a duplicate of the selected text, or an empty string. + Unicode safe. + */ +char *Fl_Text_Buffer_mod::selection_text_(Fl_Text_Selection_mod * sel) const { + int start, end; + + /* If there's no selection, return an allocated empty string */ + if (!sel->position(&start, &end)) + { + char *s = (char *) malloc(1); + *s = '\0'; + return s; + } + + /* Return the selected range */ + return text_range(start, end); +} + + +/* + Remove the selected text. + Unicode safe. + */ +void Fl_Text_Buffer_mod::remove_selection_(Fl_Text_Selection_mod * sel) +{ + int start, end; + + if (!sel->position(&start, &end)) + return; + remove(start, end); + //undoyankcut = undocut; +} + + +/* + Replace selection with text. + Unicode safe. + */ +void Fl_Text_Buffer_mod::replace_selection_(Fl_Text_Selection_mod * sel, + const char *text) +{ + Fl_Text_Selection_mod oldSelection = *sel; + + /* If there's no selection, return */ + int start, end; + if (!sel->position(&start, &end)) + return; + + /* Do the appropriate type of replace */ + replace(start, end, text); + + /* Unselect (happens automatically in BufReplace, but BufReplaceRect + can't detect when the contents of a selection goes away) */ + sel->mSelected = 0; + redisplay_selection(&oldSelection, sel); +} + + +/* + Call all callbacks. + Unicode safe. + */ +void Fl_Text_Buffer_mod::call_modify_callbacks(int pos, int nDeleted, + int nInserted, int nRestyled, + const char *deletedText) const { + IS_UTF8_ALIGNED2(this, pos) + for (int i = 0; i < mNModifyProcs; i++) + (*mModifyProcs[i]) (pos, nInserted, nDeleted, nRestyled, + deletedText, mCbArgs[i]); +} + + +/* + Call all callbacks. + Unicode safe. + */ +void Fl_Text_Buffer_mod::call_predelete_callbacks(int pos, int nDeleted) const { + for (int i = 0; i < mNPredeleteProcs; i++) + (*mPredeleteProcs[i]) (pos, nDeleted, mPredeleteCbArgs[i]); +} + + +/* + Redisplay a new selected area. + Unicode safe. + */ +void Fl_Text_Buffer_mod::redisplay_selection(Fl_Text_Selection_mod * + oldSelection, + Fl_Text_Selection_mod * + newSelection) const +{ + int oldStart, oldEnd, newStart, newEnd, ch1Start, ch1End, ch2Start, + ch2End; + + /* If either selection is rectangular, add an additional character to + the end of the selection to request the redraw routines to wipe out + the parts of the selection beyond the end of the line */ + oldStart = oldSelection->mStart; + newStart = newSelection->mStart; + oldEnd = oldSelection->mEnd; + newEnd = newSelection->mEnd; + + /* If the old or new selection is unselected, just redisplay the + single area that is (was) selected and return */ + if (!oldSelection->mSelected && !newSelection->mSelected) + return; + if (!oldSelection->mSelected) + { + call_modify_callbacks(newStart, 0, 0, newEnd - newStart, NULL); + return; + } + if (!newSelection->mSelected) { + call_modify_callbacks(oldStart, 0, 0, oldEnd - oldStart, NULL); + return; + } + + /* If the selections are non-contiguous, do two separate updates + and return */ + if (oldEnd < newStart || newEnd < oldStart) { + call_modify_callbacks(oldStart, 0, 0, oldEnd - oldStart, NULL); + call_modify_callbacks(newStart, 0, 0, newEnd - newStart, NULL); + return; + } + + /* Otherwise, separate into 3 separate regions: ch1, and ch2 (the two + changed areas), and the unchanged area of their intersection, + and update only the changed area(s) */ + ch1Start = min(oldStart, newStart); + ch2End = max(oldEnd, newEnd); + ch1End = max(oldStart, newStart); + ch2Start = min(oldEnd, newEnd); + if (ch1Start != ch1End) + call_modify_callbacks(ch1Start, 0, 0, ch1End - ch1Start, NULL); + if (ch2Start != ch2End) + call_modify_callbacks(ch2Start, 0, 0, ch2End - ch2Start, NULL); +} + + +/* + Move the gap around without changing buffer content. + Unicode safe. Pos must be at a character boundary. + */ +void Fl_Text_Buffer_mod::move_gap(int pos) +{ + int gapLen = mGapEnd - mGapStart; + + if (pos > mGapStart) + memmove(&mBuf[mGapStart], &mBuf[mGapEnd], pos - mGapStart); + else + memmove(&mBuf[pos + gapLen], &mBuf[pos], mGapStart - pos); + mGapEnd += pos - mGapStart; + mGapStart += pos - mGapStart; +} + + +/* + Create a larger gap. + Unicode safe. Start must be at a character boundary. + */ +void Fl_Text_Buffer_mod::reallocate_with_gap(int newGapStart, int newGapLen) +{ + char *newBuf = (char *) malloc(mLength + newGapLen); + int newGapEnd = newGapStart + newGapLen; + + if (newGapStart <= mGapStart) { + memcpy(newBuf, mBuf, newGapStart); + memcpy(&newBuf[newGapEnd], &mBuf[newGapStart], + mGapStart - newGapStart); + memcpy(&newBuf[newGapEnd + mGapStart - newGapStart], + &mBuf[mGapEnd], mLength - mGapStart); + } else { /* newGapStart > mGapStart */ + memcpy(newBuf, mBuf, mGapStart); + memcpy(&newBuf[mGapStart], &mBuf[mGapEnd], newGapStart - mGapStart); + memcpy(&newBuf[newGapEnd], + &mBuf[mGapEnd + newGapStart - mGapStart], + mLength - newGapStart); + } + free((void *) mBuf); + mBuf = newBuf; + mGapStart = newGapStart; + mGapEnd = newGapEnd; +} + + +/* + Update selection range if characters were inserted. + Unicode safe. Pos must be at a character boundary. + */ +void Fl_Text_Buffer_mod::update_selections(int pos, int nDeleted, + int nInserted) +{ + mPrimary.update(pos, nDeleted, nInserted); + mSecondary.update(pos, nDeleted, nInserted); + mHighlight.update(pos, nDeleted, nInserted); +} + + +// unicode safe, assuming the arguments are on character boundaries +void Fl_Text_Selection_mod::update(int pos, int nDeleted, int nInserted) +{ + if (!mSelected || pos > mEnd) + return; + if (pos + nDeleted <= mStart) { + mStart += nInserted - nDeleted; + mEnd += nInserted - nDeleted; + } else if (pos <= mStart && pos + nDeleted >= mEnd) { + mStart = pos; + mEnd = pos; + mSelected = 0; + } else if (pos <= mStart && pos + nDeleted < mEnd) { + mStart = pos; + mEnd = nInserted + mEnd - nDeleted; + } else if (pos < mEnd) { + mEnd += nInserted - nDeleted; + if (mEnd <= mStart) + mSelected = 0; + } +} + + +/* + Find a UCS-4 character. + StartPos must be at a character boundary, searchChar is UCS-4 encoded. + */ +int Fl_Text_Buffer_mod::findchar_forward(int startPos, unsigned searchChar, + int *foundPos) const +{ + if (startPos >= mLength) { + *foundPos = mLength; + return 0; + } + + if (startPos<0) + startPos = 0; + + for ( ; startPos mLength) + startPos = mLength; + + for (startPos = prev_char(startPos); startPos>=0; startPos = prev_char(startPos)) { + if (searchChar == char_at(startPos)) { + *foundPos = startPos; + return 1; + } + } + + *foundPos = 0; + return 0; +} + +//#define EXAMPLE_ENCODING // shows how to process any encoding for which a decoding function exists +#ifdef EXAMPLE_ENCODING + +// returns the UCS equivalent of *p in CP1252 and advances p by 1 +unsigned cp1252toucs(char* &p) +{ + // Codes 0x80..0x9f from the Microsoft CP1252 character set, translated + // to Unicode + static unsigned cp1252[32] = { + 0x20ac, 0x0081, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021, + 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008d, 0x017d, 0x008f, + 0x0090, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, + 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x009d, 0x017e, 0x0178 + }; + unsigned char uc = *(unsigned char*)p; + p++; + return (uc < 0x80 || uc >= 0xa0 ? uc : cp1252[uc - 0x80]); +} + +// returns the UCS equivalent of *p in UTF-16 and advances p by 2 (or more for surrogates) +unsigned utf16toucs(char* &p) +{ + union { +#if WORDS_BIGENDIAN + struct { unsigned char a, b;} chars; +#else + struct { unsigned char b, a;} chars; +#endif + U16 short_val; + } u; + u.chars.a = *(unsigned char*)p++; + u.chars.b = *(unsigned char*)p++; + return u.short_val; +} + +// filter that produces, from an input stream fed by reading from fp, +// a UTF-8-encoded output stream written in buffer. +// Input can be any (e.g., 8-bit, UTF-16) encoding. +// Output is true UTF-8. +// p_trf points to a function that transforms encoded byte(s) into one UCS +// and that increases the pointer by the adequate quantity +static int general_input_filter(char *buffer, int buflen, + char *line, int sline, char* &endline, + unsigned (*p_trf)(char* &), + FILE *fp) +{ + char *p, *q, multibyte[5]; + int lq, r, offset; + p = endline = line; + q = buffer; + while (q < buffer + buflen) { + if (p >= endline) { + r = fread(line, 1, sline, fp); + endline = line + r; + if (r == 0) return q - buffer; + p = line; + } + if (q + 4 /*max width of utf-8 char*/ > buffer + buflen) { + memmove(line, p, endline - p); + endline -= (p - line); + return q - buffer; + } + lq = fl_utf8encode( p_trf(p), multibyte ); + memcpy(q, multibyte, lq); + q += lq; + } + memmove(line, p, endline - p); + endline -= (p - line); + return q - buffer; +} +#endif // EXAMPLE_ENCODING + +/* + filter that produces, from an input stream fed by reading from fp, + a UTF-8-encoded output stream written in buffer. + Input can be UTF-8. If it is not, it is decoded with CP1252. + Output is UTF-8. + *input_was_changed is set to true if the input was not strict UTF-8 so output + differs from input. + */ +static int utf8_input_filter(char *buffer, int buflen, char *line, int sline, char* &endline, + FILE *fp, int *input_was_changed) +{ + char *p, *q, multibyte[5]; + int l, lp, lq, r; + unsigned u; + p = endline = line; + q = buffer; + while (q < buffer + buflen) { + if (p >= endline) { + r = fread(line, 1, sline, fp); + endline = line + r; + if (r == 0) return q - buffer; + p = line; + } + l = fl_utf8len1(*p); + if (p + l > endline) { + memmove(line, p, endline - p); + endline -= (p - line); + r = fread(endline, 1, sline - (endline - line), fp); + endline += r; + p = line; + if (endline - line < l) break; + } + while ( l > 0) { + u = fl_utf8decode(p, p+l, &lp); + lq = fl_utf8encode(u, multibyte); + if (lp != l || lq != l) *input_was_changed = true; + if (q + lq > buffer + buflen) { + memmove(line, p, endline - p); + endline -= (p - line); + return q - buffer; + } + memcpy(q, multibyte, lq); + q += lq; + p += lp; + l -= lp; + } + } + memmove(line, p, endline - p); + endline -= (p - line); + return q - buffer; +} + +const char *Fl_Text_Buffer_mod::file_encoding_warning_message = +"Displayed text contains the UTF-8 transcoding\n" +"of the input file which was not UTF-8 encoded.\n" +"Some changes may have occurred."; + +/* + Insert text from a file. + Input file can be of various encodings according to what input fiter is used. + utf8_input_filter accepts UTF-8 or CP1252 as input encoding. + Output is always UTF-8. + */ +int Fl_Text_Buffer_mod::insertfile(const char *file, int pos, int buflen) +{ + FILE *fp; + if (!(fp = fl_fopen(file, "r"))) + return 1; + char *buffer = new char[buflen + 1]; + char *endline, line[100]; + int l; + input_file_was_transcoded = false; + endline = line; + while (true) { +#ifdef EXAMPLE_ENCODING + // example of 16-bit encoding: UTF-16 + l = general_input_filter(buffer, buflen, + line, sizeof(line), endline, + utf16toucs, // use cp1252toucs to read CP1252-encoded files + fp); + input_file_was_transcoded = true; +#else + l = utf8_input_filter(buffer, buflen, line, sizeof(line), endline, + fp, &input_file_was_transcoded); +#endif + if (l == 0) break; + buffer[l] = 0; + insert(pos, buffer); + pos += l; + } + int e = ferror(fp) ? 2 : 0; + fclose(fp); + delete[]buffer; + if ( (!e) && input_file_was_transcoded && transcoding_warning_action) { + transcoding_warning_action(this); + } + return e; +} + + +/* + Write text to file. + Unicode safe. + */ +int Fl_Text_Buffer_mod::outputfile(const char *file, + int start, int end, + int buflen) { + FILE *fp; + if (!(fp = fl_fopen(file, "w"))) + return 1; + for (int n; (n = min(end - start, buflen)); start += n) { + const char *p = text_range(start, start + n); + int r = fwrite(p, 1, n, fp); + free((void *) p); + if (r != n) + break; + } + + int e = ferror(fp) ? 2 : 0; + fclose(fp); + return e; +} + + +/* + Return the previous character position. + Unicode safe. + */ +int Fl_Text_Buffer_mod::prev_char_clipped(int pos) const +{ + if (pos<=0) + return 0; + + IS_UTF8_ALIGNED2(this, (pos)) + + char c; + do { + pos--; + if (pos==0) + return 0; + c = byte_at(pos); + } while ( (c&0xc0) == 0x80); + + IS_UTF8_ALIGNED2(this, (pos)) + return pos; +} + + +/* + Return the previous character position. + Returns -1 if the beginning of the buffer is reached. + */ +int Fl_Text_Buffer_mod::prev_char(int pos) const +{ + if (pos==0) return -1; + return prev_char_clipped(pos); +} + + +/* + Return the next character position. + Returns length() if the end of the buffer is reached. + */ +int Fl_Text_Buffer_mod::next_char(int pos) const +{ + IS_UTF8_ALIGNED2(this, (pos)) + int n = fl_utf8len1(byte_at(pos)); + pos += n; + if (pos>=mLength) + return mLength; + IS_UTF8_ALIGNED2(this, (pos)) + return pos; +} + + +/* + Return the next character position. + If the end of the buffer is reached, it returns the current position. + */ +int Fl_Text_Buffer_mod::next_char_clipped(int pos) const +{ + return next_char(pos); +} + +/* + Align an index to the current UTF-8 boundary. + */ +int Fl_Text_Buffer_mod::utf8_align(int pos) const +{ + char c = byte_at(pos); + while ( (c&0xc0) == 0x80) { + pos--; + c = byte_at(pos); + } + return pos; +} + +// +// End of "$Id: Fl_Text_Buffer_mod.cxx 8040 2010-12-15 17:38:39Z manolo $". +// diff --git a/src/widgets/Fl_Text_Buffer_mod_1_1.cxx b/src/widgets/Fl_Text_Buffer_mod_1_1.cxx deleted file mode 100644 index 4fc7f68..0000000 --- a/src/widgets/Fl_Text_Buffer_mod_1_1.cxx +++ /dev/null @@ -1,2456 +0,0 @@ -// "$Id: Fl_Text_Buffer.cxx 6011 2008-01-04 20:32:37Z matt $" -// -// Copyright 2001-2005 by Bill Spitzak and others. -// Original code Copyright Mark Edel. Permission to distribute under -// the LGPL for the FLTK library granted by Mark Edel. -// -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ -// -// This file is part of flmsg -// -// flrig 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. -// -// flrig 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 -#include -#include "missing_strings.h" -#include -#include -#include "Fl_Text_Buffer_mod.H" - - -#define PREFERRED_GAP_SIZE 1024 -/* Initial size for the buffer gap (empty space -in the buffer where text might be inserted -if the user is typing sequential chars ) */ - -static void histogramCharacters( const char *string, int length, char hist[ 256 ], - int init ); -static void subsChars( char *string, int length, char fromChar, char toChar ); -static char chooseNullSubsChar( char hist[ 256 ] ); -static void insertColInLine( const char *line, char *insLine, int column, int insWidth, - int tabDist, int useTabs, char nullSubsChar, char *outStr, int *outLen, - int *endOffset ); -static void deleteRectFromLine( const char *line, int rectStart, int rectEnd, - int tabDist, int useTabs, char nullSubsChar, char *outStr, int *outLen, - int *endOffset ); -static void overlayRectInLine( const char *line, char *insLine, int rectStart, - int rectEnd, int tabDist, int useTabs, char nullSubsChar, char *outStr, - int *outLen, int *endOffset ); - -static void addPadding( char *string, int startIndent, int toIndent, - int tabDist, int useTabs, char nullSubsChar, int *charsAdded ); -static char *copyLine( const char* text, int *lineLen ); -static int countLines( const char *string ); -static int textWidth( const char *text, int tabDist, char nullSubsChar ); -static char *realignTabs( const char *text, int origIndent, int newIndent, - int tabDist, int useTabs, char nullSubsChar, int *newLength ); -static char *expandTabs( const char *text, int startIndent, int tabDist, - char nullSubsChar, int *newLen ); -static char *unexpandTabs( char *text, int startIndent, int tabDist, - char nullSubsChar, int *newLen ); -static int max( int i1, int i2 ); -static int min( int i1, int i2 ); - -static const char *ControlCodeTable[ 32 ] = { - "nul", "soh", "stx", "etx", "eot", "enq", "ack", "bel", - "bs", "ht", "nl", "vt", "np", "cr", "so", "si", - "dle", "dc1", "dc2", "dc3", "dc4", "nak", "syn", "etb", - "can", "em", "sub", "esc", "fs", "gs", "rs", "us"}; - -static char* undobuffer; -static int undobufferlength; -static Fl_Text_Buffer_mod* undowidget; -static int undoat; // points after insertion -static int undocut; // number of characters deleted there -static int undoinsert; // number of characters inserted -static int undoyankcut; // length of valid contents of buffer, even if undocut=0 - -static void undobuffersize(int n) { - if (n > undobufferlength) { - if (undobuffer) { - do {undobufferlength *= 2;} while (undobufferlength < n); - undobuffer = (char*)realloc(undobuffer, undobufferlength); - } else { - undobufferlength = n+9; - undobuffer = (char*)malloc(undobufferlength); - } - } -} - -/* -** Create an empty text buffer of a pre-determined size (use this to -** avoid unnecessary re-allocation if you know exactly how much the buffer -** will need to hold -*/ -Fl_Text_Buffer_mod::Fl_Text_Buffer_mod( int requestedSize ) { - mLength = 0; - mBuf = (char *)malloc( requestedSize + PREFERRED_GAP_SIZE ); - mGapStart = 0; - mGapEnd = PREFERRED_GAP_SIZE; - mTabDist = 8; - mUseTabs = 1; - mPrimary.mSelected = 0; - mPrimary.mRectangular = 0; - mPrimary.mStart = mPrimary.mEnd = 0; - mSecondary.mSelected = 0; - mSecondary.mStart = mSecondary.mEnd = 0; - mSecondary.mRectangular = 0; - mHighlight.mSelected = 0; - mHighlight.mStart = mHighlight.mEnd = 0; - mHighlight.mRectangular = 0; - mNodifyProcs = NULL; - mCbArgs = NULL; - mNModifyProcs = 0; - mNPredeleteProcs = 0; - mPredeleteProcs = NULL; - mPredeleteCbArgs = NULL; - mCursorPosHint = 0; - mNullSubsChar = '\0'; - mCanUndo = 1; -#ifdef PURIFY -{ int i; for (i = mGapStart; i < mGapEnd; i++) mBuf[ i ] = '.'; } -#endif -} - -/* -** Free a text buffer -*/ -Fl_Text_Buffer_mod::~Fl_Text_Buffer_mod() { - free( mBuf ); - if ( mNModifyProcs != 0 ) { - delete[] mNodifyProcs; - delete[] mCbArgs; - } - if ( mNPredeleteProcs != 0 ) { - delete[] mPredeleteProcs; - delete[] mPredeleteCbArgs; - } -} - -/* -** Get the entire contents of a text buffer. Memory is allocated to contain -** the returned std::string, which the caller must free. -*/ -char * Fl_Text_Buffer_mod::text() { - char *t; - - t = (char *)malloc( mLength + 1 ); - memcpy( t, mBuf, mGapStart ); - memcpy( &t[ mGapStart ], &mBuf[ mGapEnd ], - mLength - mGapStart ); - t[ mLength ] = '\0'; - return t; -} - -/* -** Replace the entire contents of the text buffer -*/ -void Fl_Text_Buffer_mod::text( const char *t ) { - int insertedLength, deletedLength; - const char *deletedText; - - call_predelete_callbacks(0, length()); - - /* Save information for redisplay, and get rid of the old buffer */ - deletedText = text(); - deletedLength = mLength; - free( (void *)mBuf ); - - /* Start a new buffer with a gap of PREFERRED_GAP_SIZE in the center */ - insertedLength = strlen( t ); - mBuf = (char *)malloc( insertedLength + PREFERRED_GAP_SIZE ); - mLength = insertedLength; - mGapStart = insertedLength / 2; - mGapEnd = mGapStart + PREFERRED_GAP_SIZE; - memcpy( mBuf, t, mGapStart ); - memcpy( &mBuf[ mGapEnd ], &t[ mGapStart ], insertedLength - mGapStart ); -#ifdef PURIFY -{ int i; for ( i = mGapStart; i < mGapEnd; i++ ) mBuf[ i ] = '.'; } -#endif - - /* Zero all of the existing selections */ - update_selections( 0, deletedLength, 0 ); - - /* Call the saved display routine(s) to update the screen */ - call_modify_callbacks( 0, deletedLength, insertedLength, 0, deletedText ); - free( (void *)deletedText ); -} - -/* -** Return a copy of the text between "start" and "end" character positions -** from text buffer "buf". Positions start at 0, and the range does not -** include the character pointed to by "end" -*/ -char * Fl_Text_Buffer_mod::text_range( int start, int end ) { - char * s; - int copiedLength, part1Length; - - /* Make sure start and end are ok, and allocate memory for returned std::string. - If start is bad, return "", if end is bad, adjust it. */ - if ( start < 0 || start > mLength ) { - s = (char *)malloc( 1 ); - s[ 0 ] = '\0'; - return s; - } - if ( end < start ) { - int temp = start; - start = end; - end = temp; - } - if ( end > mLength ) - end = mLength; - copiedLength = end - start; - s = (char *)malloc( copiedLength + 1 ); - - /* Copy the text from the buffer to the returned std::string */ - if ( end <= mGapStart ) { - memcpy( s, &mBuf[ start ], copiedLength ); - } else if ( start >= mGapStart ) { - memcpy( s, &mBuf[ start + ( mGapEnd - mGapStart ) ], copiedLength ); - } else { - part1Length = mGapStart - start; - memcpy( s, &mBuf[ start ], part1Length ); - memcpy( &s[ part1Length ], &mBuf[ mGapEnd ], copiedLength - part1Length ); - } - s[ copiedLength ] = '\0'; - return s; -} - -/* -** Return the character at buffer position "pos". Positions start at 0. -*/ -char Fl_Text_Buffer_mod::character( int pos ) { - if ( pos < 0 || pos >= mLength ) - return '\0'; - if ( pos < mGapStart ) - return mBuf[ pos ]; - else - return mBuf[ pos + mGapEnd - mGapStart ]; -} - -/* -** Insert null-terminated std::string "text" at position "pos" in "buf" -*/ -void Fl_Text_Buffer_mod::insert( int pos, const char *s ) { - int nInserted; - - /* if pos is not contiguous to existing text, make it */ - if ( pos > mLength ) pos = mLength; - if ( pos < 0 ) pos = 0; - - /* Even if nothing is deleted, we must call these callbacks */ - call_predelete_callbacks( pos, 0 ); - - /* insert and redisplay */ - nInserted = insert_( pos, s ); - mCursorPosHint = pos + nInserted; - call_modify_callbacks( pos, 0, nInserted, 0, NULL ); -} - -/* -** Delete the characters between "start" and "end", and insert the -** null-terminated std::string "text" in their place in in "buf" -*/ -void Fl_Text_Buffer_mod::replace( int start, int end, const char *s ) { - const char * deletedText; - int nInserted; - - // Range check... - if (!s) return; - if (start < 0) start = 0; - if (end < 0) end = 0; - if (end > mLength) end = mLength; - - call_predelete_callbacks( start, end-start ); - deletedText = text_range( start, end ); - remove_( start, end ); - //undoyankcut = undocut; - nInserted = insert_( start, s ); - mCursorPosHint = start + nInserted; - call_modify_callbacks( start, end - start, nInserted, 0, deletedText ); - free( (void *)deletedText ); -} - -void Fl_Text_Buffer_mod::remove( int start, int end ) { - const char * deletedText; - - /* Make sure the arguments make sense */ - if ( start > end ) { - int temp = start; - start = end; - end = temp; - } - if ( start > mLength ) start = mLength; - if ( start < 0 ) start = 0; - if ( end > mLength ) end = mLength; - if ( end < 0 ) end = 0; - - if (start == end) return; - - call_predelete_callbacks( start, end-start ); - /* Remove and redisplay */ - deletedText = text_range( start, end ); - remove_( start, end ); - mCursorPosHint = start; - call_modify_callbacks( start, end - start, 0, 0, deletedText ); - free( (void *)deletedText ); -} - -void Fl_Text_Buffer_mod::copy( Fl_Text_Buffer_mod *fromBuf, int fromStart, - int fromEnd, int toPos ) { - int copiedLength = fromEnd - fromStart; - int part1Length; - - /* Prepare the buffer to receive the new text. If the new text fits in - the current buffer, just move the gap (if necessary) to where - the text should be inserted. If the new text is too large, reallocate - the buffer with a gap large enough to accomodate the new text and a - gap of PREFERRED_GAP_SIZE */ - if ( copiedLength > mGapEnd - mGapStart ) - reallocate_with_gap( toPos, copiedLength + PREFERRED_GAP_SIZE ); - else if ( toPos != mGapStart ) - move_gap( toPos ); - - /* Insert the new text (toPos now corresponds to the start of the gap) */ - if ( fromEnd <= fromBuf->mGapStart ) { - memcpy( &mBuf[ toPos ], &fromBuf->mBuf[ fromStart ], copiedLength ); - } else if ( fromStart >= fromBuf->mGapStart ) { - memcpy( &mBuf[ toPos ], - &fromBuf->mBuf[ fromStart + ( fromBuf->mGapEnd - fromBuf->mGapStart ) ], - copiedLength ); - } else { - part1Length = fromBuf->mGapStart - fromStart; - memcpy( &mBuf[ toPos ], &fromBuf->mBuf[ fromStart ], part1Length ); - memcpy( &mBuf[ toPos + part1Length ], &fromBuf->mBuf[ fromBuf->mGapEnd ], - copiedLength - part1Length ); - } - mGapStart += copiedLength; - mLength += copiedLength; - update_selections( toPos, 0, copiedLength ); -} - -/* -** remove text according to the undo variables or insert text -** from the undo buffer -*/ -int Fl_Text_Buffer_mod::undo(int *cursorPos) { - if (undowidget != this || (!undocut && !undoinsert && !mCanUndo)) return 0; - - int ilen = undocut; - int xlen = undoinsert; - int b = undoat-xlen; - - if (xlen && undoyankcut && !ilen) { - ilen = undoyankcut; - } - - if (xlen && ilen) { - undobuffersize(ilen+1); - undobuffer[ilen] = 0; - char *tmp = strdup(undobuffer); - replace(b, undoat, tmp); - if (cursorPos) *cursorPos = mCursorPosHint; - free(tmp); - } - else if (xlen) { - remove(b, undoat); - if (cursorPos) *cursorPos = mCursorPosHint; - } - else if (ilen) { - undobuffersize(ilen+1); - undobuffer[ilen] = 0; - insert(undoat, undobuffer); - if (cursorPos) *cursorPos = mCursorPosHint; - undoyankcut = 0; - } - - return 1; -} - -/* -** let the undo system know if we can undo changes -*/ -void Fl_Text_Buffer_mod::canUndo(char flag) { - mCanUndo = flag; -} - -/* -** Insert "text" columnwise into buffer starting at displayed character -** position "column" on the line beginning at "startPos". Opens a rectangular -** space the width and height of "text", by moving all text to the right of -** "column" right. If charsInserted and charsDeleted are not NULL, the -** number of characters inserted and deleted in the operation (beginning -** at startPos) are returned in these arguments -*/ -void Fl_Text_Buffer_mod::insert_column( int column, int startPos, const char *s, - int *charsInserted, int *charsDeleted ) { - int nLines, lineStartPos, nDeleted, insertDeleted, nInserted; - const char *deletedText; - - nLines = countLines( s ); - lineStartPos = line_start( startPos ); - nDeleted = line_end( skip_lines( startPos, nLines ) ) - - lineStartPos; - call_predelete_callbacks( lineStartPos, nDeleted ); - deletedText = text_range( lineStartPos, lineStartPos + nDeleted ); - insert_column_( column, lineStartPos, s, &insertDeleted, &nInserted, - &mCursorPosHint ); - if ( nDeleted != insertDeleted ) - Fl::error("Fl_Text_Buffer_mod::insert_column(): internal consistency check ins1 failed"); - call_modify_callbacks( lineStartPos, nDeleted, nInserted, 0, deletedText ); - free( (void *) deletedText ); - if ( charsInserted != NULL ) - * charsInserted = nInserted; - if ( charsDeleted != NULL ) - * charsDeleted = nDeleted; -} - -/* -** Overlay "text" between displayed character positions "rectStart" and -** "rectEnd" on the line beginning at "startPos". If charsInserted and -** charsDeleted are not NULL, the number of characters inserted and deleted -** in the operation (beginning at startPos) are returned in these arguments. -*/ -void Fl_Text_Buffer_mod::overlay_rectangular( int startPos, int rectStart, - int rectEnd, const char *s, int *charsInserted, int *charsDeleted ) { - int nLines, lineStartPos, nDeleted, insertDeleted, nInserted; - const char *deletedText; - - nLines = countLines( s ); - lineStartPos = line_start( startPos ); - nDeleted = line_end( skip_lines( startPos, nLines ) ) - - lineStartPos; - call_predelete_callbacks( lineStartPos, nDeleted ); - deletedText = text_range( lineStartPos, lineStartPos + nDeleted ); - overlay_rectangular_( lineStartPos, rectStart, rectEnd, s, &insertDeleted, - &nInserted, &mCursorPosHint ); - if ( nDeleted != insertDeleted ) - Fl::error("Fl_Text_Buffer_mod::overlay_rectangle(): internal consistency check ovly1 failed"); - call_modify_callbacks( lineStartPos, nDeleted, nInserted, 0, deletedText ); - free( (void *) deletedText ); - if ( charsInserted != NULL ) - * charsInserted = nInserted; - if ( charsDeleted != NULL ) - * charsDeleted = nDeleted; -} - -/* -** Replace a rectangular area in buf, given by "start", "end", "rectStart", -** and "rectEnd", with "text". If "text" is vertically longer than the -** rectangle, add extra lines to make room for it. -*/ -void Fl_Text_Buffer_mod::replace_rectangular( int start, int end, int rectStart, - int rectEnd, const char *s ) { - char *insPtr; - const char *deletedText; - char *insText = (char *)""; - int i, nInsertedLines, nDeletedLines, insLen, hint; - int insertDeleted, insertInserted, deleteInserted; - int linesPadded = 0; - - /* Make sure start and end refer to complete lines, since the - columnar delete and insert operations will replace whole lines */ - start = line_start( start ); - end = line_end( end ); - - call_predelete_callbacks( start, end-start ); - - /* If more lines will be deleted than inserted, pad the inserted text - with newlines to make it as long as the number of deleted lines. This - will indent all of the text to the right of the rectangle to the same - column. If more lines will be inserted than deleted, insert extra - lines in the buffer at the end of the rectangle to make room for the - additional lines in "text" */ - nInsertedLines = countLines( s ); - nDeletedLines = count_lines( start, end ); - if ( nInsertedLines < nDeletedLines ) { - insLen = strlen( s ); - insText = (char *)malloc( insLen + nDeletedLines - nInsertedLines + 1 ); - strcpy( insText, s ); - insPtr = insText + insLen; - for ( i = 0; i < nDeletedLines - nInsertedLines; i++ ) - *insPtr++ = '\n'; - *insPtr = '\0'; - } else if ( nDeletedLines < nInsertedLines ) { - linesPadded = nInsertedLines - nDeletedLines; - for ( i = 0; i < linesPadded; i++ ) - insert_( end, "\n" ); - } /* else nDeletedLines == nInsertedLines; */ - - /* Save a copy of the text which will be modified for the modify CBs */ - deletedText = text_range( start, end ); - - /* Delete then insert */ - remove_rectangular_( start, end, rectStart, rectEnd, &deleteInserted, &hint ); - insert_column_( rectStart, start, insText, &insertDeleted, &insertInserted, - &mCursorPosHint ); - - /* Figure out how many chars were inserted and call modify callbacks */ - if ( insertDeleted != deleteInserted + linesPadded ) - Fl::error("Fl_Text_Buffer_mod::replace_rectangular(): internal consistency check repl1 failed"); - call_modify_callbacks( start, end - start, insertInserted, 0, deletedText ); - free( (void *) deletedText ); - if ( nInsertedLines < nDeletedLines ) - free( (void *) insText ); -} - -/* -** Remove a rectangular swath of characters between character positions start -** and end and horizontal displayed-character offsets rectStart and rectEnd. -*/ -void Fl_Text_Buffer_mod::remove_rectangular( int start, int end, int rectStart, - int rectEnd ) { - const char * deletedText; - int nInserted; - - start = line_start( start ); - end = line_end( end ); - call_predelete_callbacks( start, end-start ); - deletedText = text_range( start, end ); - remove_rectangular_( start, end, rectStart, rectEnd, &nInserted, - &mCursorPosHint ); - call_modify_callbacks( start, end - start, nInserted, 0, deletedText ); - free( (void *) deletedText ); -} - -/* -** Clear a rectangular "hole" out of the buffer between character positions -** start and end and horizontal displayed-character offsets rectStart and -** rectEnd. -*/ -void Fl_Text_Buffer_mod::clear_rectangular( int start, int end, int rectStart, - int rectEnd ) { - int i, nLines; - char *newlinestd::string; - - nLines = count_lines( start, end ); - newlinestd::string = (char *)malloc( nLines + 1 ); - for ( i = 0; i < nLines; i++ ) - newlinestd::string[ i ] = '\n'; - newlinestd::string[ i ] = '\0'; - overlay_rectangular( start, rectStart, rectEnd, newlinestd::string, - NULL, NULL ); - free( (void *) newlinestd::string ); -} - -char * Fl_Text_Buffer_mod::text_in_rectangle( int start, int end, - int rectStart, int rectEnd ) { - int lineStart, selLeft, selRight, len; - char *textOut, *outPtr, *retabbedStr; - const char *textIn; - - start = line_start( start ); - end = line_end( end ); - textOut = (char *)malloc( ( end - start ) + 1 ); - lineStart = start; - outPtr = textOut; - while ( lineStart <= end ) { - rectangular_selection_boundaries( lineStart, rectStart, rectEnd, - &selLeft, &selRight ); - textIn = text_range( selLeft, selRight ); - len = selRight - selLeft; - memcpy( outPtr, textIn, len ); - free( (void *) textIn ); - outPtr += len; - lineStart = line_end( selRight ) + 1; - *outPtr++ = '\n'; - } - if ( outPtr != textOut ) - outPtr--; /* don't leave trailing newline */ - *outPtr = '\0'; - - /* If necessary, realign the tabs in the selection as if the text were - positioned at the left margin */ - retabbedStr = realignTabs( textOut, rectStart, 0, mTabDist, - mUseTabs, mNullSubsChar, &len ); - free( (void *) textOut ); - return retabbedStr; -} - -/* -** Set the hardware tab distance used by all displays for this buffer, -** and used in computing offsets for rectangular selection operations. -*/ -void Fl_Text_Buffer_mod::tab_distance( int tabDist ) { - const char * deletedText; - - /* First call the pre-delete callbacks with the previous tab setting - still active. */ - call_predelete_callbacks( 0, mLength ); - - /* Change the tab setting */ - mTabDist = tabDist; - - /* Force any display routines to redisplay everything (unfortunately, - this means copying the whole buffer contents to provide "deletedText" */ - deletedText = text(); - call_modify_callbacks( 0, mLength, mLength, 0, deletedText ); - free( (void *) deletedText ); -} - -void Fl_Text_Buffer_mod::select( int start, int end ) { - Fl_Text_Selection oldSelection = mPrimary; - - mPrimary.set( start, end ); - redisplay_selection( &oldSelection, &mPrimary ); -} - -void Fl_Text_Buffer_mod::unselect() { - Fl_Text_Selection oldSelection = mPrimary; - - mPrimary.mSelected = 0; - redisplay_selection( &oldSelection, &mPrimary ); -} - -void Fl_Text_Buffer_mod::select_rectangular( int start, int end, int rectStart, - int rectEnd ) { - Fl_Text_Selection oldSelection = mPrimary; - - mPrimary.set_rectangular( start, end, rectStart, rectEnd ); - redisplay_selection( &oldSelection, &mPrimary ); -} - -int Fl_Text_Buffer_mod::selection_position( int *start, int *end - ) { - return mPrimary.position( start, end ); -} - -int Fl_Text_Buffer_mod::selection_position( int *start, int *end, - int *isRect, int *rectStart, int *rectEnd ) { - return mPrimary.position( start, end, isRect, rectStart, - rectEnd ); -} - -char * Fl_Text_Buffer_mod::selection_text() { - return selection_text_( &mPrimary ); -} - -void Fl_Text_Buffer_mod::remove_selection() { - remove_selection_( &mPrimary ); -} - -void Fl_Text_Buffer_mod::replace_selection( const char *s ) { - replace_selection_( &mPrimary, s ); -} - -void Fl_Text_Buffer_mod::secondary_select( int start, int end ) { - Fl_Text_Selection oldSelection = mSecondary; - - mSecondary.set( start, end ); - redisplay_selection( &oldSelection, &mSecondary ); -} - -void Fl_Text_Buffer_mod::secondary_unselect() { - Fl_Text_Selection oldSelection = mSecondary; - - mSecondary.mSelected = 0; - redisplay_selection( &oldSelection, &mSecondary ); -} - -void Fl_Text_Buffer_mod::secondary_select_rectangular( int start, int end, - int rectStart, int rectEnd ) { - Fl_Text_Selection oldSelection = mSecondary; - - mSecondary.set_rectangular( start, end, rectStart, rectEnd ); - redisplay_selection( &oldSelection, &mSecondary ); -} - -int Fl_Text_Buffer_mod::secondary_selection_position( int *start, int *end - ) { - return mSecondary.position( start, end ); -} - -int Fl_Text_Buffer_mod::secondary_selection_position( int *start, int *end, - int *isRect, int *rectStart, int *rectEnd ) { - return mSecondary.position( start, end, isRect, rectStart, - rectEnd ); -} - -char * Fl_Text_Buffer_mod::secondary_selection_text() { - return selection_text_( &mSecondary ); -} - -void Fl_Text_Buffer_mod::remove_secondary_selection() { - remove_selection_( &mSecondary ); -} - -void Fl_Text_Buffer_mod::replace_secondary_selection( const char *s ) { - replace_selection_( &mSecondary, s ); -} - -void Fl_Text_Buffer_mod::highlight( int start, int end ) { - Fl_Text_Selection oldSelection = mHighlight; - - mHighlight.set( start, end ); - redisplay_selection( &oldSelection, &mHighlight ); -} - -void Fl_Text_Buffer_mod::unhighlight() { - Fl_Text_Selection oldSelection = mHighlight; - - mHighlight.mSelected = 0; - redisplay_selection( &oldSelection, &mHighlight ); -} - -void Fl_Text_Buffer_mod::highlight_rectangular( int start, int end, - int rectStart, int rectEnd ) { - Fl_Text_Selection oldSelection = mHighlight; - - mHighlight.set_rectangular( start, end, rectStart, rectEnd ); - redisplay_selection( &oldSelection, &mHighlight ); -} - -int Fl_Text_Buffer_mod::highlight_position( int *start, int *end - ) { - return mHighlight.position( start, end ); -} - -int Fl_Text_Buffer_mod::highlight_position( int *start, int *end, - int *isRect, int *rectStart, int *rectEnd ) { - return mHighlight.position( start, end, isRect, rectStart, - rectEnd ); -} - -char * Fl_Text_Buffer_mod::highlight_text() { - return selection_text_( &mHighlight ); -} - -/* -** Add a callback routine to be called when the buffer is modified -*/ -void Fl_Text_Buffer_mod::add_modify_callback( Fl_Text_Modify_Cb bufModifiedCB, - void *cbArg ) { - Fl_Text_Modify_Cb * newModifyProcs; - void **newCBArgs; - int i; - - newModifyProcs = new Fl_Text_Modify_Cb [ mNModifyProcs + 1 ]; - newCBArgs = new void * [ mNModifyProcs + 1 ]; - for ( i = 0; i < mNModifyProcs; i++ ) { - newModifyProcs[ i + 1 ] = mNodifyProcs[ i ]; - newCBArgs[ i + 1 ] = mCbArgs[ i ]; - } - if ( mNModifyProcs != 0 ) { - delete [] mNodifyProcs; - delete [] mCbArgs; - } - newModifyProcs[ 0 ] = bufModifiedCB; - newCBArgs[ 0 ] = cbArg; - mNModifyProcs++; - mNodifyProcs = newModifyProcs; - mCbArgs = newCBArgs; -} - -void Fl_Text_Buffer_mod::remove_modify_callback( Fl_Text_Modify_Cb bufModifiedCB, - void *cbArg ) { - int i, toRemove = -1; - Fl_Text_Modify_Cb *newModifyProcs; - void **newCBArgs; - - /* find the matching callback to remove */ - for ( i = 0; i < mNModifyProcs; i++ ) { - if ( mNodifyProcs[ i ] == bufModifiedCB && mCbArgs[ i ] == cbArg ) { - toRemove = i; - break; - } - } - if ( toRemove == -1 ) { - Fl::error("Fl_Text_Buffer_mod::remove_modify_callback(): Can't find modify CB to remove"); - return; - } - - /* Allocate new lists for remaining callback procs and args (if - any are left) */ - mNModifyProcs--; - if ( mNModifyProcs == 0 ) { - mNModifyProcs = 0; - delete[] mNodifyProcs; - mNodifyProcs = NULL; - delete[] mCbArgs; - mCbArgs = NULL; - return; - } - newModifyProcs = new Fl_Text_Modify_Cb [ mNModifyProcs ]; - newCBArgs = new void * [ mNModifyProcs ]; - - /* copy out the remaining members and free the old lists */ - for ( i = 0; i < toRemove; i++ ) { - newModifyProcs[ i ] = mNodifyProcs[ i ]; - newCBArgs[ i ] = mCbArgs[ i ]; - } - for ( ; i < mNModifyProcs; i++ ) { - newModifyProcs[ i ] = mNodifyProcs[ i + 1 ]; - newCBArgs[ i ] = mCbArgs[ i + 1 ]; - } - delete[] mNodifyProcs; - delete[] mCbArgs; - mNodifyProcs = newModifyProcs; - mCbArgs = newCBArgs; -} - -/* -** Add a callback routine to be called before text is deleted from the buffer. -*/ -void Fl_Text_Buffer_mod::add_predelete_callback(Fl_Text_Predelete_Cb bufPreDeleteCB, - void *cbArg) { - Fl_Text_Predelete_Cb *newPreDeleteProcs; - void **newCBArgs; - int i; - - newPreDeleteProcs = new Fl_Text_Predelete_Cb[ mNPredeleteProcs + 1 ]; - newCBArgs = new void * [ mNPredeleteProcs + 1 ]; - for ( i = 0; i < mNPredeleteProcs; i++ ) { - newPreDeleteProcs[i + 1] = mPredeleteProcs[i]; - newCBArgs[i + 1] = mPredeleteCbArgs[i]; - } - if (! mNPredeleteProcs != 0) { - delete [] mPredeleteProcs; - delete [] mPredeleteCbArgs; - } - newPreDeleteProcs[0] = bufPreDeleteCB; - newCBArgs[0] = cbArg; - mNPredeleteProcs++; - mPredeleteProcs = newPreDeleteProcs; - mPredeleteCbArgs = newCBArgs; -} - -void Fl_Text_Buffer_mod::remove_predelete_callback( - Fl_Text_Predelete_Cb bufPreDeleteCB, void *cbArg) { - int i, toRemove = -1; - Fl_Text_Predelete_Cb *newPreDeleteProcs; - void **newCBArgs; - - /* find the matching callback to remove */ - for ( i = 0; i < mNPredeleteProcs; i++) { - if (mPredeleteProcs[i] == bufPreDeleteCB && - mPredeleteCbArgs[i] == cbArg) { - toRemove = i; - break; - } - } - if (toRemove == -1) { - Fl::error("Fl_Text_Buffer_mod::remove_predelete_callback(): Can't find pre-delete CB to remove"); - return; - } - - /* Allocate new lists for remaining callback procs and args (if - any are left) */ - mNPredeleteProcs--; - if (mNPredeleteProcs == 0) { - mNPredeleteProcs = 0; - delete[] mPredeleteProcs; - mPredeleteProcs = NULL; - delete[] mPredeleteCbArgs; - mPredeleteCbArgs = NULL; - return; - } - newPreDeleteProcs = new Fl_Text_Predelete_Cb [ mNPredeleteProcs ]; - newCBArgs = new void * [ mNPredeleteProcs ]; - - /* copy out the remaining members and free the old lists */ - for ( i = 0; i < toRemove; i++) { - newPreDeleteProcs[i] = mPredeleteProcs[i]; - newCBArgs[i] = mPredeleteCbArgs[i]; - } - for ( ; i < mNPredeleteProcs; i++) { - newPreDeleteProcs[i] = mPredeleteProcs[i+1]; - newCBArgs[i] = mPredeleteCbArgs[i+1]; - } - delete[] mPredeleteProcs; - delete[] mPredeleteCbArgs; - mPredeleteProcs = newPreDeleteProcs; - mPredeleteCbArgs = newCBArgs; -} - -/* -** Return the text from the entire line containing position "pos" -*/ -char * Fl_Text_Buffer_mod::line_text( int pos ) { - return text_range( line_start( pos ), line_end( pos ) ); -} - -/* -** Find the position of the start of the line containing position "pos" -*/ -int Fl_Text_Buffer_mod::line_start( int pos ) { - if ( !findchar_backward( pos, '\n', &pos ) ) - return 0; - return pos + 1; -} - -/* -** Find the position of the end of the line containing position "pos" -** (which is either a pointer to the newline character ending the line, -** or a pointer to one character beyond the end of the buffer) -*/ -int Fl_Text_Buffer_mod::line_end( int pos ) { - if ( !findchar_forward( pos, '\n', &pos ) ) - pos = mLength; - return pos; -} - -int Fl_Text_Buffer_mod::word_start( int pos ) { - while ( pos && ( isalnum( character( pos ) ) || character( pos ) == '_' ) ) { - pos--; - } - if ( !( isalnum( character( pos ) ) || character( pos ) == '_' ) ) pos++; - return pos; -} - -int Fl_Text_Buffer_mod::word_end( int pos ) { - while (pos < length() && (isalnum(character(pos)) || character(pos) == '_' )) { - pos++; - } - return pos; -} - -/* -** Get a character from the text buffer expanded into it's screen -** representation (which may be several characters for a tab or a -** control code). Returns the number of characters written to "outStr". -** "indent" is the number of characters from the start of the line -** for figuring tabs. Output std::string is guranteed to be shorter or -** equal in length to FL_TEXT_MAX_EXP_CHAR_LEN -*/ -int Fl_Text_Buffer_mod::expand_character( int pos, int indent, char *outStr ) { - return expand_character( character( pos ), indent, outStr, - mTabDist, mNullSubsChar ); -} - -/* -** Expand a single character from the text buffer into it's screen -** representation (which may be several characters for a tab or a -** control code). Returns the number of characters added to "outStr". -** "indent" is the number of characters from the start of the line -** for figuring tabs. Output std::string is guranteed to be shorter or -** equal in length to FL_TEXT_MAX_EXP_CHAR_LEN -*/ -int Fl_Text_Buffer_mod::expand_character( char c, int indent, char *outStr, int tabDist, - char nullSubsChar ) { - int i, nSpaces; - - /* Convert tabs to spaces */ - if ( c == '\t' ) { - nSpaces = tabDist - ( indent % tabDist ); - for ( i = 0; i < nSpaces; i++ ) - outStr[ i ] = ' '; - return nSpaces; - } - - /* Convert control codes to readable character sequences */ - /*... is this safe with international character sets? */ - if ( ( ( unsigned char ) c ) <= 31 ) { - sprintf( outStr, "<%s>", ControlCodeTable[ ( unsigned char ) c ] ); - return strlen( outStr ); - } else if ( c == 127 ) { - sprintf( outStr, "" ); - return 5; - } else if ( c == nullSubsChar ) { - sprintf( outStr, "" ); - return 5; - } - - /* Otherwise, just return the character */ - *outStr = c; - return 1; -} - -/* -** Return the length in displayed characters of character "c" expanded -** for display (as discussed above in BufGetExpandedChar). If the -** buffer for which the character width is being measured is doing null -** substitution, nullSubsChar should be passed as that character (or nul -** to ignore). -*/ -int Fl_Text_Buffer_mod::character_width( char c, int indent, int tabDist, char nullSubsChar ) { - /* Note, this code must parallel that in Fl_Text_Buffer_mod::ExpandCharacter */ - if ( c == '\t' ) - return tabDist - ( indent % tabDist ); - else if ( ( ( unsigned char ) c ) <= 31 ) - return strlen( ControlCodeTable[ ( unsigned char ) c ] ) + 2; - else if ( c == 127 ) - return 5; - else if ( c == nullSubsChar ) - return 5; - return 1; -} - -/* -** Count the number of displayed characters between buffer position -** "lineStartPos" and "targetPos". (displayed characters are the characters -** shown on the screen to represent characters in the buffer, where tabs and -** control characters are expanded) -*/ -int Fl_Text_Buffer_mod::count_displayed_characters( int lineStartPos, int targetPos ) { - int pos, charCount = 0; - char expandedChar[ FL_TEXT_MAX_EXP_CHAR_LEN ]; - - pos = lineStartPos; - while ( pos < targetPos ) - charCount += expand_character( pos++, charCount, expandedChar ); - return charCount; -} - -/* -** Count forward from buffer position "startPos" in displayed characters -** (displayed characters are the characters shown on the screen to represent -** characters in the buffer, where tabs and control characters are expanded) -*/ -int Fl_Text_Buffer_mod::skip_displayed_characters( int lineStartPos, int nChars ) { - int pos, charCount = 0; - char c; - - pos = lineStartPos; - while ( charCount < nChars && pos < mLength ) { - c = character( pos ); - if ( c == '\n' ) - return pos; - charCount += character_width( c, charCount, mTabDist, mNullSubsChar ); - pos++; - } - return pos; -} - -/* -** Count the number of newlines between startPos and endPos in buffer "buf". -** The character at position "endPos" is not counted. -*/ -int Fl_Text_Buffer_mod::count_lines( int startPos, int endPos ) { - int pos, gapLen = mGapEnd - mGapStart; - int lineCount = 0; - - pos = startPos; - while ( pos < mGapStart ) { - if ( pos == endPos ) - return lineCount; - if ( mBuf[ pos++ ] == '\n' ) - lineCount++; - } - while ( pos < mLength ) { - if ( pos == endPos ) - return lineCount; - if ( mBuf[ pos++ + gapLen ] == '\n' ) - lineCount++; - } - return lineCount; -} - -/* -** Find the first character of the line "nLines" forward from "startPos" -** in "buf" and return its position -*/ -int Fl_Text_Buffer_mod::skip_lines( int startPos, int nLines ) { - int pos, gapLen = mGapEnd - mGapStart; - int lineCount = 0; - - if ( nLines == 0 ) - return startPos; - - pos = startPos; - while ( pos < mGapStart ) { - if ( mBuf[ pos++ ] == '\n' ) { - lineCount++; - if ( lineCount == nLines ) - return pos; - } - } - while ( pos < mLength ) { - if ( mBuf[ pos++ + gapLen ] == '\n' ) { - lineCount++; - if ( lineCount >= nLines ) - return pos; - } - } - return pos; -} - -/* -** Find the position of the first character of the line "nLines" backwards -** from "startPos" (not counting the character pointed to by "startpos" if -** that is a newline) in "buf". nLines == 0 means find the beginning of -** the line -*/ -int Fl_Text_Buffer_mod::rewind_lines( int startPos, int nLines ) { - int pos, gapLen = mGapEnd - mGapStart; - int lineCount = -1; - - pos = startPos - 1; - if ( pos <= 0 ) - return 0; - - while ( pos >= mGapStart ) { - if ( mBuf[ pos + gapLen ] == '\n' ) { - if ( ++lineCount >= nLines ) - return pos + 1; - } - pos--; - } - while ( pos >= 0 ) { - if ( mBuf[ pos ] == '\n' ) { - if ( ++lineCount >= nLines ) - return pos + 1; - } - pos--; - } - return 0; -} - -/* -** Search forwards in buffer for std::string "searchstring", starting with the -** character "startPos", and returning the result in "foundPos" -** returns 1 if found, 0 if not. -*/ -int Fl_Text_Buffer_mod::search_forward( int startPos, const char *searchstring, - int *foundPos, int matchCase ) -{ - if (!searchstring) return 0; - int bp; - const char* sp; - while (startPos < length()) { - bp = startPos; - sp = searchstring; - do { - if (!*sp) { *foundPos = startPos; return 1; } - } while ((matchCase ? character(bp++) == *sp++ : - toupper(character(bp++)) == toupper(*sp++)) - && bp < length()); - startPos++; - } - return 0; -} - -/* -** Search backwards in buffer for std::string "searchstring", starting with the -** character BEFORE "startPos", returning the result in "foundPos" -** returns 1 if found, 0 if not. -*/ -int Fl_Text_Buffer_mod::search_backward( int startPos, const char *searchstring, - int *foundPos, int matchCase ) -{ - if (!searchstring) return 0; - int bp; - const char* sp; - while (startPos > 0) { - bp = startPos-1; - sp = searchstring+strlen(searchstring)-1; - do { - if (sp < searchstring) { *foundPos = bp+1; return 1; } - } while ((matchCase ? character(bp--) == *sp-- : - toupper(character(bp--)) == toupper(*sp--)) - && bp >= 0); - startPos--; - } - return 0; -} - -/* -** Search forwards in buffer for characters in "searchChars", starting -** with the character "startPos", and returning the result in "foundPos" -** returns 1 if found, 0 if not. -*/ -int Fl_Text_Buffer_mod::findchars_forward( int startPos, const char *searchChars, - int *foundPos ) { - int pos, gapLen = mGapEnd - mGapStart; - const char *c; - - pos = startPos; - while ( pos < mGapStart ) { - for ( c = searchChars; *c != '\0'; c++ ) { - if ( mBuf[ pos ] == *c ) { - *foundPos = pos; - return 1; - } - } - pos++; - } - while ( pos < mLength ) { - for ( c = searchChars; *c != '\0'; c++ ) { - if ( mBuf[ pos + gapLen ] == *c ) { - *foundPos = pos; - return 1; - } - } - pos++; - } - *foundPos = mLength; - return 0; -} - -/* -** Search backwards in buffer for characters in "searchChars", starting -** with the character BEFORE "startPos", returning the result in "foundPos" -** returns 1 if found, 0 if not. -*/ -int Fl_Text_Buffer_mod::findchars_backward( int startPos, const char *searchChars, - int *foundPos ) { - int pos, gapLen = mGapEnd - mGapStart; - const char *c; - - if ( startPos == 0 ) { - *foundPos = 0; - return 0; - } - pos = startPos == 0 ? 0 : startPos - 1; - while ( pos >= mGapStart ) { - for ( c = searchChars; *c != '\0'; c++ ) { - if ( mBuf[ pos + gapLen ] == *c ) { - *foundPos = pos; - return 1; - } - } - pos--; - } - while ( pos >= 0 ) { - for ( c = searchChars; *c != '\0'; c++ ) { - if ( mBuf[ pos ] == *c ) { - *foundPos = pos; - return 1; - } - } - pos--; - } - *foundPos = 0; - return 0; -} - -/* -** A horrible design flaw in NEdit (from the very start, before we knew that -** NEdit would become so popular), is that it uses C NULL terminated std::strings -** to hold text. This means editing text containing NUL characters is not -** possible without special consideration. Here is the special consideration. -** The routines below maintain a special substitution-character which stands -** in for a null, and translates std::strings an buffers back and forth from/to -** the substituted form, figure out what to substitute, and figure out -** when we're in over our heads and no translation is possible. -*/ - -/* -** The primary routine for integrating new text into a text buffer with -** substitution of another character for ascii nuls. This substitutes null -** characters in the std::string in preparation for being copied or replaced -** into the buffer, and if neccessary, adjusts the buffer as well, in the -** event that the std::string contains the character it is currently using for -** substitution. Returns 0, if substitution is no longer possible -** because all non-printable characters are already in use. -*/ -int Fl_Text_Buffer_mod::substitute_null_characters( char *string, int len ) { - char histogram[ 256 ]; - - /* Find out what characters the std::string contains */ - histogramCharacters( std::string, len, histogram, 1 ); - - /* Does the std::string contain the null-substitute character? If so, re- - histogram the buffer text to find a character which is ok in both the - std::string and the buffer, and change the buffer's null-substitution - character. If none can be found, give up and return 0 */ - if ( histogram[ ( unsigned char ) mNullSubsChar ] != 0 ) { - char * bufstd::string; - char newSubsChar; - bufstd::string = (char*)text(); - histogramCharacters( bufstd::string, mLength, histogram, 0 ); - newSubsChar = chooseNullSubsChar( histogram ); - if ( newSubsChar == '\0' ) - return 0; - subsChars( bufstd::string, mLength, mNullSubsChar, newSubsChar ); - remove_( 0, mLength ); - insert_( 0, bufstd::string ); - free( (void *) bufstd::string ); - mNullSubsChar = newSubsChar; - } - - /* If the std::string contains null characters, substitute them with the - buffer's null substitution character */ - if ( histogram[ 0 ] != 0 ) - subsChars( std::string, len, '\0', mNullSubsChar ); - return 1; -} - -/* -** Convert std::strings obtained from buffers which contain null characters, which -** have been substituted for by a special substitution character, back to -** a null-containing std::string. There is no time penalty for calling this -** routine if no substitution has been done. -*/ -void Fl_Text_Buffer_mod::unsubstitute_null_characters( char *string ) { - register char * c, subsChar = mNullSubsChar; - - if ( subsChar == '\0' ) - return; - for ( c = std::string; *c != '\0'; c++ ) - if ( *c == subsChar ) - * c = '\0'; -} - -/* -** Create a pseudo-histogram of the characters in a std::string (don't actually -** count, because we don't want overflow, just mark the character's presence -** with a 1). If init is true, initialize the histogram before acumulating. -** if not, add the new data to an existing histogram. -*/ -static void histogramCharacters( const char *string, int length, char hist[ 256 ], - int init ) { - int i; - const char *c; - - if ( init ) - for ( i = 0; i < 256; i++ ) - hist[ i ] = 0; - for ( c = std::string; c < &std::string[ length ]; c++ ) - hist[ *( ( unsigned char * ) c ) ] |= 1; -} - -/* -** Substitute fromChar with toChar in std::string. -*/ -static void subsChars( char *string, int length, char fromChar, char toChar ) { - char * c; - - for ( c = std::string; c < &std::string[ length ]; c++ ) - if ( *c == fromChar ) * c = toChar; -} - -/* -** Search through ascii control characters in histogram in order of least -** likelihood of use, find an unused character to use as a stand-in for a -** null. If the character set is full (no available characters outside of -** the printable set, return the null character. -*/ -static char chooseNullSubsChar( char hist[ 256 ] ) { -#define N_REPLACEMENTS 25 - static unsigned char replacements[ N_REPLACEMENTS ] = {1, 2, 3, 4, 5, 6, 14, 15, 16, 17, 18, 19, - 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 11, 7}; - int i; - for ( i = 0; i < N_REPLACEMENTS; i++ ) - if ( hist[ replacements[ i ] ] == 0 ) - return replacements[ i ]; - return '\0'; -} - -/* -** Internal (non-redisplaying) version of BufInsert. Returns the length of -** text inserted (this is just strlen(text), however this calculation can be -** expensive and the length will be required by any caller who will continue -** on to call redisplay). pos must be contiguous with the existing text in -** the buffer (i.e. not past the end). -*/ -int Fl_Text_Buffer_mod::insert_( int pos, const char *s ) { - int insertedLength = strlen( s ); - - /* Prepare the buffer to receive the new text. If the new text fits in - the current buffer, just move the gap (if necessary) to where - the text should be inserted. If the new text is too large, reallocate - the buffer with a gap large enough to accomodate the new text and a - gap of PREFERRED_GAP_SIZE */ - if ( insertedLength > mGapEnd - mGapStart ) - reallocate_with_gap( pos, insertedLength + PREFERRED_GAP_SIZE ); - else if ( pos != mGapStart ) - move_gap( pos ); - - /* Insert the new text (pos now corresponds to the start of the gap) */ - memcpy( &mBuf[ pos ], s, insertedLength ); - mGapStart += insertedLength; - mLength += insertedLength; - update_selections( pos, 0, insertedLength ); - - if (mCanUndo) { - if ( undowidget==this && undoat==pos && undoinsert ) { - undoinsert += insertedLength; - } - else { - undoinsert = insertedLength; - undoyankcut = (undoat==pos) ? undocut : 0 ; - } - undoat = pos+insertedLength; - undocut = 0; - undowidget = this; - } - - return insertedLength; -} - -/* -** Internal (non-redisplaying) version of BufRemove. Removes the contents -** of the buffer between start and end (and moves the gap to the site of -** the delete). -*/ -void Fl_Text_Buffer_mod::remove_( int start, int end ) { - /* if the gap is not contiguous to the area to remove, move it there */ - - if (mCanUndo) { - if ( undowidget==this && undoat==end && undocut ) { - undobuffersize( undocut+end-start+1 ); - memmove( undobuffer+end-start, undobuffer, undocut ); - undocut += end-start; - } - else { - undocut = end-start; - undobuffersize(undocut); - } - undoat = start; - undoinsert = 0; - undoyankcut = 0; - undowidget = this; - } - - if ( start > mGapStart ) { - if (mCanUndo) - memcpy( undobuffer, mBuf+(mGapEnd-mGapStart)+start, end-start ); - move_gap( start ); - } - else if ( end < mGapStart ) { - if (mCanUndo) - memcpy( undobuffer, mBuf+start, end-start ); - move_gap( end ); - } - else { - int prelen = mGapStart - start; - if (mCanUndo) { - memcpy( undobuffer, mBuf+start, prelen ); - memcpy( undobuffer+prelen, mBuf+mGapEnd, end-start-prelen); - } - } - - /* expand the gap to encompass the deleted characters */ - mGapEnd += end - mGapStart; - mGapStart -= mGapStart - start; - - /* update the length */ - mLength -= end - start; - - /* fix up any selections which might be affected by the change */ - update_selections( start, end - start, 0 ); -} - -/* -** Insert a column of text without calling the modify callbacks. Note that -** in some pathological cases, inserting can actually decrease the size of -** the buffer because of spaces being coalesced into tabs. "nDeleted" and -** "nInserted" return the number of characters deleted and inserted beginning -** at the start of the line containing "startPos". "endPos" returns buffer -** position of the lower left edge of the inserted column (as a hint for -** routines which need to set a cursor position). -*/ -void Fl_Text_Buffer_mod::insert_column_( int column, int startPos, const char *insText, - int *nDeleted, int *nInserted, int *endPos ) { - int nLines, start, end, insWidth, lineStart, lineEnd; - int expReplLen, expInsLen, len, endOffset; - char *c, *outStr, *outPtr, *expText, *insLine; - const char *line; - const char *replText; - const char *insPtr; - - if ( column < 0 ) - column = 0; - - /* Allocate a buffer for the replacement std::string large enough to hold - possibly expanded tabs in both the inserted text and the replaced - area, as well as per line: 1) an additional 2*FL_TEXT_MAX_EXP_CHAR_LEN - characters for padding where tabs and control characters cross the - column of the selection, 2) up to "column" additional spaces per - line for padding out to the position of "column", 3) padding up - to the width of the inserted text if that must be padded to align - the text beyond the inserted column. (Space for additional - newlines if the inserted text extends beyond the end of the buffer - is counted with the length of insText) */ - start = line_start( startPos ); - nLines = countLines( insText ) + 1; - insWidth = textWidth( insText, mTabDist, mNullSubsChar ); - end = line_end( skip_lines( start, nLines - 1 ) ); - replText = text_range( start, end ); - expText = expandTabs( replText, 0, mTabDist, mNullSubsChar, - &expReplLen ); - free( (void *) replText ); - free( (void *) expText ); - expText = expandTabs( insText, 0, mTabDist, mNullSubsChar, - &expInsLen ); - free( (void *) expText ); - outStr = (char *)malloc( expReplLen + expInsLen + - nLines * ( column + insWidth + FL_TEXT_MAX_EXP_CHAR_LEN ) + 1 ); - - /* Loop over all lines in the buffer between start and end removing the - text between rectStart and rectEnd and padding appropriately. Trim - trailing space from line (whitespace at the ends of lines otherwise - tends to multiply, since additional padding is added to maintain it */ - outPtr = outStr; - lineStart = start; - insPtr = insText; - for (;;) { - lineEnd = line_end( lineStart ); - line = text_range( lineStart, lineEnd ); - insLine = copyLine( insPtr, &len ); - insPtr += len; - insertColInLine( line, insLine, column, insWidth, mTabDist, - mUseTabs, mNullSubsChar, outPtr, &len, &endOffset ); - free( (void *) line ); - free( (void *) insLine ); - for ( c = outPtr + len - 1; c > outPtr && isspace( *c ); c-- ) - len--; - outPtr += len; - *outPtr++ = '\n'; - lineStart = lineEnd < mLength ? lineEnd + 1 : mLength; - if ( *insPtr == '\0' ) - break; - insPtr++; - } - if ( outPtr != outStr ) - outPtr--; /* trim back off extra newline */ - *outPtr = '\0'; - - /* replace the text between start and end with the new stuff */ - remove_( start, end ); - insert_( start, outStr ); - *nInserted = outPtr - outStr; - *nDeleted = end - start; - *endPos = start + ( outPtr - outStr ) - len + endOffset; - free( (void *) outStr ); -} - -/* -** Delete a rectangle of text without calling the modify callbacks. Returns -** the number of characters replacing those between start and end. Note that -** in some pathological cases, deleting can actually increase the size of -** the buffer because of tab expansions. "endPos" returns the buffer position -** of the point in the last line where the text was removed (as a hint for -** routines which need to position the cursor after a delete operation) -*/ -void Fl_Text_Buffer_mod::remove_rectangular_( int start, int end, int rectStart, - int rectEnd, int *replaceLen, int *endPos ) { - int nLines, lineStart, lineEnd, len, endOffset; - char *outStr, *outPtr, *expText; - const char *s, *line; - - /* allocate a buffer for the replacement std::string large enough to hold - possibly expanded tabs as well as an additional FL_TEXT_MAX_EXP_CHAR_LEN * 2 - characters per line for padding where tabs and control characters cross - the edges of the selection */ - start = line_start( start ); - end = line_end( end ); - nLines = count_lines( start, end ) + 1; - s = text_range( start, end ); - expText = expandTabs( s, 0, mTabDist, mNullSubsChar, &len ); - free( (void *) s ); - free( (void *) expText ); - outStr = (char *)malloc( len + nLines * FL_TEXT_MAX_EXP_CHAR_LEN * 2 + 1 ); - - /* loop over all lines in the buffer between start and end removing - the text between rectStart and rectEnd and padding appropriately */ - lineStart = start; - outPtr = outStr; - endOffset = 0; - while ( lineStart <= mLength && lineStart <= end ) { - lineEnd = line_end( lineStart ); - line = text_range( lineStart, lineEnd ); - deleteRectFromLine( line, rectStart, rectEnd, mTabDist, - mUseTabs, mNullSubsChar, outPtr, &len, &endOffset ); - free( (void *) line ); - outPtr += len; - *outPtr++ = '\n'; - lineStart = lineEnd + 1; - } - if ( outPtr != outStr ) - outPtr--; /* trim back off extra newline */ - *outPtr = '\0'; - - /* replace the text between start and end with the newly created std::string */ - remove_( start, end ); - insert_( start, outStr ); - *replaceLen = outPtr - outStr; - *endPos = start + ( outPtr - outStr ) - len + endOffset; - free( (void *) outStr ); -} - -/* -** Overlay a rectangular area of text without calling the modify callbacks. -** "nDeleted" and "nInserted" return the number of characters deleted and -** inserted beginning at the start of the line containing "startPos". -** "endPos" returns buffer position of the lower left edge of the inserted -** column (as a hint for routines which need to set a cursor position). -*/ -void Fl_Text_Buffer_mod::overlay_rectangular_(int startPos, int rectStart, - int rectEnd, const char *insText, - int *nDeleted, int *nInserted, - int *endPos ) { - int nLines, start, end, lineStart, lineEnd; - int expInsLen, len, endOffset; - char *c, *outStr, *outPtr, *expText, *insLine; - const char *line; - const char *insPtr; - - /* Allocate a buffer for the replacement std::string large enough to hold - possibly expanded tabs in the inserted text, as well as per line: 1) - an additional 2*FL_TEXT_MAX_EXP_CHAR_LEN characters for padding where tabs - and control characters cross the column of the selection, 2) up to - "column" additional spaces per line for padding out to the position - of "column", 3) padding up to the width of the inserted text if that - must be padded to align the text beyond the inserted column. (Space - for additional newlines if the inserted text extends beyond the end - of the buffer is counted with the length of insText) */ - start = line_start( startPos ); - nLines = countLines( insText ) + 1; - end = line_end( skip_lines( start, nLines - 1 ) ); - expText = expandTabs( insText, 0, mTabDist, mNullSubsChar, - &expInsLen ); - free( (void *) expText ); - outStr = (char *)malloc( end - start + expInsLen + - nLines * ( rectEnd + FL_TEXT_MAX_EXP_CHAR_LEN ) + 1 ); - - /* Loop over all lines in the buffer between start and end overlaying the - text between rectStart and rectEnd and padding appropriately. Trim - trailing space from line (whitespace at the ends of lines otherwise - tends to multiply, since additional padding is added to maintain it */ - outPtr = outStr; - lineStart = start; - insPtr = insText; - for (;;) { - lineEnd = line_end( lineStart ); - line = text_range( lineStart, lineEnd ); - insLine = copyLine( insPtr, &len ); - insPtr += len; - overlayRectInLine( line, insLine, rectStart, rectEnd, mTabDist, - mUseTabs, mNullSubsChar, outPtr, &len, &endOffset ); - free( (void *) line ); - free( (void *) insLine ); - for ( c = outPtr + len - 1; c > outPtr && isspace( *c ); c-- ) - len--; - outPtr += len; - *outPtr++ = '\n'; - lineStart = lineEnd < mLength ? lineEnd + 1 : mLength; - if ( *insPtr == '\0' ) - break; - insPtr++; - } - if ( outPtr != outStr ) - outPtr--; /* trim back off extra newline */ - *outPtr = '\0'; - - /* replace the text between start and end with the new stuff */ - remove_( start, end ); - insert_( start, outStr ); - *nInserted = outPtr - outStr; - *nDeleted = end - start; - *endPos = start + ( outPtr - outStr ) - len + endOffset; - free( (void *) outStr ); -} - -/* -** Insert characters from single-line std::string "insLine" in single-line std::string -** "line" at "column", leaving "insWidth" space before continuing line. -** "outLen" returns the number of characters written to "outStr", "endOffset" -** returns the number of characters from the beginning of the std::string to -** the right edge of the inserted text (as a hint for routines which need -** to position the cursor). -*/ -static void insertColInLine( const char *line, char *insLine, int column, int insWidth, - int tabDist, int useTabs, char nullSubsChar, char *outStr, int *outLen, - int *endOffset ) { - char * c, *outPtr, *retabbedStr; - const char *linePtr; - int indent, toIndent, len, postColIndent; - - /* copy the line up to "column" */ - outPtr = outStr; - indent = 0; - for ( linePtr = line; *linePtr != '\0'; linePtr++ ) { - len = Fl_Text_Buffer_mod::character_width( *linePtr, indent, tabDist, nullSubsChar ); - if ( indent + len > column ) - break; - indent += len; - *outPtr++ = *linePtr; - } - - /* If "column" falls in the middle of a character, and the character is a - tab, leave it off and leave the indent short and it will get padded - later. If it's a control character, insert it and adjust indent - accordingly. */ - if ( indent < column && *linePtr != '\0' ) { - postColIndent = indent + len; - if ( *linePtr == '\t' ) - linePtr++; - else { - *outPtr++ = *linePtr++; - indent += len; - } - } else - postColIndent = indent; - - /* If there's no text after the column and no text to insert, that's all */ - if ( *insLine == '\0' && *linePtr == '\0' ) { - *outLen = *endOffset = outPtr - outStr; - return; - } - - /* pad out to column if text is too short */ - if ( indent < column ) { - addPadding( outPtr, indent, column, tabDist, useTabs, nullSubsChar, &len ); - outPtr += len; - indent = column; - } - - /* Copy the text from "insLine" (if any), recalculating the tabs as if - the inserted std::string began at column 0 to its new column destination */ - if ( *insLine != '\0' ) { - retabbedStr = realignTabs( insLine, 0, indent, tabDist, useTabs, - nullSubsChar, &len ); - for ( c = retabbedStr; *c != '\0'; c++ ) { - *outPtr++ = *c; - len = Fl_Text_Buffer_mod::character_width( *c, indent, tabDist, nullSubsChar ); - indent += len; - } - free( (void *) retabbedStr ); - } - - /* If the original line did not extend past "column", that's all */ - if ( *linePtr == '\0' ) { - *outLen = *endOffset = outPtr - outStr; - return; - } - - /* Pad out to column + width of inserted text + (additional original - offset due to non-breaking character at column) */ - toIndent = column + insWidth + postColIndent - column; - addPadding( outPtr, indent, toIndent, tabDist, useTabs, nullSubsChar, &len ); - outPtr += len; - indent = toIndent; - - /* realign tabs for text beyond "column" and write it out */ - retabbedStr = realignTabs( linePtr, postColIndent, indent, tabDist, - useTabs, nullSubsChar, &len ); - strcpy( outPtr, retabbedStr ); - free( (void *) retabbedStr ); - *endOffset = outPtr - outStr; - *outLen = ( outPtr - outStr ) + len; -} - -/* -** Remove characters in single-line std::string "line" between displayed positions -** "rectStart" and "rectEnd", and write the result to "outStr", which is -** assumed to be large enough to hold the returned std::string. Note that in -** certain cases, it is possible for the std::string to get longer due to -** expansion of tabs. "endOffset" returns the number of characters from -** the beginning of the std::string to the point where the characters were -** deleted (as a hint for routines which need to position the cursor). -*/ -static void deleteRectFromLine( const char *line, int rectStart, int rectEnd, - int tabDist, int useTabs, char nullSubsChar, char *outStr, int *outLen, - int *endOffset ) { - int indent, preRectIndent, postRectIndent, len; - const char *c; - char *retabbedStr, *outPtr; - - /* copy the line up to rectStart */ - outPtr = outStr; - indent = 0; - for ( c = line; *c != '\0'; c++ ) { - if ( indent > rectStart ) - break; - len = Fl_Text_Buffer_mod::character_width( *c, indent, tabDist, nullSubsChar ); - if ( indent + len > rectStart && ( indent == rectStart || *c == '\t' ) ) - break; - indent += len; - *outPtr++ = *c; - } - preRectIndent = indent; - - /* skip the characters between rectStart and rectEnd */ - for ( ; *c != '\0' && indent < rectEnd; c++ ) - indent += Fl_Text_Buffer_mod::character_width( *c, indent, tabDist, nullSubsChar ); - postRectIndent = indent; - - /* If the line ended before rectEnd, there's nothing more to do */ - if ( *c == '\0' ) { - *outPtr = '\0'; - *outLen = *endOffset = outPtr - outStr; - return; - } - - /* fill in any space left by removed tabs or control characters - which straddled the boundaries */ - indent = max( rectStart + postRectIndent - rectEnd, preRectIndent ); - addPadding( outPtr, preRectIndent, indent, tabDist, useTabs, nullSubsChar, - &len ); - outPtr += len; - - /* Copy the rest of the line. If the indentation has changed, preserve - the position of non-whitespace characters by converting tabs to - spaces, then back to tabs with the correct offset */ - retabbedStr = realignTabs( c, postRectIndent, indent, tabDist, useTabs, - nullSubsChar, &len ); - strcpy( outPtr, retabbedStr ); - free( (void *) retabbedStr ); - *endOffset = outPtr - outStr; - *outLen = ( outPtr - outStr ) + len; -} - -/* -** Overlay characters from single-line std::string "insLine" on single-line std::string -** "line" between displayed character offsets "rectStart" and "rectEnd". -** "outLen" returns the number of characters written to "outStr", "endOffset" -** returns the number of characters from the beginning of the std::string to -** the right edge of the inserted text (as a hint for routines which need -** to position the cursor). -*/ -static void overlayRectInLine( const char *line, char *insLine, int rectStart, - int rectEnd, int tabDist, int useTabs, char nullSubsChar, char *outStr, - int *outLen, int *endOffset ) { - char * c, *outPtr, *retabbedStr; - int inIndent, outIndent, len, postRectIndent; - const char *linePtr; - - /* copy the line up to "rectStart" */ - outPtr = outStr; - inIndent = outIndent = 0; - for ( linePtr = line; *linePtr != '\0'; linePtr++ ) { - len = Fl_Text_Buffer_mod::character_width( *linePtr, inIndent, tabDist, nullSubsChar ); - if ( inIndent + len > rectStart ) - break; - inIndent += len; - outIndent += len; - *outPtr++ = *linePtr; - } - - /* If "rectStart" falls in the middle of a character, and the character - is a tab, leave it off and leave the outIndent short and it will get - padded later. If it's a control character, insert it and adjust - outIndent accordingly. */ - if ( inIndent < rectStart && *linePtr != '\0' ) { - if ( *linePtr == '\t' ) { - linePtr++; - inIndent += len; - } else { - *outPtr++ = *linePtr++; - outIndent += len; - inIndent += len; - } - } - - /* skip the characters between rectStart and rectEnd */ - postRectIndent = rectEnd; - for ( ; *linePtr != '\0'; linePtr++ ) { - inIndent += Fl_Text_Buffer_mod::character_width( *linePtr, inIndent, tabDist, nullSubsChar ); - if ( inIndent >= rectEnd ) { - linePtr++; - postRectIndent = inIndent; - break; - } - } - - /* If there's no text after rectStart and no text to insert, that's all */ - if ( *insLine == '\0' && *linePtr == '\0' ) { - *outLen = *endOffset = outPtr - outStr; - return; - } - - /* pad out to rectStart if text is too short */ - if ( outIndent < rectStart ) { - addPadding( outPtr, outIndent, rectStart, tabDist, useTabs, nullSubsChar, - &len ); - outPtr += len; - } - outIndent = rectStart; - - /* Copy the text from "insLine" (if any), recalculating the tabs as if - the inserted std::string began at column 0 to its new column destination */ - if ( *insLine != '\0' ) { - retabbedStr = realignTabs( insLine, 0, rectStart, tabDist, useTabs, - nullSubsChar, &len ); - for ( c = retabbedStr; *c != '\0'; c++ ) { - *outPtr++ = *c; - len = Fl_Text_Buffer_mod::character_width( *c, outIndent, tabDist, nullSubsChar ); - outIndent += len; - } - free( (void *) retabbedStr ); - } - - /* If the original line did not extend past "rectStart", that's all */ - if ( *linePtr == '\0' ) { - *outLen = *endOffset = outPtr - outStr; - return; - } - - /* Pad out to rectEnd + (additional original offset - due to non-breaking character at right boundary) */ - addPadding( outPtr, outIndent, postRectIndent, tabDist, useTabs, - nullSubsChar, &len ); - outPtr += len; - outIndent = postRectIndent; - - /* copy the text beyond "rectEnd" */ - strcpy( outPtr, linePtr ); - *endOffset = outPtr - outStr; - *outLen = ( outPtr - outStr ) + strlen( linePtr ); -} - -char * Fl_Text_Buffer_mod::selection_text_( Fl_Text_Selection *sel ) { - int start, end, isRect, rectStart, rectEnd; - char *s; - - /* If there's no selection, return an allocated empty std::string */ - if ( !sel->position( &start, &end, &isRect, &rectStart, &rectEnd ) ) { - s = (char *)malloc( 1 ); - *s = '\0'; - return s; - } - - /* If the selection is not rectangular, return the selected range */ - if ( isRect ) - return text_in_rectangle( start, end, rectStart, rectEnd ); - else - return text_range( start, end ); -} - -void Fl_Text_Buffer_mod::remove_selection_( Fl_Text_Selection *sel ) { - int start, end; - int isRect, rectStart, rectEnd; - - if ( !sel->position( &start, &end, &isRect, &rectStart, &rectEnd ) ) - return; - if ( isRect ) - remove_rectangular( start, end, rectStart, rectEnd ); - else { - remove( start, end ); - //undoyankcut = undocut; - } -} - -void Fl_Text_Buffer_mod::replace_selection_( Fl_Text_Selection *sel, const char *s ) { - int start, end, isRect, rectStart, rectEnd; - Fl_Text_Selection oldSelection = *sel; - - /* If there's no selection, return */ - if ( !sel->position( &start, &end, &isRect, &rectStart, &rectEnd ) ) - return; - - /* Do the appropriate type of replace */ - if ( isRect ) - replace_rectangular( start, end, rectStart, rectEnd, s ); - else - replace( start, end, s ); - - /* Unselect (happens automatically in BufReplace, but BufReplaceRect - can't detect when the contents of a selection goes away) */ - sel->mSelected = 0; - redisplay_selection( &oldSelection, sel ); -} - -static void addPadding( char *string, int startIndent, int toIndent, - int tabDist, int useTabs, char nullSubsChar, int *charsAdded ) { - char * outPtr; - int len, indent; - - indent = startIndent; - outPtr = std::string; - if ( useTabs ) { - while ( indent < toIndent ) { - len = Fl_Text_Buffer_mod::character_width( '\t', indent, tabDist, nullSubsChar ); - if ( len > 1 && indent + len <= toIndent ) { - *outPtr++ = '\t'; - indent += len; - } else { - *outPtr++ = ' '; - indent++; - } - } - } else { - while ( indent < toIndent ) { - *outPtr++ = ' '; - indent++; - } - } - *charsAdded = outPtr - std::string; -} - -/* -** Call the stored modify callback procedure(s) for this buffer to update the -** changed area(s) on the screen and any other listeners. -*/ -void Fl_Text_Buffer_mod::call_modify_callbacks( int pos, int nDeleted, - int nInserted, int nRestyled, const char *deletedText ) { - int i; - - for ( i = 0; i < mNModifyProcs; i++ ) - ( *mNodifyProcs[ i ] ) ( pos, nInserted, nDeleted, nRestyled, - deletedText, mCbArgs[ i ] ); -} - -/* -** Call the stored pre-delete callback procedure(s) for this buffer to update -** the changed area(s) on the screen and any other listeners. -*/ -void Fl_Text_Buffer_mod::call_predelete_callbacks(int pos, int nDeleted) { - int i; - - for (i=0; imStart; - newStart = newSelection->mStart; - oldEnd = oldSelection->mEnd; - newEnd = newSelection->mEnd; - if ( oldSelection->mRectangular ) - oldEnd++; - if ( newSelection->mRectangular ) - newEnd++; - - /* If the old or new selection is unselected, just redisplay the - single area that is (was) selected and return */ - if ( !oldSelection->mSelected && !newSelection->mSelected ) - return; - if ( !oldSelection->mSelected ) { - call_modify_callbacks( newStart, 0, 0, newEnd - newStart, NULL ); - return; - } - if ( !newSelection->mSelected ) { - call_modify_callbacks( oldStart, 0, 0, oldEnd - oldStart, NULL ); - return; - } - - /* If the selection changed from normal to rectangular or visa versa, or - if a rectangular selection changed boundaries, redisplay everything */ - if ( ( oldSelection->mRectangular && !newSelection->mRectangular ) || - ( !oldSelection->mRectangular && newSelection->mRectangular ) || - ( oldSelection->mRectangular && ( - ( oldSelection->mRectStart != newSelection->mRectStart ) || - ( oldSelection->mRectEnd != newSelection->mRectEnd ) ) ) ) { - call_modify_callbacks( min( oldStart, newStart ), 0, 0, - max( oldEnd, newEnd ) - min( oldStart, newStart ), NULL ); - return; - } - - /* If the selections are non-contiguous, do two separate updates - and return */ - if ( oldEnd < newStart || newEnd < oldStart ) { - call_modify_callbacks( oldStart, 0, 0, oldEnd - oldStart, NULL ); - call_modify_callbacks( newStart, 0, 0, newEnd - newStart, NULL ); - return; - } - - /* Otherwise, separate into 3 separate regions: ch1, and ch2 (the two - changed areas), and the unchanged area of their intersection, - and update only the changed area(s) */ - ch1Start = min( oldStart, newStart ); - ch2End = max( oldEnd, newEnd ); - ch1End = max( oldStart, newStart ); - ch2Start = min( oldEnd, newEnd ); - if ( ch1Start != ch1End ) - call_modify_callbacks( ch1Start, 0, 0, ch1End - ch1Start, NULL ); - if ( ch2Start != ch2End ) - call_modify_callbacks( ch2Start, 0, 0, ch2End - ch2Start, NULL ); -} - -void Fl_Text_Buffer_mod::move_gap( int pos ) { - int gapLen = mGapEnd - mGapStart; - - if ( pos > mGapStart ) - memmove( &mBuf[ mGapStart ], &mBuf[ mGapEnd ], - pos - mGapStart ); - else - memmove( &mBuf[ pos + gapLen ], &mBuf[ pos ], mGapStart - pos ); - mGapEnd += pos - mGapStart; - mGapStart += pos - mGapStart; -} - -/* -** reallocate the text storage in "buf" to have a gap starting at "newGapStart" -** and a gap size of "newGapLen", preserving the buffer's current contents. -*/ -void Fl_Text_Buffer_mod::reallocate_with_gap( int newGapStart, int newGapLen ) { - char * newBuf; - int newGapEnd; - - newBuf = (char *)malloc( mLength + newGapLen ); - newGapEnd = newGapStart + newGapLen; - if ( newGapStart <= mGapStart ) { - memcpy( newBuf, mBuf, newGapStart ); - memcpy( &newBuf[ newGapEnd ], &mBuf[ newGapStart ], - mGapStart - newGapStart ); - memcpy( &newBuf[ newGapEnd + mGapStart - newGapStart ], - &mBuf[ mGapEnd ], mLength - mGapStart ); - } else { /* newGapStart > mGapStart */ - memcpy( newBuf, mBuf, mGapStart ); - memcpy( &newBuf[ mGapStart ], &mBuf[ mGapEnd ], - newGapStart - mGapStart ); - memcpy( &newBuf[ newGapEnd ], - &mBuf[ mGapEnd + newGapStart - mGapStart ], - mLength - newGapStart ); - } - free( (void *) mBuf ); - mBuf = newBuf; - mGapStart = newGapStart; - mGapEnd = newGapEnd; -#ifdef PURIFY -{int i; for ( i = mGapStart; i < mGapEnd; i++ ) mBuf[ i ] = '.'; } -#endif -} - -/* -** Update all of the selections in "buf" for changes in the buffer's text -*/ -void Fl_Text_Buffer_mod::update_selections( int pos, int nDeleted, - int nInserted ) { - mPrimary.update( pos, nDeleted, nInserted ); - mSecondary.update( pos, nDeleted, nInserted ); - mHighlight.update( pos, nDeleted, nInserted ); -} - -/* -** Search forwards in buffer "buf" for character "searchChar", starting -** with the character "startPos", and returning the result in "foundPos" -** returns 1 if found, 0 if not. (The difference between this and -** BufSearchForward is that it's optimized for single characters. The -** overall performance of the text widget is dependent on its ability to -** count lines quickly, hence searching for a single character: newline) -*/ -int Fl_Text_Buffer_mod::findchar_forward( int startPos, char searchChar, - int *foundPos ) { - int pos, gapLen = mGapEnd - mGapStart; - - if (startPos < 0 || startPos >= mLength) { - *foundPos = mLength; - return 0; - } - - pos = startPos; - while ( pos < mGapStart ) { - if ( mBuf[ pos ] == searchChar ) { - *foundPos = pos; - return 1; - } - pos++; - } - while ( pos < mLength ) { - if ( mBuf[ pos + gapLen ] == searchChar ) { - *foundPos = pos; - return 1; - } - pos++; - } - *foundPos = mLength; - return 0; -} - -/* -** Search backwards in buffer "buf" for character "searchChar", starting -** with the character BEFORE "startPos", returning the result in "foundPos" -** returns 1 if found, 0 if not. (The difference between this and -** BufSearchBackward is that it's optimized for single characters. The -** overall performance of the text widget is dependent on its ability to -** count lines quickly, hence searching for a single character: newline) -*/ -int Fl_Text_Buffer_mod::findchar_backward( int startPos, char searchChar, - int *foundPos ) { - int pos, gapLen = mGapEnd - mGapStart; - - if ( startPos <= 0 || startPos > mLength ) { - *foundPos = 0; - return 0; - } - pos = startPos - 1; - while ( pos >= mGapStart ) { - if ( mBuf[ pos + gapLen ] == searchChar ) { - *foundPos = pos; - return 1; - } - pos--; - } - while ( pos >= 0 ) { - if ( mBuf[ pos ] == searchChar ) { - *foundPos = pos; - return 1; - } - pos--; - } - *foundPos = 0; - return 0; -} - -/* -** Copy from "text" to end up to but not including newline (or end of "text") -** and return the copy as the function value, and the length of the line in -** "lineLen" -*/ -static char *copyLine( const char *text, int *lineLen ) { - int len = 0; - const char *c; - char *outStr; - - for ( c = text; *c != '\0' && *c != '\n'; c++ ) - len++; - outStr = (char *)malloc( len + 1 ); - strlcpy( outStr, text, len + 1); - *lineLen = len; - return outStr; -} - -/* -** Count the number of newlines in a null-terminated text std::string; -*/ -static int countLines( const char *string ) { - const char * c; - int lineCount = 0; - - for ( c = std::string; *c != '\0'; c++ ) - if ( *c == '\n' ) lineCount++; - return lineCount; -} - -/* -** Measure the width in displayed characters of std::string "text" -*/ -static int textWidth( const char *text, int tabDist, char nullSubsChar ) { - int width = 0, maxWidth = 0; - const char *c; - - for ( c = text; *c != '\0'; c++ ) { - if ( *c == '\n' ) { - if ( width > maxWidth ) - maxWidth = width; - width = 0; - } else - width += Fl_Text_Buffer_mod::character_width( *c, width, tabDist, nullSubsChar ); - } - if ( width > maxWidth ) - return width; - return maxWidth; -} - -/* -** Find the first and last character position in a line within a rectangular -** selection (for copying). Includes tabs which cross rectStart, but not -** control characters which do so. Leaves off tabs which cross rectEnd. -** -** Technically, the calling routine should convert tab characters which -** cross the right boundary of the selection to spaces which line up with -** the edge of the selection. Unfortunately, the additional memory -** management required in the parent routine to allow for the changes -** in std::string size is not worth all the extra work just for a couple of -** shifted characters, so if a tab protrudes, just lop it off and hope -** that there are other characters in the selection to establish the right -** margin for subsequent columnar pastes of this data. -*/ -void Fl_Text_Buffer_mod::rectangular_selection_boundaries( int lineStartPos, - int rectStart, int rectEnd, int *selStart, int *selEnd ) { - int pos, width, indent = 0; - char c; - - /* find the start of the selection */ - for ( pos = lineStartPos; pos < mLength; pos++ ) { - c = character( pos ); - if ( c == '\n' ) - break; - width = Fl_Text_Buffer_mod::character_width( c, indent, mTabDist, mNullSubsChar ); - if ( indent + width > rectStart ) { - if ( indent != rectStart && c != '\t' ) { - pos++; - indent += width; - } - break; - } - indent += width; - } - *selStart = pos; - - /* find the end */ - for ( ; pos < mLength; pos++ ) { - c = character( pos ); - if ( c == '\n' ) - break; - width = Fl_Text_Buffer_mod::character_width( c, indent, mTabDist, mNullSubsChar ); - indent += width; - if ( indent > rectEnd ) { - if ( indent - width != rectEnd && c != '\t' ) - pos++; - break; - } - } - *selEnd = pos; -} - -/* -** Adjust the space and tab characters from std::string "text" so that non-white -** characters remain stationary when the text is shifted from starting at -** "origIndent" to starting at "newIndent". Returns an allocated std::string -** which must be freed by the caller with XtFree. -*/ -static char *realignTabs( const char *text, int origIndent, int newIndent, - int tabDist, int useTabs, char nullSubsChar, int *newLength ) { - char * expStr, *outStr; - int len; - - /* If the tabs settings are the same, retain original tabs */ - if ( origIndent % tabDist == newIndent % tabDist ) { - len = strlen( text ); - outStr = (char *)malloc( len + 1 ); - strcpy( outStr, text ); - *newLength = len; - return outStr; - } - - /* If the tab settings are not the same, brutally convert tabs to - spaces, then back to tabs in the new position */ - expStr = expandTabs( text, origIndent, tabDist, nullSubsChar, &len ); - if ( !useTabs ) { - *newLength = len; - return expStr; - } - outStr = unexpandTabs( expStr, newIndent, tabDist, nullSubsChar, newLength ); - free( (void *) expStr ); - return outStr; -} - -/* -** Expand tabs to spaces for a block of text. The additional parameter -** "startIndent" if nonzero, indicates that the text is a rectangular selection -** beginning at column "startIndent" -*/ -static char *expandTabs( const char *text, int startIndent, int tabDist, - char nullSubsChar, int *newLen ) { - char * outStr, *outPtr; - const char *c; - int indent, len, outLen = 0; - - /* rehearse the expansion to figure out length for output std::string */ - indent = startIndent; - for ( c = text; *c != '\0'; c++ ) { - if ( *c == '\t' ) { - len = Fl_Text_Buffer_mod::character_width( *c, indent, tabDist, nullSubsChar ); - outLen += len; - indent += len; - } else if ( *c == '\n' ) { - indent = startIndent; - outLen++; - } else { - indent += Fl_Text_Buffer_mod::character_width( *c, indent, tabDist, nullSubsChar ); - outLen++; - } - } - - /* do the expansion */ - outStr = (char *)malloc( outLen + 1 ); - outPtr = outStr; - indent = startIndent; - for ( c = text; *c != '\0'; c++ ) { - if ( *c == '\t' ) { - len = Fl_Text_Buffer_mod::expand_character( *c, indent, outPtr, tabDist, nullSubsChar ); - outPtr += len; - indent += len; - } else if ( *c == '\n' ) { - indent = startIndent; - *outPtr++ = *c; - } else { - indent += Fl_Text_Buffer_mod::character_width( *c, indent, tabDist, nullSubsChar ); - *outPtr++ = *c; - } - } - outStr[ outLen ] = '\0'; - *newLen = outLen; - return outStr; -} - -/* -** Convert sequences of spaces into tabs. The threshold for conversion is -** when 3 or more spaces can be converted into a single tab, this avoids -** converting double spaces after a period withing a block of text. -*/ -static char *unexpandTabs( char *text, int startIndent, int tabDist, - char nullSubsChar, int *newLen ) { - char * outStr, *outPtr, *c, expandedChar[ FL_TEXT_MAX_EXP_CHAR_LEN ]; - int indent, len; - - outStr = (char *)malloc( strlen( text ) + 1 ); - outPtr = outStr; - indent = startIndent; - for ( c = text; *c != '\0'; ) { - if ( *c == ' ' ) { - len = Fl_Text_Buffer_mod::expand_character( '\t', indent, expandedChar, tabDist, - nullSubsChar ); - if ( len >= 3 && !strncmp( c, expandedChar, len ) ) { - c += len; - *outPtr++ = '\t'; - indent += len; - } else { - *outPtr++ = *c++; - indent++; - } - } else if ( *c == '\n' ) { - indent = startIndent; - *outPtr++ = *c++; - } else { - *outPtr++ = *c++; - indent++; - } - } - *outPtr = '\0'; - *newLen = outPtr - outStr; - return outStr; -} - -static int max( int i1, int i2 ) { - return i1 >= i2 ? i1 : i2; -} - -static int min( int i1, int i2 ) { - return i1 <= i2 ? i1 : i2; -} - -int -Fl_Text_Buffer_mod::insertfile(const char *file, int pos, int buflen) { - FILE *fp; int r; - if (!(fp = fopen(file, "r"))) return 1; - char *buffer = new char[buflen]; - for (; (r = fread(buffer, 1, buflen - 1, fp)) > 0; pos += r) { - buffer[r] = (char)0; - insert(pos, buffer); - } - - int e = ferror(fp) ? 2 : 0; - fclose(fp); - delete[] buffer; - return e; -} - -int -Fl_Text_Buffer_mod::outputfile(const char *file, int start, int end, int buflen) { - FILE *fp; - if (!(fp = fopen(file, "w"))) return 1; - for (int n; (n = min(end - start, buflen)); start += n) { - const char *p = text_range(start, start + n); - int r = fwrite(p, 1, n, fp); - free((void *)p); - if (r != n) break; - } - - int e = ferror(fp) ? 2 : 0; - fclose(fp); - return e; -} - - -// -// End of "$Id: Fl_Text_Buffer.cxx 6011 2008-01-04 20:32:37Z matt $". -// diff --git a/src/widgets/Fl_Text_Buffer_mod_1_3.cxx b/src/widgets/Fl_Text_Buffer_mod_1_3.cxx deleted file mode 100644 index 502b1e2..0000000 --- a/src/widgets/Fl_Text_Buffer_mod_1_3.cxx +++ /dev/null @@ -1,1846 +0,0 @@ -// "$Id: Fl_Text_Buffer_mod.cxx 8040 2010-12-15 17:38:39Z manolo $" -// -// Copyright 2001-2010 by Bill Spitzak and others. -// Original code Copyright Mark Edel. Permission to distribute under -// the LGPL for the FLTK library granted by Mark Edel. -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ -// -// This file is part of flmsg -// -// flrig 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. -// -// flrig 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 -#include -#include -#include "missing_strings.h" -#include -#include -#include -#include "Fl_Text_Buffer_mod.H" - - -/* - This file is based on a port of NEdit to FLTK many years ago. NEdit at that - point was already stretched beyond the task it was designed for which explains - why the source code is sometimes pretty convoluted. It still is a very useful - widget for FLTK, and we are thankful that the nedit team allowed us to - integrate their code. - - With the introduction of Unicode and UTF-8, Fl_Text_... has to go into a whole - new generation of code. Originally designed for monospaced fonts only, many - features make less sense in the multibyte and multiwidth world of UTF-8. - - Columns are a good example. There is simply no such thing. The new Fl_Text_... - widget converts columns to pixels by multiplying them with the average - character width for a given font. - - Rectangular selections were rarely used (if at all) and make little sense when - using variable width fonts. They have been removed. - - Using multiple spaces to emulate tab stops has been replaced by pixel counting - routines. They are slower, but give the expected result for proportional fonts. - - And constantly recalculating character widths is just much too expensive. Lines - of text are now subdivided into blocks of text which are measured at once - instead of individual characters. - */ - - -#ifndef min - -static int max(int i1, int i2) -{ - return i1 >= i2 ? i1 : i2; -} - -static int min(int i1, int i2) -{ - return i1 <= i2 ? i1 : i2; -} - -#endif - - -static char *undobuffer; -static int undobufferlength; -static Fl_Text_Buffer_mod *undowidget; -static int undoat; // points after insertion -static int undocut; // number of characters deleted there -static int undoinsert; // number of characters inserted -static int undoyankcut; // length of valid contents of buffer, even if undocut=0 - -/* - Resize the undo buffer to match at least the requested size. - */ -static void undobuffersize(int n) -{ - if (n > undobufferlength) { - if (undobuffer) { - do { - undobufferlength *= 2; - } while (undobufferlength < n); - undobuffer = (char *) realloc(undobuffer, undobufferlength); - } else { - undobufferlength = n + 9; - undobuffer = (char *) malloc(undobufferlength); - } - } -} - -static void def_transcoding_warning_action(Fl_Text_Buffer_mod *text) -{ - fl_alert("%s", text->file_encoding_warning_message); -} - -/* - Initialize all variables. - */ -Fl_Text_Buffer_mod::Fl_Text_Buffer_mod(int requestedSize, int preferredGapSize) -{ - mLength = 0; - mPreferredGapSize = preferredGapSize; - mBuf = (char *) malloc(requestedSize + mPreferredGapSize); - mGapStart = 0; - mGapEnd = mPreferredGapSize; - mTabDist = 8; - mPrimary.mSelected = 0; - mPrimary.mStart = mPrimary.mEnd = 0; - mSecondary.mSelected = 0; - mSecondary.mStart = mSecondary.mEnd = 0; - mHighlight.mSelected = 0; - mHighlight.mStart = mHighlight.mEnd = 0; - mModifyProcs = NULL; - mCbArgs = NULL; - mNModifyProcs = 0; - mNPredeleteProcs = 0; - mPredeleteProcs = NULL; - mPredeleteCbArgs = NULL; - mCursorPosHint = 0; - mCanUndo = 1; - input_file_was_transcoded = 0; - transcoding_warning_action = def_transcoding_warning_action; -} - - -/* - Free all resources. - */ -Fl_Text_Buffer_mod::~Fl_Text_Buffer_mod() -{ - free(mBuf); - if (mNModifyProcs != 0) { - delete[]mModifyProcs; - delete[]mCbArgs; - } - if (mNPredeleteProcs != 0) { - delete[]mPredeleteProcs; - delete[]mPredeleteCbArgs; - } -} - - -/* - This function copies verbose whatever is in front and after the gap into a - single buffer. - */ -char *Fl_Text_Buffer_mod::text() const { - char *t = (char *) malloc(mLength + 1); - memcpy(t, mBuf, mGapStart); - memcpy(t+mGapStart, mBuf+mGapEnd, mLength - mGapStart); - t[mLength] = '\0'; - return t; -} - - -/* - Set the text buffer to a new std::string. - */ -void Fl_Text_Buffer_mod::text(const char *t) -{ - IS_UTF8_ALIGNED(t) - - call_predelete_callbacks(0, length()); - - /* Save information for redisplay, and get rid of the old buffer */ - const char *deletedText = text(); - int deletedLength = mLength; - free((void *) mBuf); - - /* Start a new buffer with a gap of mPreferredGapSize at the end */ - int insertedLength = strlen(t); - mBuf = (char *) malloc(insertedLength + mPreferredGapSize); - mLength = insertedLength; - mGapStart = insertedLength; - mGapEnd = mGapStart + mPreferredGapSize; - memcpy(mBuf, t, insertedLength); - - /* Zero all of the existing selections */ - update_selections(0, deletedLength, 0); - - /* Call the saved display routine(s) to update the screen */ - call_modify_callbacks(0, deletedLength, insertedLength, 0, deletedText); - free((void *) deletedText); -} - - -/* - Creates a range of text to a new buffer and copies verbose from around the gap. - */ -char *Fl_Text_Buffer_mod::text_range(int start, int end) const { - IS_UTF8_ALIGNED2(this, (start)) - IS_UTF8_ALIGNED2(this, (end)) - - char *s = NULL; - - /* Make sure start and end are ok, and allocate memory for returned std::string. - If start is bad, return "", if end is bad, adjust it. */ - if (start < 0 || start > mLength) - { - s = (char *) malloc(1); - s[0] = '\0'; - return s; - } - if (end < start) { - int temp = start; - start = end; - end = temp; - } - if (end > mLength) - end = mLength; - int copiedLength = end - start; - s = (char *) malloc(copiedLength + 1); - - /* Copy the text from the buffer to the returned std::string */ - if (end <= mGapStart) { - memcpy(s, mBuf + start, copiedLength); - } else if (start >= mGapStart) { - memcpy(s, mBuf + start + (mGapEnd - mGapStart), copiedLength); - } else { - int part1Length = mGapStart - start; - memcpy(s, mBuf + start, part1Length); - memcpy(s + part1Length, mBuf + mGapEnd, copiedLength - part1Length); - } - s[copiedLength] = '\0'; - return s; -} - -/* - Return a UCS-4 character at the given index. - Pos must be at a character boundary. - */ -unsigned int Fl_Text_Buffer_mod::char_at(int pos) const { - if (pos < 0 || pos >= mLength) - return '\0'; - - IS_UTF8_ALIGNED2(this, (pos)) - - const char *src = address(pos); - return fl_utf8decode(src, 0, 0); -} - - -/* - Return the raw byte at the given index. - This function ignores all unicode encoding. - */ -char Fl_Text_Buffer_mod::byte_at(int pos) const { - if (pos < 0 || pos >= mLength) - return '\0'; - const char *src = address(pos); - return *src; -} - - -/* - Insert some text at the given index. - Pos must be at a character boundary. -*/ -void Fl_Text_Buffer_mod::insert(int pos, const char *text) -{ - IS_UTF8_ALIGNED2(this, (pos)) - IS_UTF8_ALIGNED(text) - - /* check if there is actually any text */ - if (!text || !*text) - return; - - /* if pos is not contiguous to existing text, make it */ - if (pos > mLength) - pos = mLength; - if (pos < 0) - pos = 0; - - /* Even if nothing is deleted, we must call these callbacks */ - call_predelete_callbacks(pos, 0); - - /* insert and redisplay */ - int nInserted = insert_(pos, text); - mCursorPosHint = pos + nInserted; - IS_UTF8_ALIGNED2(this, (mCursorPosHint)) - call_modify_callbacks(pos, 0, nInserted, 0, NULL); -} - - -/* - Replace a range of text with new text. - Start and end must be at a character boundary. -*/ -void Fl_Text_Buffer_mod::replace(int start, int end, const char *text) -{ - // Range check... - if (!text) - return; - if (start < 0) - start = 0; - if (end > mLength) - end = mLength; - - IS_UTF8_ALIGNED2(this, (start)) - IS_UTF8_ALIGNED2(this, (end)) - IS_UTF8_ALIGNED(text) - - call_predelete_callbacks(start, end - start); - const char *deletedText = text_range(start, end); - remove_(start, end); - int nInserted = insert_(start, text); - mCursorPosHint = start + nInserted; - call_modify_callbacks(start, end - start, nInserted, 0, deletedText); - free((void *) deletedText); -} - - -/* - Remove a range of text. - Start and End must be at a character boundary. -*/ -void Fl_Text_Buffer_mod::remove(int start, int end) -{ - /* Make sure the arguments make sense */ - if (start > end) { - int temp = start; - start = end; - end = temp; - } - if (start > mLength) - start = mLength; - if (start < 0) - start = 0; - if (end > mLength) - end = mLength; - if (end < 0) - end = 0; - - IS_UTF8_ALIGNED2(this, (start)) - IS_UTF8_ALIGNED2(this, (end)) - - if (start == end) - return; - - call_predelete_callbacks(start, end - start); - /* Remove and redisplay */ - const char *deletedText = text_range(start, end); - remove_(start, end); - mCursorPosHint = start; - call_modify_callbacks(start, end - start, 0, 0, deletedText); - free((void *) deletedText); -} - - -/* - Copy a range of text from another text buffer. - fromStart, fromEnd, and toPos must be at a character boundary. - */ -void Fl_Text_Buffer_mod::copy(Fl_Text_Buffer_mod * fromBuf, int fromStart, - int fromEnd, int toPos) -{ - IS_UTF8_ALIGNED2(fromBuf, fromStart) - IS_UTF8_ALIGNED2(fromBuf, fromEnd) - IS_UTF8_ALIGNED2(this, (toPos)) - - int copiedLength = fromEnd - fromStart; - - /* Prepare the buffer to receive the new text. If the new text fits in - the current buffer, just move the gap (if necessary) to where - the text should be inserted. If the new text is too large, reallocate - the buffer with a gap large enough to accomodate the new text and a - gap of mPreferredGapSize */ - if (copiedLength > mGapEnd - mGapStart) - reallocate_with_gap(toPos, copiedLength + mPreferredGapSize); - else if (toPos != mGapStart) - move_gap(toPos); - - /* Insert the new text (toPos now corresponds to the start of the gap) */ - if (fromEnd <= fromBuf->mGapStart) { - memcpy(&mBuf[toPos], &fromBuf->mBuf[fromStart], copiedLength); - } else if (fromStart >= fromBuf->mGapStart) { - memcpy(&mBuf[toPos], - &fromBuf->mBuf[fromStart + (fromBuf->mGapEnd - fromBuf->mGapStart)], - copiedLength); - } else { - int part1Length = fromBuf->mGapStart - fromStart; - memcpy(&mBuf[toPos], &fromBuf->mBuf[fromStart], part1Length); - memcpy(&mBuf[toPos + part1Length], - &fromBuf->mBuf[fromBuf->mGapEnd], copiedLength - part1Length); - } - mGapStart += copiedLength; - mLength += copiedLength; - update_selections(toPos, 0, copiedLength); -} - - -/* - Take the previous changes and undo them. Return the previous - cursor position in cursorPos. Returns 1 if the undo was applied. - CursorPos will be at a character boundary. - */ -int Fl_Text_Buffer_mod::undo(int *cursorPos) -{ - if (undowidget != this || (!undocut && !undoinsert && !mCanUndo)) - return 0; - - int ilen = undocut; - int xlen = undoinsert; - int b = undoat - xlen; - - if (xlen && undoyankcut && !ilen) { - ilen = undoyankcut; - } - - if (xlen && ilen) { - undobuffersize(ilen + 1); - undobuffer[ilen] = 0; - char *tmp = strdup(undobuffer); - replace(b, undoat, tmp); - if (cursorPos) - *cursorPos = mCursorPosHint; - free(tmp); - } else if (xlen) { - remove(b, undoat); - if (cursorPos) - *cursorPos = mCursorPosHint; - } else if (ilen) { - undobuffersize(ilen + 1); - undobuffer[ilen] = 0; - insert(undoat, undobuffer); - if (cursorPos) - *cursorPos = mCursorPosHint; - undoyankcut = 0; - } - - return 1; -} - - -/* - Set a flag if undo function will work. - */ -void Fl_Text_Buffer_mod::canUndo(char flag) -{ - mCanUndo = flag; - // disabling undo also clears the last undo operation! - if (!mCanUndo && undowidget==this) - undowidget = 0; -} - - -/* - Change the tab width. This will cause a couple of callbacks and a complete - redisplay. - Matt: I am not entirely sure why we need to trigger callbacks because - tabs are only a graphical hint, not changing any text at all, but I leave - this in here for back compatibility. - */ -void Fl_Text_Buffer_mod::tab_distance(int tabDist) -{ - /* First call the pre-delete callbacks with the previous tab setting - still active. */ - call_predelete_callbacks(0, mLength); - - /* Change the tab setting */ - mTabDist = tabDist; - - /* Force any display routines to redisplay everything (unfortunately, - this means copying the whole buffer contents to provide "deletedText" */ - const char *deletedText = text(); - call_modify_callbacks(0, mLength, mLength, 0, deletedText); - free((void *) deletedText); -} - - -/* - Select a range of text. - Start and End must be at a character boundary. - */ -void Fl_Text_Buffer_mod::select(int start, int end) -{ - IS_UTF8_ALIGNED2(this, (start)) - IS_UTF8_ALIGNED2(this, (end)) - - Fl_Text_Selection_mod oldSelection = mPrimary; - - mPrimary.set(start, end); - redisplay_selection(&oldSelection, &mPrimary); -} - - -/* - Clear the primary selection. - */ -void Fl_Text_Buffer_mod::unselect() -{ - Fl_Text_Selection_mod oldSelection = mPrimary; - - mPrimary.mSelected = 0; - redisplay_selection(&oldSelection, &mPrimary); -} - - -/* - Return the primary selection range. - */ -int Fl_Text_Buffer_mod::selection_position(int *start, int *end) -{ - return mPrimary.position(start, end); -} - - -/* - Return a copy of the selected text. - */ -char *Fl_Text_Buffer_mod::selection_text() -{ - return selection_text_(&mPrimary); -} - - -/* - Remove the selected text. - */ -void Fl_Text_Buffer_mod::remove_selection() -{ - remove_selection_(&mPrimary); -} - - -/* - Replace the selected text. - */ -void Fl_Text_Buffer_mod::replace_selection(const char *text) -{ - replace_selection_(&mPrimary, text); -} - - -/* - Select text. - Start and End must be at a character boundary. - */ -void Fl_Text_Buffer_mod::secondary_select(int start, int end) -{ - Fl_Text_Selection_mod oldSelection = mSecondary; - - mSecondary.set(start, end); - redisplay_selection(&oldSelection, &mSecondary); -} - - -/* - Deselect text. - */ -void Fl_Text_Buffer_mod::secondary_unselect() -{ - Fl_Text_Selection_mod oldSelection = mSecondary; - - mSecondary.mSelected = 0; - redisplay_selection(&oldSelection, &mSecondary); -} - - -/* - Return the selected range. - */ -int Fl_Text_Buffer_mod::secondary_selection_position(int *start, int *end) -{ - return mSecondary.position(start, end); -} - - -/* - Return a copy of the text in this selection. - */ -char *Fl_Text_Buffer_mod::secondary_selection_text() -{ - return selection_text_(&mSecondary); -} - - -/* - Remove the selected text. - */ -void Fl_Text_Buffer_mod::remove_secondary_selection() -{ - remove_selection_(&mSecondary); -} - - -/* - Replace selected text. - */ -void Fl_Text_Buffer_mod::replace_secondary_selection(const char *text) -{ - replace_selection_(&mSecondary, text); -} - - -/* - Highlight a range of text. - Start and End must be at a character boundary. - */ -void Fl_Text_Buffer_mod::highlight(int start, int end) -{ - Fl_Text_Selection_mod oldSelection = mHighlight; - - mHighlight.set(start, end); - redisplay_selection(&oldSelection, &mHighlight); -} - - -/* - Remove text highlighting. - */ -void Fl_Text_Buffer_mod::unhighlight() -{ - Fl_Text_Selection_mod oldSelection = mHighlight; - - mHighlight.mSelected = 0; - redisplay_selection(&oldSelection, &mHighlight); -} - - -/* - Return position of highlight. - */ -int Fl_Text_Buffer_mod::highlight_position(int *start, int *end) -{ - return mHighlight.position(start, end); -} - - -/* - Return a copy of highlighted text. - */ -char *Fl_Text_Buffer_mod::highlight_text() -{ - return selection_text_(&mHighlight); -} - - -/* - Add a callback that is called whenever text is modified. - */ -void Fl_Text_Buffer_mod::add_modify_callback(Fl_Text_Modify_Cb bufModifiedCB, - void *cbArg) -{ - Fl_Text_Modify_Cb *newModifyProcs = - new Fl_Text_Modify_Cb[mNModifyProcs + 1]; - void **newCBArgs = new void *[mNModifyProcs + 1]; - for (int i = 0; i < mNModifyProcs; i++) { - newModifyProcs[i + 1] = mModifyProcs[i]; - newCBArgs[i + 1] = mCbArgs[i]; - } - if (mNModifyProcs != 0) { - delete[]mModifyProcs; - delete[]mCbArgs; - } - newModifyProcs[0] = bufModifiedCB; - newCBArgs[0] = cbArg; - mNModifyProcs++; - mModifyProcs = newModifyProcs; - mCbArgs = newCBArgs; -} - - -/* - Remove a callback. - */ -void Fl_Text_Buffer_mod::remove_modify_callback(Fl_Text_Modify_Cb bufModifiedCB, - void *cbArg) -{ - int i, toRemove = -1; - - /* find the matching callback to remove */ - for (i = 0; i < mNModifyProcs; i++) { - if (mModifyProcs[i] == bufModifiedCB && mCbArgs[i] == cbArg) { - toRemove = i; - break; - } - } - if (toRemove == -1) { - Fl::error - ("Fl_Text_Buffer_mod::remove_modify_callback(): Can't find modify CB to remove"); - return; - } - - /* Allocate new lists for remaining callback procs and args (if - any are left) */ - mNModifyProcs--; - if (mNModifyProcs == 0) { - mNModifyProcs = 0; - delete[]mModifyProcs; - mModifyProcs = NULL; - delete[]mCbArgs; - mCbArgs = NULL; - return; - } - Fl_Text_Modify_Cb *newModifyProcs = new Fl_Text_Modify_Cb[mNModifyProcs]; - void **newCBArgs = new void *[mNModifyProcs]; - - /* copy out the remaining members and free the old lists */ - for (i = 0; i < toRemove; i++) { - newModifyProcs[i] = mModifyProcs[i]; - newCBArgs[i] = mCbArgs[i]; - } - for (; i < mNModifyProcs; i++) { - newModifyProcs[i] = mModifyProcs[i + 1]; - newCBArgs[i] = mCbArgs[i + 1]; - } - delete[]mModifyProcs; - delete[]mCbArgs; - mModifyProcs = newModifyProcs; - mCbArgs = newCBArgs; -} - - -/* - Add a callback that is called before deleting text. - */ -void Fl_Text_Buffer_mod::add_predelete_callback(Fl_Text_Predelete_Cb bufPreDeleteCB, - void *cbArg) -{ - Fl_Text_Predelete_Cb *newPreDeleteProcs = - new Fl_Text_Predelete_Cb[mNPredeleteProcs + 1]; - void **newCBArgs = new void *[mNPredeleteProcs + 1]; - for (int i = 0; i < mNPredeleteProcs; i++) { - newPreDeleteProcs[i + 1] = mPredeleteProcs[i]; - newCBArgs[i + 1] = mPredeleteCbArgs[i]; - } - if (!mNPredeleteProcs != 0) { - delete[]mPredeleteProcs; - delete[]mPredeleteCbArgs; - } - newPreDeleteProcs[0] = bufPreDeleteCB; - newCBArgs[0] = cbArg; - mNPredeleteProcs++; - mPredeleteProcs = newPreDeleteProcs; - mPredeleteCbArgs = newCBArgs; -} - - -/* - Remove a callback. - */ -void Fl_Text_Buffer_mod::remove_predelete_callback(Fl_Text_Predelete_Cb bufPreDeleteCB, void *cbArg) -{ - int i, toRemove = -1; - /* find the matching callback to remove */ - for (i = 0; i < mNPredeleteProcs; i++) { - if (mPredeleteProcs[i] == bufPreDeleteCB && - mPredeleteCbArgs[i] == cbArg) { - toRemove = i; - break; - } - } - if (toRemove == -1) { - Fl::error - ("Fl_Text_Buffer_mod::remove_predelete_callback(): Can't find pre-delete CB to remove"); - return; - } - - /* Allocate new lists for remaining callback procs and args (if - any are left) */ - mNPredeleteProcs--; - if (mNPredeleteProcs == 0) { - mNPredeleteProcs = 0; - delete[]mPredeleteProcs; - mPredeleteProcs = NULL; - delete[]mPredeleteCbArgs; - mPredeleteCbArgs = NULL; - return; - } - Fl_Text_Predelete_Cb *newPreDeleteProcs = - new Fl_Text_Predelete_Cb[mNPredeleteProcs]; - void **newCBArgs = new void *[mNPredeleteProcs]; - - /* copy out the remaining members and free the old lists */ - for (i = 0; i < toRemove; i++) { - newPreDeleteProcs[i] = mPredeleteProcs[i]; - newCBArgs[i] = mPredeleteCbArgs[i]; - } - for (; i < mNPredeleteProcs; i++) { - newPreDeleteProcs[i] = mPredeleteProcs[i + 1]; - newCBArgs[i] = mPredeleteCbArgs[i + 1]; - } - delete[]mPredeleteProcs; - delete[]mPredeleteCbArgs; - mPredeleteProcs = newPreDeleteProcs; - mPredeleteCbArgs = newCBArgs; -} - - -/* - Return a copy of the line that contains a given index. - Pos must be at a character boundary. - */ -char *Fl_Text_Buffer_mod::line_text(int pos) const { - return text_range(line_start(pos), line_end(pos)); -} - - -/* - Find the beginning of the line. - */ -int Fl_Text_Buffer_mod::line_start(int pos) const -{ - if (!findchar_backward(pos, '\n', &pos)) - return 0; - return pos + 1; -} - - -/* - Find the end of the line. - */ -int Fl_Text_Buffer_mod::line_end(int pos) const { - if (!findchar_forward(pos, '\n', &pos)) - pos = mLength; - return pos; -} - - -/* - Find the beginning of a word. - NOT UNICODE SAFE. - */ -int Fl_Text_Buffer_mod::word_start(int pos) const { - // FIXME: character is ucs-4 - while (pos>0 && (isalnum(char_at(pos)) || char_at(pos) == '_')) { - pos = prev_char(pos); - } - // FIXME: character is ucs-4 - if (!(isalnum(char_at(pos)) || char_at(pos) == '_')) - pos = next_char(pos); - return pos; -} - -/* -** Search backwards in buffer for characters in "searchChars", starting -** with the character BEFORE "startPos", returning the result in "foundPos" -** returns 1 if found, 0 if not. -*/ -int Fl_Text_Buffer_mod::findchars_backward( int startPos, const char *searchChars, - int *foundPos ) { - int pos = startPos; - const char *c; - char ch = 0; - - if ( startPos == 0 ) { - *foundPos = 0; - return 0; - } - while ( pos > 0 ) { - ch = char_at(pos); - for ( c = searchChars; *c != '\0'; c++ ) { - if ( ch == *c ) { - *foundPos = pos; - return 1; - } - } - pos = prev_char(pos); - } - *foundPos = 0; - return 0; -} - - -/* - Find the end of a word. - NOT UNICODE SAFE. - */ -int Fl_Text_Buffer_mod::word_end(int pos) const { - // FIXME: character is ucs-4 - while (pos < length() && (isalnum(char_at(pos)) || char_at(pos) == '_')) - { - pos = next_char(pos); - } - return pos; -} - -/* -** Search forwards in buffer for characters in "searchChars", starting -** with the character "startPos", and returning the result in "foundPos" -** returns 1 if found, 0 if not. -*/ -int Fl_Text_Buffer_mod::findchars_forward( int startPos, const char *searchChars, - int *foundPos ) { - int pos = startPos; - const char *c; - char ch = 0; - - while ( pos < length() ) { - ch = char_at(pos); - for ( c = searchChars; *c != '\0'; c++ ) { - if ( ch == *c ) { - *foundPos = pos; - return 1; - } - } - pos = next_char(pos); - } - *foundPos = length(); - return 0; -} - - -/* - Count the number of characters between two positions. - */ -int Fl_Text_Buffer_mod::count_displayed_characters(int lineStartPos, - int targetPos) const -{ - IS_UTF8_ALIGNED2(this, (lineStartPos)) - IS_UTF8_ALIGNED2(this, (targetPos)) - - int charCount = 0; - - int pos = lineStartPos; - while (pos < targetPos) { - pos = next_char(pos); - charCount++; - } - return charCount; -} - - -/* - Skip ahead a number of characters from a given index. - This function breaks early if it encounters a newline character. - */ -int Fl_Text_Buffer_mod::skip_displayed_characters(int lineStartPos, int nChars) -{ - IS_UTF8_ALIGNED2(this, (lineStartPos)) - - int pos = lineStartPos; - - for (int charCount = 0; charCount < nChars && pos < mLength; charCount++) { - unsigned int c = char_at(pos); - if (c == '\n') - return pos; - pos = next_char(pos); - } - return pos; -} - - -/* - Count the number of newline characters between start and end. - startPos and endPos must be at a character boundary. - This function is optimized for speed by not using UTF-8 calls. - */ -int Fl_Text_Buffer_mod::count_lines(int startPos, int endPos) const { - IS_UTF8_ALIGNED2(this, (startPos)) - IS_UTF8_ALIGNED2(this, (endPos)) - - int gapLen = mGapEnd - mGapStart; - int lineCount = 0; - - int pos = startPos; - while (pos < mGapStart) - { - if (pos == endPos) - return lineCount; - if (mBuf[pos++] == '\n') - lineCount++; - } - while (pos < mLength) { - if (pos == endPos) - return lineCount; - if (mBuf[pos++ + gapLen] == '\n') - lineCount++; - } - return lineCount; -} - - -/* - Skip to the first character, n lines ahead. - StartPos must be at a character boundary. - This function is optimized for speed by not using UTF-8 calls. - */ -int Fl_Text_Buffer_mod::skip_lines(int startPos, int nLines) -{ - IS_UTF8_ALIGNED2(this, (startPos)) - - if (nLines == 0) - return startPos; - - int gapLen = mGapEnd - mGapStart; - int pos = startPos; - int lineCount = 0; - while (pos < mGapStart) { - if (mBuf[pos++] == '\n') { - lineCount++; - if (lineCount == nLines) { - IS_UTF8_ALIGNED2(this, (pos)) - return pos; - } - } - } - while (pos < mLength) { - if (mBuf[pos++ + gapLen] == '\n') { - lineCount++; - if (lineCount >= nLines) { - IS_UTF8_ALIGNED2(this, (pos)) - return pos; - } - } - } - IS_UTF8_ALIGNED2(this, (pos)) - return pos; -} - - -/* - Skip to the first character, n lines back. - StartPos must be at a character boundary. - This function is optimized for speed by not using UTF-8 calls. - */ -int Fl_Text_Buffer_mod::rewind_lines(int startPos, int nLines) -{ - IS_UTF8_ALIGNED2(this, (startPos)) - - int pos = startPos - 1; - if (pos <= 0) - return 0; - - int gapLen = mGapEnd - mGapStart; - int lineCount = -1; - while (pos >= mGapStart) { - if (mBuf[pos + gapLen] == '\n') { - if (++lineCount >= nLines) { - IS_UTF8_ALIGNED2(this, (pos+1)) - return pos + 1; - } - } - pos--; - } - while (pos >= 0) { - if (mBuf[pos] == '\n') { - if (++lineCount >= nLines) { - IS_UTF8_ALIGNED2(this, (pos+1)) - return pos + 1; - } - } - pos--; - } - return 0; -} - - -/* - Find a matching std::string in the buffer. - */ -int Fl_Text_Buffer_mod::search_forward(int startPos, const char *searchstring, - int *foundPos, int matchCase) const -{ - IS_UTF8_ALIGNED2(this, (startPos)) - IS_UTF8_ALIGNED(searchstring) - - if (!searchstring) - return 0; - int bp; - const char *sp; - if (matchCase) { - while (startPos < length()) { - bp = startPos; - sp = searchstring; - for (;;) { - char c = *sp; - // we reached the end of the "needle", so we found the std::string! - if (!c) { - *foundPos = startPos; - return 1; - } - int l = fl_utf8len1(c); - if (memcmp(sp, address(bp), l)) - break; - sp += l; bp += l; - } - startPos = next_char(startPos); - } - } else { - while (startPos < length()) { - bp = startPos; - sp = searchstring; - for (;;) { - // we reached the end of the "needle", so we found the std::string! - if (!*sp) { - *foundPos = startPos; - return 1; - } - int l; - unsigned int b = char_at(bp); - unsigned int s = fl_utf8decode(sp, 0, &l); - if (fl_tolower(b)!=fl_tolower(s)) - break; - sp += l; - bp = next_char(bp); - } - startPos = next_char(startPos); - } - } - return 0; -} - -int Fl_Text_Buffer_mod::search_backward(int startPos, const char *searchstring, - int *foundPos, int matchCase) const -{ - IS_UTF8_ALIGNED2(this, (startPos)) - IS_UTF8_ALIGNED(searchstring) - - if (!searchstring) - return 0; - int bp; - const char *sp; - if (matchCase) { - while (startPos >= 0) { - bp = startPos; - sp = searchstring; - for (;;) { - char c = *sp; - // we reached the end of the "needle", so we found the std::string! - if (!c) { - *foundPos = startPos; - return 1; - } - int l = fl_utf8len1(c); - if (memcmp(sp, address(bp), l)) - break; - sp += l; bp += l; - } - startPos = prev_char(startPos); - } - } else { - while (startPos >= 0) { - bp = startPos; - sp = searchstring; - for (;;) { - // we reached the end of the "needle", so we found the std::string! - if (!*sp) { - *foundPos = startPos; - return 1; - } - int l; - unsigned int b = char_at(bp); - unsigned int s = fl_utf8decode(sp, 0, &l); - if (fl_tolower(b)!=fl_tolower(s)) - break; - sp += l; - bp = next_char(bp); - } - startPos = prev_char(startPos); - } - } - return 0; -} - - - -/* - Insert a std::string into the buffer. - Pos must be at a character boundary. Text must be a correct UTF-8 std::string. - */ -int Fl_Text_Buffer_mod::insert_(int pos, const char *text) -{ - if (!text || !*text) - return 0; - - int insertedLength = strlen(text); - - /* Prepare the buffer to receive the new text. If the new text fits in - the current buffer, just move the gap (if necessary) to where - the text should be inserted. If the new text is too large, reallocate - the buffer with a gap large enough to accomodate the new text and a - gap of mPreferredGapSize */ - if (insertedLength > mGapEnd - mGapStart) - reallocate_with_gap(pos, insertedLength + mPreferredGapSize); - else if (pos != mGapStart) - move_gap(pos); - - /* Insert the new text (pos now corresponds to the start of the gap) */ - memcpy(&mBuf[pos], text, insertedLength); - mGapStart += insertedLength; - mLength += insertedLength; - update_selections(pos, 0, insertedLength); - - if (mCanUndo) { - if (undowidget == this && undoat == pos && undoinsert) { - undoinsert += insertedLength; - } else { - undoinsert = insertedLength; - undoyankcut = (undoat == pos) ? undocut : 0; - } - undoat = pos + insertedLength; - undocut = 0; - undowidget = this; - } - - return insertedLength; -} - - -/* - Remove a std::string from the buffer. - Unicode safe. Start and end must be at a character boundary. - */ -void Fl_Text_Buffer_mod::remove_(int start, int end) -{ - /* if the gap is not contiguous to the area to remove, move it there */ - - if (mCanUndo) { - if (undowidget == this && undoat == end && undocut) { - undobuffersize(undocut + end - start + 1); - memmove(undobuffer + end - start, undobuffer, undocut); - undocut += end - start; - } else { - undocut = end - start; - undobuffersize(undocut); - } - undoat = start; - undoinsert = 0; - undoyankcut = 0; - undowidget = this; - } - - if (start > mGapStart) { - if (mCanUndo) - memcpy(undobuffer, mBuf + (mGapEnd - mGapStart) + start, - end - start); - move_gap(start); - } else if (end < mGapStart) { - if (mCanUndo) - memcpy(undobuffer, mBuf + start, end - start); - move_gap(end); - } else { - int prelen = mGapStart - start; - if (mCanUndo) { - memcpy(undobuffer, mBuf + start, prelen); - memcpy(undobuffer + prelen, mBuf + mGapEnd, end - start - prelen); - } - } - - /* expand the gap to encompass the deleted characters */ - mGapEnd += end - mGapStart; - mGapStart -= mGapStart - start; - - /* update the length */ - mLength -= end - start; - - /* fix up any selections which might be affected by the change */ - update_selections(start, end - start, 0); -} - - -/* - simple setter. - Unicode safe. Start and end must be at a character boundary. - */ -void Fl_Text_Selection_mod::set(int startpos, int endpos) -{ - mSelected = startpos != endpos; - mStart = min(startpos, endpos); - mEnd = max(startpos, endpos); -} - - -/* - simple getter. - Unicode safe. Start and end will be at a character boundary. - */ -int Fl_Text_Selection_mod::position(int *startpos, int *endpos) const { - if (!mSelected) - return 0; - *startpos = mStart; - *endpos = mEnd; - - return 1; -} - - -/* - Return if a position is inside the selected area. - Unicode safe. Pos must be at a character boundary. - */ -int Fl_Text_Selection_mod::includes(int pos) const { - return (selected() && pos >= start() && pos < end() ); -} - - -/* - Return a duplicate of the selected text, or an empty std::string. - Unicode safe. - */ -char *Fl_Text_Buffer_mod::selection_text_(Fl_Text_Selection_mod * sel) const { - int start, end; - - /* If there's no selection, return an allocated empty std::string */ - if (!sel->position(&start, &end)) - { - char *s = (char *) malloc(1); - *s = '\0'; - return s; - } - - /* Return the selected range */ - return text_range(start, end); -} - - -/* - Remove the selected text. - Unicode safe. - */ -void Fl_Text_Buffer_mod::remove_selection_(Fl_Text_Selection_mod * sel) -{ - int start, end; - - if (!sel->position(&start, &end)) - return; - remove(start, end); - //undoyankcut = undocut; -} - - -/* - Replace selection with text. - Unicode safe. - */ -void Fl_Text_Buffer_mod::replace_selection_(Fl_Text_Selection_mod * sel, - const char *text) -{ - Fl_Text_Selection_mod oldSelection = *sel; - - /* If there's no selection, return */ - int start, end; - if (!sel->position(&start, &end)) - return; - - /* Do the appropriate type of replace */ - replace(start, end, text); - - /* Unselect (happens automatically in BufReplace, but BufReplaceRect - can't detect when the contents of a selection goes away) */ - sel->mSelected = 0; - redisplay_selection(&oldSelection, sel); -} - - -/* - Call all callbacks. - Unicode safe. - */ -void Fl_Text_Buffer_mod::call_modify_callbacks(int pos, int nDeleted, - int nInserted, int nRestyled, - const char *deletedText) const { - IS_UTF8_ALIGNED2(this, pos) - for (int i = 0; i < mNModifyProcs; i++) - (*mModifyProcs[i]) (pos, nInserted, nDeleted, nRestyled, - deletedText, mCbArgs[i]); -} - - -/* - Call all callbacks. - Unicode safe. - */ -void Fl_Text_Buffer_mod::call_predelete_callbacks(int pos, int nDeleted) const { - for (int i = 0; i < mNPredeleteProcs; i++) - (*mPredeleteProcs[i]) (pos, nDeleted, mPredeleteCbArgs[i]); -} - - -/* - Redisplay a new selected area. - Unicode safe. - */ -void Fl_Text_Buffer_mod::redisplay_selection(Fl_Text_Selection_mod * - oldSelection, - Fl_Text_Selection_mod * - newSelection) const -{ - int oldStart, oldEnd, newStart, newEnd, ch1Start, ch1End, ch2Start, - ch2End; - - /* If either selection is rectangular, add an additional character to - the end of the selection to request the redraw routines to wipe out - the parts of the selection beyond the end of the line */ - oldStart = oldSelection->mStart; - newStart = newSelection->mStart; - oldEnd = oldSelection->mEnd; - newEnd = newSelection->mEnd; - - /* If the old or new selection is unselected, just redisplay the - single area that is (was) selected and return */ - if (!oldSelection->mSelected && !newSelection->mSelected) - return; - if (!oldSelection->mSelected) - { - call_modify_callbacks(newStart, 0, 0, newEnd - newStart, NULL); - return; - } - if (!newSelection->mSelected) { - call_modify_callbacks(oldStart, 0, 0, oldEnd - oldStart, NULL); - return; - } - - /* If the selections are non-contiguous, do two separate updates - and return */ - if (oldEnd < newStart || newEnd < oldStart) { - call_modify_callbacks(oldStart, 0, 0, oldEnd - oldStart, NULL); - call_modify_callbacks(newStart, 0, 0, newEnd - newStart, NULL); - return; - } - - /* Otherwise, separate into 3 separate regions: ch1, and ch2 (the two - changed areas), and the unchanged area of their intersection, - and update only the changed area(s) */ - ch1Start = min(oldStart, newStart); - ch2End = max(oldEnd, newEnd); - ch1End = max(oldStart, newStart); - ch2Start = min(oldEnd, newEnd); - if (ch1Start != ch1End) - call_modify_callbacks(ch1Start, 0, 0, ch1End - ch1Start, NULL); - if (ch2Start != ch2End) - call_modify_callbacks(ch2Start, 0, 0, ch2End - ch2Start, NULL); -} - - -/* - Move the gap around without changing buffer content. - Unicode safe. Pos must be at a character boundary. - */ -void Fl_Text_Buffer_mod::move_gap(int pos) -{ - int gapLen = mGapEnd - mGapStart; - - if (pos > mGapStart) - memmove(&mBuf[mGapStart], &mBuf[mGapEnd], pos - mGapStart); - else - memmove(&mBuf[pos + gapLen], &mBuf[pos], mGapStart - pos); - mGapEnd += pos - mGapStart; - mGapStart += pos - mGapStart; -} - - -/* - Create a larger gap. - Unicode safe. Start must be at a character boundary. - */ -void Fl_Text_Buffer_mod::reallocate_with_gap(int newGapStart, int newGapLen) -{ - char *newBuf = (char *) malloc(mLength + newGapLen); - int newGapEnd = newGapStart + newGapLen; - - if (newGapStart <= mGapStart) { - memcpy(newBuf, mBuf, newGapStart); - memcpy(&newBuf[newGapEnd], &mBuf[newGapStart], - mGapStart - newGapStart); - memcpy(&newBuf[newGapEnd + mGapStart - newGapStart], - &mBuf[mGapEnd], mLength - mGapStart); - } else { /* newGapStart > mGapStart */ - memcpy(newBuf, mBuf, mGapStart); - memcpy(&newBuf[mGapStart], &mBuf[mGapEnd], newGapStart - mGapStart); - memcpy(&newBuf[newGapEnd], - &mBuf[mGapEnd + newGapStart - mGapStart], - mLength - newGapStart); - } - free((void *) mBuf); - mBuf = newBuf; - mGapStart = newGapStart; - mGapEnd = newGapEnd; - } - - -/* - Update selection range if characters were inserted. - Unicode safe. Pos must be at a character boundary. - */ -void Fl_Text_Buffer_mod::update_selections(int pos, int nDeleted, - int nInserted) -{ - mPrimary.update(pos, nDeleted, nInserted); - mSecondary.update(pos, nDeleted, nInserted); - mHighlight.update(pos, nDeleted, nInserted); -} - - -// unicode safe, assuming the arguments are on character boundaries -void Fl_Text_Selection_mod::update(int pos, int nDeleted, int nInserted) -{ - if (!mSelected || pos > mEnd) - return; - if (pos + nDeleted <= mStart) { - mStart += nInserted - nDeleted; - mEnd += nInserted - nDeleted; - } else if (pos <= mStart && pos + nDeleted >= mEnd) { - mStart = pos; - mEnd = pos; - mSelected = 0; - } else if (pos <= mStart && pos + nDeleted < mEnd) { - mStart = pos; - mEnd = nInserted + mEnd - nDeleted; - } else if (pos < mEnd) { - mEnd += nInserted - nDeleted; - if (mEnd <= mStart) - mSelected = 0; - } -} - - -/* - Find a UCS-4 character. - StartPos must be at a character boundary, searchChar is UCS-4 encoded. - */ -int Fl_Text_Buffer_mod::findchar_forward(int startPos, unsigned searchChar, - int *foundPos) const -{ - if (startPos >= mLength) { - *foundPos = mLength; - return 0; - } - - if (startPos<0) - startPos = 0; - - for ( ; startPos mLength) - startPos = mLength; - - for (startPos = prev_char(startPos); startPos>=0; startPos = prev_char(startPos)) { - if (searchChar == char_at(startPos)) { - *foundPos = startPos; - return 1; - } - } - - *foundPos = 0; - return 0; -} - -//#define EXAMPLE_ENCODING // shows how to process any encoding for which a decoding function exists -#ifdef EXAMPLE_ENCODING - -// returns the UCS equivalent of *p in CP1252 and advances p by 1 -unsigned cp1252toucs(char* &p) -{ - // Codes 0x80..0x9f from the Microsoft CP1252 character set, translated - // to Unicode - static unsigned cp1252[32] = { - 0x20ac, 0x0081, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021, - 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008d, 0x017d, 0x008f, - 0x0090, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, - 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x009d, 0x017e, 0x0178 - }; - unsigned char uc = *(unsigned char*)p; - p++; - return (uc < 0x80 || uc >= 0xa0 ? uc : cp1252[uc - 0x80]); -} - -// returns the UCS equivalent of *p in UTF-16 and advances p by 2 (or more for surrogates) -unsigned utf16toucs(char* &p) -{ - union { -#if WORDS_BIGENDIAN - struct { unsigned char a, b;} chars; -#else - struct { unsigned char b, a;} chars; -#endif - U16 short_val; - } u; - u.chars.a = *(unsigned char*)p++; - u.chars.b = *(unsigned char*)p++; - return u.short_val; -} - -// filter that produces, from an input stream fed by reading from fp, -// a UTF-8-encoded output stream written in buffer. -// Input can be any (e.g., 8-bit, UTF-16) encoding. -// Output is true UTF-8. -// p_trf points to a function that transforms encoded byte(s) into one UCS -// and that increases the pointer by the adequate quantity -static int general_input_filter(char *buffer, int buflen, - char *line, int sline, char* &endline, - unsigned (*p_trf)(char* &), - FILE *fp) -{ - char *p, *q, multibyte[5]; - int lq, r, offset; - p = endline = line; - q = buffer; - while (q < buffer + buflen) { - if (p >= endline) { - r = fread(line, 1, sline, fp); - endline = line + r; - if (r == 0) return q - buffer; - p = line; - } - if (q + 4 /*max width of utf-8 char*/ > buffer + buflen) { - memmove(line, p, endline - p); - endline -= (p - line); - return q - buffer; - } - lq = fl_utf8encode( p_trf(p), multibyte ); - memcpy(q, multibyte, lq); - q += lq; - } - memmove(line, p, endline - p); - endline -= (p - line); - return q - buffer; -} -#endif // EXAMPLE_ENCODING - -/* - filter that produces, from an input stream fed by reading from fp, - a UTF-8-encoded output stream written in buffer. - Input can be UTF-8. If it is not, it is decoded with CP1252. - Output is UTF-8. - *input_was_changed is set to true if the input was not strict UTF-8 so output - differs from input. - */ -static int utf8_input_filter(char *buffer, int buflen, char *line, int sline, char* &endline, - FILE *fp, int *input_was_changed) -{ - char *p, *q, multibyte[5]; - int l, lp, lq, r; - unsigned u; - p = endline = line; - q = buffer; - while (q < buffer + buflen) { - if (p >= endline) { - r = fread(line, 1, sline, fp); - endline = line + r; - if (r == 0) return q - buffer; - p = line; - } - l = fl_utf8len1(*p); - if (p + l > endline) { - memmove(line, p, endline - p); - endline -= (p - line); - r = fread(endline, 1, sline - (endline - line), fp); - endline += r; - p = line; - if (endline - line < l) break; - } - while ( l > 0) { - u = fl_utf8decode(p, p+l, &lp); - lq = fl_utf8encode(u, multibyte); - if (lp != l || lq != l) *input_was_changed = true; - if (q + lq > buffer + buflen) { - memmove(line, p, endline - p); - endline -= (p - line); - return q - buffer; - } - memcpy(q, multibyte, lq); - q += lq; - p += lp; - l -= lp; - } - } - memmove(line, p, endline - p); - endline -= (p - line); - return q - buffer; -} - -const char *Fl_Text_Buffer_mod::file_encoding_warning_message = -"Displayed text contains the UTF-8 transcoding\n" -"of the input file which was not UTF-8 encoded.\n" -"Some changes may have occurred."; - -/* - Insert text from a file. - Input file can be of various encodings according to what input fiter is used. - utf8_input_filter accepts UTF-8 or CP1252 as input encoding. - Output is always UTF-8. - */ - int Fl_Text_Buffer_mod::insertfile(const char *file, int pos, int buflen) -{ - FILE *fp; - if (!(fp = fl_fopen(file, "r"))) - return 1; - char *buffer = new char[buflen + 1]; - char *endline, line[100]; - int l; - input_file_was_transcoded = false; - endline = line; - while (true) { -#ifdef EXAMPLE_ENCODING - // example of 16-bit encoding: UTF-16 - l = general_input_filter(buffer, buflen, - line, sizeof(line), endline, - utf16toucs, // use cp1252toucs to read CP1252-encoded files - fp); - input_file_was_transcoded = true; -#else - l = utf8_input_filter(buffer, buflen, line, sizeof(line), endline, - fp, &input_file_was_transcoded); -#endif - if (l == 0) break; - buffer[l] = 0; - insert(pos, buffer); - pos += l; - } - int e = ferror(fp) ? 2 : 0; - fclose(fp); - delete[]buffer; - if ( (!e) && input_file_was_transcoded && transcoding_warning_action) { - transcoding_warning_action(this); - } - return e; -} - - -/* - Write text to file. - Unicode safe. - */ -int Fl_Text_Buffer_mod::outputfile(const char *file, - int start, int end, - int buflen) { - FILE *fp; - if (!(fp = fl_fopen(file, "w"))) - return 1; - for (int n; (n = min(end - start, buflen)); start += n) { - const char *p = text_range(start, start + n); - int r = fwrite(p, 1, n, fp); - free((void *) p); - if (r != n) - break; - } - - int e = ferror(fp) ? 2 : 0; - fclose(fp); - return e; -} - - -/* - Return the previous character position. - Unicode safe. - */ -int Fl_Text_Buffer_mod::prev_char_clipped(int pos) const -{ - if (pos<=0) - return 0; - - IS_UTF8_ALIGNED2(this, (pos)) - - char c; - do { - pos--; - if (pos==0) - return 0; - c = byte_at(pos); - } while ( (c&0xc0) == 0x80); - - IS_UTF8_ALIGNED2(this, (pos)) - return pos; -} - - -/* - Return the previous character position. - Returns -1 if the beginning of the buffer is reached. - */ -int Fl_Text_Buffer_mod::prev_char(int pos) const -{ - if (pos==0) return -1; - return prev_char_clipped(pos); -} - - -/* - Return the next character position. - Returns length() if the end of the buffer is reached. - */ -int Fl_Text_Buffer_mod::next_char(int pos) const -{ - IS_UTF8_ALIGNED2(this, (pos)) - int n = fl_utf8len1(byte_at(pos)); - pos += n; - if (pos>=mLength) - return mLength; - IS_UTF8_ALIGNED2(this, (pos)) - return pos; -} - - -/* - Return the next character position. - If the end of the buffer is reached, it returns the current position. - */ -int Fl_Text_Buffer_mod::next_char_clipped(int pos) const -{ - return next_char(pos); -} - -/* - Align an index to the current UTF-8 boundary. - */ -int Fl_Text_Buffer_mod::utf8_align(int pos) const -{ - char c = byte_at(pos); - while ( (c&0xc0) == 0x80) { - pos--; - c = byte_at(pos); - } - return pos; -} - -// -// End of "$Id: Fl_Text_Buffer_mod.cxx 8040 2010-12-15 17:38:39Z manolo $". -// diff --git a/src/widgets/Fl_Text_Display_mod.cxx b/src/widgets/Fl_Text_Display_mod.cxx index 69c5035..274b67c 100644 --- a/src/widgets/Fl_Text_Display_mod.cxx +++ b/src/widgets/Fl_Text_Display_mod.cxx @@ -1,27 +1,3808 @@ -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ // -// This file is part of flmsg +// "$Id: Fl_Text_Display_mod.cxx 8808 2011-06-16 13:31:25Z manolo $" // -// flrig 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. +// Copyright 2001-2010 by Bill Spitzak and others. +// Original code Copyright Mark Edel. Permission to distribute under +// the LGPL for the FLTK library granted by Mark Edel. // -// flrig is distributed in the hope that it will be useful, +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Library General Public +// License as published by the Free Software Foundation; either +// version 2 of the License, or (at your option) any later version. +// +// This library 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. +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Library 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 . -// ---------------------------------------------------------------------------- +// You should have received a copy of the GNU Library General Public +// License along with this library; if not, write to the +// +// Free Software Foundation, Inc. +// 51 Franklin Street, Fifth Floor +// Boston, MA 02110-1301 USA. +// +// Please report all bugs and problems on the following page: +// +// http://www.fltk.org/str.php +// + +// TODO: rendering of the "optional hyphen" +// TODO: make line numbering work again + +#include +#include +#include +#include "missing_strings.h" +#include +#include +#include +#include +#include +#include "Fl_Text_Buffer_mod.H" +#include "Fl_Text_Display_mod.H" #include -#if FLMSG_FLTK_API_MINOR < 3 -# include "Fl_Text_Display_mod_1_1.cxx" -#else -# include "Fl_Text_Display_mod_1_3.cxx" +#if FLCLUSTER_FLTK_API_MAJOR == 1 && FLCLUSTER_FLTK_API_MINOR < 3 +# error "FLTK versions less then 1.3 are no longer supported" #endif + +#undef min +#undef max + +// Text area margins. Left & right margins should be at least 3 so that +// there is some room for the overhanging parts of the cursor! +const int Fl_Text_Display_mod::DEFAULT_TOP_MARGIN = 1; +const int Fl_Text_Display_mod::DEFAULT_BOTTOM_MARGIN = 1; +const int Fl_Text_Display_mod::DEFAULT_LEFT_MARGIN = 3; +const int Fl_Text_Display_mod::DEFAULT_RIGHT_MARGIN = 3; +//#define TOP_MARGIN 1 +//#define BOTTOM_MARGIN 1 +//#define LEFT_MARGIN 3 +//#define RIGHT_MARGIN 3 + +#define NO_HINT -1 + +/* Masks for text drawing methods. These are or'd together to form an + integer which describes what drawing calls to use to draw a string */ +#define FILL_MASK 0x0100 +#define SECONDARY_MASK 0x0200 +#define PRIMARY_MASK 0x0400 +#define HIGHLIGHT_MASK 0x0800 +#define BG_ONLY_MASK 0x1000 +#define TEXT_ONLY_MASK 0x2000 +#define STYLE_LOOKUP_MASK 0xff + +/* Maximum displayable line length (how many characters will fit across the + widest window). This amount of memory is temporarily allocated from the + stack in the draw_vline() method for drawing strings */ +#define MAX_DISP_LINE_LEN 1000 + +static int max( int i1, int i2 ); +static int min( int i1, int i2 ); +static int countlines( const char *string ); + +/* The variables below are used in a timer event to allow smooth + scrolling of the text area when the pointer has left the area. */ +static int scroll_direction = 0; +static int scroll_amount = 0; +static int scroll_y = 0; +static int scroll_x = 0; + +// CET - FIXME +#define TMPFONTWIDTH 6 + + + +/** + \brief Creates a new text display widget. + + \param X, Y, W, H position and size of widget + \param l label text, defaults to none + */ +Fl_Text_Display_mod::Fl_Text_Display_mod(int X, int Y, int W, int H, const char* l) +: Fl_Group(X, Y, W, H, l) { + int i; + + TOP_MARGIN = DEFAULT_TOP_MARGIN; + BOTTOM_MARGIN = DEFAULT_BOTTOM_MARGIN; + LEFT_MARGIN = DEFAULT_LEFT_MARGIN; + RIGHT_MARGIN = DEFAULT_RIGHT_MARGIN; + + mMaxsize = 0; + damage_range1_start = damage_range1_end = -1; + damage_range2_start = damage_range2_end = -1; + dragPos = dragging = 0; + dragType = DRAG_CHAR; + display_insert_position_hint = 0; + shortcut_ = 0; + + color(FL_BACKGROUND2_COLOR, FL_SELECTION_COLOR); + box(FL_DOWN_FRAME); + textsize(FL_NORMAL_SIZE); + textcolor(FL_FOREGROUND_COLOR); + textfont(FL_HELVETICA); + set_flag(SHORTCUT_LABEL); + + text_area.x = 0; + text_area.y = 0; + text_area.w = 0; + text_area.h = 0; + + mVScrollBar = new Fl_Scrollbar(0,0,1,1); + mVScrollBar->callback((Fl_Callback*)v_scrollbar_cb, this); + mHScrollBar = new Fl_Scrollbar(0,0,1,1); + mHScrollBar->callback((Fl_Callback*)h_scrollbar_cb, this); + mHScrollBar->type(FL_HORIZONTAL); + + end(); + + scrollbar_width(Fl::scrollbar_size()); + scrollbar_align(FL_ALIGN_BOTTOM_RIGHT); + + mCursorOn = 0; + mCursorPos = 0; + mCursorOldY = -100; + mCursorToHint = NO_HINT; + mCursorStyle = NORMAL_CURSOR; + mCursorPreferredXPos = -1; + mBuffer = 0; + mFirstChar = 0; + mLastChar = 0; + mNBufferLines = 0; + mTopLineNum = mTopLineNumHint = 1; + mAbsTopLineNum = 1; + mNeedAbsTopLineNum = 0; + mHorizOffset = mHorizOffsetHint = 0; + + mCursor_color = FL_FOREGROUND_COLOR; + + mStyleBuffer = 0; + mStyleTable = 0; + mNStyles = 0; + mNVisibleLines = 1; + mLineStarts = new int[mNVisibleLines]; + mLineStarts[0] = 0; + for (i=1; iremove_modify_callback(buffer_modified_cb, this); + // mBuffer->remove_predelete_callback(buffer_predelete_cb, this); + // } + if (mLineStarts) delete[] mLineStarts; +} + + + +/** + Attach a text buffer to display, replacing the current buffer (if any) + \param buf attach this text buffer + */ +void Fl_Text_Display_mod::buffer( Fl_Text_Buffer_mod *buf ) { + /* If the text display is already displaying a buffer, clear it off + of the display and remove our callback from it */ + if ( buf == mBuffer) return; + if ( mBuffer != 0 ) { + // we must provide a copy of the buffer that we are deleting! + char *deletedText = mBuffer->text(); + buffer_modified_cb( 0, 0, mBuffer->length(), 0, deletedText, this ); + free(deletedText); + mNBufferLines = 0; + mBuffer->remove_modify_callback( buffer_modified_cb, this ); + mBuffer->remove_predelete_callback( buffer_predelete_cb, this ); + } + + /* Add the buffer to the display, and attach a callback to the buffer for + receiving modification information when the buffer contents change */ + mBuffer = buf; + if (mBuffer) { + mBuffer->add_modify_callback( buffer_modified_cb, this ); + mBuffer->add_predelete_callback( buffer_predelete_cb, this ); + + /* Update the display */ + buffer_modified_cb( 0, buf->length(), 0, 0, 0, this ); + } + + /* Resize the widget to update the screen... */ + resize(x(), y(), w(), h()); +} + + + +/** + \brief Attach (or remove) highlight information in text display and redisplay. + + Highlighting information consists of a style buffer which parallels the + normal text buffer, but codes font and color information for the display; + a style table which translates style buffer codes (indexed by buffer + character - 'A') into fonts and colors; and a callback mechanism for + as-needed highlighting, triggered by a style buffer entry of + "unfinishedStyle". Style buffer can trigger additional redisplay during + a normal buffer modification if the buffer contains a primary Fl_Text_Selection + (see extendRangeForStyleMods for more information on this protocol). + + Style buffers, tables and their associated memory are managed by the caller. + + Styles are ranged from 65 ('A') to 126. + + \param styleBuffer this buffer works in parallel to the text buffer. For every + character in the text buffer, the stye buffer has a byte at the same offset + that contains an index into an array of possible styles. + \param styleTable a list of styles indexed by the style buffer + \param nStyles number of styles in the style table + \param unfinishedStyle if this style is found, the callback below is called + \param unfinishedHighlightCB if a character with an unfinished style is found, + this callback will be called + \param cbArg and optional argument for the callback above, usually a pointer + to the Text Display. + */ +void Fl_Text_Display_mod::highlight_data(Fl_Text_Buffer_mod *styleBuffer, + const Style_Table_Entry *styleTable, + int nStyles, char unfinishedStyle, + Unfinished_Style_Cb unfinishedHighlightCB, + void *cbArg ) { + mStyleBuffer = styleBuffer; + mStyleTable = styleTable; + mNStyles = nStyles; + mUnfinishedStyle = unfinishedStyle; + mUnfinishedHighlightCB = unfinishedHighlightCB; + mHighlightCBArg = cbArg; + mColumnScale = 0; + + mStyleBuffer->canUndo(0); + damage(FL_DAMAGE_EXPOSE); +} + + + +/** + \brief Find the longest line of all visible lines. + \return the width of the longest visible line in pixels + */ +int Fl_Text_Display_mod::longest_vline() const { + int longest = 0; + for (int i = 0; i < mNVisibleLines; i++) + longest = max(longest, measure_vline(i)); + return longest; +} + + + +/** + \brief Change the size of the displayed text area. + Calling this function will trigger a recalculation of all lines visible and + of all scrollbar sizes. + \param X, Y, W, H new position and size of this widget + */ +void Fl_Text_Display_mod::resize(int X, int Y, int W, int H) { +#ifdef DEBUG + printf("Fl_Text_Display_mod::resize(X=%d, Y=%d, W=%d, H=%d)\n", X, Y, W, H); +#endif // DEBUG + const int oldWidth = w(); +#ifdef DEBUG + printf(" oldWidth=%d, mContinuousWrap=%d, mWrapMargin=%d\n", oldWidth, mContinuousWrap, mWrapMarginPix); +#endif // DEBUG + Fl_Widget::resize(X,Y,W,H); + if (!buffer()) return; + X += Fl::box_dx(box()); + Y += Fl::box_dy(box()); + W -= Fl::box_dw(box()); + H -= Fl::box_dh(box()); + + text_area.x = X+LEFT_MARGIN; + text_area.y = Y+TOP_MARGIN; + text_area.w = W-LEFT_MARGIN-RIGHT_MARGIN - (mVScrollBar->visible() ? scrollbar_width() : 0); + text_area.h = H-TOP_MARGIN-BOTTOM_MARGIN - (mHScrollBar->visible() ? scrollbar_width() : 0); + int i; + + if (!mStyleTable) + return; + + /* Find the new maximum font height for this text display */ + for (i = 0, mMaxsize = fl_height(textfont(), textsize()); i < mNStyles; i++) + mMaxsize = max(mMaxsize, fl_height(mStyleTable[i].font, mStyleTable[i].size)); + + // did we have scrollbars initially? + unsigned int hscrollbarvisible = mHScrollBar->visible(); + unsigned int vscrollbarvisible = mVScrollBar->visible(); + + // try without scrollbars first + mVScrollBar->clear_visible(); + mHScrollBar->clear_visible(); + + for (int again = 1; again;) { + again = 0; + /* In continuous wrap mode, a change in width affects the total number of + lines in the buffer, and can leave the top line number incorrect, and + the top character no longer pointing at a valid line start */ + if (!mFastDisplay && mContinuousWrap && !mWrapMarginPix && W!=oldWidth) { + int oldFirstChar = mFirstChar; + mNBufferLines = count_lines(0, buffer()->length(), true); + mFirstChar = line_start(mFirstChar); + mTopLineNum = count_lines(0, mFirstChar, true)+1; + absolute_top_line_number(oldFirstChar); +#ifdef DEBUG + printf(" mNBufferLines=%d\n", mNBufferLines); +#endif // DEBUG + } + + /* reallocate and update the line starts array, which may have changed + size and / or contents. */ + int nvlines = (text_area.h + mMaxsize - 1) / mMaxsize; + if (nvlines < 1) nvlines = 1; + if (mNVisibleLines != nvlines) { + mNVisibleLines = nvlines; + if (mLineStarts) delete[] mLineStarts; + mLineStarts = new int [mNVisibleLines]; + } + + calc_line_starts(0, mNVisibleLines); + calc_last_char(); + + // figure the scrollbars + if (scrollbar_width()) { + /* Decide if the vertical scrollbar needs to be visible */ + // always display vertical scroll bar + // if (scrollbar_align() & (FL_ALIGN_LEFT|FL_ALIGN_RIGHT) && + // mNBufferLines >= mNVisibleLines - 1) + { + mVScrollBar->set_visible(); + if (scrollbar_align() & FL_ALIGN_LEFT) { + text_area.x = X+scrollbar_width()+LEFT_MARGIN; + text_area.w = W-scrollbar_width()-LEFT_MARGIN-RIGHT_MARGIN - scrollbar_width(); + mVScrollBar->resize(X, text_area.y-TOP_MARGIN, scrollbar_width(), + text_area.h+TOP_MARGIN+BOTTOM_MARGIN); + } else { + text_area.x = X+LEFT_MARGIN; + text_area.w = W-scrollbar_width()-LEFT_MARGIN-RIGHT_MARGIN; + mVScrollBar->resize(X+W-scrollbar_width(), text_area.y-TOP_MARGIN, + scrollbar_width(), text_area.h+TOP_MARGIN+BOTTOM_MARGIN); + } + } + + /* + Decide if the horizontal scrollbar needs to be visible. If there + is a vertical scrollbar, a horizontal is always created too. This + is because the alternatives are unattractive: + * Dynamically creating a horizontal scrollbar based on the currently + visible lines is what the original nedit does, but it always wastes + space for the scrollbar even when it's not used. Since the FLTK + widget dynamically allocates the space for the scrollbar and + rearranges the widget to make room for it, this would create a very + visually displeasing "bounce" effect when the vertical scrollbar is + dragged. Trust me, I tried it and it looks really bad. + * The other alternative would be to keep track of what the longest + line in the entire buffer is and base the scrollbar on that. I + didn't do this because I didn't see any easy way to do that using + the nedit code and this could involve a lengthy calculation for + large buffers. If an efficient and non-costly way of doing this + can be found, this might be a way to go. + */ + /* WAS: Suggestion: Try turning the horizontal scrollbar on when + you first see a line that is too wide in the window, but then + don't turn it off (ie mix both of your solutions). */ + if (!mFastDisplay && !mContinuousWrap && scrollbar_align() & (FL_ALIGN_TOP|FL_ALIGN_BOTTOM) && + (mVScrollBar->visible() || longest_vline() > text_area.w)) + { + if (!mHScrollBar->visible()) { + mHScrollBar->set_visible(); + again = 1; // loop again to see if we now need vert. & recalc sizes + } + if (scrollbar_align() & FL_ALIGN_TOP) { + text_area.y = Y + scrollbar_width()+TOP_MARGIN; + text_area.h = H - scrollbar_width()-TOP_MARGIN-BOTTOM_MARGIN; + mHScrollBar->resize(text_area.x-LEFT_MARGIN, Y, + text_area.w+LEFT_MARGIN+RIGHT_MARGIN, scrollbar_width()); + } else { + text_area.y = Y+TOP_MARGIN; + text_area.h = H - scrollbar_width()-TOP_MARGIN-BOTTOM_MARGIN; + mHScrollBar->resize(text_area.x-LEFT_MARGIN, Y+H-scrollbar_width(), + text_area.w+LEFT_MARGIN+RIGHT_MARGIN, scrollbar_width()); + } + } + } + } + + // user request to change viewport + if (mTopLineNumHint != mTopLineNum || mHorizOffsetHint != mHorizOffset) + scroll_(mTopLineNumHint, mHorizOffsetHint); + + // everything will fit in the viewport + if (mNBufferLines < mNVisibleLines || mBuffer == NULL || mBuffer->length() == 0) { + scroll_(1, mHorizOffset); + /* if empty lines become visible, there may be an opportunity to + display more text by scrolling down */ + } else { + while ( mNVisibleLines>=2 + && (mLineStarts[mNVisibleLines-2]==-1) + && scroll_(mTopLineNum-1, mHorizOffset)) + { } + } + + // user request to display insert position + if (display_insert_position_hint) + display_insert(); + + // in case horizontal offset is now greater than longest line + int maxhoffset = max(0, longest_vline()-text_area.w); + if (mHorizOffset > maxhoffset) + scroll_(mTopLineNumHint, maxhoffset); + + mTopLineNumHint = mTopLineNum; + mHorizOffsetHint = mHorizOffset; + display_insert_position_hint = 0; + + if ((!mFastDisplay && mContinuousWrap) || + hscrollbarvisible != mHScrollBar->visible() || + vscrollbarvisible != mVScrollBar->visible()) + redraw(); + + update_v_scrollbar(); + update_h_scrollbar(); +} + + + +/** + \brief Refresh a rectangle of the text display. + \param left, top are in coordinates of the text drawing window. + \param width, height size in pixels + */ +void Fl_Text_Display_mod::draw_text( int left, int top, int width, int height ) { + int fontHeight, firstLine, lastLine, line; + + /* find the line number range of the display */ + fontHeight = mMaxsize ? mMaxsize : textsize_; + firstLine = ( top - text_area.y - fontHeight + 1 ) / fontHeight; + lastLine = ( top + height - text_area.y ) / fontHeight + 1; + + fl_push_clip( left, top, width, height ); + + /* draw the lines */ + for ( line = firstLine; line <= lastLine; line++ ) + draw_vline( line, left, left + width, 0, INT_MAX ); + + /* draw the line numbers if exposed area includes them */ + if (mLineNumWidth != 0 && left <= mLineNumLeft + mLineNumWidth) + draw_line_numbers(false); + + fl_pop_clip(); +} + + + +/** + \brief Marks text from start to end as needing a redraw. + This function will trigger a damage event and later a redraw of parts of + the widget. + \param startpos index of first character needing redraw + \param endpos index after last character needing redraw + */ +void Fl_Text_Display_mod::redisplay_range(int startpos, int endpos) { + IS_UTF8_ALIGNED2(buffer(), startpos) + IS_UTF8_ALIGNED2(buffer(), endpos) + + if (damage_range1_start == -1 && damage_range1_end == -1) { + damage_range1_start = startpos; + damage_range1_end = endpos; + } else if ((startpos >= damage_range1_start && startpos <= damage_range1_end) || + (endpos >= damage_range1_start && endpos <= damage_range1_end)) { + damage_range1_start = min(damage_range1_start, startpos); + damage_range1_end = max(damage_range1_end, endpos); + } else if (damage_range2_start == -1 && damage_range2_end == -1) { + damage_range2_start = startpos; + damage_range2_end = endpos; + } else { + damage_range2_start = min(damage_range2_start, startpos); + damage_range2_end = max(damage_range2_end, endpos); + } + damage(FL_DAMAGE_SCROLL); +} + + + +/** + \brief Draw a range of text. + + Refresh all of the text between buffer positions \p startpos and + \p endpos not including the character at the position \p endpos. + + If \p endpos points beyond the end of the buffer, refresh the whole display + after \p startpos, including blank lines which are not technically part of + any range of characters. + + \param startpos index of first character to draw + \param endpos index after last character to draw + */ +void Fl_Text_Display_mod::draw_range(int startpos, int endpos) { + startpos = buffer()->utf8_align(startpos); + endpos = buffer()->utf8_align(endpos); + + int i, startLine, lastLine, startIndex, endIndex; + + /* If the range is outside of the displayed text, just return */ + if ( endpos < mFirstChar || ( startpos > mLastChar && !empty_vlines() ) ) + return; + + /* Clean up the starting and ending values */ + if ( startpos < 0 ) startpos = 0; + if ( startpos > mBuffer->length() ) startpos = mBuffer->length(); + if ( endpos < 0 ) endpos = 0; + if ( endpos > mBuffer->length() ) endpos = mBuffer->length(); + + /* Get the starting and ending lines */ + if ( startpos < mFirstChar ) + startpos = mFirstChar; + if ( !position_to_line( startpos, &startLine ) ) + startLine = mNVisibleLines - 1; + if ( endpos >= mLastChar ) { + lastLine = mNVisibleLines - 1; + } else { + if ( !position_to_line( endpos, &lastLine ) ) { + /* shouldn't happen */ + lastLine = mNVisibleLines - 1; + } + } + + /* Get the starting and ending positions within the lines */ + startIndex = mLineStarts[ startLine ] == -1 ? 0 : startpos - mLineStarts[ startLine ]; + if ( endpos >= mLastChar ) + endIndex = INT_MAX; + else if ( mLineStarts[ lastLine ] == -1 ) + endIndex = 0; + else + endIndex = endpos - mLineStarts[ lastLine ]; + + /* If the starting and ending lines are the same, redisplay the single + line between "start" and "end" */ + if ( startLine == lastLine ) { + draw_vline( startLine, 0, INT_MAX, startIndex, endIndex ); + return; + } + + /* Redisplay the first line from "start" */ + draw_vline( startLine, 0, INT_MAX, startIndex, INT_MAX ); + + /* Redisplay the lines in between at their full width */ + for ( i = startLine + 1; i < lastLine; i++ ) + draw_vline( i, 0, INT_MAX, 0, INT_MAX ); + + /* Redisplay the last line to "end" */ + draw_vline( lastLine, 0, INT_MAX, 0, endIndex ); +} + + + +/** + \brief Sets the position of the text insertion cursor for text display. + Move the insertion cursor in front of the character at \p newPos. + This function may trigger a redraw. + \param newPos new caret position + */ +void Fl_Text_Display_mod::insert_position( int newPos ) { + IS_UTF8_ALIGNED2(buffer(), newPos) + + /* make sure new position is ok, do nothing if it hasn't changed */ + if ( newPos == mCursorPos ) return; + if ( newPos < 0 ) newPos = 0; + if ( newPos > mBuffer->length() ) newPos = mBuffer->length(); + + /* cursor movement cancels vertical cursor motion column */ + mCursorPreferredXPos = -1; + + /* erase the cursor at its previous position */ + redisplay_range(buffer()->prev_char_clipped(mCursorPos), buffer()->next_char(mCursorPos)); + + mCursorPos = newPos; + + /* draw cursor at its new position */ + redisplay_range(buffer()->prev_char_clipped(mCursorPos), buffer()->next_char(mCursorPos)); +} + + + +/** + \brief Shows the text cursor. + This function may trigger a redraw. + \param b show(1) or hide(0) the text cursor (caret). + */ +void Fl_Text_Display_mod::show_cursor(int b) { + mCursorOn = b; + redisplay_range(buffer()->prev_char_clipped(mCursorPos), buffer()->next_char(mCursorPos)); +} + + + +/** + \brief Sets the text cursor style. + Sets the text cursor style to one of the following: + + \li Fl_Text_Display_mod::NORMAL_CURSOR - Shows an I beam. + \li Fl_Text_Display_mod::CARET_CURSOR - Shows a caret under the text. + \li Fl_Text_Display_mod::DIM_CURSOR - Shows a dimmed I beam. + \li Fl_Text_Display_mod::BLOCK_CURSOR - Shows an unfilled box around the current + character. + \li Fl_Text_Display_mod::HEAVY_CURSOR - Shows a thick I beam. + + This call also switches the cursor on and may trigger a redraw. + + \param style new cursor style + */ +void Fl_Text_Display_mod::cursor_style(int style) { + mCursorStyle = style; + if (mCursorOn) show_cursor(); +} + + + +/** + \brief Set the new text wrap mode. + + If \p wrap mode is not zero, this call enables automatic word wrapping at column + \p wrapMargin. Word-wrapping does not change the text buffer itself, only the way + the text is displayed. Different Text Displays can have different wrap modes, + even if they share the same Text Buffer. + + \param wrap new wrap mode is WRAP_NONE (don't wrap text at all), WRAP_AT_COLUMN + (wrap text at the given text column), WRAP_AT_PIXEL (wrap text at a pixel + position), or WRAP_AT_BOUNDS (wrap text so that it fits into the + widget width) + \param wrapMargin in WRAP_AT_COLUMN mode, text will wrap at the n'th character. + For variable width fonts, an average character width is calculated. The + column width is calculated using the current textfont or the first style + when this function is called. If the font size changes, this function + must be called again. In WRAP_AT_PIXEL mode, this is the pixel position. + \todo we need new wrap modes to wrap at the window edge and based on pixel width + or average character width. + */ +void Fl_Text_Display_mod::wrap_mode(int wrap, int wrapMargin) { + switch (wrap) { + case WRAP_NONE: + mWrapMarginPix = 0; + mContinuousWrap = 0; + break; + case WRAP_AT_COLUMN: + default: + mWrapMarginPix = int(col_to_x(wrapMargin)); + mContinuousWrap = 1; + break; + case WRAP_AT_PIXEL: + mWrapMarginPix = wrapMargin; + mContinuousWrap = 1; + break; + case WRAP_AT_BOUNDS: + mWrapMarginPix = 0; + mContinuousWrap = 1; + break; + } + + if (buffer()) { + /* wrapping can change the total number of lines, re-count */ + mNBufferLines = count_lines(0, buffer()->length(), true); + + /* changing wrap margins or changing from wrapped mode to non-wrapped + can leave the character at the top no longer at a line start, and/or + change the line number */ + mFirstChar = line_start(mFirstChar); + mTopLineNum = count_lines(0, mFirstChar, true) + 1; + + reset_absolute_top_line_number(); + + /* update the line starts array */ + calc_line_starts(0, mNVisibleLines); + calc_last_char(); + } else { + // No buffer, so just clear the state info for later... + mNBufferLines = 0; + mFirstChar = 0; + mTopLineNum = 1; + mAbsTopLineNum = 0; + } + + resize(x(), y(), w(), h()); +} + + + +/** + \brief Inserts "text" at the current cursor location. + + This has the same effect as inserting the text into the buffer using BufInsert + and then moving the insert position after the newly inserted text, except + that it's optimized to do less redrawing. + + \param text new text in UTF-8 encoding. + */ +void Fl_Text_Display_mod::insert(const char* text) { + IS_UTF8_ALIGNED2(buffer(), mCursorPos) + IS_UTF8_ALIGNED(text) + + int pos = mCursorPos; + + mCursorToHint = pos + strlen( text ); + mBuffer->insert( pos, text ); + mCursorToHint = NO_HINT; +} + + + +/** + \brief Replaces text at the current insert position. + \param text new text in UTF-8 encoding + + \todo Unicode? Find out exactly what we do here and simplify. + */ +void Fl_Text_Display_mod::overstrike(const char* text) { + IS_UTF8_ALIGNED2(buffer(), mCursorPos) + IS_UTF8_ALIGNED(text) + + int startPos = mCursorPos; + Fl_Text_Buffer_mod *buf = mBuffer; + int lineStart = buf->line_start( startPos ); + int textLen = strlen( text ); + int i, p, endPos, indent, startIndent, endIndent; + const char *c; + unsigned int ch; + char *paddedText = NULL; + + /* determine how many displayed character positions are covered */ + startIndent = mBuffer->count_displayed_characters( lineStart, startPos ); + indent = startIndent; + for ( c = text; *c != '\0'; c += fl_utf8len1(*c) ) + indent++; + endIndent = indent; + + /* find which characters to remove, and if necessary generate additional + padding to make up for removed control characters at the end */ + indent = startIndent; + for ( p = startPos; ; p=buffer()->next_char(p) ) { + if ( p == buf->length() ) + break; + ch = buf->char_at( p ); + if ( ch == '\n' ) + break; + indent++; + if ( indent == endIndent ) { + p++; + break; + } else if ( indent > endIndent ) { + if ( ch != '\t' ) { + p++; + paddedText = new char [ textLen + FL_TEXT_MAX_EXP_CHAR_LEN + 1 ]; + strcpy( paddedText, text ); + for ( i = 0; i < indent - endIndent; i++ ) + paddedText[ textLen + i ] = ' '; + paddedText[ textLen + i ] = '\0'; + } + break; + } + } + endPos = p; + + mCursorToHint = startPos + textLen; + buf->replace( startPos, endPos, paddedText == NULL ? text : paddedText ); + mCursorToHint = NO_HINT; + if ( paddedText != NULL ) + delete [] paddedText; +} + + + +/** + \brief Convert a character index into a pixel position. + + Translate a buffer text position to the XY location where the top left of the + cursor would be positioned to point to that character. Returns 0 if the + position is not displayed because it is \e \b vertically out of view. + If the position is horizontally out of view, returns the X coordinate where + the position would be if it were visible. + + \param pos character index + \param[out] X, Y pixel position of character on screen + \return 0 if character vertically out of view, X position otherwise + */ +int Fl_Text_Display_mod::position_to_xy( int pos, int* X, int* Y ) const { + IS_UTF8_ALIGNED2(buffer(), pos) + + int lineStartPos, fontHeight; + int visLineNum; + + /* If position is not displayed, return false */ + if (pos < mFirstChar || (pos > mLastChar && !empty_vlines())) { + return 0; + } + + /* Calculate Y coordinate */ + if (!position_to_line(pos, &visLineNum)) { + return 0; + } + if (visLineNum < 0 || visLineNum > mNBufferLines) { + return 0; + } + + fontHeight = mMaxsize; + *Y = text_area.y + visLineNum * fontHeight; + + /* Get the text, length, and buffer position of the line. If the position + is beyond the end of the buffer and should be at the first position on + the first empty line, don't try to get or scan the text */ + lineStartPos = mLineStarts[visLineNum]; + if ( lineStartPos == -1 ) { + *X = text_area.x - mHorizOffset; + return 1; + } + *X = text_area.x + handle_vline(GET_WIDTH, lineStartPos, pos-lineStartPos, 0, 0, 0, 0, 0, 0) - mHorizOffset; + return 1; +} + + + +/** + \brief Find the line and column number of position \p pos. + + This only works for displayed lines. If the line is not displayed, the + function returns 0 (without the mLineStarts array it could turn in to very long + calculation involving scanning large amounts of text in the buffer). + If continuous wrap mode is on, returns the absolute line number (as opposed + to the wrapped line number which is used for scrolling). + + \param pos character index + \param[out] lineNum absolute (unwrapped) line number + \param[out] column character offset to the beginning of the line + \return 0 if \p pos is off screen, line number otherwise + \todo a column number makes little sense in the UTF-8/variable font width + environment. We will have to further define what exactly we want to return. + Please check the functions that call this particular function. + */ +int Fl_Text_Display_mod::position_to_linecol( int pos, int* lineNum, int* column ) const { + IS_UTF8_ALIGNED2(buffer(), pos) + + int retVal; + + /* In continuous wrap mode, the absolute (non-wrapped) line count is + maintained separately, as needed. Only return it if we're actually + keeping track of it and pos is in the displayed text */ + if (!mFastDisplay && mContinuousWrap) { + if (!maintaining_absolute_top_line_number() || pos < mFirstChar || pos > mLastChar) + return 0; + *lineNum = mAbsTopLineNum + buffer()->count_lines(mFirstChar, pos); + *column = buffer()->count_displayed_characters(buffer()->line_start(pos), pos); + return 1; + } + + retVal = position_to_line( pos, lineNum ); + if ( retVal ) { + *column = mBuffer->count_displayed_characters( mLineStarts[ *lineNum ], pos ); + *lineNum += mTopLineNum; + } + return retVal; +} + + + +/** + \brief Check if a pixel position is within the primary selection. + \param X, Y pixel position to test + \return 1 if position (X, Y) is inside of the primary Fl_Text_Selection + */ +int Fl_Text_Display_mod::in_selection( int X, int Y ) const { + int pos = xy_to_position( X, Y, CHARACTER_POS ); + IS_UTF8_ALIGNED2(buffer(), pos) + Fl_Text_Buffer_mod *buf = mBuffer; + return buf->primary_selection()->includes(pos); +} + + + +/** + \brief Nobody knows what this function does. + + Correct a column number based on an unconstrained position (as returned by + TextDXYToUnconstrainedPosition) to be relative to the last actual newline + in the buffer before the row and column position given, rather than the + last line start created by line wrapping. This is an adapter + for rectangular selections and code written before continuous wrap mode, + which thinks that the unconstrained column is the number of characters + from the last newline. Obviously this is time consuming, because it + invloves character re-counting. + + \param row + \param column + \return something unknown + \todo What does this do and how is it useful? Column numbers mean little in + this context. Which functions depend on this one? + + \todo Unicode? + */ +int Fl_Text_Display_mod::wrapped_column(int row, int column) const { + int lineStart, dispLineStart; + + if (mFastDisplay || !mContinuousWrap || row < 0 || row > mNVisibleLines) + return column; + dispLineStart = mLineStarts[row]; + if (dispLineStart == -1) + return column; + lineStart = buffer()->line_start(dispLineStart); + return column + buffer()->count_displayed_characters(lineStart, dispLineStart); +} + + + +/** + \brief Nobody knows what this function does. + + Correct a row number from an unconstrained position (as returned by + TextDXYToUnconstrainedPosition) to a straight number of newlines from the + top line of the display. Because rectangular selections are based on + newlines, rather than display wrapping, and anywhere a rectangular selection + needs a row, it needs it in terms of un-wrapped lines. + + \param row + \return something unknown + \todo What does this do and how is it useful? Column numbers mean little in + this context. Which functions depend on this one? + */ +int Fl_Text_Display_mod::wrapped_row(int row) const { + if (mFastDisplay || !mContinuousWrap || row < 0 || row > mNVisibleLines) + return row; + return buffer()->count_lines(mFirstChar, mLineStarts[row]); +} + + + +/** + \brief Scroll the display to bring insertion cursor into view. + + Note: it would be nice to be able to do this without counting lines twice + (scroll_() counts them too) and/or to count from the most efficient + starting point, but the efficiency of this routine is not as important to + the overall performance of the text display. + + \todo Unicode? + */ +void Fl_Text_Display_mod::display_insert() { + int hOffset, topLine, X, Y; + hOffset = mHorizOffset; + topLine = mTopLineNum; + + if (insert_position() < mFirstChar) { + topLine -= count_lines(insert_position(), mFirstChar, false); + } else if (mNVisibleLines>=2 && mLineStarts[mNVisibleLines-2] != -1) { + int lastChar = line_end(mLineStarts[mNVisibleLines-2],true); + if (insert_position() >= lastChar) + topLine += count_lines(lastChar - (wrap_uses_character(mLastChar) ? 0 : 1), + insert_position(), false); + } + + /* Find the new setting for horizontal offset (this is a bit ungraceful). + If the line is visible, just use PositionToXY to get the position + to scroll to, otherwise, do the vertical scrolling first, then the + horizontal */ + if (!position_to_xy( mCursorPos, &X, &Y )) { + scroll_(topLine, hOffset); + if (!position_to_xy( mCursorPos, &X, &Y )) { +#ifdef DEBUG + printf ("*** display_insert/position_to_xy # GIVE UP !\n"); fflush(stdout); +#endif // DEBUG + return; /* Give up, it's not worth it (but why does it fail?) */ + } + } + if (X > text_area.x + text_area.w) + hOffset += X-(text_area.x + text_area.w); + else if (X < text_area.x) + hOffset += X-text_area.x; + + /* Do the scroll */ + if (topLine != mTopLineNum || hOffset != mHorizOffset) + scroll_(topLine, hOffset); +} + + +/** + \brief Scrolls the text buffer to show the current insert position. + This function triggers a complete recalculation, ending in a call to + Fl_Text_Display_mod::display_insert() + */ +void Fl_Text_Display_mod::show_insert_position() { + display_insert_position_hint = 1; + resize(x(), y(), w(), h()); +} + + +/* + Cursor movement functions + */ + +/** + \brief Moves the current insert position right one character. + \return 1 if the cursor moved, 0 if the end of the text was reached + */ +int Fl_Text_Display_mod::move_right() { + if ( mCursorPos >= mBuffer->length() ) + return 0; + int p = insert_position(); + int q = buffer()->next_char(p); + insert_position(q); + return 1; +} + + + +/** + \brief Moves the current insert position left one character. + \return 1 if the cursor moved, 0 if the beginning of the text was reached + */ +int Fl_Text_Display_mod::move_left() { + if ( mCursorPos <= 0 ) + return 0; + int p = insert_position(); + int q = buffer()->prev_char_clipped(p); + insert_position(q); + return 1; +} + + + +/** + \brief Moves the current insert position up one line. + \return 1 if the cursor moved, 0 if the beginning of the text was reached + */ +int Fl_Text_Display_mod::move_up() { + int lineStartPos, xPos, prevLineStartPos, newPos, visLineNum; + + /* Find the position of the start of the line. Use the line starts array + if possible */ + if ( position_to_line( mCursorPos, &visLineNum ) ) + lineStartPos = mLineStarts[ visLineNum ]; + else { + lineStartPos = line_start( mCursorPos ); + visLineNum = -1; + } + if ( lineStartPos == 0 ) + return 0; + + /* Decide what column to move to, if there's a preferred column use that */ + if (mCursorPreferredXPos >= 0) + xPos = mCursorPreferredXPos; + else + xPos = handle_vline(GET_WIDTH, lineStartPos, mCursorPos-lineStartPos, + 0, 0, 0, 0, 0, INT_MAX); + + /* count forward from the start of the previous line to reach the column */ + if ( visLineNum != -1 && visLineNum != 0 ) + prevLineStartPos = mLineStarts[ visLineNum - 1 ]; + else + prevLineStartPos = rewind_lines( lineStartPos, 1 ); + + int lineEnd = line_end(prevLineStartPos, true); + newPos = handle_vline(FIND_INDEX_FROM_ZERO, prevLineStartPos, lineEnd-prevLineStartPos, + 0, 0, 0, 0, 0, xPos); + + /* move the cursor */ + insert_position( newPos ); + + /* if a preferred column wasn't aleady established, establish it */ + mCursorPreferredXPos = xPos; + return 1; +} + + + +/** + \brief Moves the current insert position down one line. + \return 1 if the cursor moved, 0 if the beginning of the text was reached + */ +int Fl_Text_Display_mod::move_down() { + int lineStartPos, xPos, newPos, visLineNum; + + if ( mCursorPos == mBuffer->length() ) + return 0; + + if ( position_to_line( mCursorPos, &visLineNum ) ) + lineStartPos = mLineStarts[ visLineNum ]; + else { + lineStartPos = line_start( mCursorPos ); + visLineNum = -1; + } + if (mCursorPreferredXPos >= 0) { + xPos = mCursorPreferredXPos; + } else { + xPos = handle_vline(GET_WIDTH, lineStartPos, mCursorPos-lineStartPos, + 0, 0, 0, 0, 0, INT_MAX); + } + + int nextLineStartPos = skip_lines( lineStartPos, 1, true ); + int lineEnd = line_end(nextLineStartPos, true); + newPos = handle_vline(FIND_INDEX_FROM_ZERO, nextLineStartPos, lineEnd-nextLineStartPos, + 0, 0, 0, 0, 0, xPos); + + insert_position( newPos ); + mCursorPreferredXPos = xPos; + return 1; +} + + + +/** + \brief Count the number of lines between two positions. + + Same as BufCountLines, but takes into account wrapping if wrapping is + turned on. If the caller knows that \p startPos is at a line start, it + can pass \p startPosIsLineStart as True to make the call more efficient + by avoiding the additional step of scanning back to the last newline. + + \param startPos index to first character + \param endPos index after last character + \param startPosIsLineStart avoid scanning back to the line start + \return number of lines + */ +int Fl_Text_Display_mod::count_lines(int startPos, int endPos, + bool startPosIsLineStart) const { + IS_UTF8_ALIGNED2(buffer(), startPos) + IS_UTF8_ALIGNED2(buffer(), endPos) + + int retLines, retPos, retLineStart, retLineEnd; + +#ifdef DEBUG + printf("Fl_Text_Display_mod::count_lines(startPos=%d, endPos=%d, startPosIsLineStart=%d\n", + startPos, endPos, startPosIsLineStart); +#endif // DEBUG + + /* If we're not wrapping use simple (and more efficient) BufCountLines */ + if (mFastDisplay || !mContinuousWrap) + return buffer()->count_lines(startPos, endPos); + + wrapped_line_counter(buffer(), startPos, endPos, INT_MAX, + startPosIsLineStart, 0, &retPos, &retLines, &retLineStart, + &retLineEnd); + +#ifdef DEBUG + printf(" # after WLC: retPos=%d, retLines=%d, retLineStart=%d, retLineEnd=%d\n", + retPos, retLines, retLineStart, retLineEnd); +#endif // DEBUG + + return retLines; +} + + + +/** + \brief Skip a number of lines forward. + + Same as BufCountForwardNLines, but takes into account line breaks when + wrapping is turned on. If the caller knows that startPos is at a line start, + it can pass "startPosIsLineStart" as True to make the call more efficient + by avoiding the additional step of scanning back to the last newline. + + \param startPos index to starting character + \param nLines number of lines to skip ahead + \param startPosIsLineStart avoid scanning back to the line start + \return new position as index + */ +int Fl_Text_Display_mod::skip_lines(int startPos, int nLines, + bool startPosIsLineStart) { + IS_UTF8_ALIGNED2(buffer(), startPos) + + int retLines, retPos, retLineStart, retLineEnd; + + /* if we're not wrapping use more efficient BufCountForwardNLines */ + if (mFastDisplay || !mContinuousWrap) + return buffer()->skip_lines(startPos, nLines); + + /* wrappedLineCounter can't handle the 0 lines case */ + if (nLines == 0) + return startPos; + + /* use the common line counting routine to count forward */ + wrapped_line_counter(buffer(), startPos, buffer()->length(), + nLines, startPosIsLineStart, 0, + &retPos, &retLines, &retLineStart, &retLineEnd); + IS_UTF8_ALIGNED2(buffer(), retPos) + return retPos; +} + + + +/** + \brief Returns the end of a line. + + Same as BufEndOfLine, but takes into account line breaks when wrapping + is turned on. If the caller knows that \p startPos is at a line start, it + can pass "startPosIsLineStart" as True to make the call more efficient + by avoiding the additional step of scanning back to the last newline. + + Note that the definition of the end of a line is less clear when continuous + wrap is on. With continuous wrap off, it's just a pointer to the newline + that ends the line. When it's on, it's the character beyond the last + \b displayable character on the line, where a whitespace character which has + been "converted" to a newline for wrapping is not considered displayable. + Also note that a line can be wrapped at a non-whitespace character if the + line had no whitespace. In this case, this routine returns a pointer to + the start of the next line. This is also consistent with the model used by + visLineLength. + + \param startPos index to starting character + \param startPosIsLineStart avoid scanning back to the line start + \return new position as index + */ +int Fl_Text_Display_mod::line_end(int startPos, bool startPosIsLineStart) const { + IS_UTF8_ALIGNED2(buffer(), startPos) + + int retLines, retPos, retLineStart, retLineEnd; + + /* If we're not wrapping use more efficient BufEndOfLine */ + if (mFastDisplay || !mContinuousWrap) + return buffer()->line_end(startPos); + + if (startPos == buffer()->length()) + return startPos; + + wrapped_line_counter(buffer(), startPos, buffer()->length(), 1, + startPosIsLineStart, 0, &retPos, &retLines, &retLineStart, + &retLineEnd); + + IS_UTF8_ALIGNED2(buffer(), retLineEnd) + return retLineEnd; +} + + + +/** + \brief Return the beginning of a line. + + Same as BufStartOfLine, but returns the character after last wrap point + rather than the last newline. + + \param pos index to starting character + \return new position as index + */ +int Fl_Text_Display_mod::line_start(int pos) const { + IS_UTF8_ALIGNED2(buffer(), pos) + + int retLines, retPos, retLineStart, retLineEnd; + + /* If we're not wrapping, use the more efficient BufStartOfLine */ + if (mFastDisplay || !mContinuousWrap) + return buffer()->line_start(pos); + + wrapped_line_counter(buffer(), buffer()->line_start(pos), pos, INT_MAX, true, 0, + &retPos, &retLines, &retLineStart, &retLineEnd); + + IS_UTF8_ALIGNED2(buffer(), retLineStart) + return retLineStart; +} + + + +/** + \brief Skip a number of lines back. + + Same as BufCountBackwardNLines, but takes into account line breaks when + wrapping is turned on. + + \param startPos index to starting character + \param nLines number of lines to skip back + \return new position as index + */ +int Fl_Text_Display_mod::rewind_lines(int startPos, int nLines) { + IS_UTF8_ALIGNED2(buffer(), startPos) + + Fl_Text_Buffer_mod *buf = buffer(); + int pos, lineStart, retLines, retPos, retLineStart, retLineEnd; + + /* If we're not wrapping, use the more efficient BufCountBackwardNLines */ + if (mFastDisplay || !mContinuousWrap) + return buf->rewind_lines(startPos, nLines); + + pos = startPos; + for (;;) { + lineStart = buf->line_start(pos); + wrapped_line_counter(buf, lineStart, pos, INT_MAX, true, 0, + &retPos, &retLines, &retLineStart, &retLineEnd, false); + if (retLines > nLines) + return skip_lines(lineStart, retLines-nLines, true); + nLines -= retLines; + pos = lineStart - 1; + if (pos < 0) + return 0; + nLines -= 1; + } +} + + + +static inline int fl_isseparator(unsigned int c) { + // FIXME: this does not take UCS-4 encoding into account + return c != '$' && c != '_' && (isspace(c) || ispunct(c)); +} + + + +/** + \brief Moves the current insert position right one word. + */ +void Fl_Text_Display_mod::next_word() { + int pos = insert_position(); + + while (pos < buffer()->length() && !fl_isseparator(buffer()->char_at(pos))) { + pos = buffer()->next_char(pos); + } + + while (pos < buffer()->length() && fl_isseparator(buffer()->char_at(pos))) { + pos = buffer()->next_char(pos); + } + + insert_position( pos ); +} + + + +/** + \brief Moves the current insert position left one word. + */ +void Fl_Text_Display_mod::previous_word() { + int pos = insert_position(); + if (pos==0) return; + pos = buffer()->prev_char(pos); + + while (pos && fl_isseparator(buffer()->char_at(pos))) { + pos = buffer()->prev_char(pos); + } + + while (pos && !fl_isseparator(buffer()->char_at(pos))) { + pos = buffer()->prev_char(pos); + } + + if (fl_isseparator(buffer()->char_at(pos))) { + pos = buffer()->next_char(pos); + } + + insert_position( pos ); +} + + + +/** + \brief This is called before any characters are deleted. + + Callback attached to the text buffer to receive delete information before + the modifications are actually made. + + \param pos starting index of deletion + \param nDeleted number of bytes we will delete (must be UTF-8 aligned!) + \param cbArg "this" pointer for static callback function + */ +void Fl_Text_Display_mod::buffer_predelete_cb(int pos, int nDeleted, void *cbArg) { + Fl_Text_Display_mod *textD = (Fl_Text_Display_mod *)cbArg; + if (textD->mContinuousWrap && !textD->mFastDisplay) { + /* Note: we must perform this measurement, even if there is not a + single character deleted; the number of "deleted" lines is the + number of visual lines spanned by the real line in which the + modification takes place. + Also, a modification of the tab distance requires the same + kind of calculations in advance, even if the font width is "fixed", + because when the width of the tab characters changes, the layout + of the text may be completely different. */ + IS_UTF8_ALIGNED2(textD->buffer(), pos) + textD->measure_deleted_lines(pos, nDeleted); + } else { + textD->mSuppressResync = 0; /* Probably not needed, but just in case */ + } +} + + + +/** + \brief This is called whenever the buffer is modified. + + Callback attached to the text buffer to receive modification information + + \param pos starting index of modification + \param nInserted number of bytes we inserted (must be UTF-8 aligned!) + \param nDeleted number of bytes deleted (must be UTF-8 aligned!) + \param nRestyled ?? + \param deletedText this is what was removed, must not be NULL if nDeleted is set + \param cbArg "this" pointer for static callback function + */ +void Fl_Text_Display_mod::buffer_modified_cb( int pos, int nInserted, int nDeleted, + int nRestyled, const char *deletedText, void *cbArg ) { + int linesInserted, linesDeleted, startDispPos, endDispPos; + Fl_Text_Display_mod *textD = ( Fl_Text_Display_mod * ) cbArg; + Fl_Text_Buffer_mod *buf = textD->mBuffer; + int oldFirstChar = textD->mFirstChar; + int scrolled, origCursorPos = textD->mCursorPos; + int wrapModStart = 0, wrapModEnd = 0; + + IS_UTF8_ALIGNED2(buf, pos) + IS_UTF8_ALIGNED2(buf, oldFirstChar) + + /* buffer modification cancels vertical cursor motion column */ + if ( nInserted != 0 || nDeleted != 0 ) + textD->mCursorPreferredXPos = -1; + + /* Count the number of lines inserted and deleted, and in the case + of continuous wrap mode, how much has changed */ + if (textD->mContinuousWrap && !textD->mFastDisplay) { + textD->find_wrap_range(deletedText, pos, nInserted, nDeleted, + &wrapModStart, &wrapModEnd, &linesInserted, &linesDeleted); + } else { + linesInserted = nInserted == 0 ? 0 : buf->count_lines( pos, pos + nInserted ); + linesDeleted = nDeleted == 0 ? 0 : countlines( deletedText ); + } + + /* Update the line starts and mTopLineNum */ + if ( nInserted != 0 || nDeleted != 0 ) { + if (textD->mContinuousWrap && !textD->mFastDisplay) { + textD->update_line_starts( wrapModStart, wrapModEnd-wrapModStart, + nDeleted + pos-wrapModStart + (wrapModEnd-(pos+nInserted)), + linesInserted, linesDeleted, &scrolled ); + } else { + textD->update_line_starts( pos, nInserted, nDeleted, linesInserted, + linesDeleted, &scrolled ); + } + } else + scrolled = 0; + + /* If we're counting non-wrapped lines as well, maintain the absolute + (non-wrapped) line number of the text displayed */ + if (textD->maintaining_absolute_top_line_number() && + (nInserted != 0 || nDeleted != 0)) { + if (deletedText && (pos + nDeleted < oldFirstChar)) + textD->mAbsTopLineNum += buf->count_lines(pos, pos + nInserted) - + countlines(deletedText); + else if (pos < oldFirstChar) + textD->reset_absolute_top_line_number(); + } + + /* Update the line count for the whole buffer */ + textD->mNBufferLines += linesInserted - linesDeleted; + + /* Update the cursor position */ + if ( textD->mCursorToHint != NO_HINT ) { + textD->mCursorPos = textD->mCursorToHint; + textD->mCursorToHint = NO_HINT; + } else if ( textD->mCursorPos > pos ) { + if ( textD->mCursorPos < pos + nDeleted ) + textD->mCursorPos = pos; + else + textD->mCursorPos += nInserted - nDeleted; + } + + // refigure scrollbars & stuff + textD->resize(textD->x(), textD->y(), textD->w(), textD->h()); + + // don't need to do anything else if not visible? + if (!textD->visible_r()) return; + + /* If the changes caused scrolling, re-paint everything and we're done. */ + if ( scrolled ) { + textD->damage(FL_DAMAGE_EXPOSE); + if ( textD->mStyleBuffer ) /* See comments in extendRangeForStyleMods */ + textD->mStyleBuffer->primary_selection()->selected(0); + return; + } + + /* If the changes didn't cause scrolling, decide the range of characters + that need to be re-painted. Also if the cursor position moved, be + sure that the redisplay range covers the old cursor position so the + old cursor gets erased, and erase the bits of the cursor which extend + beyond the left and right edges of the text. */ + startDispPos = (textD->mContinuousWrap && !textD->mFastDisplay) ? wrapModStart : pos; + IS_UTF8_ALIGNED2(buf, startDispPos) + + if ( origCursorPos == startDispPos && textD->mCursorPos != startDispPos ) + startDispPos = min( startDispPos, buf->prev_char_clipped(origCursorPos) ); + IS_UTF8_ALIGNED2(buf, startDispPos) + + if ( linesInserted == linesDeleted ) { + if ( nInserted == 0 && nDeleted == 0 ) + endDispPos = pos + nRestyled; + else { + endDispPos = textD->mContinuousWrap ? wrapModEnd : + buf->line_end( pos + nInserted ) + 1; + if (textD->mContinuousWrap && !textD->mFastDisplay) + endDispPos = wrapModEnd; + else + endDispPos = buf->next_char(buf->line_end( pos + nInserted )); + + // CET - FIXME if ( origCursorPos >= startDispPos && + // ( origCursorPos <= endDispPos || endDispPos == buf->length() ) ) + } + + if (linesInserted > 1) textD->draw_line_numbers(false); + } else { + endDispPos = buf->next_char(textD->mLastChar); + // CET - FIXME if ( origCursorPos >= pos ) + /* If more than one line is inserted/deleted, a line break may have + been inserted or removed in between, and the line numbers may + have changed. If only one line is altered, line numbers cannot + be affected (the insertion or removal of a line break always + results in at least two lines being redrawn). */ + textD->draw_line_numbers(false); + } + IS_UTF8_ALIGNED2(buf, startDispPos) + IS_UTF8_ALIGNED2(buf, endDispPos) + + /* If there is a style buffer, check if the modification caused additional + changes that need to be redisplayed. (Redisplaying separately would + cause double-redraw on almost every modification involving styled + text). Extend the redraw range to incorporate style changes */ + if ( textD->mStyleBuffer ) + textD->extend_range_for_styles( &startDispPos, &endDispPos ); + IS_UTF8_ALIGNED2(buf, startDispPos) + IS_UTF8_ALIGNED2(buf, endDispPos) + + /* Redisplay computed range */ + textD->redisplay_range( startDispPos, endDispPos ); +} + + + +/** + \brief Line numbering stuff, currently unused. + + In continuous wrap mode, internal line numbers are calculated after + wrapping. A separate non-wrapped line count is maintained when line + numbering is turned on. There is some performance cost to maintaining this + line count, so normally absolute line numbers are not tracked if line + numbering is off. This routine allows callers to specify that they still + want this line count maintained (for use via TextDPosToLineAndCol). + More specifically, this allows the line number reported in the statistics + line to be calibrated in absolute lines, rather than post-wrapped lines. + */ +void Fl_Text_Display_mod::maintain_absolute_top_line_number(int state) { + mNeedAbsTopLineNum = state; + reset_absolute_top_line_number(); +} + + + +/** + \brief Line numbering stuff, currently unused. + + Returns the absolute (non-wrapped) line number of the first line displayed. + Returns 0 if the absolute top line number is not being maintained. + */ +int Fl_Text_Display_mod::get_absolute_top_line_number() const { + if (mFastDisplay || !mContinuousWrap) + return mTopLineNum; + if (maintaining_absolute_top_line_number()) + return mAbsTopLineNum; + return 0; +} + + + +/** + \brief Line numbering stuff, currently unused. + + Re-calculate absolute top line number for a change in scroll position. + */ +void Fl_Text_Display_mod::absolute_top_line_number(int oldFirstChar) { + if (maintaining_absolute_top_line_number()) { + if (mFirstChar < oldFirstChar) + mAbsTopLineNum -= buffer()->count_lines(mFirstChar, oldFirstChar); + else + mAbsTopLineNum += buffer()->count_lines(oldFirstChar, mFirstChar); + } +} + + + +/** + \brief Line numbering stuff, currently unused. + + Return true if a separate absolute top line number is being maintained + (for displaying line numbers or showing in the statistics line). + */ +int Fl_Text_Display_mod::maintaining_absolute_top_line_number() const { + return (!mFastDisplay && mContinuousWrap && (mLineNumWidth != 0 || mNeedAbsTopLineNum)); +} + + + +/** + \brief Line numbering stuff, probably unused. + + Count lines from the beginning of the buffer to reestablish the + absolute (non-wrapped) top line number. If mode is not continuous wrap, + or the number is not being maintained, does nothing. + */ +void Fl_Text_Display_mod::reset_absolute_top_line_number() { + mAbsTopLineNum = 1; + absolute_top_line_number(0); +} + + + +/** + \brief Convert a position index into a line number offset. + + Find the line number of position \p pos relative to the first line of + displayed text. Returns 0 if the line is not displayed. + + \param pos ?? + \param[out] lineNum ?? + \return ?? + \todo What does this do? + */ +int Fl_Text_Display_mod::position_to_line( int pos, int *lineNum ) const { + IS_UTF8_ALIGNED2(buffer(), pos) + + int i; + + *lineNum = 0; + if ( pos < mFirstChar ) return 0; + if ( pos > mLastChar ) { + if ( empty_vlines() ) { + if ( mLastChar < mBuffer->length() ) { + if ( !position_to_line( mLastChar, lineNum ) ) { + Fl::error("Fl_Text_Display_mod::position_to_line(): Consistency check ptvl failed"); + return 0; + } + return ++( *lineNum ) <= mNVisibleLines - 1; + } else { + position_to_line( buffer()->prev_char_clipped(mLastChar), lineNum ); + return 1; + } + } + return 0; + } + + for ( i = mNVisibleLines - 1; i >= 0; i-- ) { + if ( mLineStarts[ i ] != -1 && pos >= mLineStarts[ i ] ) { + *lineNum = i; + return 1; + } + } + return 0; /* probably never be reached */ +} + + +/** + Universal pixel machine. + + We use a single function that handles all line layout, measuring, and drawing + \li draw a text range + \li return the width of a text range in pixels + \li return the index of a character that is at a pixel position + + \param[in] mode DRAW_LINE, GET_WIDTH, FIND_INDEX + \param[in] lineStartPos index of first character + \param[in] lineLen size of string in bytes + \param[in] leftChar, rightChar + \param[in] Y drawing position + \param[in] bottomClip, leftClip, rightClip stop work when we reach the clipped + area. rightClip is the X position that we search in FIND_INDEX. + \retval DRAW_LINE index of last drawn character + \retval GET_WIDTH width in pixels of text segment if we would draw it + \retval FIND_INDEX index of character at given x position in window coordinates + \retval FIND_INDEX_FROM_ZERO index of character at given x position without scrolling and widget offsets + \todo we need to handle hidden hyphens and tabs here! + \todo we handle all styles and selections + \todo we must provide code to get pixel positions of the middle of a character as well + */ +int Fl_Text_Display_mod::handle_vline( + int mode, + int lineStartPos, int lineLen, int leftChar, int rightChar, + int Y, int bottomClip, + int leftClip, int rightClip) const +{ + IS_UTF8_ALIGNED2(buffer(), lineStartPos) + + // FIXME: we need to allow two modes for FIND_INDEX: one on the edge of the + // FIXME: character for selection, and one on the character center for cursors. + int i, X, startX, startIndex, style, charStyle; + char *lineStr; + + if ( lineStartPos == -1 ) { + lineStr = NULL; + } else { + lineStr = mBuffer->text_range( lineStartPos, lineStartPos + lineLen ); + } + + if (mode==GET_WIDTH) { + X = 0; + } else if (mode==FIND_INDEX_FROM_ZERO) { + X = 0; + mode = FIND_INDEX; + } else { + X = text_area.x - mHorizOffset; + } + + startX = X; + startIndex = 0; + if (!lineStr) { + // just clear the background + if (mode==DRAW_LINE) { + style = position_style(lineStartPos, lineLen, -1); + draw_string( style|BG_ONLY_MASK, text_area.x, Y, text_area.x+text_area.w, lineStr, lineLen ); + } + if (mode==FIND_INDEX) { + IS_UTF8_ALIGNED2(buffer(), lineStartPos) + return lineStartPos; + } + return 0; + } + + char currChar = 0, prevChar = 0; + // draw the line + style = position_style(lineStartPos, lineLen, 0); + for (i=0; itab_distance()); + int xAbs = (mode==GET_WIDTH) ? startX : startX+mHorizOffset-text_area.x; + w = (((xAbs/tab)+1)*tab) - xAbs; + if (mode==DRAW_LINE) + draw_string( style|BG_ONLY_MASK, startX, Y, startX+w, 0, 0 ); + if (mode==FIND_INDEX && startX+w>rightClip) { + // find x pos inside block + free(lineStr); + return lineStartPos + startIndex; + } + } else { + // draw a text segment + w = int( string_width( lineStr+startIndex, i-startIndex, style ) ); + if (mode==DRAW_LINE) + draw_string( style, startX, Y, startX+w, lineStr+startIndex, i-startIndex ); + if (mode==FIND_INDEX && startX+w>rightClip) { + // find x pos inside block + int di = find_x(lineStr+startIndex, i-startIndex, style, rightClip-startX); + free(lineStr); + IS_UTF8_ALIGNED2(buffer(), (lineStartPos+startIndex+di)) + return lineStartPos + startIndex + di; + } + } + style = charStyle; + startX += w; + startIndex = i; + } + i += len; + prevChar = currChar; + } + int w = 0; + if (currChar=='\t') { + // draw a single Tab space + int tab = (int)col_to_x(mBuffer->tab_distance()); + int xAbs = (mode==GET_WIDTH) ? startX : startX+mHorizOffset-text_area.x; + w = (((xAbs/tab)+1)*tab) - xAbs; + if (mode==DRAW_LINE) + draw_string( style|BG_ONLY_MASK, startX, Y, startX+w, 0, 0 ); + if (mode==FIND_INDEX) { + // find x pos inside block + free(lineStr); + return lineStartPos + startIndex + ( rightClip-startX>w ? 1 : 0 ); + } + } else { + w = int( string_width( lineStr+startIndex, i-startIndex, style ) ); + if (mode==DRAW_LINE) + draw_string( style, startX, Y, startX+w, lineStr+startIndex, i-startIndex ); + if (mode==FIND_INDEX) { + // find x pos inside block + int di = find_x(lineStr+startIndex, i-startIndex, style, rightClip-startX); + free(lineStr); + IS_UTF8_ALIGNED2(buffer(), (lineStartPos+startIndex+di)) + return lineStartPos + startIndex + di; + } + } + if (mode==GET_WIDTH) { + free(lineStr); + return startX+w; + } + + // clear the rest of the line + startX += w; + style = position_style(lineStartPos, lineLen, i); + if (mode==DRAW_LINE) + draw_string( style|BG_ONLY_MASK, startX, Y, text_area.x+text_area.w, lineStr, lineLen ); + + free(lineStr); + IS_UTF8_ALIGNED2(buffer(), (lineStartPos+lineLen)) + return lineStartPos + lineLen; +} + + +/** + \brief Find the index of the character that lies at the given x position. + \param s UTF-8 text string + \param len length of string + \param style index into style lookup table + \param x position in pixels + \return index into buffer + */ +int Fl_Text_Display_mod::find_x(const char *s, int len, int style, int x) const { + IS_UTF8_ALIGNED(s) + + // TODO: use binary search which may be quicker. + int i = 0; + while (ix) + return i; + i += cl; + } + return len; +} + + + +/** + \brief Draw a single line of text. + + Draw the text on a single line represented by \p visLineNum (the + number of lines down from the top of the display), limited by + \p leftClip and \p rightClip window coordinates and \p leftCharIndex and + \p rightCharIndex character positions (not including the character at + position \p rightCharIndex). + + \param visLineNum index of line in the visible line number lookup + \param leftClip, rightClip pixel position of clipped area + \param leftCharIndex, rightCharIndex index into line of segment that we want to draw + */ +void Fl_Text_Display_mod::draw_vline(int visLineNum, int leftClip, int rightClip, + int leftCharIndex, int rightCharIndex) { + int Y, lineStartPos, lineLen, fontHeight; + + // printf("draw_vline(visLineNum=%d, leftClip=%d, rightClip=%d, leftCharIndex=%d, rightCharIndex=%d)\n", + // visLineNum, leftClip, rightClip, leftCharIndex, rightCharIndex); + // printf("nNVisibleLines=%d\n", mNVisibleLines); + + /* If line is not displayed, skip it */ + if ( visLineNum < 0 || visLineNum >= mNVisibleLines ) + return; + + /* Calculate Y coordinate of the string to draw */ + fontHeight = mMaxsize; + Y = text_area.y + visLineNum * fontHeight; + + /* Get the text, length, and buffer position of the line to display */ + lineStartPos = mLineStarts[ visLineNum ]; + if ( lineStartPos == -1 ) { + lineLen = 0; + } else { + lineLen = vline_length( visLineNum ); + } + + /* Shrink the clipping range to the active display area */ + leftClip = max( text_area.x, leftClip ); + rightClip = min( rightClip, text_area.x + text_area.w ); + + handle_vline(DRAW_LINE, + lineStartPos, lineLen, leftCharIndex, rightCharIndex, + Y, Y+fontHeight, leftClip, rightClip); + return; +} + + + +/** + \brief Draw a text segment in a single style. + + Draw a string or blank area according to parameter \p style, using the + appropriate colors and drawing method for that style, with top left + corner at \p X, \p Y. If style says to draw text, use \p string as + source of characters, and draw \p nChars, if style is FILL, erase + rectangle where text would have drawn from \p X to \p toX and from + \p Y to the maximum y extent of the current font(s). + + \param style index into style lookup table + \param X, Y drawing origin + \param toX rightmost position if this is a fill operation + \param string text if this is a drawing operation + \param nChars number of characters to draw + */ +void Fl_Text_Display_mod::draw_string(int style, + int X, int Y, int toX, + const char *string, int nChars) const { + IS_UTF8_ALIGNED(string) + + const Style_Table_Entry * styleRec; + + /* Draw blank area rather than text, if that was the request */ + if ( style & FILL_MASK ) { + if (style & TEXT_ONLY_MASK) return; + clear_rect( style, X, Y, toX - X, mMaxsize ); + return; + } + /* Set font, color, and gc depending on style. For normal text, GCs + for normal drawing, or drawing within a Fl_Text_Selection or highlight are + pre-allocated and pre-configured. For syntax highlighting, GCs are + configured here, on the fly. */ + + Fl_Font font = textfont(); + int fsize = textsize(); + Fl_Color foreground; + Fl_Color background; + + if ( style & STYLE_LOOKUP_MASK ) { + int si = (style & STYLE_LOOKUP_MASK) - 'A'; + if (si < 0) si = 0; + else if (si >= mNStyles) si = mNStyles - 1; + + styleRec = mStyleTable + si; + font = styleRec->font; + fsize = styleRec->size; + + if (style & PRIMARY_MASK) { + if (Fl::focus() == (Fl_Widget*)this) background = selection_color(); + else background = fl_color_average(color(), selection_color(), 0.4f); + } else if (style & HIGHLIGHT_MASK) { + if (Fl::focus() == (Fl_Widget*)this) background = fl_color_average(color(), selection_color(), 0.5f); + else background = fl_color_average(color(), selection_color(), 0.6f); + } else background = color(); + foreground = fl_contrast(styleRec->color, background); + } else if (style & PRIMARY_MASK) { + if (Fl::focus() == (Fl_Widget*)this) background = selection_color(); + else background = fl_color_average(color(), selection_color(), 0.4f); + foreground = fl_contrast(textcolor(), background); + } else if (style & HIGHLIGHT_MASK) { + if (Fl::focus() == (Fl_Widget*)this) background = fl_color_average(color(), selection_color(), 0.5f); + else background = fl_color_average(color(), selection_color(), 0.6f); + foreground = fl_contrast(textcolor(), background); + } else { + foreground = textcolor(); + background = color(); + } + + if (!(style & TEXT_ONLY_MASK)) { + fl_color( background ); + fl_rectf( X, Y, toX - X, mMaxsize ); + } + if (!(style & BG_ONLY_MASK)) { + fl_color( foreground ); + fl_font( font, fsize ); +#if !(defined(__APPLE__) || defined(WIN32)) && USE_XFT + // makes sure antialiased ÄÖÜ do not leak on line above + fl_push_clip(X, Y, toX - X, mMaxsize); +#endif + fl_draw( string, nChars, X, Y + mMaxsize - fl_descent()); +#if !(defined(__APPLE__) || defined(WIN32)) && USE_XFT + fl_pop_clip(); +#endif + } + + // CET - FIXME + /* If any space around the character remains unfilled (due to use of + different sized fonts for highlighting), fill in above or below + to erase previously drawn characters */ + /* + if (fs->ascent < mAscent) + clear_rect( style, X, Y, toX - X, mAscent - fs->ascent); + if (fs->descent < mDescent) + clear_rect( style, X, Y + mAscent + fs->descent, toX - x, + mDescent - fs->descent); + */ + /* Underline if style is secondary Fl_Text_Selection */ + + /* + if (style & SECONDARY_MASK) + XDrawLine(XtDisplay(mW), XtWindow(mW), gc, x, + y + mAscent, toX - 1, Y + fs->ascent); + */ +} + + + +/** + \brief Clear a rectangle with the appropriate background color for \p style. + + \param style index into style table + \param X, Y, width, height size and position of background area + */ +void Fl_Text_Display_mod::clear_rect(int style, + int X, int Y, + int width, int height) const { + /* A width of zero means "clear to end of window" to XClearArea */ + if ( width == 0 ) + return; + + if (style & PRIMARY_MASK) { + if (Fl::focus()==(Fl_Widget*)this) { + fl_color(selection_color()); + } else { + fl_color(fl_color_average(color(), selection_color(), 0.4f)); + } + } else if (style & HIGHLIGHT_MASK) { + if (Fl::focus()==(Fl_Widget*)this) { + fl_color(fl_color_average(color(), selection_color(), 0.5f)); + } else { + fl_color(fl_color_average(color(), selection_color(), 0.6f)); + } + } else { + fl_color( color() ); + } + fl_rectf( X, Y, width, height ); +} + + + +/** + \brief Draw a cursor with top center at \p X, \p Y. + + \param X, Y cursor position in pixels + */ +void Fl_Text_Display_mod::draw_cursor( int X, int Y ) { + + typedef struct { + int x1, y1, x2, y2; + } + Segment; + + Segment segs[ 5 ]; + int left, right, cursorWidth, midY; + // int fontWidth = mFontStruct->min_bounds.width, nSegs = 0; + int fontWidth = TMPFONTWIDTH; // CET - FIXME + int nSegs = 0; + int fontHeight = mMaxsize; + int bot = Y + fontHeight - 1; + + if ( X < text_area.x - 1 || X > text_area.x + text_area.w ) + return; + + /* For cursors other than the block, make them around 2/3 of a character + width, rounded to an even number of pixels so that X will draw an + odd number centered on the stem at x. */ + cursorWidth = 4; //(fontWidth/3) * 2; + left = X - cursorWidth / 2; + right = left + cursorWidth; + + /* Create segments and draw cursor */ + if ( mCursorStyle == CARET_CURSOR ) { + midY = bot - fontHeight / 5; + segs[ 0 ].x1 = left; segs[ 0 ].y1 = bot; segs[ 0 ].x2 = X; segs[ 0 ].y2 = midY; + segs[ 1 ].x1 = X; segs[ 1 ].y1 = midY; segs[ 1 ].x2 = right; segs[ 1 ].y2 = bot; + segs[ 2 ].x1 = left; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = X; segs[ 2 ].y2 = midY - 1; + segs[ 3 ].x1 = X; segs[ 3 ].y1 = midY - 1; segs[ 3 ].x2 = right; segs[ 3 ].y2 = bot; + nSegs = 4; + } else if ( mCursorStyle == NORMAL_CURSOR ) { + segs[ 0 ].x1 = left; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = right; segs[ 0 ].y2 = Y; + segs[ 1 ].x1 = X; segs[ 1 ].y1 = Y; segs[ 1 ].x2 = X; segs[ 1 ].y2 = bot; + segs[ 2 ].x1 = left; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = right; segs[ 2 ].y2 = bot; + nSegs = 3; + } else if ( mCursorStyle == HEAVY_CURSOR ) { + segs[ 0 ].x1 = X - 1; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = X - 1; segs[ 0 ].y2 = bot; + segs[ 1 ].x1 = X; segs[ 1 ].y1 = Y; segs[ 1 ].x2 = X; segs[ 1 ].y2 = bot; + segs[ 2 ].x1 = X + 1; segs[ 2 ].y1 = Y; segs[ 2 ].x2 = X + 1; segs[ 2 ].y2 = bot; + segs[ 3 ].x1 = left; segs[ 3 ].y1 = Y; segs[ 3 ].x2 = right; segs[ 3 ].y2 = Y; + segs[ 4 ].x1 = left; segs[ 4 ].y1 = bot; segs[ 4 ].x2 = right; segs[ 4 ].y2 = bot; + nSegs = 5; + } else if ( mCursorStyle == DIM_CURSOR ) { + midY = Y + fontHeight / 2; + segs[ 0 ].x1 = X; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = X; segs[ 0 ].y2 = Y; + segs[ 1 ].x1 = X; segs[ 1 ].y1 = midY; segs[ 1 ].x2 = X; segs[ 1 ].y2 = midY; + segs[ 2 ].x1 = X; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = X; segs[ 2 ].y2 = bot; + nSegs = 3; + } else if ( mCursorStyle == BLOCK_CURSOR ) { + right = X + fontWidth; + segs[ 0 ].x1 = X; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = right; segs[ 0 ].y2 = Y; + segs[ 1 ].x1 = right; segs[ 1 ].y1 = Y; segs[ 1 ].x2 = right; segs[ 1 ].y2 = bot; + segs[ 2 ].x1 = right; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = X; segs[ 2 ].y2 = bot; + segs[ 3 ].x1 = X; segs[ 3 ].y1 = bot; segs[ 3 ].x2 = X; segs[ 3 ].y2 = Y; + nSegs = 4; + } + fl_color( mCursor_color ); + + for ( int k = 0; k < nSegs; k++ ) { + fl_line( segs[ k ].x1, segs[ k ].y1, segs[ k ].x2, segs[ k ].y2 ); + } +} + + + +/** + \brief Find the correct style for a character. + + Determine the drawing method to use to draw a specific character from "buf". + \p lineStartPos gives the character index where the line begins, \p lineIndex, + the number of characters past the beginning of the line, and \p lineIndex + the number of displayed characters past the beginning of the line. Passing + \p lineStartPos of -1 returns the drawing style for "no text". + + Why not just: position_style(pos)? Because style applies to blank areas + of the window beyond the text boundaries, and because this routine must also + decide whether a position is inside of a rectangular Fl_Text_Selection, and do + so efficiently, without re-counting character positions from the start of the + line. + + Note that style is a somewhat incorrect name, drawing method would + be more appropriate. + + \param lineStartPos beginning of this line + \param lineLen number of bytes in line + \param lineIndex position of character within line + \return style for the given character + */ +int Fl_Text_Display_mod::position_style( int lineStartPos, int lineLen, int lineIndex) const +{ + IS_UTF8_ALIGNED2(buffer(), lineStartPos) + + Fl_Text_Buffer_mod * buf = mBuffer; + Fl_Text_Buffer_mod *styleBuf = mStyleBuffer; + int pos, style = 0; + + if ( lineStartPos == -1 || buf == NULL ) + return FILL_MASK; + + pos = lineStartPos + min( lineIndex, lineLen ); + + if ( lineIndex >= lineLen ) + style = FILL_MASK; + else if ( styleBuf != NULL ) { + style = ( unsigned char ) styleBuf->byte_at( pos ); + if (style == mUnfinishedStyle && mUnfinishedHighlightCB) { + /* encountered "unfinished" style, trigger parsing */ + (mUnfinishedHighlightCB)( pos, mHighlightCBArg); + style = (unsigned char) styleBuf->byte_at( pos); + } + } + if (buf->primary_selection()->includes(pos)) + style |= PRIMARY_MASK; + if (buf->highlight_selection()->includes(pos)) + style |= HIGHLIGHT_MASK; + if (buf->secondary_selection()->includes(pos)) + style |= SECONDARY_MASK; + return style; +} + + +/** + \brief Find the width of a string in the font of a particular style. + + \param string the text + \param length number of bytes in string + \param style index into style table + \return width of text segment in pixels + */ +double Fl_Text_Display_mod::string_width( const char *string, int length, int style ) const { + IS_UTF8_ALIGNED(string) + + Fl_Font font; + Fl_Fontsize fsize; + + if ( mNStyles && (style & STYLE_LOOKUP_MASK) ) { + int si = (style & STYLE_LOOKUP_MASK) - 'A'; + if (si < 0) si = 0; + else if (si >= mNStyles) si = mNStyles - 1; + + font = mStyleTable[si].font; + fsize = mStyleTable[si].size; + } else { + font = textfont(); + fsize = textsize(); + } + fl_font( font, fsize ); + return fl_width( string, length ); +} + + + +/** + \brief Translate a pixel position into a character index. + + Translate window coordinates to the nearest (insert cursor or character + cell) text position. The parameter \p posType specifies how to interpret the + position: CURSOR_POS means translate the coordinates to the nearest cursor + position, and CHARACTER_POS means return the position of the character + closest to (\p X, \p Y). + + \param X, Y pixel position + \param posType CURSOR_POS or CHARACTER_POS + \return index into text buffer + */ +int Fl_Text_Display_mod::xy_to_position( int X, int Y, int posType ) const { + int lineStart, lineLen, fontHeight; + int visLineNum; + + /* Find the visible line number corresponding to the Y coordinate */ + fontHeight = mMaxsize; + visLineNum = ( Y - text_area.y ) / fontHeight; + if ( visLineNum < 0 ) + return mFirstChar; + if ( visLineNum >= mNVisibleLines ) + visLineNum = mNVisibleLines - 1; + + /* Find the position at the start of the line */ + lineStart = mLineStarts[ visLineNum ]; + + /* If the line start was empty, return the last position in the buffer */ + if ( lineStart == -1 ) + return mBuffer->length(); + + /* Get the line text and its length */ + lineLen = vline_length( visLineNum ); + + return handle_vline(FIND_INDEX, + lineStart, lineLen, 0, 0, + 0, 0, + text_area.x, X); +} + + + +/** + \brief Translate pixel coordinates into row and column. + + Translate window coordinates to the nearest row and column number for + positioning the cursor. This, of course, makes no sense when the font is + proportional, since there are no absolute columns. The parameter posType + specifies how to interpret the position: CURSOR_POS means translate the + coordinates to the nearest position between characters, and CHARACTER_POS + means translate the position to the nearest character cell. + + \param X, Y pixel coordinates + \param[out] row, column neares row and column + \param posType CURSOR_POS or CHARACTER_POS + */ +void Fl_Text_Display_mod::xy_to_rowcol( int X, int Y, int *row, + int *column, int posType ) const { + int fontHeight = mMaxsize; + int fontWidth = TMPFONTWIDTH; //mFontStruct->max_bounds.width; + + /* Find the visible line number corresponding to the Y coordinate */ + *row = ( Y - text_area.y ) / fontHeight; + if ( *row < 0 ) *row = 0; + if ( *row >= mNVisibleLines ) *row = mNVisibleLines - 1; + + *column = ( ( X - text_area.x ) + mHorizOffset + + ( posType == CURSOR_POS ? fontWidth / 2 : 0 ) ) / fontWidth; + if ( *column < 0 ) * column = 0; +} + + + +/** + \brief Offset line start counters for a new vertical scroll position. + + Offset the line starts array, mTopLineNum, mFirstChar and lastChar, for a new + vertical scroll position given by newTopLineNum. If any currently displayed + lines will still be visible, salvage the line starts values, otherwise, + count lines from the nearest known line start (start or end of buffer, or + the closest value in the mLineStarts array) + + \param newTopLineNum index into buffer + */ +void Fl_Text_Display_mod::offset_line_starts( int newTopLineNum ) { + int oldTopLineNum = mTopLineNum; + int oldFirstChar = mFirstChar; + int lineDelta = newTopLineNum - oldTopLineNum; + int nVisLines = mNVisibleLines; + int *lineStarts = mLineStarts; + int i, lastLineNum; + Fl_Text_Buffer_mod *buf = mBuffer; + + /* If there was no offset, nothing needs to be changed */ + if ( lineDelta == 0 ) + return; + + /* Find the new value for mFirstChar by counting lines from the nearest + known line start (start or end of buffer, or the closest value in the + lineStarts array) */ + lastLineNum = oldTopLineNum + nVisLines - 1; + if ( newTopLineNum < oldTopLineNum && newTopLineNum < -lineDelta ) { + mFirstChar = skip_lines( 0, newTopLineNum - 1, true ); + } else if ( newTopLineNum < oldTopLineNum ) { + mFirstChar = rewind_lines( mFirstChar, -lineDelta ); + } else if ( newTopLineNum < lastLineNum ) { + mFirstChar = lineStarts[ newTopLineNum - oldTopLineNum ]; + } else if ( newTopLineNum - lastLineNum < mNBufferLines - newTopLineNum ) { + mFirstChar = skip_lines( lineStarts[ nVisLines - 1 ], + newTopLineNum - lastLineNum, true ); + } else { + mFirstChar = rewind_lines( buf->length(), mNBufferLines - newTopLineNum + 1 ); + } + + /* Fill in the line starts array */ + if ( lineDelta < 0 && -lineDelta < nVisLines ) { + for ( i = nVisLines - 1; i >= -lineDelta; i-- ) + lineStarts[ i ] = lineStarts[ i + lineDelta ]; + calc_line_starts( 0, -lineDelta ); + } else if ( lineDelta > 0 && lineDelta < nVisLines ) { + for ( i = 0; i < nVisLines - lineDelta; i++ ) + lineStarts[ i ] = lineStarts[ i + lineDelta ]; + calc_line_starts( nVisLines - lineDelta, nVisLines - 1 ); + } else + calc_line_starts( 0, nVisLines ); + + /* Set lastChar and mTopLineNum */ + calc_last_char(); + mTopLineNum = newTopLineNum; + + /* If we're numbering lines or being asked to maintain an absolute line + number, re-calculate the absolute line number */ + absolute_top_line_number(oldFirstChar); +} + + + +/** + \brief Update line start arrays and variables. + + Update the line starts array, mTopLineNum, mFirstChar and lastChar for this + text display after a modification to the text buffer, given by the + position \p pos where the change began, and the numbers of characters + and lines inserted and deleted. + + \param pos index into buffer of recent changes + \param charsInserted number of bytes(!) inserted + \param charsDeleted number of bytes(!) deleted + \param linesInserted number of lines + \param linesDeleted number of lines + \param[out] scrolled set to 1 if the text display needs to be scrolled + */ +void Fl_Text_Display_mod::update_line_starts(int pos, int charsInserted, + int charsDeleted, int linesInserted, + int linesDeleted, int *scrolled ) { + IS_UTF8_ALIGNED2(buffer(), pos) + + int *lineStarts = mLineStarts; + int i, lineOfPos, lineOfEnd, nVisLines = mNVisibleLines; + int charDelta = charsInserted - charsDeleted; + int lineDelta = linesInserted - linesDeleted; + + /* If all of the changes were before the displayed text, the display + doesn't change, just update the top line num and offset the line + start entries and first and last characters */ + if ( pos + charsDeleted < mFirstChar ) { + mTopLineNum += lineDelta; + for ( i = 0; i < nVisLines && lineStarts[i] != -1; i++ ) + lineStarts[ i ] += charDelta; + mFirstChar += charDelta; + mLastChar += charDelta; + *scrolled = 0; + return; + } + + /* The change began before the beginning of the displayed text, but + part or all of the displayed text was deleted */ + if ( pos < mFirstChar ) { + /* If some text remains in the window, anchor on that */ + if ( position_to_line( pos + charsDeleted, &lineOfEnd ) && + ++lineOfEnd < nVisLines && lineStarts[ lineOfEnd ] != -1 ) { + mTopLineNum = max( 1, mTopLineNum + lineDelta ); + mFirstChar = rewind_lines(lineStarts[ lineOfEnd ] + charDelta, lineOfEnd ); + /* Otherwise anchor on original line number and recount everything */ + } else { + if ( mTopLineNum > mNBufferLines + lineDelta ) { + mTopLineNum = 1; + mFirstChar = 0; + } else + mFirstChar = skip_lines( 0, mTopLineNum - 1, true ); + } + calc_line_starts( 0, nVisLines - 1 ); + /* calculate lastChar by finding the end of the last displayed line */ + calc_last_char(); + *scrolled = 1; + return; + } + + /* If the change was in the middle of the displayed text (it usually is), + salvage as much of the line starts array as possible by moving and + offsetting the entries after the changed area, and re-counting the + added lines or the lines beyond the salvaged part of the line starts + array */ + if ( pos <= mLastChar ) { + /* find line on which the change began */ + position_to_line( pos, &lineOfPos ); + /* salvage line starts after the changed area */ + if ( lineDelta == 0 ) { + for ( i = lineOfPos + 1; i < nVisLines && lineStarts[ i ] != -1; i++ ) + lineStarts[ i ] += charDelta; + } else if ( lineDelta > 0 ) { + for ( i = nVisLines - 1; i >= lineOfPos + lineDelta + 1; i-- ) + lineStarts[ i ] = lineStarts[ i - lineDelta ] + + ( lineStarts[ i - lineDelta ] == -1 ? 0 : charDelta ); + } else /* (lineDelta < 0) */ { + for ( i = max( 0, lineOfPos + 1 ); i < nVisLines + lineDelta; i++ ) + lineStarts[ i ] = lineStarts[ i - lineDelta ] + + ( lineStarts[ i - lineDelta ] == -1 ? 0 : charDelta ); + } + /* fill in the missing line starts */ + if ( linesInserted >= 0 ) + calc_line_starts( lineOfPos + 1, lineOfPos + linesInserted ); + if ( lineDelta < 0 ) + calc_line_starts( nVisLines + lineDelta, nVisLines ); + /* calculate lastChar by finding the end of the last displayed line */ + calc_last_char(); + *scrolled = 0; + return; + } + + /* Change was past the end of the displayed text, but displayable by virtue + of being an insert at the end of the buffer into visible blank lines */ + if ( empty_vlines() ) { + position_to_line( pos, &lineOfPos ); + calc_line_starts( lineOfPos, lineOfPos + linesInserted ); + calc_last_char(); + *scrolled = 0; + return; + } + + /* Change was beyond the end of the buffer and not visible, do nothing */ + *scrolled = 0; +} + + + +/** + \brief Update the line start arrays. + + Scan through the text in the "textD"'s buffer and recalculate the line + starts array values beginning at index "startLine" and continuing through + (including) "endLine". It assumes that the line starts entry preceding + "startLine" (or mFirstChar if startLine is 0) is good, and re-counts + newlines to fill in the requested entries. Out of range values for + "startLine" and "endLine" are acceptable. + + \param startLine, endLine range of lines to scan as line numbers + */ +void Fl_Text_Display_mod::calc_line_starts( int startLine, int endLine ) { + int startPos, bufLen = mBuffer->length(); + int line, lineEnd, nextLineStart, nVis = mNVisibleLines; + int *lineStarts = mLineStarts; + + /* Clean up (possibly) messy input parameters */ + if ( endLine < 0 ) endLine = 0; + if ( endLine >= nVis ) endLine = nVis - 1; + if ( startLine < 0 ) startLine = 0; + if ( startLine >= nVis ) startLine = nVis - 1; + if ( startLine > endLine ) + return; + + /* Find the last known good line number -> position mapping */ + if ( startLine == 0 ) { + lineStarts[ 0 ] = mFirstChar; + startLine = 1; + } + startPos = lineStarts[ startLine - 1 ]; + + /* If the starting position is already past the end of the text, + fill in -1's (means no text on line) and return */ + if ( startPos == -1 ) { + for ( line = startLine; line <= endLine; line++ ) + lineStarts[ line ] = -1; + return; + } + + /* Loop searching for ends of lines and storing the positions of the + start of the next line in lineStarts */ + for ( line = startLine; line <= endLine; line++ ) { + find_line_end(startPos, true, &lineEnd, &nextLineStart); + startPos = nextLineStart; + if ( startPos >= bufLen ) { + /* If the buffer ends with a newline or line break, put + buf->length() in the next line start position (instead of + a -1 which is the normal marker for an empty line) to + indicate that the cursor may safely be displayed there */ + if ( line == 0 || ( lineStarts[ line - 1 ] != bufLen && + lineEnd != nextLineStart ) ) { + lineStarts[ line ] = bufLen; + line++; + } + break; + } + lineStarts[ line ] = startPos; + } + + /* Set any entries beyond the end of the text to -1 */ + for ( ; line <= endLine; line++ ) + lineStarts[ line ] = -1; +} + + + +/** + \brief Update last display character index. + + Given a Fl_Text_Display_mod with a complete, up-to-date lineStarts array, update + the lastChar entry to point to the last buffer position displayed. + */ +void Fl_Text_Display_mod::calc_last_char() { + int i; + for (i = mNVisibleLines - 1; i >= 0 && mLineStarts[i] == -1; i--) ; + mLastChar = i < 0 ? 0 : line_end(mLineStarts[i], true); +} + + + +/** + \brief Scrolls the current buffer to start at the specified line and column. + \param topLineNum top line number + \param horizOffset column number + \todo Column numbers make little sense here. + */ +void Fl_Text_Display_mod::scroll(int topLineNum, int horizOffset) { + mTopLineNumHint = topLineNum; + mHorizOffsetHint = horizOffset; + resize(x(), y(), w(), h()); +} + + + +/** + \brief Scrolls the current buffer to start at the specified line and column. + \param topLineNum top line number + \param horizOffset in pixels + \return 0 if nothing changed, 1 if we scrolled + */ +int Fl_Text_Display_mod::scroll_(int topLineNum, int horizOffset) { + /* Limit the requested scroll position to allowable values */ + if (topLineNum > mNBufferLines + 3 - mNVisibleLines) + topLineNum = mNBufferLines + 3 - mNVisibleLines; + if (topLineNum < 1) topLineNum = 1; + + if (horizOffset > longest_vline() - text_area.w) + horizOffset = longest_vline() - text_area.w; + if (horizOffset < 0) horizOffset = 0; + + /* Do nothing if scroll position hasn't actually changed or there's no + window to draw in yet */ + if (mHorizOffset == horizOffset && mTopLineNum == topLineNum) + return 0; + + /* If the vertical scroll position has changed, update the line + starts array and related counters in the text display */ + offset_line_starts(topLineNum); + + /* Just setting mHorizOffset is enough information for redisplay */ + mHorizOffset = horizOffset; + + // redraw all text + damage(FL_DAMAGE_EXPOSE); + return 1; +} + + + +/** + \brief Update vertical scrollbar. + + Update the minimum, maximum, slider size, page increment, and value + for vertical scrollbar. + */ +void Fl_Text_Display_mod::update_v_scrollbar() { + /* The vertical scrollbar value and slider size directly represent the top + line number, and the number of visible lines respectively. The scroll + bar maximum value is chosen to generally represent the size of the whole + buffer, with minor adjustments to keep the scrollbar widget happy */ +#ifdef DEBUG + printf("Fl_Text_Display_mod::update_v_scrollbar():\n" + " mTopLineNum=%d, mNVisibleLines=%d, mNBufferLines=%d\n", + mTopLineNum, mNVisibleLines, mNBufferLines); +#endif // DEBUG + + mVScrollBar->value(mTopLineNum, mNVisibleLines, 1, mNBufferLines + 2); + mVScrollBar->linesize(3); +} + + +/** + \brief Update vertical scrollbar. + + Update the minimum, maximum, slider size, page increment, and value + for the horizontal scrollbar. + */ +void Fl_Text_Display_mod::update_h_scrollbar() { + int sliderMax = max(longest_vline(), text_area.w + mHorizOffset); + mHScrollBar->value( mHorizOffset, text_area.w, 0, sliderMax ); +} + + + +/** + \brief Callbacks for drag or valueChanged on scrollbars. + */ +void Fl_Text_Display_mod::v_scrollbar_cb(Fl_Scrollbar* b, Fl_Text_Display_mod* textD) { + if (b->value() == textD->mTopLineNum) return; + textD->scroll(b->value(), textD->mHorizOffset); +} + + + +/** + \brief Callbacks for drag or valueChanged on scrollbars. + */ +void Fl_Text_Display_mod::h_scrollbar_cb(Fl_Scrollbar* b, Fl_Text_Display_mod* textD) { + if (b->value() == textD->mHorizOffset) return; + textD->scroll(textD->mTopLineNum, b->value()); +} + + + +/** + \brief Refresh the line number area. + + If clearAll is False, writes only over the character cell areas. Setting + clearAll to True will clear out any stray marks outside of the character cell + area, which might have been left from before a resize or font change. + + This function is not used. + */ +void Fl_Text_Display_mod::draw_line_numbers(bool /*clearAll*/) { +#if 0 + int y, line, visLine, nCols, lineStart; + char lineNumString[12]; + int lineHeight = mMaxsize ? mMaxsize : textsize_; + int charWidth = TMPFONTWIDTH; //mFontStruct->max_bounds.width; + + /* Don't draw if mLineNumWidth == 0 (line numbers are hidden), or widget is + not yet realized */ + if (mLineNumWidth == 0 || visible_r()) + return; + + /* GC is allocated on demand, since not everyone will use line numbering */ + if (textD->lineNumGC == NULL) { + XGCValues values; + values.foreground = textD->lineNumFGPixel; + values.background = textD->bgPixel; + values.font = textD->fontStruct->fid; + textD->lineNumGC = XtGetGC(textD->w, + GCFont| GCForeground | GCBackground, &values); + } + + /* Erase the previous contents of the line number area, if requested */ + if (clearAll) + XClearArea(XtDisplay(textD->w), XtWindow(textD->w), textD->lineNumLeft, + textD->top, textD->lineNumWidth, textD->height, False); + + /* Draw the line numbers, aligned to the text */ + nCols = min(11, textD->lineNumWidth / charWidth); + y = textD->top; + line = getAbsTopLineNum(textD); + for (visLine=0; visLine < textD->nVisibleLines; visLine++) { + lineStart = textD->lineStarts[visLine]; + if (lineStart != -1 && (lineStart==0 || + BufGetCharacter(textD->buffer, lineStart-1)=='\n')) { + sprintf(lineNumString, "%*d", nCols, line); + XDrawImageString(XtDisplay(textD->w), XtWindow(textD->w), + textD->lineNumGC, textD->lineNumLeft, y + textD->ascent, + lineNumString, strlen(lineNumString)); + line++; + } else { + XClearArea(XtDisplay(textD->w), XtWindow(textD->w), + textD->lineNumLeft, y, textD->lineNumWidth, + textD->ascent + textD->descent, False); + if (visLine == 0) + line++; + } + y += lineHeight; + } +#endif +} + +static int max( int i1, int i2 ) { + return i1 >= i2 ? i1 : i2; +} + +static int min( int i1, int i2 ) { + return i1 <= i2 ? i1 : i2; +} + + + +/** + Count the number of newlines in a null-terminated text string; + */ +static int countlines( const char *string ) { + IS_UTF8_ALIGNED(string) + + const char * c; + int lineCount = 0; + + if (!string) return 0; + + for ( c = string; *c != '\0'; c++ ) + if ( *c == '\n' ) lineCount++; + return lineCount; +} + + + + +/** + \brief Returns the width in pixels of the displayed line pointed to by "visLineNum". + \param visLineNum index into visible lines array + \return width of line in pixels + */ +int Fl_Text_Display_mod::measure_vline( int visLineNum ) const { + int lineLen = vline_length( visLineNum ); + int lineStartPos = mLineStarts[ visLineNum ]; + if (lineStartPos < 0 || lineLen == 0) return 0; + return handle_vline(GET_WIDTH, lineStartPos, lineLen, 0, 0, 0, 0, 0, 0); +} + + + +/** + \brief Return true if there are lines visible with no corresponding buffer text. + \return 1 if there are empty lines + */ +int Fl_Text_Display_mod::empty_vlines() const { + return (mNVisibleLines > 0) && (mLineStarts[ mNVisibleLines - 1 ] == -1); +} + + +/** + \brief Count number of bytes in a visible line. + + Return the length of a line (number of bytes) by examining + entries in the line starts array rather than by scanning for newlines. + + \param visLineNum index of line in visible line array + \return number of bytes in this line + */ +int Fl_Text_Display_mod::vline_length( int visLineNum ) const { + int nextLineStart, lineStartPos; + + if (visLineNum < 0 || visLineNum >= mNVisibleLines) + return (0); + + lineStartPos = mLineStarts[ visLineNum ]; + + if ( lineStartPos == -1 ) + return 0; + + if ( visLineNum + 1 >= mNVisibleLines ) + return mLastChar - lineStartPos; + + nextLineStart = mLineStarts[ visLineNum + 1 ]; + if ( nextLineStart == -1 ) + return mLastChar - lineStartPos; + + int nextLineStartMinus1 = buffer()->prev_char(nextLineStart); + if (wrap_uses_character(nextLineStartMinus1)) + return nextLineStartMinus1 - lineStartPos; + + return nextLineStart - lineStartPos; +} + + + +/** + \brief Wrapping calculations. + + When continuous wrap is on, and the user inserts or deletes characters, + wrapping can happen before and beyond the changed position. This routine + finds the extent of the changes, and counts the deleted and inserted lines + over that range. It also attempts to minimize the size of the range to + what has to be counted and re-displayed, so the results can be useful + both for delimiting where the line starts need to be recalculated, and + for deciding what part of the text to redisplay. + + \param deletedText + \param pos + \param nInserted + \param nDeleted + \param modRangeStart + \param modRangeEnd + \param linesInserted + \param linesDeleted + */ +void Fl_Text_Display_mod::find_wrap_range(const char *deletedText, int pos, + int nInserted, int nDeleted, + int *modRangeStart, int *modRangeEnd, + int *linesInserted, int *linesDeleted) { + IS_UTF8_ALIGNED(deletedText) + IS_UTF8_ALIGNED2(buffer(), pos) + + int length, retPos, retLines, retLineStart, retLineEnd; + Fl_Text_Buffer_mod *deletedTextBuf, *buf = buffer(); + int nVisLines = mNVisibleLines; + int *lineStarts = mLineStarts; + int countFrom, countTo, lineStart, adjLineStart, i; + int visLineNum = 0, nLines = 0; + + /* + ** Determine where to begin searching: either the previous newline, or + ** if possible, limit to the start of the (original) previous displayed + ** line, using information from the existing line starts array + */ + if (pos >= mFirstChar && pos <= mLastChar) { + for (i=nVisLines-1; i>0; i--) { + if (lineStarts[i] != -1 && pos >= lineStarts[i]) { + break; + } + } + if (i > 0) { + countFrom = lineStarts[i-1]; + visLineNum = i-1; + } else { + countFrom = buf->line_start(pos); + } + } else { + countFrom = buf->line_start(pos); + } + + IS_UTF8_ALIGNED2(buf, countFrom) + + /* + ** Move forward through the (new) text one line at a time, counting + ** displayed lines, and looking for either a real newline, or for the + ** line starts to re-sync with the original line starts array + */ + lineStart = countFrom; + *modRangeStart = countFrom; + for (;;) { + + /* advance to the next line. If the line ended in a real newline + or the end of the buffer, that's far enough */ + wrapped_line_counter(buf, lineStart, buf->length(), 1, true, 0, + &retPos, &retLines, &retLineStart, &retLineEnd); + if (retPos >= buf->length()) { + countTo = buf->length(); + *modRangeEnd = countTo; + if (retPos != retLineEnd) + nLines++; + break; + } else { + lineStart = retPos; + } + nLines++; + if (lineStart > pos + nInserted && buf->char_at(buf->prev_char(lineStart)) == '\n') { + countTo = lineStart; + *modRangeEnd = lineStart; + break; + } + + /* Don't try to resync in continuous wrap mode with non-fixed font + sizes; it would result in a chicken-and-egg dependency between + the calculations for the inserted and the deleted lines. + If we're in that mode, the number of deleted lines is calculated in + advance, without resynchronization, so we shouldn't resynchronize + for the inserted lines either. */ + if (mSuppressResync) + continue; + + /* check for synchronization with the original line starts array + before pos, if so, the modified range can begin later */ + if (lineStart <= pos) { + while (visLineNumprev_char(lineStarts[visLineNum+1])); + else + *modRangeStart = countFrom; + } else + *modRangeStart = min(*modRangeStart, buf->prev_char(lineStart)); + } + + /* check for synchronization with the original line starts array + after pos, if so, the modified range can end early */ + else if (lineStart > pos + nInserted) { + adjLineStart = lineStart - nInserted + nDeleted; + while (visLineNumcopy(buffer(), countFrom, pos, 0); + if (nDeleted != 0) + deletedTextBuf->insert(pos-countFrom, deletedText); + deletedTextBuf->copy(buffer(), pos+nInserted, countTo, pos-countFrom+nDeleted); + /* Note that we need to take into account an offset for the style buffer: + the deletedTextBuf can be out of sync with the style buffer. */ + wrapped_line_counter(deletedTextBuf, 0, length, INT_MAX, true, countFrom, + &retPos, &retLines, &retLineStart, &retLineEnd, false); + delete deletedTextBuf; + *linesDeleted = retLines; + mSuppressResync = 0; +} + + + +/** + \brief Wrapping calculations. + + This is a stripped-down version of the findWrapRange() function above, + intended to be used to calculate the number of "deleted" lines during + a buffer modification. It is called _before_ the modification takes place. + + This function should only be called in continuous wrap mode with a + non-fixed font width. In that case, it is impossible to calculate + the number of deleted lines, because the necessary style information + is no longer available _after_ the modification. In other cases, we + can still perform the calculation afterwards (possibly even more + efficiently). + + \param pos + \param nDeleted + */ +void Fl_Text_Display_mod::measure_deleted_lines(int pos, int nDeleted) { + IS_UTF8_ALIGNED2(buffer(), pos) + + int retPos, retLines, retLineStart, retLineEnd; + Fl_Text_Buffer_mod *buf = buffer(); + int nVisLines = mNVisibleLines; + int *lineStarts = mLineStarts; + int countFrom, lineStart; + int nLines = 0, i; + /* + ** Determine where to begin searching: either the previous newline, or + ** if possible, limit to the start of the (original) previous displayed + ** line, using information from the existing line starts array + */ + if (pos >= mFirstChar && pos <= mLastChar) { + for (i=nVisLines-1; i>0; i--) + if (lineStarts[i] != -1 && pos >= lineStarts[i]) + break; + if (i > 0) { + countFrom = lineStarts[i-1]; + } else + countFrom = buf->line_start(pos); + } else + countFrom = buf->line_start(pos); + + /* + ** Move forward through the (new) text one line at a time, counting + ** displayed lines, and looking for either a real newline, or for the + ** line starts to re-sync with the original line starts array + */ + lineStart = countFrom; + for (;;) { + /* advance to the next line. If the line ended in a real newline + or the end of the buffer, that's far enough */ + wrapped_line_counter(buf, lineStart, buf->length(), 1, true, 0, + &retPos, &retLines, &retLineStart, &retLineEnd); + if (retPos >= buf->length()) { + if (retPos != retLineEnd) + nLines++; + break; + } else + lineStart = retPos; + nLines++; + if (lineStart > pos + nDeleted && buf->char_at(lineStart-1) == '\n') { + break; + } + + /* Unlike in the findWrapRange() function above, we don't try to + resync with the line starts, because we don't know the length + of the inserted text yet, nor the updated style information. + + Because of that, we also shouldn't resync with the line starts + after the modification either, because we must perform the + calculations for the deleted and inserted lines in the same way. + + This can result in some unnecessary recalculation and redrawing + overhead, and therefore we should only use this two-phase mode + of calculation when it's really needed (continuous wrap + variable + font width). */ + } + mNLinesDeleted = nLines; + mSuppressResync = 1; +} + + + +/** + \brief Wrapping calculations. + + Count forward from startPos to either maxPos or maxLines (whichever is + reached first), and return all relevant positions and line count. + The provided textBuffer may differ from the actual text buffer of the + widget. In that case it must be a (partial) copy of the actual text buffer + and the styleBufOffset argument must indicate the starting position of the + copy, to take into account the correct style information. + + \param buf + \param startPos + \param maxPos + \param maxLines + \param startPosIsLineStart + \param styleBufOffset + + \param[out] retPos Position where counting ended. When counting lines, the + position returned is the start of the line "maxLines" lines + beyond "startPos". + \param[out] retLines Number of line breaks counted + \param[out] retLineStart Start of the line where counting ended + \param[out] retLineEnd End position of the last line traversed + \param[out] countLastLineMissingNewLine + */ +void Fl_Text_Display_mod::wrapped_line_counter(Fl_Text_Buffer_mod *buf, int startPos, + int maxPos, int maxLines, bool startPosIsLineStart, int styleBufOffset, + int *retPos, int *retLines, int *retLineStart, int *retLineEnd, + bool countLastLineMissingNewLine) const { + IS_UTF8_ALIGNED2(buf, startPos) + IS_UTF8_ALIGNED2(buf, maxPos) + + int lineStart, newLineStart = 0, b, p, colNum, wrapMarginPix; + int i, foundBreak; + double width; + int nLines = 0; + unsigned int c; + + /* Set the wrap margin to the wrap column or the view width */ + if (mWrapMarginPix != 0) { + wrapMarginPix = mWrapMarginPix; + } else { + wrapMarginPix = text_area.w; + } + + /* Find the start of the line if the start pos is not marked as a + line start. */ + if (startPosIsLineStart) + lineStart = startPos; + else + lineStart = line_start(startPos); + + /* + ** Loop until position exceeds maxPos or line count exceeds maxLines. + ** (actually, continues beyond maxPos to end of line containing maxPos, + ** in case later characters cause a word wrap back before maxPos) + */ + colNum = 0; + width = 0; + for (p=lineStart; plength(); p=buf->next_char(p)) { + c = buf->char_at(p); // UCS-4 + + /* If the character was a newline, count the line and start over, + otherwise, add it to the width and column counts */ + if (c == '\n') { + if (p >= maxPos) { + *retPos = maxPos; + *retLines = nLines; + *retLineStart = lineStart; + *retLineEnd = maxPos; + return; + } + nLines++; + int p1 = buf->next_char(p); + if (nLines >= maxLines) { + *retPos = p1; + *retLines = nLines; + *retLineStart = p1; + *retLineEnd = p; + return; + } + lineStart = p1; + colNum = 0; + width = 0; + } else { + const char *s = buf->address(p); + colNum++; + // FIXME: it is not a good idea to simply add character widths because on + // some platforms, the width is a floating point value and depends on the + // previous character as well. + width += measure_proportional_character(s, (int)width, p+styleBufOffset); + } + + /* If character exceeded wrap margin, find the break point and wrap there */ + if (width > wrapMarginPix) { + foundBreak = false; + for (b=p; b>=lineStart; b=buf->prev_char(b)) { + c = buf->char_at(b); + if (c == '\t' || c == ' ') { + newLineStart = buf->next_char(b); + colNum = 0; + width = 0; + int iMax = buf->next_char(p); + for (i=buf->next_char(b); inext_char(i)) { + width += measure_proportional_character(buf->address(i), (int)width, + i+styleBufOffset); + colNum++; + } + foundBreak = true; + break; + } + } + if (!foundBreak) { /* no whitespace, just break at margin */ + newLineStart = max(p, buf->next_char(lineStart)); + const char *s = buf->address(b); + colNum++; + width = measure_proportional_character(s, 0, p+styleBufOffset); + } + if (p >= maxPos) { + *retPos = maxPos; + *retLines = maxPos < newLineStart ? nLines : nLines + 1; + *retLineStart = maxPos < newLineStart ? lineStart : newLineStart; + *retLineEnd = maxPos; + return; + } + nLines++; + if (nLines >= maxLines) { + *retPos = foundBreak ? buf->next_char(b) : max(p, buf->next_char(lineStart)); + *retLines = nLines; + *retLineStart = lineStart; + *retLineEnd = foundBreak ? b : p; + return; + } + lineStart = newLineStart; + } + } + + /* reached end of buffer before reaching pos or line target */ + *retPos = buf->length(); + *retLines = nLines; + if (countLastLineMissingNewLine && colNum > 0) + *retLines = buf->next_char(*retLines); + *retLineStart = lineStart; + *retLineEnd = buf->length(); +} + + + +/** + \brief Wrapping calculations. + + Measure the width in pixels of the first character of string "s" at a + particular column "colNum" and buffer position "pos". This is for measuring + characters in proportional or mixed-width highlighting fonts. + + A note about proportional and mixed-width fonts: the mixed width and + proportional font code in nedit does not get much use in general editing, + because nedit doesn't allow per-language-mode fonts, and editing programs + in a proportional font is usually a bad idea, so very few users would + choose a proportional font as a default. There are still probably mixed- + width syntax highlighting cases where things don't redraw properly for + insertion/deletion, though static display and wrapping and resizing + should now be solid because they are now used for online help display. + + \param s text string + \param xPix x pixel position needed for calculating tab widths + \param pos offset within string + \return width of character in pixels + */ +double Fl_Text_Display_mod::measure_proportional_character(const char *s, int xPix, int pos) const { + IS_UTF8_ALIGNED(s) + + if (*s=='\t') { + int tab = (int)col_to_x(mBuffer->tab_distance()); + return (((xPix/tab)+1)*tab) - xPix; + } + + int charLen = fl_utf8len1(*s), style = 0; + if (mStyleBuffer) { + style = mStyleBuffer->byte_at(pos); + } + return string_width(s, charLen, style); +} + + + +/** + \brief Finds both the end of the current line and the start of the next line. + + Why? + In continuous wrap mode, if you need to know both, figuring out one from the + other can be expensive or error prone. The problem comes when there's a + trailing space or tab just before the end of the buffer. To translate an + end of line value to or from the next lines start value, you need to know + whether the trailing space or tab is being used as a line break or just a + normal character, and to find that out would otherwise require counting all + the way back to the beginning of the line. + + \param startPos + \param startPosIsLineStart + \param[out] lineEnd + \param[out] nextLineStart + */ +void Fl_Text_Display_mod::find_line_end(int startPos, bool startPosIsLineStart, + int *lineEnd, int *nextLineStart) const { + IS_UTF8_ALIGNED2(buffer(), startPos) + + int retLines, retLineStart; + + /* if we're not wrapping use more efficient BufEndOfLine */ + if (mFastDisplay || !mContinuousWrap) { + int le = buffer()->line_end(startPos); + int ls = buffer()->next_char(le); + *lineEnd = le; + *nextLineStart = min(buffer()->length(), ls); + return; + } + + /* use the wrapped line counter routine to count forward one line */ + wrapped_line_counter(buffer(), startPos, buffer()->length(), + 1, startPosIsLineStart, 0, nextLineStart, &retLines, + &retLineStart, lineEnd); +} + + + +/** + \brief Check if the line break is caused by a \\n or by line wrapping. + + Line breaks in continuous wrap mode usually happen at newlines or + whitespace. This line-terminating character is not included in line + width measurements and has a special status as a non-visible character. + However, lines with no whitespace are wrapped without the benefit of a + line terminating character, and this distinction causes endless trouble + with all of the text display code which was originally written without + continuous wrap mode and always expects to wrap at a newline character. + + Given the position of the end of the line, as returned by TextDEndOfLine + or BufEndOfLine, this returns true if there is a line terminating + character, and false if there's not. On the last character in the + buffer, this function can't tell for certain whether a trailing space was + used as a wrap point, and just guesses that it wasn't. So if an exact + accounting is necessary, don't use this function. + + \param lineEndPos index of character where the line wraps + \return 1 if a \\n character causes the line wrap + */ +int Fl_Text_Display_mod::wrap_uses_character(int lineEndPos) const { + IS_UTF8_ALIGNED2(buffer(), lineEndPos) + + unsigned int c; + + if (mFastDisplay || !mContinuousWrap || lineEndPos == buffer()->length()) + return 1; + + c = buffer()->char_at(lineEndPos); + return c == '\n' || ((c == '\t' || c == ' ') && + lineEndPos + 1 < buffer()->length()); +} + +/** + \brief I don't know what this does! + + Extend the range of a redraw request (from *start to *end) with additional + redraw requests resulting from changes to the attached style buffer (which + contains auxiliary information for coloring or styling text). + + \param startpos ?? + \param endpos ?? + + \todo Unicode? + */ +void Fl_Text_Display_mod::extend_range_for_styles( int *startpos, int *endpos ) { + IS_UTF8_ALIGNED2(buffer(), (*startpos)) + IS_UTF8_ALIGNED2(buffer(), (*endpos)) + + Fl_Text_Selection_mod * sel = mStyleBuffer->primary_selection(); + int extended = 0; + + /* The peculiar protocol used here is that modifications to the style + buffer are marked by selecting them with the buffer's primary Fl_Text_Selection. + The style buffer is usually modified in response to a modify callback on + the text buffer BEFORE Fl_Text_Display_mod.c's modify callback, so that it can keep + the style buffer in step with the text buffer. The style-update + callback can't just call for a redraw, because Fl_Text_Display_mod hasn't processed + the original text changes yet. Anyhow, to minimize redrawing and to + avoid the complexity of scheduling redraws later, this simple protocol + tells the text display's buffer modify callback to extend its redraw + range to show the text color/and font changes as well. */ + if ( sel->selected() ) { + if ( sel->start() < *startpos ) { + *startpos = sel->start(); + // somewhere while deleting, alignment is lost. We do this just to be sure. + *startpos = buffer()->utf8_align(*startpos); + IS_UTF8_ALIGNED2(buffer(), (*startpos)) + extended = 1; + } + if ( sel->end() > *endpos ) { + *endpos = sel->end(); + *endpos = buffer()->utf8_align(*endpos); + IS_UTF8_ALIGNED2(buffer(), (*endpos)) + extended = 1; + } + } + + /* If the Fl_Text_Selection was extended due to a style change, and some of the + fonts don't match in spacing, extend redraw area to end of line to + redraw characters exposed by possible font size changes */ + if ( extended ) + *endpos = mBuffer->line_end( *endpos ) + 1; + + IS_UTF8_ALIGNED2(buffer(), (*endpos)) +} + + + +/** + \brief Draw the widget. + + This function tries to limit drawing to smaller areas if possible. + */ +void Fl_Text_Display_mod::draw(void) { + // don't even try if there is no associated text buffer! + if (!buffer()) { draw_box(); return; } + + fl_push_clip(x(),y(),w(),h()); // prevent drawing outside widget area + + // draw the non-text, non-scrollbar areas. + if (damage() & FL_DAMAGE_ALL) { + // draw the box() + int W = w(), H = h(); + draw_box(box(), x(), y(), W, H, color()); + + if (mHScrollBar->visible()) + W -= scrollbar_width(); + if (mVScrollBar->visible()) + H -= scrollbar_width(); + + // left margin + fl_rectf(text_area.x-LEFT_MARGIN, text_area.y-TOP_MARGIN, + LEFT_MARGIN, text_area.h+TOP_MARGIN+BOTTOM_MARGIN, + color()); + + // right margin + fl_rectf(text_area.x+text_area.w, text_area.y-TOP_MARGIN, + RIGHT_MARGIN, text_area.h+TOP_MARGIN+BOTTOM_MARGIN, + color()); + + // top margin + fl_rectf(text_area.x, text_area.y-TOP_MARGIN, + text_area.w, TOP_MARGIN, color()); + + // bottom margin + fl_rectf(text_area.x, text_area.y+text_area.h, + text_area.w, BOTTOM_MARGIN, color()); + + // draw that little box in the corner of the scrollbars + if (mVScrollBar->visible() && mHScrollBar->visible()) + fl_rectf(mVScrollBar->x(), mHScrollBar->y(), + mVScrollBar->w(), mHScrollBar->h(), + FL_GRAY); + + // blank the previous cursor protrusions + } + else if (damage() & (FL_DAMAGE_SCROLL | FL_DAMAGE_EXPOSE)) { + // printf("blanking previous cursor extrusions at Y: %d\n", mCursorOldY); + // CET - FIXME - save old cursor position instead and just draw side needed? + fl_push_clip(text_area.x-LEFT_MARGIN, + text_area.y, + text_area.w+LEFT_MARGIN+RIGHT_MARGIN, + text_area.h); + fl_rectf(text_area.x-LEFT_MARGIN, mCursorOldY, + LEFT_MARGIN, mMaxsize, color()); + fl_rectf(text_area.x+text_area.w, mCursorOldY, + RIGHT_MARGIN, mMaxsize, color()); + fl_pop_clip(); + } + + // draw the scrollbars + if (damage() & (FL_DAMAGE_ALL | FL_DAMAGE_CHILD)) { + mVScrollBar->damage(FL_DAMAGE_ALL); + mHScrollBar->damage(FL_DAMAGE_ALL); + } + update_child(*mVScrollBar); + update_child(*mHScrollBar); + + // draw all of the text + if (damage() & (FL_DAMAGE_ALL | FL_DAMAGE_EXPOSE)) { + //printf("drawing all text\n"); + int X, Y, W, H; + if (fl_clip_box(text_area.x, text_area.y, text_area.w, text_area.h, + X, Y, W, H)) { + // Draw text using the intersected clipping box... + // (this sets the clipping internally) + draw_text(X, Y, W, H); + } else { + // Draw the whole area... + draw_text(text_area.x, text_area.y, text_area.w, text_area.h); + } + } + else if (damage() & FL_DAMAGE_SCROLL) { + // draw some lines of text + fl_push_clip(text_area.x, text_area.y, + text_area.w, text_area.h); + //printf("drawing text from %d to %d\n", damage_range1_start, damage_range1_end); + draw_range(damage_range1_start, damage_range1_end); + if (damage_range2_end != -1) { + //printf("drawing text from %d to %d\n", damage_range2_start, damage_range2_end); + draw_range(damage_range2_start, damage_range2_end); + } + damage_range1_start = damage_range1_end = -1; + damage_range2_start = damage_range2_end = -1; + fl_pop_clip(); + } + + // draw the text cursor + if (damage() & (FL_DAMAGE_ALL | FL_DAMAGE_SCROLL | FL_DAMAGE_EXPOSE) + && !buffer()->primary_selection()->selected() && + mCursorOn && Fl::focus() == (Fl_Widget*)this ) { + fl_push_clip(text_area.x-LEFT_MARGIN, + text_area.y, + text_area.w+LEFT_MARGIN+RIGHT_MARGIN, + text_area.h); + + int X, Y; + if (position_to_xy(mCursorPos, &X, &Y)) draw_cursor(X, Y); + // else puts("position_to_xy() failed - unable to draw cursor!"); + //printf("drew cursor at pos: %d (%d,%d)\n", mCursorPos, X, Y); + mCursorOldY = Y; + fl_pop_clip(); + } + fl_pop_clip(); +} + + + +// this processes drag events due to mouse for Fl_Text_Display_mod and +// also drags due to cursor movement with shift held down for +// Fl_Text_Editor_mod +void fl_text_drag_me(int pos, Fl_Text_Display_mod* d) { + if (d->dragType == Fl_Text_Display_mod::DRAG_CHAR) { + if (pos >= d->dragPos) { + d->buffer()->select(d->dragPos, pos); + } else { + d->buffer()->select(pos, d->dragPos); + } + d->insert_position(pos); + } else if (d->dragType == Fl_Text_Display_mod::DRAG_WORD) { + if (pos >= d->dragPos) { + d->insert_position(d->word_end(pos)); + d->buffer()->select(d->word_start(d->dragPos), d->word_end(pos)); + } else { + d->insert_position(d->word_start(pos)); + d->buffer()->select(d->word_start(pos), d->word_end(d->dragPos)); + } + } else if (d->dragType == Fl_Text_Display_mod::DRAG_LINE) { + if (pos >= d->dragPos) { + d->insert_position(d->buffer()->line_end(pos)+1); + d->buffer()->select(d->buffer()->line_start(d->dragPos), + d->buffer()->line_end(pos)+1); + } else { + d->insert_position(d->buffer()->line_start(pos)); + d->buffer()->select(d->buffer()->line_start(pos), + d->buffer()->line_end(d->dragPos)+1); + } + } +} + + + +/** + \brief Timer callback for scroll events. + + This timer event scrolls the text view proportionally to + how far the mouse pointer has left the text area. This + allows for smooth scrolling without "wiggeling" the mouse. + */ +void Fl_Text_Display_mod::scroll_timer_cb(void *user_data) { + Fl_Text_Display_mod *w = (Fl_Text_Display_mod*)user_data; + int pos; + switch (scroll_direction) { + case 1: // mouse is to the right, scroll left + w->scroll(w->mTopLineNum, w->mHorizOffset + scroll_amount); + pos = w->xy_to_position(w->text_area.x + w->text_area.w, scroll_y, CURSOR_POS); + break; + case 2: // mouse is to the left, scroll right + w->scroll(w->mTopLineNum, w->mHorizOffset + scroll_amount); + pos = w->xy_to_position(w->text_area.x, scroll_y, CURSOR_POS); + break; + case 3: // mouse is above, scroll down + w->scroll(w->mTopLineNum + scroll_amount, w->mHorizOffset); + pos = w->xy_to_position(scroll_x, w->text_area.y, CURSOR_POS); + break; + case 4: // mouse is below, scroll up + w->scroll(w->mTopLineNum + scroll_amount, w->mHorizOffset); + pos = w->xy_to_position(scroll_x, w->text_area.y + w->text_area.h, CURSOR_POS); + break; + default: + return; + } + fl_text_drag_me(pos, w); + Fl::repeat_timeout(.1, scroll_timer_cb, user_data); +} + + + +/** + \brief Event handling. + */ +int Fl_Text_Display_mod::handle(int event) { + if (!buffer()) return 0; + // This isn't very elegant! + if (!Fl::event_inside(text_area.x, text_area.y, text_area.w, text_area.h) && + !dragging && event != FL_LEAVE && event != FL_ENTER && + event != FL_MOVE && event != FL_FOCUS && event != FL_UNFOCUS && + event != FL_KEYBOARD && event != FL_KEYUP) { + return Fl_Group::handle(event); + } + + switch (event) { + case FL_ENTER: + case FL_MOVE: + if (active_r()) { + if (Fl::event_inside(text_area.x, text_area.y, text_area.w, + text_area.h)) window()->cursor(FL_CURSOR_INSERT); + else window()->cursor(FL_CURSOR_DEFAULT); + return 1; + } else { + return 0; + } + + case FL_LEAVE: + case FL_HIDE: + if (active_r() && window()) { + window()->cursor(FL_CURSOR_DEFAULT); + + return 1; + } else { + return 0; + } + + case FL_PUSH: { + if (active_r() && window()) { + if (Fl::event_inside(text_area.x, text_area.y, text_area.w, + text_area.h)) window()->cursor(FL_CURSOR_INSERT); + else window()->cursor(FL_CURSOR_DEFAULT); + } + + if (Fl::focus() != this) { + Fl::focus(this); + handle(FL_FOCUS); + } + if (Fl_Group::handle(event)) return 1; + if (Fl::event_state()&FL_SHIFT) return handle(FL_DRAG); + dragging = 1; + int pos = xy_to_position(Fl::event_x(), Fl::event_y(), CURSOR_POS); + dragPos = pos; + if (buffer()->primary_selection()->includes(pos)) { + dragType = DRAG_START_DND; + return 1; + } + dragType = Fl::event_clicks(); + if (dragType == DRAG_CHAR) { + buffer()->unselect(); + // Fl::copy("", 0, 0); /* removed for STR 2668 */ + } + else if (dragType == DRAG_WORD) { + buffer()->select(word_start(pos), word_end(pos)); + dragPos = word_start(pos); + } + + if (buffer()->primary_selection()->selected()) + insert_position(buffer()->primary_selection()->end()); + else + insert_position(pos); + show_insert_position(); + return 1; + } + + case FL_DRAG: { + if (dragType==DRAG_NONE) + return 1; + if (dragType==DRAG_START_DND) { + if (!Fl::event_is_click() && Fl::dnd_text_ops()) { + const char* copy = buffer()->selection_text(); + Fl::dnd(); + free((void*)copy); + } + return 1; + } + int X = Fl::event_x(), Y = Fl::event_y(), pos = insert_position(); + // if we leave the text_area, we start a timer event + // that will take care of scrolling and selecting + if (Y < text_area.y) { + scroll_x = X; + scroll_amount = (Y - text_area.y) / 5 - 1; + if (!scroll_direction) { + Fl::add_timeout(.01, scroll_timer_cb, this); + } + scroll_direction = 3; + } else if (Y >= text_area.y+text_area.h) { + scroll_x = X; + scroll_amount = (Y - text_area.y - text_area.h) / 5 + 1; + if (!scroll_direction) { + Fl::add_timeout(.01, scroll_timer_cb, this); + } + scroll_direction = 4; + } else if (X < text_area.x) { + scroll_y = Y; + scroll_amount = (X - text_area.x) / 2 - 1; + if (!scroll_direction) { + Fl::add_timeout(.01, scroll_timer_cb, this); + } + scroll_direction = 2; + } else if (X >= text_area.x+text_area.w) { + scroll_y = Y; + scroll_amount = (X - text_area.x - text_area.w) / 2 + 1; + if (!scroll_direction) { + Fl::add_timeout(.01, scroll_timer_cb, this); + } + scroll_direction = 1; + } else { + if (scroll_direction) { + Fl::remove_timeout(scroll_timer_cb, this); + scroll_direction = 0; + } + pos = xy_to_position(X, Y, CURSOR_POS); + pos = buffer()->next_char(pos); + } + fl_text_drag_me(pos, this); + return 1; + } + + case FL_RELEASE: { + if (Fl::event_is_click() && (! Fl::event_clicks()) && + buffer()->primary_selection()->includes(dragPos) && !(Fl::event_state()&FL_SHIFT) ) { + buffer()->unselect(); // clicking in the selection: unselect and move cursor + insert_position(dragPos); + return 1; + } else if (Fl::event_clicks() == DRAG_LINE && Fl::event_button() == FL_LEFT_MOUSE) { + buffer()->select(buffer()->line_start(dragPos), buffer()->next_char(buffer()->line_end(dragPos))); + dragPos = line_start(dragPos); + dragType = DRAG_CHAR; + } else { + dragging = 0; + if (scroll_direction) { + Fl::remove_timeout(scroll_timer_cb, this); + scroll_direction = 0; + } + + // convert from WORD or LINE selection to CHAR + /*if (insert_position() >= dragPos) + dragPos = buffer()->primary_selection()->start(); + else + dragPos = buffer()->primary_selection()->end();*/ + dragType = DRAG_CHAR; + } + + const char* copy = buffer()->selection_text(); + if (*copy) Fl::copy(copy, strlen(copy), 0); + free((void*)copy); + return 1; + } + + case FL_MOUSEWHEEL: + if (Fl::event_dy()) return mVScrollBar->handle(event); + else return mHScrollBar->handle(event); + + case FL_UNFOCUS: + if (active_r() && window()) window()->cursor(FL_CURSOR_DEFAULT); + case FL_FOCUS: + if (buffer()->selected()) { + int start, end; + if (buffer()->selection_position(&start, &end)) + redisplay_range(start, end); + } + if (buffer()->secondary_selected()) { + int start, end; + if (buffer()->secondary_selection_position(&start, &end)) + redisplay_range(start, end); + } + if (buffer()->highlight()) { + int start, end; + if (buffer()->highlight_position(&start, &end)) + redisplay_range(start, end); + } + return 1; + + case FL_KEYBOARD: + // Copy? + if ((Fl::event_state()&(FL_CTRL|FL_COMMAND)) && Fl::event_key()=='c') { + if (!buffer()->selected()) return 1; + const char *copy = buffer()->selection_text(); + if (*copy) Fl::copy(copy, strlen(copy), 1); + free((void*)copy); + return 1; + } + + // Select all ? + if ((Fl::event_state()&(FL_CTRL|FL_COMMAND)) && Fl::event_key()=='a') { + buffer()->select(0,buffer()->length()); + const char *copy = buffer()->selection_text(); + if (*copy) Fl::copy(copy, strlen(copy), 0); + free((void*)copy); + return 1; + } + + if (mVScrollBar->handle(event)) return 1; + if (mHScrollBar->handle(event)) return 1; + + break; + + case FL_SHORTCUT: + if (!(shortcut() ? Fl::test_shortcut(shortcut()) : test_shortcut())) + return 0; + if (Fl::visible_focus() && handle(FL_FOCUS)) { + Fl::focus(this); + return 1; + } + break; + + } + + return 0; +} + + +/* + Convert an x pixel position into a column number. + */ +double Fl_Text_Display_mod::x_to_col(double y) const +{ + if (!mColumnScale) { + mColumnScale = string_width("Mitg", 4, 'A') / 4.0; + } + return (y/mColumnScale)+0.5; +} + + +/** + Convert a column number into an x pixel position. + */ +double Fl_Text_Display_mod::col_to_x(double col) const +{ + if (!mColumnScale) { + // recalculate column scale value + x_to_col(0); + } + return col*mColumnScale; +} + +// +// End of "$Id: Fl_Text_Display_mod.cxx 8808 2011-06-16 13:31:25Z manolo $". +// diff --git a/src/widgets/Fl_Text_Display_mod_1_1.cxx b/src/widgets/Fl_Text_Display_mod_1_1.cxx deleted file mode 100644 index 0d9242d..0000000 --- a/src/widgets/Fl_Text_Display_mod_1_1.cxx +++ /dev/null @@ -1,3266 +0,0 @@ -// "$Id: Fl_Text_Display.cxx 5848 2007-05-20 16:18:31Z mike $" -// -// Copyright 2001-2006 by Bill Spitzak and others. -// Original code Copyright Mark Edel. Permission to distribute under -// the LGPL for the FLTK library granted by Mark Edel. -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ -// -// This file is part of flmsg -// -// flrig 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. -// -// flrig 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 - -#include -#include -#include "missing_strings.h" -#include -#include -#include -#include "Fl_Text_Buffer_mod.H" -#include "Fl_Text_Display_mod.H" -#include - -#undef min -#undef max - -// Text area margins. Left & right margins should be at least 3 so that -// there is some room for the overhanging parts of the cursor! -const int Fl_Text_Display_mod::DEFAULT_TOP_MARGIN = 1; -const int Fl_Text_Display_mod::DEFAULT_BOTTOM_MARGIN = 1; -const int Fl_Text_Display_mod::DEFAULT_LEFT_MARGIN = 3; -const int Fl_Text_Display_mod::DEFAULT_RIGHT_MARGIN = 3; - -#define NO_HINT -1 - -/* Masks for text drawing methods. These are or'd together to form an - integer which describes what drawing calls to use to draw a std::string */ -#define FILL_MASK 0x0100 -#define SECONDARY_MASK 0x0200 -#define PRIMARY_MASK 0x0400 -#define HIGHLIGHT_MASK 0x0800 -#define BG_ONLY_MASK 0x1000 -#define TEXT_ONLY_MASK 0x2000 -#define STYLE_LOOKUP_MASK 0xff - -/* Maximum displayable line length (how many characters will fit across the - widest window). This amount of memory is temporarily allocated from the - stack in the draw_vline() method for drawing std::strings */ -#define MAX_DISP_LINE_LEN 1000 - -static int max( int i1, int i2 ); -static int min( int i1, int i2 ); -static int countlines( const char *string ); - -/* The variables below are used in a timer event to allow smooth - scrolling of the text area when the pointer has left the area. */ -static int scroll_direction = 0; -static int scroll_amount = 0; -static int scroll_y = 0; -static int scroll_x = 0; - -// CET - FIXME -#define TMPFONTWIDTH 6 - -Fl_Text_Display_mod::Fl_Text_Display_mod(int X, int Y, int W, int H, const char* l) - : Fl_Group(X, Y, W, H, l) { - int i; - - TOP_MARGIN = DEFAULT_TOP_MARGIN; - BOTTOM_MARGIN = DEFAULT_BOTTOM_MARGIN; - LEFT_MARGIN = DEFAULT_LEFT_MARGIN; - RIGHT_MARGIN = DEFAULT_RIGHT_MARGIN; - - mMaxsize = 0; - damage_range1_start = damage_range1_end = -1; - damage_range2_start = damage_range2_end = -1; - dragPos = dragType = dragging = 0; - display_insert_position_hint = 0; - - color(FL_BACKGROUND2_COLOR, FL_SELECTION_COLOR); -// box(FL_DOWN_FRAME); - box(FL_DOWN_BOX); // DO NOT USE FRAME OR TILED GROUP WILL NOT CORRECTLY DRAW THE BORDERS !! - textsize((uchar)FL_NORMAL_SIZE); - textcolor(FL_FOREGROUND_COLOR); - textfont(FL_HELVETICA); - - text_area.x = 0; - text_area.y = 0; - text_area.w = 0; - text_area.h = 0; - - mVScrollBar = new Fl_Scrollbar(0,0,1,1); - mVScrollBar->callback((Fl_Callback*)v_scrollbar_cb, this); - mHScrollBar = new Fl_Scrollbar(0,0,1,1); - mHScrollBar->callback((Fl_Callback*)h_scrollbar_cb, this); - mHScrollBar->type(FL_HORIZONTAL); - - end(); - - scrollbar_width(16); - scrollbar_align(FL_ALIGN_BOTTOM_RIGHT); - - mCursorOn = 0; - mCursorPos = 0; - mCursorOldY = -100; - mCursorToHint = NO_HINT; - mCursorStyle = NORMAL_CURSOR; - mCursorPreferredCol = -1; - mBuffer = 0; - mFirstChar = 0; - mLastChar = 0; - mNBufferLines = 0; - mTopLineNum = mTopLineNumHint = 1; - mAbsTopLineNum = 1; - mNeedAbsTopLineNum = 0; - mHorizOffset = mHorizOffsetHint = 0; - - mCursor_color = FL_FOREGROUND_COLOR; - - mFixedFontWidth = -1; - mStyleBuffer = 0; - mStyleTable = 0; - mNStyles = 0; - mNVisibleLines = 1; - mLineStarts = new int[mNVisibleLines]; - mLineStarts[0] = 0; - for (i=1; iremove_modify_callback(buffer_modified_cb, this); - // mBuffer->remove_predelete_callback(buffer_predelete_cb, this); - // } - if (mLineStarts) delete[] mLineStarts; -} - -/* -** Attach a text buffer to display, replacing the current buffer (if any) -*/ -void Fl_Text_Display_mod::buffer( Fl_Text_Buffer_mod*buf ) { - /* If the text display is already displaying a buffer, clear it off - of the display and remove our callback from it */ - if ( buf == mBuffer) return; - if ( mBuffer != 0 ) { - buffer_modified_cb( 0, 0, mBuffer->length(), 0, 0, this ); - mNBufferLines = 0; - mBuffer->remove_modify_callback( buffer_modified_cb, this ); - mBuffer->remove_predelete_callback( buffer_predelete_cb, this ); - } - - /* Add the buffer to the display, and attach a callback to the buffer for - receiving modification information when the buffer contents change */ - mBuffer = buf; - if (mBuffer) { - mBuffer->add_modify_callback( buffer_modified_cb, this ); - mBuffer->add_predelete_callback( buffer_predelete_cb, this ); - - /* Update the display */ - buffer_modified_cb( 0, buf->length(), 0, 0, 0, this ); - } - - /* Resize the widget to update the screen... */ - resize(x(), y(), w(), h()); -} - -/* -** Attach (or remove) highlight information in text display and redisplay. -** Highlighting information consists of a style buffer which parallels the -** normal text buffer, but codes font and color information for the display; -** a style table which translates style buffer codes (indexed by buffer -** character - 'A') into fonts and colors; and a callback mechanism for -** as-needed highlighting, triggered by a style buffer entry of -** "unfinishedStyle". Style buffer can trigger additional redisplay during -** a normal buffer modification if the buffer contains a primary Fl_Text_Selection -** (see extendRangeForStyleMods for more information on this protocol). -** -** Style buffers, tables and their associated memory are managed by the caller. -*/ -void -Fl_Text_Display_mod::highlight_data(Fl_Text_Buffer_mod*styleBuffer, - const Style_Table_Entry *styleTable, - int nStyles, char unfinishedStyle, - Unfinished_Style_Cb unfinishedHighlightCB, - void *cbArg ) { - mStyleBuffer = styleBuffer; - mStyleTable = styleTable; - mNStyles = nStyles; - mUnfinishedStyle = unfinishedStyle; - mUnfinishedHighlightCB = unfinishedHighlightCB; - mHighlightCBArg = cbArg; - - mStyleBuffer->canUndo(0); -#if 0 - // FIXME: this is in nedit code -- is it needed? - /* Call TextDSetFont to combine font information from style table and - primary font, adjust font-related parameters, and then redisplay */ - TextDSetFont(textD, textD->fontStruct); -#endif - damage(FL_DAMAGE_EXPOSE); -} - -#if 0 - // FIXME: this is in nedit code -- is it needed? -/* -** Change the (non highlight) font -*/ -void TextDSetFont(textDisp *textD, XFontStruct *fontStruct) { - Display *display = XtDisplay(textD->w); - int i, maxAscent = fontStruct->ascent, maxDescent = fontStruct->descent; - int width, height, fontWidth; - Pixel bgPixel, fgPixel, selectFGPixel, selectBGPixel; - Pixel highlightFGPixel, highlightBGPixel; - XGCValues values; - XFontStruct *styleFont; - - /* If font size changes, cursor will be redrawn in a new position */ - blankCursorProtrusions(textD); - - /* If there is a (syntax highlighting) style table in use, find the new - maximum font height for this text display */ - for (i=0; inStyles; i++) { - styleFont = textD->styleTable[i].font; - if (styleFont != NULL && styleFont->ascent > maxAscent) - maxAscent = styleFont->ascent; - if (styleFont != NULL && styleFont->descent > maxDescent) - maxDescent = styleFont->descent; - } - textD->ascent = maxAscent; - textD->descent = maxDescent; - - /* If all of the current fonts are fixed and match in width, compute */ - fontWidth = fontStruct->max_bounds.width; - if (fontWidth != fontStruct->min_bounds.width) - fontWidth = -1; - else { - for (i=0; inStyles; i++) { - styleFont = textD->styleTable[i].font; - if (styleFont != NULL && (styleFont->max_bounds.width != fontWidth || - styleFont->max_bounds.width != styleFont->min_bounds.width)) - fontWidth = -1; - } - } - textD->fixedFontWidth = fontWidth; - - /* Don't let the height dip below one line, or bad things can happen */ - if (textD->height < maxAscent + maxDescent) - textD->height = maxAscent + maxDescent; - - /* Change the font. In most cases, this means re-allocating the - affected GCs (they are shared with other widgets, and if the primary - font changes, must be re-allocated to change it). Unfortunately, - this requres recovering all of the colors from the existing GCs */ - textD->fontStruct = fontStruct; - XGetGCValues(display, textD->gc, GCForeground|GCBackground, &values); - fgPixel = values.foreground; - bgPixel = values.background; - XGetGCValues(display, textD->selectGC, GCForeground|GCBackground, &values); - selectFGPixel = values.foreground; - selectBGPixel = values.background; - XGetGCValues(display, textD->highlightGC,GCForeground|GCBackground,&values); - highlightFGPixel = values.foreground; - highlightBGPixel = values.background; - releaseGC(textD->w, textD->gc); - releaseGC(textD->w, textD->selectGC); - releaseGC(textD->w, textD->highlightGC); - releaseGC(textD->w, textD->selectBGGC); - releaseGC(textD->w, textD->highlightBGGC); - if (textD->lineNumGC != NULL) - releaseGC(textD->w, textD->lineNumGC); - textD->lineNumGC = NULL; - allocateFixedFontGCs(textD, fontStruct, bgPixel, fgPixel, selectFGPixel, - selectBGPixel, highlightFGPixel, highlightBGPixel); - XSetFont(display, textD->styleGC, fontStruct->fid); - - /* Do a full resize to force recalculation of font related parameters */ - width = textD->width; - height = textD->height; - textD->width = textD->height = 0; - TextDResize(textD, width, height); - - /* Redisplay */ - TextDRedisplayRect(textD, textD->left, textD->top, textD->width, - textD->height); - - /* Clean up line number area in case spacing has changed */ - draw_line_numbers(textD, True); -} - -int TextDMinFontWidth(textDisp *textD, Boolean considerStyles) { - int fontWidth = textD->fontStruct->max_bounds.width; - int i; - - if (considerStyles) { - for (i = 0; i < textD->nStyles; ++i) { - int thisWidth = (textD->styleTable[i].font)->min_bounds.width; - if (thisWidth < fontWidth) { - fontWidth = thisWidth; - } - } - } - return(fontWidth); -} - -int TextDMaxFontWidth(textDisp *textD, Boolean considerStyles) { - int fontWidth = textD->fontStruct->max_bounds.width; - int i; - - if (considerStyles) { - for (i = 0; i < textD->nStyles; ++i) { - int thisWidth = (textD->styleTable[i].font)->max_bounds.width; - if (thisWidth > fontWidth) { - fontWidth = thisWidth; - } - } - } - return(fontWidth); -} -#endif - -int Fl_Text_Display_mod::longest_vline() { - int longest = 0; - for (int i = 0; i < mNVisibleLines; i++) - longest = max(longest, measure_vline(i)); - return longest; -} - -/* -** Change the size of the displayed text area -*/ -void Fl_Text_Display_mod::resize(int X, int Y, int W, int H) { -#ifdef DEBUG - printf("Fl_Text_Display_mod::resize(X=%d, Y=%d, W=%d, H=%d)\n", X, Y, W, H); -#endif // DEBUG - const int oldWidth = w(); -#ifdef DEBUG - printf(" oldWidth=%d, mContinuousWrap=%d, mWrapMargin=%d\n", oldWidth, - mContinuousWrap, mWrapMargin); -#endif // DEBUG - Fl_Widget::resize(X,Y,W,H); - if (!buffer()) return; - X += Fl::box_dx(box()); - Y += Fl::box_dy(box()); - W -= Fl::box_dw(box()); - H -= Fl::box_dh(box()); - - text_area.x = X+LEFT_MARGIN; - text_area.y = Y+TOP_MARGIN; - text_area.w = W-LEFT_MARGIN-RIGHT_MARGIN; - text_area.h = H-TOP_MARGIN-BOTTOM_MARGIN; - int i = 0; - - /* Find the new maximum font height for this text display */ - for (i = 0, mMaxsize = fl_height(textfont(), textsize()); i < mNStyles; i++) - mMaxsize = max(mMaxsize, fl_height(mStyleTable[i].font, mStyleTable[i].size)); - - // did we have scrollbars initially? - int hscrollbarvisible = mHScrollBar->visible(); - int vscrollbarvisible = mVScrollBar->visible(); - - // try without scrollbars first - mVScrollBar->clear_visible(); - mHScrollBar->clear_visible(); - - for (int again = 1; again;) { - again = 0; - /* In continuous wrap mode, a change in width affects the total number of - lines in the buffer, and can leave the top line number incorrect, and - the top character no longer pointing at a valid line start */ - if (mContinuousWrap && !mWrapMargin && W!=oldWidth) { - int oldFirstChar = mFirstChar; - mNBufferLines = count_lines(0, buffer()->length(), true); - mFirstChar = line_start(mFirstChar); - mTopLineNum = count_lines(0, mFirstChar, true)+1; - absolute_top_line_number(oldFirstChar); - -#ifdef DEBUG - printf(" mNBufferLines=%d\n", mNBufferLines); -#endif // DEBUG - } - - /* reallocate and update the line starts array, which may have changed - size and / or contents. */ - int nvlines = (text_area.h + mMaxsize - 1) / mMaxsize; - if (nvlines < 1) nvlines = 1; - if (mNVisibleLines != nvlines) { - mNVisibleLines = nvlines; - if (mLineStarts) delete[] mLineStarts; - mLineStarts = new int [mNVisibleLines]; - } - - calc_line_starts(0, mNVisibleLines); - calc_last_char(); - - // figure the scrollbars - if (scrollbar_width()) { - /* Decide if the vertical scroll bar needs to be visible */ - if (scrollbar_align() & (FL_ALIGN_LEFT|FL_ALIGN_RIGHT) && - mNBufferLines >= mNVisibleLines - 1) - { - if (!mVScrollBar->visible()) - again = 1; - mVScrollBar->set_visible(); - if (scrollbar_align() & FL_ALIGN_LEFT) { - text_area.x = X+scrollbar_width()+LEFT_MARGIN; - text_area.w = W-scrollbar_width()-LEFT_MARGIN-RIGHT_MARGIN; - mVScrollBar->resize(X, text_area.y-TOP_MARGIN, scrollbar_width(), - text_area.h+TOP_MARGIN+BOTTOM_MARGIN); - } else { - text_area.x = X+LEFT_MARGIN; - text_area.w = W-scrollbar_width()-LEFT_MARGIN-RIGHT_MARGIN; - mVScrollBar->resize(X+W-scrollbar_width(), text_area.y-TOP_MARGIN, - scrollbar_width(), text_area.h+TOP_MARGIN+BOTTOM_MARGIN); - } - } - - /* - Decide if the horizontal scroll bar needs to be visible. If there - is a vertical scrollbar, a horizontal is always created too. This - is because the alternatives are unatractive: - * Dynamically creating a horizontal scrollbar based on the currently - visible lines is what the original nedit does, but it always wastes - space for the scrollbar even when it's not used. Since the FLTK - widget dynamically allocates the space for the scrollbar and - rearranges the widget to make room for it, this would create a very - visually displeasing "bounce" effect when the vertical scrollbar is - dragged. Trust me, I tried it and it looks really bad. - * The other alternative would be to keep track of what the longest - line in the entire buffer is and base the scrollbar on that. I - didn't do this because I didn't see any easy way to do that using - the nedit code and this could involve a lengthy calculation for - large buffers. If an efficient and non-costly way of doing this - can be found, this might be a way to go. - */ - /* WAS: Suggestion: Try turning the horizontal scrollbar on when - you first see a line that is too wide in the window, but then - don't turn it off (ie mix both of your solutions). */ - if (!mContinuousWrap && scrollbar_align() & (FL_ALIGN_TOP|FL_ALIGN_BOTTOM) && - (mVScrollBar->visible() || longest_vline() > text_area.w)) - { - if (!mHScrollBar->visible()) { - mHScrollBar->set_visible(); - again = 1; // loop again to see if we now need vert. & recalc sizes - } - if (scrollbar_align() & FL_ALIGN_TOP) { - text_area.y = Y + scrollbar_width()+TOP_MARGIN; - text_area.h = H - scrollbar_width()-TOP_MARGIN-BOTTOM_MARGIN; - mHScrollBar->resize(text_area.x-LEFT_MARGIN, Y, - text_area.w+LEFT_MARGIN+RIGHT_MARGIN, scrollbar_width()); - } else { - text_area.y = Y+TOP_MARGIN; - text_area.h = H - scrollbar_width()-TOP_MARGIN-BOTTOM_MARGIN; - mHScrollBar->resize(text_area.x-LEFT_MARGIN, Y+H-scrollbar_width(), - text_area.w+LEFT_MARGIN+RIGHT_MARGIN, scrollbar_width()); - } - } - } - } - - // user request to change viewport - if (mTopLineNumHint != mTopLineNum || mHorizOffsetHint != mHorizOffset) - scroll_(mTopLineNumHint, mHorizOffsetHint); - - // everything will fit in the viewport - if (mNBufferLines < mNVisibleLines || mBuffer == NULL || mBuffer->length() == 0) - scroll_(1, mHorizOffset); - /* if empty lines become visible, there may be an opportunity to - display more text by scrolling down */ - else while (mLineStarts[mNVisibleLines-2] == -1) - scroll_(mTopLineNum-1, mHorizOffset); - - // user request to display insert position - if (display_insert_position_hint) - display_insert(); - - // in case horizontal offset is now greater than longest line - int maxhoffset = max(0, longest_vline()-text_area.w); - if (mHorizOffset > maxhoffset) - scroll_(mTopLineNumHint, maxhoffset); - - mTopLineNumHint = mTopLineNum; - mHorizOffsetHint = mHorizOffset; - display_insert_position_hint = 0; - - if (mContinuousWrap || - hscrollbarvisible != mHScrollBar->visible() || - vscrollbarvisible != mVScrollBar->visible()) - redraw(); - - update_v_scrollbar(); - update_h_scrollbar(); -} - -/* -** Refresh a rectangle of the text display. left and top are in coordinates of -** the text drawing window -*/ -void Fl_Text_Display_mod::draw_text( int left, int top, int width, int height ) { - int fontHeight, firstLine, lastLine, line; - - /* find the line number range of the display */ - fontHeight = mMaxsize ? mMaxsize : textsize_; - firstLine = ( top - text_area.y - fontHeight + 1 ) / fontHeight; - lastLine = ( top + height - text_area.y ) / fontHeight + 1; - - fl_push_clip( left, top, width, height ); - - /* draw the lines */ - for ( line = firstLine; line <= lastLine; line++ ) - draw_vline( line, left, left + width, 0, INT_MAX ); - - /* draw the line numbers if exposed area includes them */ - if (mLineNumWidth != 0 && left <= mLineNumLeft + mLineNumWidth) - draw_line_numbers(false); - - fl_pop_clip(); -} - -void Fl_Text_Display_mod::redisplay_range(int startpos, int endpos) { - if (damage_range1_start == -1 && damage_range1_end == -1) { - damage_range1_start = startpos; - damage_range1_end = endpos; - } else if ((startpos >= damage_range1_start && startpos <= damage_range1_end) || - (endpos >= damage_range1_start && endpos <= damage_range1_end)) { - damage_range1_start = min(damage_range1_start, startpos); - damage_range1_end = max(damage_range1_end, endpos); - } else if (damage_range2_start == -1 && damage_range2_end == -1) { - damage_range2_start = startpos; - damage_range2_end = endpos; - } else { - damage_range2_start = min(damage_range2_start, startpos); - damage_range2_end = max(damage_range2_end, endpos); - } - damage(FL_DAMAGE_SCROLL); -} -/* -** Refresh all of the text between buffer positions "start" and "end" -** not including the character at the position "end". -** If end points beyond the end of the buffer, refresh the whole display -** after pos, including blank lines which are not technically part of -** any range of characters. -*/ -void Fl_Text_Display_mod::draw_range(int startpos, int endpos) { - int i, startLine, lastLine, startIndex, endIndex; - - /* If the range is outside of the displayed text, just return */ - if ( endpos < mFirstChar || ( startpos > mLastChar && - !empty_vlines() ) ) return; - - /* Clean up the starting and ending values */ - if ( startpos < 0 ) startpos = 0; - if ( startpos > mBuffer->length() ) startpos = mBuffer->length(); - if ( endpos < 0 ) endpos = 0; - if ( endpos > mBuffer->length() ) endpos = mBuffer->length(); - - /* Get the starting and ending lines */ - if ( startpos < mFirstChar ) - startpos = mFirstChar; - if ( !position_to_line( startpos, &startLine ) ) - startLine = mNVisibleLines - 1; - if ( endpos >= mLastChar ) { - lastLine = mNVisibleLines - 1; - } else { - if ( !position_to_line( endpos, &lastLine ) ) { - /* shouldn't happen */ - lastLine = mNVisibleLines - 1; - } - } - - /* Get the starting and ending positions within the lines */ - startIndex = mLineStarts[ startLine ] == -1 ? 0 : - startpos - mLineStarts[ startLine ]; - if ( endpos >= mLastChar ) - endIndex = INT_MAX; - else if ( mLineStarts[ lastLine ] == -1 ) - endIndex = 0; - else - endIndex = endpos - mLineStarts[ lastLine ]; - - /* If the starting and ending lines are the same, redisplay the single - line between "start" and "end" */ - if ( startLine == lastLine ) { - draw_vline( startLine, 0, INT_MAX, startIndex, endIndex ); - return; - } - - /* Redisplay the first line from "start" */ - draw_vline( startLine, 0, INT_MAX, startIndex, INT_MAX ); - - /* Redisplay the lines in between at their full width */ - for ( i = startLine + 1; i < lastLine; i++ ) - draw_vline( i, 0, INT_MAX, 0, INT_MAX ); - - /* Redisplay the last line to "end" */ - draw_vline( lastLine, 0, INT_MAX, 0, endIndex ); -} - -/* -** Set the position of the text insertion cursor for text display -*/ -void Fl_Text_Display_mod::insert_position( int newPos ) { - /* make sure new position is ok, do nothing if it hasn't changed */ - if ( newPos == mCursorPos ) - return; - if ( newPos < 0 ) newPos = 0; - if ( newPos > mBuffer->length() ) newPos = mBuffer->length(); - - /* cursor movement cancels vertical cursor motion column */ - mCursorPreferredCol = -1; - - /* erase the cursor at it's previous position */ - redisplay_range(mCursorPos - 1, mCursorPos + 1); - - mCursorPos = newPos; - - /* draw cursor at its new position */ - redisplay_range(mCursorPos - 1, mCursorPos + 1); -} - -void Fl_Text_Display_mod::show_cursor(int b) { - mCursorOn = b; - redisplay_range(mCursorPos - 1, mCursorPos + 1); -} - -void Fl_Text_Display_mod::cursor_style(int style) { - mCursorStyle = style; - if (mCursorOn) show_cursor(); -} - -void Fl_Text_Display_mod::wrap_mode(int wrap, int wrapMargin) { - mWrapMargin = wrapMargin; - mContinuousWrap = wrap; - - if (buffer()) { - /* wrapping can change the total number of lines, re-count */ - mNBufferLines = count_lines(0, buffer()->length(), true); - - /* changing wrap margins or changing from wrapped mode to non-wrapped - can leave the character at the top no longer at a line start, and/or - change the line number */ - mFirstChar = line_start(mFirstChar); - mTopLineNum = count_lines(0, mFirstChar, true) + 1; - - reset_absolute_top_line_number(); - - /* update the line starts array */ - calc_line_starts(0, mNVisibleLines); - calc_last_char(); - } else { - // No buffer, so just clear the state info for later... - mNBufferLines = 0; - mFirstChar = 0; - mTopLineNum = 1; - mAbsTopLineNum = 0; - } - - resize(x(), y(), w(), h()); -} - -/* -** Insert "text" at the current cursor location. This has the same -** effect as inserting the text into the buffer using BufInsert and -** then moving the insert position after the newly inserted text, except -** that it's optimized to do less redrawing. -*/ -void Fl_Text_Display_mod::insert(const char* text) { - int pos = mCursorPos; - - mCursorToHint = pos + strlen( text ); - mBuffer->insert( pos, text ); - mCursorToHint = NO_HINT; -} - -/* -** Insert "text" (which must not contain newlines), overstriking the current -** cursor location. -*/ -void Fl_Text_Display_mod::overstrike(const char* text) { - int startPos = mCursorPos; - Fl_Text_Buffer_mod*buf = mBuffer; - int lineStart = buf->line_start( startPos ); - int textLen = strlen( text ); - int i, p, endPos, indent, startIndent, endIndent; - const char *c; - char ch, *paddedText = NULL; - - /* determine how many displayed character positions are covered */ - startIndent = mBuffer->count_displayed_characters( lineStart, startPos ); - indent = startIndent; - for ( c = text; *c != '\0'; c++ ) - indent += Fl_Text_Buffer_mod::character_width( *c, indent, buf->tab_distance(), buf->null_substitution_character() ); - endIndent = indent; - - /* find which characters to remove, and if necessary generate additional - padding to make up for removed control characters at the end */ - indent = startIndent; - for ( p = startPos; ; p++ ) { - if ( p == buf->length() ) - break; - ch = buf->character( p ); - if ( ch == '\n' ) - break; - indent += Fl_Text_Buffer_mod::character_width( ch, indent, buf->tab_distance(), buf->null_substitution_character() ); - if ( indent == endIndent ) { - p++; - break; - } else if ( indent > endIndent ) { - if ( ch != '\t' ) { - p++; - paddedText = new char [ textLen + FL_TEXT_MAX_EXP_CHAR_LEN + 1 ]; - strcpy( paddedText, text ); - for ( i = 0; i < indent - endIndent; i++ ) - paddedText[ textLen + i ] = ' '; - paddedText[ textLen + i ] = '\0'; - } - break; - } - } - endPos = p; - - mCursorToHint = startPos + textLen; - buf->replace( startPos, endPos, paddedText == NULL ? text : paddedText ); - mCursorToHint = NO_HINT; - if ( paddedText != NULL ) - delete [] paddedText; -} - -/* -** Translate a buffer text position to the XY location where the top left -** of the cursor would be positioned to point to that character. Returns -** 0 if the position is not displayed because it is VERTICALLY out -** of view. If the position is horizontally out of view, returns the -** X coordinate where the position would be if it were visible. -*/ - -int Fl_Text_Display_mod::position_to_xy( int pos, int* X, int* Y ) { - int charIndex, lineStartPos, fontHeight, lineLen; - int visLineNum, charLen, outIndex, xStep, charStyle; - char expandedChar[ FL_TEXT_MAX_EXP_CHAR_LEN ]; - const char *lineStr; - -// printf("position_to_xy(pos=%d, X=%p, Y=%p)\n", pos, X, Y); - - /* If position is not displayed, return false */ - if (pos < mFirstChar || (pos > mLastChar && !empty_vlines())) { -// printf(" returning 0\n" -// " mFirstChar=%d, mLastChar=%d, empty_vlines()=0\n", -// mFirstChar, mLastChar); - return 0; - } - - /* Calculate Y coordinate */ - if (!position_to_line(pos, &visLineNum)) { -// puts(" returning 0\n" -// " position_to_line()=0"); - return 0; - } - - if (visLineNum < 0 || visLineNum > mNBufferLines) { -// printf(" returning 0\n" -// " visLineNum=%d, mNBufferLines=%d\n", -// visLineNum, mNBufferLines); - return 0; - } - - fontHeight = mMaxsize; - *Y = text_area.y + visLineNum * fontHeight; - - /* Get the text, length, and buffer position of the line. If the position - is beyond the end of the buffer and should be at the first position on - the first empty line, don't try to get or scan the text */ - lineStartPos = mLineStarts[visLineNum]; - if ( lineStartPos == -1 ) { - *X = text_area.x - mHorizOffset; - return 1; - } - lineLen = vline_length( visLineNum ); - lineStr = mBuffer->text_range( lineStartPos, lineStartPos + lineLen ); - - /* Step through character positions from the beginning of the line - to "pos" to calculate the X coordinate */ - xStep = text_area.x - mHorizOffset; - outIndex = 0; - for ( charIndex = 0; charIndex < lineLen && charIndex < pos - lineStartPos; charIndex++ ) { - charLen = Fl_Text_Buffer_mod::expand_character( lineStr[ charIndex ], outIndex, expandedChar, - mBuffer->tab_distance(), mBuffer->null_substitution_character() ); - charStyle = position_style( lineStartPos, lineLen, charIndex, - outIndex ); - xStep += string_width( expandedChar, charLen, charStyle ); - outIndex += charLen; - } - *X = xStep; - free((char *)lineStr); - return 1; -} - -/* -** Find the line number of position "pos". Note: this only works for -** displayed lines. If the line is not displayed, the function returns -** 0 (without the mLineStarts array it could turn in to very long -** calculation involving scanning large amounts of text in the buffer). -** If continuous wrap mode is on, returns the absolute line number (as opposed -** to the wrapped line number which is used for scrolling). -*/ -int Fl_Text_Display_mod::position_to_linecol( int pos, int* lineNum, int* column ) { - int retVal; - - /* In continuous wrap mode, the absolute (non-wrapped) line count is - maintained separately, as needed. Only return it if we're actually - keeping track of it and pos is in the displayed text */ - if (mContinuousWrap) { - if (!maintaining_absolute_top_line_number() || - pos < mFirstChar || pos > mLastChar) - return 0; - *lineNum = mAbsTopLineNum + buffer()->count_lines(mFirstChar, pos); - *column - = buffer()->count_displayed_characters(buffer()->line_start(pos), pos); - return 1; - } - - retVal = position_to_line( pos, lineNum ); - if ( retVal ) { - *column = mBuffer->count_displayed_characters( - mLineStarts[ *lineNum ], pos ); - *lineNum += mTopLineNum; - } - return retVal; -} - -/* -** Return 1 if position (X, Y) is inside of the primary Fl_Text_Selection -*/ -int Fl_Text_Display_mod::in_selection( int X, int Y ) { - int row, column, pos = xy_to_position( X, Y, CHARACTER_POS ); - Fl_Text_Buffer_mod*buf = mBuffer; - - xy_to_rowcol( X, Y, &row, &column, CHARACTER_POS ); - if (range_touches_selection(buf->primary_selection(), mFirstChar, mLastChar)) - column = wrapped_column(row, column); - return buf->primary_selection()->includes(pos, buf->line_start( pos ), column); -} - -/* -** Correct a column number based on an unconstrained position (as returned by -** TextDXYToUnconstrainedPosition) to be relative to the last actual newline -** in the buffer before the row and column position given, rather than the -** last line start created by line wrapping. This is an adapter -** for rectangular selections and code written before continuous wrap mode, -** which thinks that the unconstrained column is the number of characters -** from the last newline. Obviously this is time consuming, because it -** invloves character re-counting. -*/ -int Fl_Text_Display_mod::wrapped_column(int row, int column) { - int lineStart, dispLineStart; - - if (!mContinuousWrap || row < 0 || row > mNVisibleLines) - return column; - dispLineStart = mLineStarts[row]; - if (dispLineStart == -1) - return column; - lineStart = buffer()->line_start(dispLineStart); - return column - + buffer()->count_displayed_characters(lineStart, dispLineStart); -} - -/* -** Correct a row number from an unconstrained position (as returned by -** TextDXYToUnconstrainedPosition) to a straight number of newlines from the -** top line of the display. Because rectangular selections are based on -** newlines, rather than display wrapping, and anywhere a rectangular selection -** needs a row, it needs it in terms of un-wrapped lines. -*/ -int Fl_Text_Display_mod::wrapped_row(int row) { - if (!mContinuousWrap || row < 0 || row > mNVisibleLines) - return row; - return buffer()->count_lines(mFirstChar, mLineStarts[row]); -} - -/* -** Scroll the display to bring insertion cursor into view. -** -** Note: it would be nice to be able to do this without counting lines twice -** (scroll_() counts them too) and/or to count from the most efficient -** starting point, but the efficiency of this routine is not as important to -** the overall performance of the text display. -*/ -void Fl_Text_Display_mod::display_insert() { - int hOffset, topLine, X, Y; - hOffset = mHorizOffset; - topLine = mTopLineNum; - -// FIXME: I don't understand this well enough to know if it is correct -// it is different than nedit 5.3 - if (insert_position() < mFirstChar) { - topLine -= count_lines(insert_position(), mFirstChar, false); - } else if (mLineStarts[mNVisibleLines-2] != -1) { - int lastChar = line_end(mLineStarts[mNVisibleLines-2],true); - if (insert_position() >= lastChar) - topLine - += count_lines(lastChar - (wrap_uses_character(mLastChar) ? 0 : 1), - insert_position(), false); - } - - /* Find the new setting for horizontal offset (this is a bit ungraceful). - If the line is visible, just use PositionToXY to get the position - to scroll to, otherwise, do the vertical scrolling first, then the - horizontal */ - if (!position_to_xy( mCursorPos, &X, &Y )) { - scroll_(topLine, hOffset); - if (!position_to_xy( mCursorPos, &X, &Y )) { - #ifdef DEBUG - printf ("*** display_insert/position_to_xy # GIVE UP !\n"); fflush(stdout); - #endif // DEBUG - return; /* Give up, it's not worth it (but why does it fail?) */ - } - } - if (X > text_area.x + text_area.w) - hOffset += X-(text_area.x + text_area.w); - else if (X < text_area.x) - hOffset += X-text_area.x; - - /* Do the scroll */ - if (topLine != mTopLineNum || hOffset != mHorizOffset) - scroll_(topLine, hOffset); -} - -void Fl_Text_Display_mod::show_insert_position() { - display_insert_position_hint = 1; - resize(x(), y(), w(), h()); -} - -/* -** Cursor movement functions -*/ -int Fl_Text_Display_mod::move_right() { - if ( mCursorPos >= mBuffer->length() ) - return 0; - insert_position( mCursorPos + 1 ); - return 1; -} - -int Fl_Text_Display_mod::move_left() { - if ( mCursorPos <= 0 ) - return 0; - insert_position( mCursorPos - 1 ); - return 1; -} - -int Fl_Text_Display_mod::move_up() { - int lineStartPos, column, prevLineStartPos, newPos, visLineNum; - - /* Find the position of the start of the line. Use the line starts array - if possible */ - if ( position_to_line( mCursorPos, &visLineNum ) ) - lineStartPos = mLineStarts[ visLineNum ]; - else { - lineStartPos = line_start( mCursorPos ); - visLineNum = -1; - } - if ( lineStartPos == 0 ) - return 0; - - /* Decide what column to move to, if there's a preferred column use that */ - column = mCursorPreferredCol >= 0 ? mCursorPreferredCol : - mBuffer->count_displayed_characters( lineStartPos, mCursorPos ); - - /* count forward from the start of the previous line to reach the column */ - if ( visLineNum != -1 && visLineNum != 0 ) - prevLineStartPos = mLineStarts[ visLineNum - 1 ]; - else - prevLineStartPos = rewind_lines( lineStartPos, 1 ); - newPos = mBuffer->skip_displayed_characters( prevLineStartPos, column ); - if (mContinuousWrap) - newPos = min(newPos, line_end(prevLineStartPos, true)); - - /* move the cursor */ - insert_position( newPos ); - - /* if a preferred column wasn't aleady established, establish it */ - mCursorPreferredCol = column; - return 1; -} - -int Fl_Text_Display_mod::move_down() { - int lineStartPos, column, nextLineStartPos, newPos, visLineNum; - - if ( mCursorPos == mBuffer->length() ) - return 0; - if ( position_to_line( mCursorPos, &visLineNum ) ) - lineStartPos = mLineStarts[ visLineNum ]; - else { - lineStartPos = line_start( mCursorPos ); - visLineNum = -1; - } - column = mCursorPreferredCol >= 0 ? mCursorPreferredCol : - mBuffer->count_displayed_characters( lineStartPos, mCursorPos ); - nextLineStartPos = skip_lines( lineStartPos, 1, true ); - newPos = mBuffer->skip_displayed_characters( nextLineStartPos, column ); - if (mContinuousWrap) - newPos = min(newPos, line_end(nextLineStartPos, true)); - - insert_position( newPos ); - mCursorPreferredCol = column; - return 1; -} - -/* -** Same as BufCountLines, but takes in to account wrapping if wrapping is -** turned on. If the caller knows that startPos is at a line start, it -** can pass "startPosIsLineStart" as True to make the call more efficient -** by avoiding the additional step of scanning back to the last newline. -*/ -int Fl_Text_Display_mod::count_lines(int startPos, int endPos, - bool startPosIsLineStart) { - int retLines, retPos, retLineStart, retLineEnd; - -#ifdef DEBUG - printf("Fl_Text_Display_mod::count_lines(startPos=%d, endPos=%d, startPosIsLineStart=%d\n", - startPos, endPos, startPosIsLineStart); -#endif // DEBUG - - /* If we're not wrapping use simple (and more efficient) BufCountLines */ - if (!mContinuousWrap) - return buffer()->count_lines(startPos, endPos); - - wrapped_line_counter(buffer(), startPos, endPos, INT_MAX, - startPosIsLineStart, 0, &retPos, &retLines, &retLineStart, - &retLineEnd); - -#ifdef DEBUG - printf(" # after WLC: retPos=%d, retLines=%d, retLineStart=%d, retLineEnd=%d\n", - retPos, retLines, retLineStart, retLineEnd); -#endif // DEBUG - - return retLines; -} - -/* -** Same as BufCountForwardNLines, but takes in to account line breaks when -** wrapping is turned on. If the caller knows that startPos is at a line start, -** it can pass "startPosIsLineStart" as True to make the call more efficient -** by avoiding the additional step of scanning back to the last newline. -*/ -int Fl_Text_Display_mod::skip_lines(int startPos, int nLines, - bool startPosIsLineStart) { - int retLines, retPos, retLineStart, retLineEnd; - - /* if we're not wrapping use more efficient BufCountForwardNLines */ - if (!mContinuousWrap) - return buffer()->skip_lines(startPos, nLines); - - /* wrappedLineCounter can't handle the 0 lines case */ - if (nLines == 0) - return startPos; - - /* use the common line counting routine to count forward */ - wrapped_line_counter(buffer(), startPos, buffer()->length(), - nLines, startPosIsLineStart, 0, &retPos, &retLines, &retLineStart, - &retLineEnd); - return retPos; -} - -/* -** Same as BufEndOfLine, but takes in to account line breaks when wrapping -** is turned on. If the caller knows that startPos is at a line start, it -** can pass "startPosIsLineStart" as True to make the call more efficient -** by avoiding the additional step of scanning back to the last newline. -** -** Note that the definition of the end of a line is less clear when continuous -** wrap is on. With continuous wrap off, it's just a pointer to the newline -** that ends the line. When it's on, it's the character beyond the last -** DISPLAYABLE character on the line, where a whitespace character which has -** been "converted" to a newline for wrapping is not considered displayable. -** Also note that, a line can be wrapped at a non-whitespace character if the -** line had no whitespace. In this case, this routine returns a pointer to -** the start of the next line. This is also consistent with the model used by -** visLineLength. -*/ -int Fl_Text_Display_mod::line_end(int pos, bool startPosIsLineStart) { - int retLines, retPos, retLineStart, retLineEnd; - - /* If we're not wrapping use more efficien BufEndOfLine */ - if (!mContinuousWrap) - return buffer()->line_end(pos); - - if (pos == buffer()->length()) - return pos; - wrapped_line_counter(buffer(), pos, buffer()->length(), 1, - startPosIsLineStart, 0, &retPos, &retLines, &retLineStart, - &retLineEnd); - return retLineEnd; -} - -/* -** Same as BufStartOfLine, but returns the character after last wrap point -** rather than the last newline. -*/ -int Fl_Text_Display_mod::line_start(int pos) { - int retLines, retPos, retLineStart, retLineEnd; - - /* If we're not wrapping, use the more efficient BufStartOfLine */ - if (!mContinuousWrap) - return buffer()->line_start(pos); - - wrapped_line_counter(buffer(), buffer()->line_start(pos), pos, INT_MAX, true, 0, - &retPos, &retLines, &retLineStart, &retLineEnd); - return retLineStart; -} - -/* -** Same as BufCountBackwardNLines, but takes in to account line breaks when -** wrapping is turned on. -*/ -int Fl_Text_Display_mod::rewind_lines(int startPos, int nLines) { - Fl_Text_Buffer_mod*buf = buffer(); - int pos, lineStart, retLines, retPos, retLineStart, retLineEnd; - - /* If we're not wrapping, use the more efficient BufCountBackwardNLines */ - if (!mContinuousWrap) - return buf->rewind_lines(startPos, nLines); - - pos = startPos; - for (;;) { - lineStart = buf->line_start(pos); - wrapped_line_counter(buf, lineStart, pos, INT_MAX, - true, 0, &retPos, &retLines, &retLineStart, &retLineEnd, false); - if (retLines > nLines) - return skip_lines(lineStart, retLines-nLines, - true); - nLines -= retLines; - pos = lineStart - 1; - if (pos < 0) - return 0; - nLines -= 1; - } -} - -static inline int fl_isseparator(int c) { - return c != '$' && c != '_' && (isspace(c) || ispunct(c)); -} - -void Fl_Text_Display_mod::next_word() { - int pos = insert_position(); - while (pos < buffer()->length() && !fl_isseparator(buffer()->character(pos))) { - pos++; - } - while (pos < buffer()->length() && fl_isseparator(buffer()->character(pos))) { - pos++; - } - - insert_position( pos ); -} - -void Fl_Text_Display_mod::previous_word() { - int pos = insert_position(); - if (pos==0) return; - pos--; - while (pos && fl_isseparator(buffer()->character(pos))) { - pos--; - } - while (pos && !fl_isseparator(buffer()->character(pos))) { - pos--; - } - if (fl_isseparator(buffer()->character(pos))) pos++; - - insert_position( pos ); -} - -/* -** Callback attached to the text buffer to receive delete information before -** the modifications are actually made. -*/ -void Fl_Text_Display_mod::buffer_predelete_cb(int pos, int nDeleted, void *cbArg) { - Fl_Text_Display_mod *textD = (Fl_Text_Display_mod *)cbArg; - if (textD->mContinuousWrap && - (textD->mFixedFontWidth == -1 || textD->mModifyingTabDistance)) - /* Note: we must perform this measurement, even if there is not a - single character deleted; the number of "deleted" lines is the - number of visual lines spanned by the real line in which the - modification takes place. - Also, a modification of the tab distance requires the same - kind of calculations in advance, even if the font width is "fixed", - because when the width of the tab characters changes, the layout - of the text may be completely different. */ - textD->measure_deleted_lines(pos, nDeleted); - else - textD->mSuppressResync = 0; /* Probably not needed, but just in case */ -} - -/* -** Callback attached to the text buffer to receive modification information -*/ -void Fl_Text_Display_mod::buffer_modified_cb( int pos, int nInserted, int nDeleted, - int nRestyled, const char *deletedText, void *cbArg ) { - int linesInserted, linesDeleted, startDispPos, endDispPos; - Fl_Text_Display_mod *textD = ( Fl_Text_Display_mod * ) cbArg; - Fl_Text_Buffer_mod*buf = textD->mBuffer; - int oldFirstChar = textD->mFirstChar; - int scrolled, origCursorPos = textD->mCursorPos; - int wrapModStart, wrapModEnd; - - /* buffer modification cancels vertical cursor motion column */ - if ( nInserted != 0 || nDeleted != 0 ) - textD->mCursorPreferredCol = -1; - - /* Count the number of lines inserted and deleted, and in the case - of continuous wrap mode, how much has changed */ - if (textD->mContinuousWrap) { - textD->find_wrap_range(deletedText, pos, nInserted, nDeleted, - &wrapModStart, &wrapModEnd, &linesInserted, &linesDeleted); - } else { - linesInserted = nInserted == 0 ? 0 : - buf->count_lines( pos, pos + nInserted ); - linesDeleted = nDeleted == 0 ? 0 : countlines( deletedText ); - } - - /* Update the line starts and mTopLineNum */ - if ( nInserted != 0 || nDeleted != 0 ) { - if (textD->mContinuousWrap) { - textD->update_line_starts( wrapModStart, wrapModEnd-wrapModStart, - nDeleted + pos-wrapModStart + (wrapModEnd-(pos+nInserted)), - linesInserted, linesDeleted, &scrolled ); - } else { - textD->update_line_starts( pos, nInserted, nDeleted, linesInserted, - linesDeleted, &scrolled ); - } - } else - scrolled = 0; - - /* If we're counting non-wrapped lines as well, maintain the absolute - (non-wrapped) line number of the text displayed */ - if (textD->maintaining_absolute_top_line_number() && - (nInserted != 0 || nDeleted != 0)) { - if (pos + nDeleted < oldFirstChar) - textD->mAbsTopLineNum += buf->count_lines(pos, pos + nInserted) - - countlines(deletedText); - else if (pos < oldFirstChar) - textD->reset_absolute_top_line_number(); - } - - /* Update the line count for the whole buffer */ - textD->mNBufferLines += linesInserted - linesDeleted; - - /* Update the cursor position */ - if ( textD->mCursorToHint != NO_HINT ) { - textD->mCursorPos = textD->mCursorToHint; - textD->mCursorToHint = NO_HINT; - } else if ( textD->mCursorPos > pos ) { - if ( textD->mCursorPos < pos + nDeleted ) - textD->mCursorPos = pos; - else - textD->mCursorPos += nInserted - nDeleted; - } - - // refigure scrollbars & stuff - textD->resize(textD->x(), textD->y(), textD->w(), textD->h()); - - // don't need to do anything else if not visible? - if (!textD->visible_r()) return; - - /* If the changes caused scrolling, re-paint everything and we're done. */ - if ( scrolled ) { - textD->damage(FL_DAMAGE_EXPOSE); - if ( textD->mStyleBuffer ) /* See comments in extendRangeForStyleMods */ - textD->mStyleBuffer->primary_selection()->selected(0); - return; - } - - /* If the changes didn't cause scrolling, decide the range of characters - that need to be re-painted. Also if the cursor position moved, be - sure that the redisplay range covers the old cursor position so the - old cursor gets erased, and erase the bits of the cursor which extend - beyond the left and right edges of the text. */ - startDispPos = textD->mContinuousWrap ? wrapModStart : pos; - if ( origCursorPos == startDispPos && textD->mCursorPos != startDispPos ) - startDispPos = min( startDispPos, origCursorPos - 1 ); - if ( linesInserted == linesDeleted ) { - if ( nInserted == 0 && nDeleted == 0 ) - endDispPos = pos + nRestyled; - else { - endDispPos = textD->mContinuousWrap ? wrapModEnd : - buf->line_end( pos + nInserted ) + 1; - // CET - FIXME if ( origCursorPos >= startDispPos && - // ( origCursorPos <= endDispPos || endDispPos == buf->length() ) ) - } - - if (linesInserted > 1) textD->draw_line_numbers(false); - } else { - endDispPos = textD->mLastChar + 1; - // CET - FIXME if ( origCursorPos >= pos ) - /* If more than one line is inserted/deleted, a line break may have - been inserted or removed in between, and the line numbers may - have changed. If only one line is altered, line numbers cannot - be affected (the insertion or removal of a line break always - results in at least two lines being redrawn). */ - textD->draw_line_numbers(false); - } - - /* If there is a style buffer, check if the modification caused additional - changes that need to be redisplayed. (Redisplaying separately would - cause double-redraw on almost every modification involving styled - text). Extend the redraw range to incorporate style changes */ - if ( textD->mStyleBuffer ) - textD->extend_range_for_styles( &startDispPos, &endDispPos ); - - /* Redisplay computed range */ - textD->redisplay_range( startDispPos, endDispPos ); -} - -/* -** In continuous wrap mode, internal line numbers are calculated after -** wrapping. A separate non-wrapped line count is maintained when line -** numbering is turned on. There is some performance cost to maintaining this -** line count, so normally absolute line numbers are not tracked if line -** numbering is off. This routine allows callers to specify that they still -** want this line count maintained (for use via TextDPosToLineAndCol). -** More specifically, this allows the line number reported in the statistics -** line to be calibrated in absolute lines, rather than post-wrapped lines. -*/ -void Fl_Text_Display_mod::maintain_absolute_top_line_number(int state) { - mNeedAbsTopLineNum = state; - reset_absolute_top_line_number(); -} - -/* -** Returns the absolute (non-wrapped) line number of the first line displayed. -** Returns 0 if the absolute top line number is not being maintained. -*/ -int Fl_Text_Display_mod::get_absolute_top_line_number() { - if (!mContinuousWrap) - return mTopLineNum; - if (maintaining_absolute_top_line_number()) - return mAbsTopLineNum; - return 0; -} - -/* -** Re-calculate absolute top line number for a change in scroll position. -*/ -void Fl_Text_Display_mod::absolute_top_line_number(int oldFirstChar) { - if (maintaining_absolute_top_line_number()) { - if (mFirstChar < oldFirstChar) - mAbsTopLineNum -= buffer()->count_lines(mFirstChar, oldFirstChar); - else - mAbsTopLineNum += buffer()->count_lines(oldFirstChar, mFirstChar); - } -} - -/* -** Return true if a separate absolute top line number is being maintained -** (for displaying line numbers or showing in the statistics line). -*/ -int Fl_Text_Display_mod::maintaining_absolute_top_line_number() { - return mContinuousWrap && - (mLineNumWidth != 0 || mNeedAbsTopLineNum); -} - -/* -** Count lines from the beginning of the buffer to reestablish the -** absolute (non-wrapped) top line number. If mode is not continuous wrap, -** or the number is not being maintained, does nothing. -*/ -void Fl_Text_Display_mod::reset_absolute_top_line_number() { - mAbsTopLineNum = 1; - absolute_top_line_number(0); -} - -/* -** Find the line number of position "pos" relative to the first line of -** displayed text. Returns 0 if the line is not displayed. -*/ -//int Fl_Text_Display_mod::position_to_line( int pos, int *lineNum ) { -int Fl_Text_Display_mod::position_to_line( size_t pos, int *lineNum ) { - int i; - - *lineNum = 0; - if ( pos < (unsigned int)mFirstChar ) return 0; - if ( pos > (unsigned int)mLastChar ) { - if ( empty_vlines() ) { - if ( mLastChar < mBuffer->length() ) { - if ( !position_to_line( mLastChar, lineNum ) ) { -#ifdef DEBUG - Fl::error("Fl_Text_Display_mod::position_to_line(): Consistency check ptvl failed"); -#endif - return 0; - } - return ++( *lineNum ) <= mNVisibleLines - 1; - } else { - position_to_line( mLastChar - 1, lineNum ); - return 1; - } - } - return 0; - } - - for ( i = mNVisibleLines - 1; i >= 0; i-- ) { - if ( mLineStarts[ i ] != -1 && pos >= (unsigned int)mLineStarts[ i ] ) { - *lineNum = i; - return 1; - } - } - return 0; /* probably never be reached */ -} - -/* -** Draw the text on a single line represented by "visLineNum" (the -** number of lines down from the top of the display), limited by -** "leftClip" and "rightClip" window coordinates and "leftCharIndex" and -** "rightCharIndex" character positions (not including the character at -** position "rightCharIndex"). -*/ -void Fl_Text_Display_mod::draw_vline(int visLineNum, int leftClip, int rightClip, - int leftCharIndex, int rightCharIndex) { - Fl_Text_Buffer_mod* buf = mBuffer; - int i, X, Y, startX, charIndex, lineStartPos, lineLen, fontHeight; - int stdCharWidth, charWidth, startIndex, charStyle, style; - int charLen, outStartIndex, outIndex; - int dispIndexOffset; - char expandedChar[ FL_TEXT_MAX_EXP_CHAR_LEN ], outStr[ MAX_DISP_LINE_LEN ]; - char *outPtr; - const char *lineStr; - -// printf("draw_vline(visLineNum=%d, leftClip=%d, rightClip=%d, leftCharIndex=%d, rightCharIndex=%d)\n", -// visLineNum, leftClip, rightClip, leftCharIndex, rightCharIndex); -// printf("nNVisibleLines=%d\n", mNVisibleLines); - - /* If line is not displayed, skip it */ - if ( visLineNum < 0 || visLineNum >= mNVisibleLines ) - return; - - /* Calculate Y coordinate of the std::string to draw */ - fontHeight = mMaxsize; - Y = text_area.y + visLineNum * fontHeight; - - /* Get the text, length, and buffer position of the line to display */ - lineStartPos = mLineStarts[ visLineNum ]; -// printf("lineStartPos=%d\n", lineStartPos); - if ( lineStartPos == -1 ) { - lineLen = 0; - lineStr = NULL; - } else { - lineLen = vline_length( visLineNum ); - lineStr = buf->text_range( lineStartPos, lineStartPos + lineLen ); - } - - /* Space beyond the end of the line is still counted in units of characters - of a standardized character width (this is done mostly because style - changes based on character position can still occur in this region due - to rectangular Fl_Text_Selections). stdCharWidth must be non-zero to - prevent a potential infinite loop if X does not advance */ - stdCharWidth = TMPFONTWIDTH; //mFontStruct->max_bounds.width; - if ( stdCharWidth <= 0 ) { - Fl::error("Fl_Text_Display_mod::draw_vline(): bad font measurement"); - free((void *)lineStr); - return; - } - - /* Shrink the clipping range to the active display area */ - leftClip = max( text_area.x, leftClip ); - rightClip = min( rightClip, text_area.x + text_area.w ); - - /* Rectangular Fl_Text_Selections are based on "real" line starts (after - a newline or start of buffer). Calculate the difference between the - last newline position and the line start we're using. Since scanning - back to find a newline is expensive, only do so if there's actually a - rectangular Fl_Text_Selection which needs it */ - if (mContinuousWrap && (range_touches_selection(buf->primary_selection(), - lineStartPos, lineStartPos + lineLen) || range_touches_selection( - buf->secondary_selection(), lineStartPos, lineStartPos + lineLen) || - range_touches_selection(buf->highlight_selection(), lineStartPos, - lineStartPos + lineLen))) { - dispIndexOffset = buf->count_displayed_characters( - buf->line_start(lineStartPos), lineStartPos); - } else - dispIndexOffset = 0; - - /* Step through character positions from the beginning of the line (even if - that's off the left edge of the displayed area) to find the first - character position that's not clipped, and the X coordinate for drawing - that character */ - X = text_area.x - mHorizOffset; - outIndex = 0; - for ( charIndex = 0; ; charIndex++ ) { - charLen = charIndex >= lineLen ? 1 : - Fl_Text_Buffer_mod::expand_character( lineStr[ charIndex ], outIndex, - expandedChar, buf->tab_distance(), buf->null_substitution_character() ); - style = position_style( lineStartPos, lineLen, charIndex, - outIndex + dispIndexOffset ); - charWidth = charIndex >= lineLen ? stdCharWidth : - string_width( expandedChar, charLen, style ); - if ( X + charWidth >= leftClip && charIndex >= leftCharIndex ) { - startIndex = charIndex; - outStartIndex = outIndex; - startX = X; - break; - } - X += charWidth; - outIndex += charLen; - } - - /* Scan character positions from the beginning of the clipping range, and - draw parts whenever the style changes (also note if the cursor is on - this line, and where it should be drawn to take advantage of the x - position which we've gone to so much trouble to calculate) */ - /* since characters between style may overlap, we draw the full - background first */ - int sX = startX; - outPtr = outStr; - outIndex = outStartIndex; - X = startX; - for ( charIndex = startIndex; charIndex < rightCharIndex; charIndex++ ) { - charLen = charIndex >= lineLen ? 1 : - Fl_Text_Buffer_mod::expand_character( lineStr[ charIndex ], outIndex, expandedChar, - buf->tab_distance(), buf->null_substitution_character() ); - charStyle = position_style( lineStartPos, lineLen, charIndex, - outIndex + dispIndexOffset ); - for ( i = 0; i < charLen; i++ ) { - if ( i != 0 && charIndex < lineLen && lineStr[ charIndex ] == '\t' ) - charStyle = position_style( lineStartPos, lineLen, - charIndex, outIndex + dispIndexOffset ); - if ( charStyle != style ) { - draw_string( style|BG_ONLY_MASK, sX, Y, X, outStr, outPtr - outStr ); - outPtr = outStr; - sX = X; - style = charStyle; - } - if ( charIndex < lineLen ) { - *outPtr = expandedChar[ i ]; - charWidth = string_width( &expandedChar[ i ], 1, charStyle ); - } else - charWidth = stdCharWidth; - outPtr++; - X += charWidth; - outIndex++; - } - if ( outPtr - outStr + FL_TEXT_MAX_EXP_CHAR_LEN >= MAX_DISP_LINE_LEN || X >= rightClip ) - break; - } - draw_string( style|BG_ONLY_MASK, sX, Y, X, outStr, outPtr - outStr ); - - /* now draw the text over the previously erased background */ - outPtr = outStr; - outIndex = outStartIndex; - X = startX; - for ( charIndex = startIndex; charIndex < rightCharIndex; charIndex++ ) { - charLen = charIndex >= lineLen ? 1 : - Fl_Text_Buffer_mod::expand_character( lineStr[ charIndex ], outIndex, expandedChar, - buf->tab_distance(), buf->null_substitution_character() ); - charStyle = position_style( lineStartPos, lineLen, charIndex, - outIndex + dispIndexOffset ); - for ( i = 0; i < charLen; i++ ) { - if ( i != 0 && charIndex < lineLen && lineStr[ charIndex ] == '\t' ) - charStyle = position_style( lineStartPos, lineLen, - charIndex, outIndex + dispIndexOffset ); - if ( charStyle != style ) { - draw_string( style|TEXT_ONLY_MASK, startX, Y, X, outStr, outPtr - outStr ); - outPtr = outStr; - startX = X; - style = charStyle; - } - if ( charIndex < lineLen ) { - *outPtr = expandedChar[ i ]; - charWidth = string_width( &expandedChar[ i ], 1, charStyle ); - } else - charWidth = stdCharWidth; - outPtr++; - X += charWidth; - outIndex++; - } - if ( outPtr - outStr + FL_TEXT_MAX_EXP_CHAR_LEN >= MAX_DISP_LINE_LEN || X >= rightClip ) - break; - } - - /* Draw the remaining style segment */ - draw_string( style|TEXT_ONLY_MASK, startX, Y, X, outStr, outPtr - outStr ); - - /* Draw the cursor if part of it appeared on the redisplayed part of - this line. Also check for the cases which are not caught as the - line is scanned above: when the cursor appears at the very end - of the redisplayed section. */ - /* CET - FIXME - if ( mCursorOn ) - { - if ( hasCursor ) - draw_cursor( cursorX, Y ); - else if ( charIndex < lineLen && ( lineStartPos + charIndex + 1 == cursorPos ) - && X == rightClip ) - { - if ( cursorPos >= buf->length() ) - draw_cursor( X - 1, Y ); - else - { - draw_cursor( X - 1, Y ); - } - } - } - */ - if ( lineStr != NULL ) - free((void *)lineStr); -} - -/* -** Draw a std::string or blank area according to parameter "style", using the -** appropriate colors and drawing method for that style, with top left -** corner at X, y. If style says to draw text, use "std::string" as source of -** characters, and draw "nChars", if style is FILL, erase -** rectangle where text would have drawn from X to toX and from Y to -** the maximum Y extent of the current font(s). -*/ -void Fl_Text_Display_mod::draw_string( int style, int X, int Y, int toX, - const char *string, int nChars ) { - const Style_Table_Entry * styleRec; - - /* Draw blank area rather than text, if that was the request */ - if ( style & FILL_MASK ) { - if (style & TEXT_ONLY_MASK) return; - clear_rect( style, X, Y, toX - X, mMaxsize ); - return; - } - - /* Set font, color, and gc depending on style. For normal text, GCs - for normal drawing, or drawing within a Fl_Text_Selection or highlight are - pre-allocated and pre-configured. For syntax highlighting, GCs are - configured here, on the fly. */ - - Fl_Font font = textfont(); - int fsize = textsize(); - Fl_Color foreground; - Fl_Color background; - - if ( style & STYLE_LOOKUP_MASK ) { - int si = (style & STYLE_LOOKUP_MASK) - 'A'; - if (si < 0) si = 0; - else if (si >= mNStyles) si = mNStyles - 1; - - styleRec = mStyleTable + si; - font = styleRec->font; - fsize = styleRec->size; - - if (style & (HIGHLIGHT_MASK | PRIMARY_MASK)) { - if (Fl::focus() == this) background = selection_color(); - else background = fl_color_average(color(), selection_color(), 0.8f); - } else - background = color(); - foreground = fl_contrast(styleRec->color, background); - } else if (style & (HIGHLIGHT_MASK | PRIMARY_MASK)) { - if (Fl::focus() == this) background = selection_color(); - else background = fl_color_average(color(), selection_color(), 0.5f); - foreground = fl_contrast(textcolor(), background); - } else { - foreground = textcolor(); - background = color(); - } - - if (!(style & TEXT_ONLY_MASK)) { - fl_color( background ); - fl_rectf( X, Y, toX - X, mMaxsize ); - } - if (!(style & BG_ONLY_MASK)) { - fl_color( foreground ); - fl_font( font, fsize ); - fl_draw( std::string, nChars, X, Y + mMaxsize - fl_descent()); - } - - // CET - FIXME - /* If any space around the character remains unfilled (due to use of - different sized fonts for highlighting), fill in above or below - to erase previously drawn characters */ - /* - if (fs->ascent < mAscent) - clear_rect( style, X, Y, toX - X, mAscent - fs->ascent); - if (fs->descent < mDescent) - clear_rect( style, X, Y + mAscent + fs->descent, toX - x, - mDescent - fs->descent); - */ - /* Underline if style is secondary Fl_Text_Selection */ - - /* - if (style & SECONDARY_MASK) - XDrawLine(XtDisplay(mW), XtWindow(mW), gc, x, - y + mAscent, toX - 1, Y + fs->ascent); - */ -} - -/* -** Clear a rectangle with the appropriate background color for "style" -*/ -void Fl_Text_Display_mod::clear_rect( int style, int X, int Y, - int width, int height ) { - /* A width of zero means "clear to end of window" to XClearArea */ - if ( width == 0 ) - return; - - if ( Fl::focus() != this ) { - if (style & (HIGHLIGHT_MASK | PRIMARY_MASK)) { - fl_color(fl_color_average(color(), selection_color(), 0.5f)); - } else { - fl_color( color() ); - } - fl_rectf( X, Y, width, height ); - } else if ( style & HIGHLIGHT_MASK ) { - fl_color( fl_contrast(textcolor(), color()) ); - fl_rectf( X, Y, width, height ); - } else if ( style & PRIMARY_MASK ) { - fl_color( selection_color() ); - fl_rectf( X, Y, width, height ); - } else { - fl_color( color() ); - fl_rectf( X, Y, width, height ); - } -} - - - -/* -** Draw a cursor with top center at X, y. -*/ -void Fl_Text_Display_mod::draw_cursor( int X, int Y ) { - typedef struct { - int x1, y1, x2, y2; - } - Segment; - - Segment segs[ 5 ]; - int left, right, cursorWidth, midY; - // int fontWidth = mFontStruct->min_bounds.width, nSegs = 0; - int fontWidth = TMPFONTWIDTH; // CET - FIXME - int nSegs = 0; - int fontHeight = mMaxsize; - int bot = Y + fontHeight - 1; - - if ( X < text_area.x - 1 || X > text_area.x + text_area.w ) - return; - - /* For cursors other than the block, make them around 2/3 of a character - width, rounded to an even number of pixels so that X will draw an - odd number centered on the stem at x. */ - cursorWidth = 4; //(fontWidth/3) * 2; - left = X - cursorWidth / 2; - right = left + cursorWidth; - - /* Create segments and draw cursor */ - if ( mCursorStyle == CARET_CURSOR ) { - midY = bot - fontHeight / 5; - segs[ 0 ].x1 = left; segs[ 0 ].y1 = bot; segs[ 0 ].x2 = X; segs[ 0 ].y2 = midY; - segs[ 1 ].x1 = X; segs[ 1 ].y1 = midY; segs[ 1 ].x2 = right; segs[ 1 ].y2 = bot; - segs[ 2 ].x1 = left; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = X; segs[ 2 ].y2 = midY - 1; - segs[ 3 ].x1 = X; segs[ 3 ].y1 = midY - 1; segs[ 3 ].x2 = right; segs[ 3 ].y2 = bot; - nSegs = 4; - } else if ( mCursorStyle == NORMAL_CURSOR ) { - segs[ 0 ].x1 = left; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = right; segs[ 0 ].y2 = Y; - segs[ 1 ].x1 = X; segs[ 1 ].y1 = Y; segs[ 1 ].x2 = X; segs[ 1 ].y2 = bot; - segs[ 2 ].x1 = left; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = right; segs[ 2 ].y2 = bot; - nSegs = 3; - } else if ( mCursorStyle == HEAVY_CURSOR ) { - segs[ 0 ].x1 = X - 1; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = X - 1; segs[ 0 ].y2 = bot; - segs[ 1 ].x1 = X; segs[ 1 ].y1 = Y; segs[ 1 ].x2 = X; segs[ 1 ].y2 = bot; - segs[ 2 ].x1 = X + 1; segs[ 2 ].y1 = Y; segs[ 2 ].x2 = X + 1; segs[ 2 ].y2 = bot; - segs[ 3 ].x1 = left; segs[ 3 ].y1 = Y; segs[ 3 ].x2 = right; segs[ 3 ].y2 = Y; - segs[ 4 ].x1 = left; segs[ 4 ].y1 = bot; segs[ 4 ].x2 = right; segs[ 4 ].y2 = bot; - nSegs = 5; - } else if ( mCursorStyle == DIM_CURSOR ) { - midY = Y + fontHeight / 2; - segs[ 0 ].x1 = X; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = X; segs[ 0 ].y2 = Y; - segs[ 1 ].x1 = X; segs[ 1 ].y1 = midY; segs[ 1 ].x2 = X; segs[ 1 ].y2 = midY; - segs[ 2 ].x1 = X; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = X; segs[ 2 ].y2 = bot; - nSegs = 3; - } else if ( mCursorStyle == BLOCK_CURSOR ) { - right = X + fontWidth; - segs[ 0 ].x1 = X; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = right; segs[ 0 ].y2 = Y; - segs[ 1 ].x1 = right; segs[ 1 ].y1 = Y; segs[ 1 ].x2 = right; segs[ 1 ].y2 = bot; - segs[ 2 ].x1 = right; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = X; segs[ 2 ].y2 = bot; - segs[ 3 ].x1 = X; segs[ 3 ].y1 = bot; segs[ 3 ].x2 = X; segs[ 3 ].y2 = Y; - nSegs = 4; - } - fl_color( mCursor_color ); - - for ( int k = 0; k < nSegs; k++ ) { - fl_line( segs[ k ].x1, segs[ k ].y1, segs[ k ].x2, segs[ k ].y2 ); - } -} - -/* -** Determine the drawing method to use to draw a specific character from "buf". -** "lineStartPos" gives the character index where the line begins, "lineIndex", -** the number of characters past the beginning of the line, and "dispIndex", -** the number of displayed characters past the beginning of the line. Passing -** lineStartPos of -1 returns the drawing style for "no text". -** -** Why not just: position_style(pos)? Because style applies to blank areas -** of the window beyond the text boundaries, and because this routine must also -** decide whether a position is inside of a rectangular Fl_Text_Selection, and do -** so efficiently, without re-counting character positions from the start of the -** line. -** -** Note that style is a somewhat incorrect name, drawing method would -** be more appropriate. -*/ -int Fl_Text_Display_mod::position_style( int lineStartPos, - int lineLen, int lineIndex, int dispIndex ) { - Fl_Text_Buffer_mod* buf = mBuffer; - Fl_Text_Buffer_mod*styleBuf = mStyleBuffer; - int pos, style = 0; - - if ( lineStartPos == -1 || buf == NULL ) - return FILL_MASK; - - pos = lineStartPos + min( lineIndex, lineLen ); - - if ( lineIndex >= lineLen ) - style = FILL_MASK; - else if ( styleBuf != NULL ) { - style = ( unsigned char ) styleBuf->character( pos ); - if (style == mUnfinishedStyle && mUnfinishedHighlightCB) { - /* encountered "unfinished" style, trigger parsing */ - (mUnfinishedHighlightCB)( pos, mHighlightCBArg); - style = (unsigned char) styleBuf->character( pos); - } - } - if (buf->primary_selection()->includes(pos, lineStartPos, dispIndex)) - style |= PRIMARY_MASK; - if (buf->highlight_selection()->includes(pos, lineStartPos, dispIndex)) - style |= HIGHLIGHT_MASK; - if (buf->secondary_selection()->includes(pos, lineStartPos, dispIndex)) - style |= SECONDARY_MASK; - return style; -} - -/* -** Find the width of a std::string in the font of a particular style -*/ -int Fl_Text_Display_mod::string_width( const char *string, int length, int style ) { - Fl_Font font; - int fsize; - - if ( style & STYLE_LOOKUP_MASK ) { - int si = (style & STYLE_LOOKUP_MASK) - 'A'; - if (si < 0) si = 0; - else if (si >= mNStyles) si = mNStyles - 1; - - font = mStyleTable[si].font; - fsize = mStyleTable[si].size; - } else { - font = textfont(); - fsize = textsize(); - } - fl_font( font, fsize ); - - return ( int ) ( fl_width( std::string, length ) ); -} - -/* -** Translate window coordinates to the nearest (insert cursor or character -** cell) text position. The parameter posType specifies how to interpret the -** position: CURSOR_POS means translate the coordinates to the nearest cursor -** position, and CHARACTER_POS means return the position of the character -** closest to (X, Y). -*/ -int Fl_Text_Display_mod::xy_to_position( int X, int Y, int posType ) { - int charIndex, lineStart, lineLen, fontHeight; - int charWidth, charLen, charStyle, visLineNum, xStep, outIndex; - char expandedChar[ FL_TEXT_MAX_EXP_CHAR_LEN ]; - const char *lineStr; - - /* Find the visible line number corresponding to the Y coordinate */ - fontHeight = mMaxsize; - visLineNum = ( Y - text_area.y ) / fontHeight; - if ( visLineNum < 0 ) - return mFirstChar; - if ( visLineNum >= mNVisibleLines ) - visLineNum = mNVisibleLines - 1; - - /* Find the position at the start of the line */ - lineStart = mLineStarts[ visLineNum ]; - - /* If the line start was empty, return the last position in the buffer */ - if ( lineStart == -1 ) - return mBuffer->length(); - - /* Get the line text and its length */ - lineLen = vline_length( visLineNum ); - lineStr = mBuffer->text_range( lineStart, lineStart + lineLen ); - - /* Step through character positions from the beginning of the line - to find the character position corresponding to the X coordinate */ - xStep = text_area.x - mHorizOffset; - outIndex = 0; - for ( charIndex = 0; charIndex < lineLen; charIndex++ ) { - charLen = Fl_Text_Buffer_mod::expand_character( lineStr[ charIndex ], outIndex, expandedChar, - mBuffer->tab_distance(), mBuffer->null_substitution_character() ); - charStyle = position_style( lineStart, lineLen, charIndex, outIndex ); - charWidth = string_width( expandedChar, charLen, charStyle ); - if ( X < xStep + ( posType == CURSOR_POS ? charWidth / 2 : charWidth ) ) { - free((char *)lineStr); - return lineStart + charIndex; - } - xStep += charWidth; - outIndex += charLen; - } - - /* If the X position was beyond the end of the line, return the position - of the newline at the end of the line */ - free((char *)lineStr); - return lineStart + lineLen; -} - -/* -** Translate window coordinates to the nearest row and column number for -** positioning the cursor. This, of course, makes no sense when the font is -** proportional, since there are no absolute columns. The parameter posType -** specifies how to interpret the position: CURSOR_POS means translate the -** coordinates to the nearest position between characters, and CHARACTER_POS -** means translate the position to the nearest character cell. -*/ -void Fl_Text_Display_mod::xy_to_rowcol( int X, int Y, int *row, - int *column, int posType ) { - int fontHeight = mMaxsize; - int fontWidth = TMPFONTWIDTH; //mFontStruct->max_bounds.width; - - /* Find the visible line number corresponding to the Y coordinate */ - *row = ( Y - text_area.y ) / fontHeight; - if ( *row < 0 ) * row = 0; - if ( *row >= mNVisibleLines ) * row = mNVisibleLines - 1; - *column = ( ( X - text_area.x ) + mHorizOffset + - ( posType == CURSOR_POS ? fontWidth / 2 : 0 ) ) / fontWidth; - if ( *column < 0 ) * column = 0; -} - -/* -** Offset the line starts array, mTopLineNum, mFirstChar and lastChar, for a new -** vertical scroll position given by newTopLineNum. If any currently displayed -** lines will still be visible, salvage the line starts values, otherwise, -** count lines from the nearest known line start (start or end of buffer, or -** the closest value in the mLineStarts array) -*/ -void Fl_Text_Display_mod::offset_line_starts( int newTopLineNum ) { - int oldTopLineNum = mTopLineNum; - int oldFirstChar = mFirstChar; - int lineDelta = newTopLineNum - oldTopLineNum; - int nVisLines = mNVisibleLines; - int *lineStarts = mLineStarts; - int i, lastLineNum; - Fl_Text_Buffer_mod*buf = mBuffer; - - /* If there was no offset, nothing needs to be changed */ - if ( lineDelta == 0 ) - return; - - /* Find the new value for mFirstChar by counting lines from the nearest - known line start (start or end of buffer, or the closest value in the - lineStarts array) */ - lastLineNum = oldTopLineNum + nVisLines - 1; - if ( newTopLineNum < oldTopLineNum && newTopLineNum < -lineDelta ) { - mFirstChar = skip_lines( 0, newTopLineNum - 1, true ); - } else if ( newTopLineNum < oldTopLineNum ) { - mFirstChar = rewind_lines( mFirstChar, -lineDelta ); - } else if ( newTopLineNum < lastLineNum ) { - mFirstChar = lineStarts[ newTopLineNum - oldTopLineNum ]; - } else if ( newTopLineNum - lastLineNum < mNBufferLines - newTopLineNum ) { - mFirstChar = skip_lines( lineStarts[ nVisLines - 1 ], - newTopLineNum - lastLineNum, true ); - } else { - mFirstChar = rewind_lines( buf->length(), mNBufferLines - newTopLineNum + 1 ); - } - - /* Fill in the line starts array */ - if ( lineDelta < 0 && -lineDelta < nVisLines ) { - for ( i = nVisLines - 1; i >= -lineDelta; i-- ) - lineStarts[ i ] = lineStarts[ i + lineDelta ]; - calc_line_starts( 0, -lineDelta ); - } else if ( lineDelta > 0 && lineDelta < nVisLines ) { - for ( i = 0; i < nVisLines - lineDelta; i++ ) - lineStarts[ i ] = lineStarts[ i + lineDelta ]; - calc_line_starts( nVisLines - lineDelta, nVisLines - 1 ); - } else - calc_line_starts( 0, nVisLines ); - - /* Set lastChar and mTopLineNum */ - calc_last_char(); - mTopLineNum = newTopLineNum; - - /* If we're numbering lines or being asked to maintain an absolute line - number, re-calculate the absolute line number */ - absolute_top_line_number(oldFirstChar); -} - -/* -** Update the line starts array, mTopLineNum, mFirstChar and lastChar for text -** display "textD" after a modification to the text buffer, given by the -** position where the change began "pos", and the nmubers of characters -** and lines inserted and deleted. -*/ -void Fl_Text_Display_mod::update_line_starts( int pos, int charsInserted, - int charsDeleted, int linesInserted, int linesDeleted, int *scrolled ) { - int * lineStarts = mLineStarts; - int i, lineOfPos, lineOfEnd, nVisLines = mNVisibleLines; - int charDelta = charsInserted - charsDeleted; - int lineDelta = linesInserted - linesDeleted; - - /* If all of the changes were before the displayed text, the display - doesn't change, just update the top line num and offset the line - start entries and first and last characters */ - if ( pos + charsDeleted < mFirstChar ) { - mTopLineNum += lineDelta; - for ( i = 0; i < nVisLines && lineStarts[i] != -1; i++ ) - lineStarts[ i ] += charDelta; - mFirstChar += charDelta; - mLastChar += charDelta; - *scrolled = 0; - return; - } - - /* The change began before the beginning of the displayed text, but - part or all of the displayed text was deleted */ - if ( pos < mFirstChar ) { - /* If some text remains in the window, anchor on that */ - if ( position_to_line( pos + charsDeleted, &lineOfEnd ) && - ++lineOfEnd < nVisLines && lineStarts[ lineOfEnd ] != -1 ) { - mTopLineNum = max( 1, mTopLineNum + lineDelta ); - mFirstChar = rewind_lines( - lineStarts[ lineOfEnd ] + charDelta, lineOfEnd ); - /* Otherwise anchor on original line number and recount everything */ - } else { - if ( mTopLineNum > mNBufferLines + lineDelta ) { - mTopLineNum = 1; - mFirstChar = 0; - } else - mFirstChar = skip_lines( 0, mTopLineNum - 1, true ); - } - calc_line_starts( 0, nVisLines - 1 ); - /* calculate lastChar by finding the end of the last displayed line */ - calc_last_char(); - *scrolled = 1; - return; - } - - /* If the change was in the middle of the displayed text (it usually is), - salvage as much of the line starts array as possible by moving and - offsetting the entries after the changed area, and re-counting the - added lines or the lines beyond the salvaged part of the line starts - array */ - if ( pos <= mLastChar ) { - /* find line on which the change began */ - position_to_line( pos, &lineOfPos ); - /* salvage line starts after the changed area */ - if ( lineDelta == 0 ) { - for ( i = lineOfPos + 1; i < nVisLines && lineStarts[ i ] != -1; i++ ) - lineStarts[ i ] += charDelta; - } else if ( lineDelta > 0 ) { - for ( i = nVisLines - 1; i >= lineOfPos + lineDelta + 1; i-- ) - lineStarts[ i ] = lineStarts[ i - lineDelta ] + - ( lineStarts[ i - lineDelta ] == -1 ? 0 : charDelta ); - } else /* (lineDelta < 0) */ { - for ( i = max( 0, lineOfPos + 1 ); i < nVisLines + lineDelta; i++ ) - lineStarts[ i ] = lineStarts[ i - lineDelta ] + - ( lineStarts[ i - lineDelta ] == -1 ? 0 : charDelta ); - } - /* fill in the missing line starts */ - if ( linesInserted >= 0 ) - calc_line_starts( lineOfPos + 1, lineOfPos + linesInserted ); - if ( lineDelta < 0 ) - calc_line_starts( nVisLines + lineDelta, nVisLines ); - /* calculate lastChar by finding the end of the last displayed line */ - calc_last_char(); - *scrolled = 0; - return; - } - - /* Change was past the end of the displayed text, but displayable by virtue - of being an insert at the end of the buffer into visible blank lines */ - if ( empty_vlines() ) { - position_to_line( pos, &lineOfPos ); - calc_line_starts( lineOfPos, lineOfPos + linesInserted ); - calc_last_char(); - *scrolled = 0; - return; - } - - /* Change was beyond the end of the buffer and not visible, do nothing */ - *scrolled = 0; -} - -/* -** Scan through the text in the "textD"'s buffer and recalculate the line -** starts array values beginning at index "startLine" and continuing through -** (including) "endLine". It assumes that the line starts entry preceding -** "startLine" (or mFirstChar if startLine is 0) is good, and re-counts -** newlines to fill in the requested entries. Out of range values for -** "startLine" and "endLine" are acceptable. -*/ -void Fl_Text_Display_mod::calc_line_starts( int startLine, int endLine ) { - int startPos, bufLen = mBuffer->length(); - int line, lineEnd, nextLineStart, nVis = mNVisibleLines; - int *lineStarts = mLineStarts; - - /* Clean up (possibly) messy input parameters */ - if ( endLine < 0 ) endLine = 0; - if ( endLine >= nVis ) endLine = nVis - 1; - if ( startLine < 0 ) startLine = 0; - if ( startLine >= nVis ) startLine = nVis - 1; - if ( startLine > endLine ) - return; - - /* Find the last known good line number -> position mapping */ - if ( startLine == 0 ) { - lineStarts[ 0 ] = mFirstChar; - startLine = 1; - } - startPos = lineStarts[ startLine - 1 ]; - - /* If the starting position is already past the end of the text, - fill in -1's (means no text on line) and return */ - if ( startPos == -1 ) { - for ( line = startLine; line <= endLine; line++ ) - lineStarts[ line ] = -1; - return; - } - - /* Loop searching for ends of lines and storing the positions of the - start of the next line in lineStarts */ - for ( line = startLine; line <= endLine; line++ ) { - find_line_end(startPos, true, &lineEnd, &nextLineStart); - startPos = nextLineStart; - if ( startPos >= bufLen ) { - /* If the buffer ends with a newline or line break, put - buf->length() in the next line start position (instead of - a -1 which is the normal marker for an empty line) to - indicate that the cursor may safely be displayed there */ - if ( line == 0 || ( lineStarts[ line - 1 ] != bufLen && - lineEnd != nextLineStart ) ) { - lineStarts[ line ] = bufLen; - line++; - } - break; - } - lineStarts[ line ] = startPos; - } - - /* Set any entries beyond the end of the text to -1 */ - for ( ; line <= endLine; line++ ) - lineStarts[ line ] = -1; -} - -/* -** Given a Fl_Text_Display with a complete, up-to-date lineStarts array, update -** the lastChar entry to point to the last buffer position displayed. -*/ -void Fl_Text_Display_mod::calc_last_char() { - int i; - for (i = mNVisibleLines - 1; i >= 0 && mLineStarts[i] == -1; i--) ; - mLastChar = i < 0 ? 0 : line_end(mLineStarts[i], true); -} - -void Fl_Text_Display_mod::scroll(int topLineNum, int horizOffset) { - mTopLineNumHint = topLineNum; - mHorizOffsetHint = horizOffset; - resize(x(), y(), w(), h()); -} - -void Fl_Text_Display_mod::scroll_(int topLineNum, int horizOffset) { - /* Limit the requested scroll position to allowable values */ - if (topLineNum > mNBufferLines + 3 - mNVisibleLines) - topLineNum = mNBufferLines + 3 - mNVisibleLines; - if (topLineNum < 1) topLineNum = 1; - - if (horizOffset > longest_vline() - text_area.w) - horizOffset = longest_vline() - text_area.w; - if (horizOffset < 0) horizOffset = 0; - - /* Do nothing if scroll position hasn't actually changed or there's no - window to draw in yet */ - if (mHorizOffset == horizOffset && mTopLineNum == topLineNum) - return; - - /* If the vertical scroll position has changed, update the line - starts array and related counters in the text display */ - offset_line_starts(topLineNum); - - /* Just setting mHorizOffset is enough information for redisplay */ - mHorizOffset = horizOffset; - - // redraw all text - damage(FL_DAMAGE_EXPOSE); -} - -/* -** Update the minimum, maximum, slider size, page increment, and value -** for vertical scroll bar. -*/ -void Fl_Text_Display_mod::update_v_scrollbar() { - /* The Vert. scroll bar value and slider size directly represent the top - line number, and the number of visible lines respectively. The scroll - bar maximum value is chosen to generally represent the size of the whole - buffer, with minor adjustments to keep the scroll bar widget happy */ -#ifdef DEBUG - printf("Fl_Text_Display_mod::update_v_scrollbar():\n" - " mTopLineNum=%d, mNVisibleLines=%d, mNBufferLines=%d\n", - mTopLineNum, mNVisibleLines, mNBufferLines); -#endif // DEBUG - - mVScrollBar->value(mTopLineNum, mNVisibleLines, 1, mNBufferLines+2); - mVScrollBar->linesize(3); -} - -/* -** Update the minimum, maximum, slider size, page increment, and value -** for the horizontal scroll bar. -*/ -void Fl_Text_Display_mod::update_h_scrollbar() { - int sliderMax = max(longest_vline(), text_area.w + mHorizOffset); - mHScrollBar->value( mHorizOffset, text_area.w, 0, sliderMax ); -} - -/* -** Callbacks for drag or valueChanged on scroll bars -*/ -void Fl_Text_Display_mod::v_scrollbar_cb(Fl_Scrollbar* b, Fl_Text_Display_mod* textD) { - if (b->value() == textD->mTopLineNum) return; - textD->scroll(b->value(), textD->mHorizOffset); -} - -void Fl_Text_Display_mod::h_scrollbar_cb(Fl_Scrollbar* b, Fl_Text_Display_mod* textD) { - if (b->value() == textD->mHorizOffset) return; - textD->scroll(textD->mTopLineNum, b->value()); -} - -/* -** Refresh the line number area. If clearAll is False, writes only over -** the character cell areas. Setting clearAll to True will clear out any -** stray marks outside of the character cell area, which might have been -** left from before a resize or font change. -*/ -void Fl_Text_Display_mod::draw_line_numbers(bool /*clearAll*/) { -#if 0 - // FIXME: don't want this yet, so will leave for another time - - int y, line, visLine, nCols, lineStart; - char lineNumstd::string[12]; - int lineHeight = mMaxsize ? mMaxsize : textsize_; - int charWidth = TMPFONTWIDTH; //mFontStruct->max_bounds.width; - - /* Don't draw if mLineNumWidth == 0 (line numbers are hidden), or widget is - not yet realized */ - if (mLineNumWidth == 0 || visible_r()) - return; - - /* GC is allocated on demand, since not everyone will use line numbering */ - if (textD->lineNumGC == NULL) { - XGCValues values; - values.foreground = textD->lineNumFGPixel; - values.background = textD->bgPixel; - values.font = textD->fontStruct->fid; - textD->lineNumGC = XtGetGC(textD->w, - GCFont| GCForeground | GCBackground, &values); - } - - /* Erase the previous contents of the line number area, if requested */ - if (clearAll) - XClearArea(XtDisplay(textD->w), XtWindow(textD->w), textD->lineNumLeft, - textD->top, textD->lineNumWidth, textD->height, False); - - /* Draw the line numbers, aligned to the text */ - nCols = min(11, textD->lineNumWidth / charWidth); - y = textD->top; - line = getAbsTopLineNum(textD); - for (visLine=0; visLine < textD->nVisibleLines; visLine++) { - lineStart = textD->lineStarts[visLine]; - if (lineStart != -1 && (lineStart==0 || - BufGetCharacter(textD->buffer, lineStart-1)=='\n')) { - snprintf(lineNumstd::string, sizeof(lineNumstd::string), "%*d", nCols, line); - XDrawImagestd::string(XtDisplay(textD->w), XtWindow(textD->w), - textD->lineNumGC, textD->lineNumLeft, y + textD->ascent, - lineNumstd::string, strlen(lineNumstd::string)); - line++; - } else { - XClearArea(XtDisplay(textD->w), XtWindow(textD->w), - textD->lineNumLeft, y, textD->lineNumWidth, - textD->ascent + textD->descent, False); - if (visLine == 0) - line++; - } - y += lineHeight; - } -#endif -} - -static int max( int i1, int i2 ) { - return i1 >= i2 ? i1 : i2; -} - -static int min( int i1, int i2 ) { - return i1 <= i2 ? i1 : i2; -} - -/* -** Count the number of newlines in a null-terminated text std::string; -*/ -static int countlines( const char *string ) { - const char * c; - int lineCount = 0; - - if (!std::string) return 0; - - for ( c = std::string; *c != '\0'; c++ ) - if ( *c == '\n' ) lineCount++; - return lineCount; -} - -/* -** Return the width in pixels of the displayed line pointed to by "visLineNum" -*/ -int Fl_Text_Display_mod::measure_vline( int visLineNum ) { - int i, width = 0, len, style, lineLen = vline_length( visLineNum ); - int charCount = 0, lineStartPos = mLineStarts[ visLineNum ]; - char expandedChar[ FL_TEXT_MAX_EXP_CHAR_LEN ]; - - if (lineStartPos < 0 || lineLen == 0) return 0; - if ( mStyleBuffer == NULL ) { - for ( i = 0; i < lineLen; i++ ) { - len = mBuffer->expand_character( lineStartPos + i, - charCount, expandedChar ); - - fl_font( textfont(), textsize() ); - - width += ( int ) fl_width( expandedChar, len ); - - charCount += len; - } - } else { - for ( i = 0; i < lineLen; i++ ) { - len = mBuffer->expand_character( lineStartPos + i, - charCount, expandedChar ); - style = ( unsigned char ) mStyleBuffer->character( - lineStartPos + i ) - 'A'; - - if (style < 0) style = 0; - else if (style >= mNStyles) style = mNStyles - 1; - - fl_font( mStyleTable[ style ].font, mStyleTable[ style ].size ); - - width += ( int ) fl_width( expandedChar, len ); - - charCount += len; - } - } - return width; -} - -/* -** Return true if there are lines visible with no corresponding buffer text -*/ -int Fl_Text_Display_mod::empty_vlines() { - return mNVisibleLines > 0 && - mLineStarts[ mNVisibleLines - 1 ] == -1; -} - -/* -** Return the length of a line (number of displayable characters) by examining -** entries in the line starts array rather than by scanning for newlines -*/ -int Fl_Text_Display_mod::vline_length( int visLineNum ) { - int nextLineStart, lineStartPos; - - if (visLineNum < 0 || visLineNum >= mNVisibleLines) - return (0); - - lineStartPos = mLineStarts[ visLineNum ]; - - if ( lineStartPos == -1 ) - return 0; - if ( visLineNum + 1 >= mNVisibleLines ) - return mLastChar - lineStartPos; - nextLineStart = mLineStarts[ visLineNum + 1 ]; - if ( nextLineStart == -1 ) - return mLastChar - lineStartPos; - if (wrap_uses_character(nextLineStart-1)) - return nextLineStart-1 - lineStartPos; - return nextLineStart - lineStartPos; -} - -/* -** When continuous wrap is on, and the user inserts or deletes characters, -** wrapping can happen before and beyond the changed position. This routine -** finds the extent of the changes, and counts the deleted and inserted lines -** over that range. It also attempts to minimize the size of the range to -** what has to be counted and re-displayed, so the results can be useful -** both for delimiting where the line starts need to be recalculated, and -** for deciding what part of the text to redisplay. -*/ -void Fl_Text_Display_mod::find_wrap_range(const char *deletedText, int pos, - int nInserted, int nDeleted, int *modRangeStart, int *modRangeEnd, - int *linesInserted, int *linesDeleted) { - int length, retPos, retLines, retLineStart, retLineEnd; - Fl_Text_Buffer_mod*deletedTextBuf, *buf = buffer(); - int nVisLines = mNVisibleLines; - int *lineStarts = mLineStarts; - int countFrom, countTo, lineStart, adjLineStart, i; - int visLineNum = 0, nLines = 0; - - /* - ** Determine where to begin searching: either the previous newline, or - ** if possible, limit to the start of the (original) previous displayed - ** line, using information from the existing line starts array - */ - if (pos >= mFirstChar && pos <= mLastChar) { - for (i=nVisLines-1; i>0; i--) - if (lineStarts[i] != -1 && pos >= lineStarts[i]) - break; - if (i > 0) { - countFrom = lineStarts[i-1]; - visLineNum = i-1; - } else - countFrom = buf->line_start(pos); - } else - countFrom = buf->line_start(pos); - - - /* - ** Move forward through the (new) text one line at a time, counting - ** displayed lines, and looking for either a real newline, or for the - ** line starts to re-sync with the original line starts array - */ - lineStart = countFrom; - *modRangeStart = countFrom; - for (;;) { - - /* advance to the next line. If the line ended in a real newline - or the end of the buffer, that's far enough */ - wrapped_line_counter(buf, lineStart, buf->length(), 1, true, 0, - &retPos, &retLines, &retLineStart, &retLineEnd); - if (retPos >= buf->length()) { - countTo = buf->length(); - *modRangeEnd = countTo; - if (retPos != retLineEnd) - nLines++; - break; - } else - lineStart = retPos; - nLines++; - if (lineStart > pos + nInserted && - buf->character(lineStart-1) == '\n') { - countTo = lineStart; - *modRangeEnd = lineStart; - break; - } - - /* Don't try to resync in continuous wrap mode with non-fixed font - sizes; it would result in a chicken-and-egg dependency between - the calculations for the inserted and the deleted lines. - If we're in that mode, the number of deleted lines is calculated in - advance, without resynchronization, so we shouldn't resynchronize - for the inserted lines either. */ - if (mSuppressResync) - continue; - - /* check for synchronization with the original line starts array - before pos, if so, the modified range can begin later */ - if (lineStart <= pos) { - while (visLineNum pos + nInserted) { - adjLineStart = lineStart - nInserted + nDeleted; - while (visLineNumcopy(buffer(), countFrom, pos, 0); - if (nDeleted != 0) - deletedTextBuf->insert(pos-countFrom, deletedText); - deletedTextBuf->copy(buffer(), - pos+nInserted, countTo, pos-countFrom+nDeleted); - /* Note that we need to take into account an offset for the style buffer: - the deletedTextBuf can be out of sync with the style buffer. */ - wrapped_line_counter(deletedTextBuf, 0, length, INT_MAX, true, - countFrom, &retPos, &retLines, &retLineStart, &retLineEnd, false); - delete deletedTextBuf; - *linesDeleted = retLines; - mSuppressResync = 0; -} - -/* -** This is a stripped-down version of the findWrapRange() function above, -** intended to be used to calculate the number of "deleted" lines during -** a buffer modification. It is called _before_ the modification takes place. -** -** This function should only be called in continuous wrap mode with a -** non-fixed font width. In that case, it is impossible to calculate -** the number of deleted lines, because the necessary style information -** is no longer available _after_ the modification. In other cases, we -** can still perform the calculation afterwards (possibly even more -** efficiently). -*/ -void Fl_Text_Display_mod::measure_deleted_lines(int pos, int nDeleted) { - int retPos, retLines, retLineStart, retLineEnd; - Fl_Text_Buffer_mod*buf = buffer(); - int nVisLines = mNVisibleLines; - int *lineStarts = mLineStarts; - int countFrom, lineStart; - int nLines = 0, i; - /* - ** Determine where to begin searching: either the previous newline, or - ** if possible, limit to the start of the (original) previous displayed - ** line, using information from the existing line starts array - */ - if (pos >= mFirstChar && pos <= mLastChar) { - for (i=nVisLines-1; i>0; i--) - if (lineStarts[i] != -1 && pos >= lineStarts[i]) - break; - if (i > 0) countFrom = lineStarts[i-1]; - else countFrom = buf->line_start(pos); - } else - countFrom = buf->line_start(pos); - - /* - ** Move forward through the (new) text one line at a time, counting - ** displayed lines, and looking for either a real newline, or for the - ** line starts to re-sync with the original line starts array - */ - lineStart = countFrom; - for (;;) { - /* advance to the next line. If the line ended in a real newline - or the end of the buffer, that's far enough */ - wrapped_line_counter(buf, lineStart, buf->length(), 1, true, 0, - &retPos, &retLines, &retLineStart, &retLineEnd); - if (retPos >= buf->length()) { - if (retPos != retLineEnd) - nLines++; - break; - } else - lineStart = retPos; - nLines++; - if (lineStart > pos + nDeleted && - buf->character(lineStart-1) == '\n') { - break; - } - - /* Unlike in the findWrapRange() function above, we don't try to - resync with the line starts, because we don't know the length - of the inserted text yet, nor the updated style information. - - Because of that, we also shouldn't resync with the line starts - after the modification either, because we must perform the - calculations for the deleted and inserted lines in the same way. - - This can result in some unnecessary recalculation and redrawing - overhead, and therefore we should only use this two-phase mode - of calculation when it's really needed (continuous wrap + variable - font width). */ - } - mNLinesDeleted = nLines; - mSuppressResync = 1; -} - -/* -** Count forward from startPos to either maxPos or maxLines (whichever is -** reached first), and return all relevant positions and line count. -** The provided textBuffer may differ from the actual text buffer of the -** widget. In that case it must be a (partial) copy of the actual text buffer -** and the styleBufOffset argument must indicate the starting position of the -** copy, to take into account the correct style information. -** -** Returned values: -** -** retPos: Position where counting ended. When counting lines, the -** position returned is the start of the line "maxLines" -** lines beyond "startPos". -** retLines: Number of line breaks counted -** retLineStart: Start of the line where counting ended -** retLineEnd: End position of the last line traversed -*/ -void Fl_Text_Display_mod::wrapped_line_counter(Fl_Text_Buffer_mod*buf, int startPos, - int maxPos, int maxLines, bool startPosIsLineStart, int styleBufOffset, - int *retPos, int *retLines, int *retLineStart, int *retLineEnd, - bool countLastLineMissingNewLine) { - int lineStart, newLineStart = 0, b, p, colNum, wrapMargin; - int maxWidth, i, foundBreak, width; - bool countPixels; - int nLines = 0, tabDist = buffer()->tab_distance(); - unsigned char c; - char nullSubsChar = buffer()->null_substitution_character(); - - /* If the font is fixed, or there's a wrap margin set, it's more efficient - to measure in columns, than to count pixels. Determine if we can count - in columns (countPixels == False) or must count pixels (countPixels == - True), and set the wrap target for either pixels or columns */ - if (mFixedFontWidth != -1 || mWrapMargin != 0) { - countPixels = false; - wrapMargin = mWrapMargin ? mWrapMargin : text_area.w / (mFixedFontWidth + 1); - maxWidth = INT_MAX; - } else { - countPixels = true; - wrapMargin = INT_MAX; - maxWidth = text_area.w; - } - - /* Find the start of the line if the start pos is not marked as a - line start. */ - if (startPosIsLineStart) - lineStart = startPos; - else - lineStart = line_start(startPos); - - /* - ** Loop until position exceeds maxPos or line count exceeds maxLines. - ** (actually, contines beyond maxPos to end of line containing maxPos, - ** in case later characters cause a word wrap back before maxPos) - */ - colNum = 0; - width = 0; - for (p=lineStart; plength(); p++) { - c = (unsigned char)buf->character(p); - - /* If the character was a newline, count the line and start over, - otherwise, add it to the width and column counts */ - if (c == '\n') { - if (p >= maxPos) { - *retPos = maxPos; - *retLines = nLines; - *retLineStart = lineStart; - *retLineEnd = maxPos; - return; - } - nLines++; - if (nLines >= maxLines) { - *retPos = p + 1; - *retLines = nLines; - *retLineStart = p + 1; - *retLineEnd = p; - return; - } - lineStart = p + 1; - colNum = 0; - width = 0; - } else { - colNum += Fl_Text_Buffer_mod::character_width(c, colNum, tabDist, nullSubsChar); - if (countPixels) - width += measure_proportional_character(c, colNum, p+styleBufOffset); - } - - /* If character exceeded wrap margin, find the break point - and wrap there */ - if (colNum > wrapMargin || width > maxWidth) { - foundBreak = false; - for (b=p; b>=lineStart; b--) { - c = (unsigned char)buf->character(b); - if (c == '\t' || c == ' ') { - newLineStart = b + 1; - if (countPixels) { - colNum = 0; - width = 0; - for (i=b+1; icharacter(i), colNum, - i+styleBufOffset); - colNum++; - } - } else - colNum = buf->count_displayed_characters(b+1, p+1); - foundBreak = true; - break; - } - } - if (!foundBreak) { /* no whitespace, just break at margin */ - newLineStart = max(p, lineStart+1); - colNum = Fl_Text_Buffer_mod::character_width(c, colNum, tabDist, nullSubsChar); - if (countPixels) - width = measure_proportional_character(c, colNum, p+styleBufOffset); - } - if (p >= maxPos) { - *retPos = maxPos; - *retLines = maxPos < newLineStart ? nLines : nLines + 1; - *retLineStart = maxPos < newLineStart ? lineStart : - newLineStart; - *retLineEnd = maxPos; - return; - } - nLines++; - if (nLines >= maxLines) { - *retPos = foundBreak ? b + 1 : max(p, lineStart+1); - *retLines = nLines; - *retLineStart = lineStart; - *retLineEnd = foundBreak ? b : p; - return; - } - lineStart = newLineStart; - } - } - - /* reached end of buffer before reaching pos or line target */ - *retPos = buf->length(); - *retLines = nLines; - if (countLastLineMissingNewLine && colNum > 0) - ++(*retLines); - *retLineStart = lineStart; - *retLineEnd = buf->length(); -} - -/* -** Measure the width in pixels of a character "c" at a particular column -** "colNum" and buffer position "pos". This is for measuring characters in -** proportional or mixed-width highlighting fonts. -** -** A note about proportional and mixed-width fonts: the mixed width and -** proportional font code in nedit does not get much use in general editing, -** because nedit doesn't allow per-language-mode fonts, and editing programs -** in a proportional font is usually a bad idea, so very few users would -** choose a proportional font as a default. There are still probably mixed- -** width syntax highlighting cases where things don't redraw properly for -** insertion/deletion, though static display and wrapping and resizing -** should now be solid because they are now used for online help display. -*/ -int Fl_Text_Display_mod::measure_proportional_character(char c, int colNum, int pos) { - int charLen, style; - char expChar[ FL_TEXT_MAX_EXP_CHAR_LEN ]; - Fl_Text_Buffer_mod*styleBuf = mStyleBuffer; - - charLen = Fl_Text_Buffer_mod::expand_character(c, colNum, expChar, - buffer()->tab_distance(), buffer()->null_substitution_character()); - if (styleBuf == 0) { - style = 0; - } else { - style = (unsigned char)styleBuf->character(pos); - if (style == mUnfinishedStyle && mUnfinishedHighlightCB) { - /* encountered "unfinished" style, trigger parsing */ - (mUnfinishedHighlightCB)(pos, mHighlightCBArg); - style = (unsigned char)styleBuf->character(pos); - } - } - return string_width(expChar, charLen, style); -} - -/* -** Finds both the end of the current line and the start of the next line. Why? -** In continuous wrap mode, if you need to know both, figuring out one from the -** other can be expensive or error prone. The problem comes when there's a -** trailing space or tab just before the end of the buffer. To translate an -** end of line value to or from the next lines start value, you need to know -** whether the trailing space or tab is being used as a line break or just a -** normal character, and to find that out would otherwise require counting all -** the way back to the beginning of the line. -*/ -void Fl_Text_Display_mod::find_line_end(int startPos, bool startPosIsLineStart, - int *lineEnd, int *nextLineStart) { - int retLines, retLineStart; - - /* if we're not wrapping use more efficient BufEndOfLine */ - if (!mContinuousWrap) { - *lineEnd = buffer()->line_end(startPos); - *nextLineStart = min(buffer()->length(), *lineEnd + 1); - return; - } - - /* use the wrapped line counter routine to count forward one line */ - wrapped_line_counter(buffer(), startPos, buffer()->length(), - 1, startPosIsLineStart, 0, nextLineStart, &retLines, - &retLineStart, lineEnd); - return; -} - -/* -** Line breaks in continuous wrap mode usually happen at newlines or -** whitespace. This line-terminating character is not included in line -** width measurements and has a special status as a non-visible character. -** However, lines with no whitespace are wrapped without the benefit of a -** line terminating character, and this distinction causes endless trouble -** with all of the text display code which was originally written without -** continuous wrap mode and always expects to wrap at a newline character. -** -** Given the position of the end of the line, as returned by TextDEndOfLine -** or BufEndOfLine, this returns true if there is a line terminating -** character, and false if there's not. On the last character in the -** buffer, this function can't tell for certain whether a trailing space was -** used as a wrap point, and just guesses that it wasn't. So if an exact -** accounting is necessary, don't use this function. -*/ -int Fl_Text_Display_mod::wrap_uses_character(int lineEndPos) { - char c; - - if (!mContinuousWrap || lineEndPos == buffer()->length()) - return 1; - - c = buffer()->character(lineEndPos); - return c == '\n' || ((c == '\t' || c == ' ') && - lineEndPos + 1 != buffer()->length()); -} - -/* -** Return true if the selection "sel" is rectangular, and touches a -** buffer position withing "rangeStart" to "rangeEnd" -*/ -int Fl_Text_Display_mod::range_touches_selection(Fl_Text_Selection *sel, - int rangeStart, int rangeEnd) { - return sel->selected() && sel->rectangular() && sel->end() >= rangeStart && - sel->start() <= rangeEnd; -} - -/* -** Extend the range of a redraw request (from *start to *end) with additional -** redraw requests resulting from changes to the attached style buffer (which -** contains auxiliary information for coloring or styling text). -*/ -void Fl_Text_Display_mod::extend_range_for_styles( int *startpos, int *endpos ) { - Fl_Text_Selection * sel = mStyleBuffer->primary_selection(); - int extended = 0; - - /* The peculiar protocol used here is that modifications to the style - buffer are marked by selecting them with the buffer's primary Fl_Text_Selection. - The style buffer is usually modified in response to a modify callback on - the text buffer BEFORE Fl_Text_Display.c's modify callback, so that it can keep - the style buffer in step with the text buffer. The style-update - callback can't just call for a redraw, because Fl_Text_Display hasn't processed - the original text changes yet. Anyhow, to minimize redrawing and to - avoid the complexity of scheduling redraws later, this simple protocol - tells the text display's buffer modify callback to extend it's redraw - range to show the text color/and font changes as well. */ - if ( sel->selected() ) { - if ( sel->start() < *startpos ) { - *startpos = sel->start(); - extended = 1; - } - if ( sel->end() > *endpos ) { - *endpos = sel->end(); - extended = 1; - } - } - - /* If the Fl_Text_Selection was extended due to a style change, and some of the - fonts don't match in spacing, extend redraw area to end of line to - redraw characters exposed by possible font size changes */ - if ( mFixedFontWidth == -1 && extended ) - *endpos = mBuffer->line_end( *endpos ) + 1; -} - -// The draw() method. It tries to minimize what is draw as much as possible. -void Fl_Text_Display_mod::draw(void) { - // don't even try if there is no associated text buffer! - if (!buffer()) { draw_box(); return; } - - fl_push_clip(x(),y(),w(),h()); // prevent drawing outside widget area - - // draw the non-text, non-scrollbar areas. - if (damage() & FL_DAMAGE_ALL) { -// printf("drawing all (box = %d)\n", box()); - // draw the box() - int W = w(), H = h(); - draw_box(box(), x(), y(), W, H, color()); - - if (mHScrollBar->visible()) - W -= scrollbar_width(); - if (mVScrollBar->visible()) - H -= scrollbar_width(); - - // left margin - fl_rectf(text_area.x-LEFT_MARGIN, text_area.y-TOP_MARGIN, - LEFT_MARGIN, text_area.h+TOP_MARGIN+BOTTOM_MARGIN, - color()); - - // right margin - fl_rectf(text_area.x+text_area.w, text_area.y-TOP_MARGIN, - RIGHT_MARGIN, text_area.h+TOP_MARGIN+BOTTOM_MARGIN, - color()); - - // top margin - fl_rectf(text_area.x, text_area.y-TOP_MARGIN, - text_area.w, TOP_MARGIN, color()); - - // bottom margin - fl_rectf(text_area.x, text_area.y+text_area.h, - text_area.w, BOTTOM_MARGIN, color()); - - // draw that little box in the corner of the scrollbars - if (mVScrollBar->visible() && mHScrollBar->visible()) - fl_rectf(mVScrollBar->x(), mHScrollBar->y(), - mVScrollBar->w(), mHScrollBar->h(), - FL_GRAY); - - // blank the previous cursor protrusions - } - else if (damage() & (FL_DAMAGE_SCROLL | FL_DAMAGE_EXPOSE)) { -// printf("blanking previous cursor extrusions at Y: %d\n", mCursorOldY); - // CET - FIXME - save old cursor position instead and just draw side needed? - fl_push_clip(text_area.x-LEFT_MARGIN, - text_area.y, - text_area.w+LEFT_MARGIN+RIGHT_MARGIN, - text_area.h); - fl_rectf(text_area.x-LEFT_MARGIN, mCursorOldY, - LEFT_MARGIN, mMaxsize, color()); - fl_rectf(text_area.x+text_area.w, mCursorOldY, - RIGHT_MARGIN, mMaxsize, color()); - fl_pop_clip(); - } - - // draw the scrollbars - if (damage() & (FL_DAMAGE_ALL | FL_DAMAGE_CHILD)) { - mVScrollBar->damage(FL_DAMAGE_ALL); - mHScrollBar->damage(FL_DAMAGE_ALL); - } - update_child(*mVScrollBar); - update_child(*mHScrollBar); - - // draw all of the text - if (damage() & (FL_DAMAGE_ALL | FL_DAMAGE_EXPOSE)) { - //printf("drawing all text\n"); - int X, Y, W, H; - if (fl_clip_box(text_area.x, text_area.y, text_area.w, text_area.h, - X, Y, W, H)) { - // Draw text using the intersected clipping box... - // (this sets the clipping internally) - draw_text(X, Y, W, H); - } else { - // Draw the whole area... - draw_text(text_area.x, text_area.y, text_area.w, text_area.h); - } - } - else if (damage() & FL_DAMAGE_SCROLL) { - // draw some lines of text - fl_push_clip(text_area.x, text_area.y, - text_area.w, text_area.h); - //printf("drawing text from %d to %d\n", damage_range1_start, damage_range1_end); - draw_range(damage_range1_start, damage_range1_end); - if (damage_range2_end != -1) { - //printf("drawing text from %d to %d\n", damage_range2_start, damage_range2_end); - draw_range(damage_range2_start, damage_range2_end); - } - damage_range1_start = damage_range1_end = -1; - damage_range2_start = damage_range2_end = -1; - fl_pop_clip(); - } - - // draw the text cursor - if (damage() & (FL_DAMAGE_ALL | FL_DAMAGE_SCROLL | FL_DAMAGE_EXPOSE) - && !buffer()->primary_selection()->selected() && - mCursorOn && Fl::focus() == this ) { - fl_push_clip(text_area.x-LEFT_MARGIN, - text_area.y, - text_area.w+LEFT_MARGIN+RIGHT_MARGIN, - text_area.h); - - int X, Y; - if (position_to_xy(mCursorPos, &X, &Y)) draw_cursor(X, Y); -// else puts("position_to_xy() failed - unable to draw cursor!"); - //printf("drew cursor at pos: %d (%d,%d)\n", mCursorPos, X, Y); - mCursorOldY = Y; - fl_pop_clip(); - } - fl_pop_clip(); -} - -// this processes drag events due to mouse for Fl_Text_Display and -// also drags due to cursor movement with shift held down for -// Fl_Text_Editor -void fl_text_drag_me(int pos, Fl_Text_Display_mod* d) { - if (d->dragType == Fl_Text_Display_mod::DRAG_CHAR) { - if (pos >= d->dragPos) { - d->buffer()->select(d->dragPos, pos); - } else { - d->buffer()->select(pos, d->dragPos); - } - d->insert_position(pos); - } else if (d->dragType == Fl_Text_Display_mod::DRAG_WORD) { - if (pos >= d->dragPos) { - d->insert_position(d->word_end(pos)); - d->buffer()->select(d->word_start(d->dragPos), d->word_end(pos)); - } else { - d->insert_position(d->word_start(pos)); - d->buffer()->select(d->word_start(pos), d->word_end(d->dragPos)); - } - } else if (d->dragType == Fl_Text_Display_mod::DRAG_LINE) { - if (pos >= d->dragPos) { - d->insert_position(d->buffer()->line_end(pos)+1); - d->buffer()->select(d->buffer()->line_start(d->dragPos), - d->buffer()->line_end(pos)+1); - } else { - d->insert_position(d->buffer()->line_start(pos)); - d->buffer()->select(d->buffer()->line_start(pos), - d->buffer()->line_end(d->dragPos)+1); - } - } -} - -// This timer event scrolls the text view proportionally to -// how far the mouse pointer has left the text area. This -// allows for smooth scrolling without "wiggeling" the mouse. -void Fl_Text_Display_mod::scroll_timer_cb(void *user_data) { - Fl_Text_Display_mod *w = (Fl_Text_Display_mod*)user_data; - int pos; - switch (scroll_direction) { - case 1: // mouse is to the right, scroll left - w->scroll(w->mTopLineNum, w->mHorizOffset + scroll_amount); - pos = w->xy_to_position(w->text_area.x + w->text_area.w, scroll_y, CURSOR_POS); - break; - case 2: // mouse is to the left, scroll right - w->scroll(w->mTopLineNum, w->mHorizOffset + scroll_amount); - pos = w->xy_to_position(w->text_area.x, scroll_y, CURSOR_POS); - break; - case 3: // mouse is above, scroll down - w->scroll(w->mTopLineNum + scroll_amount, w->mHorizOffset); - pos = w->xy_to_position(scroll_x, w->text_area.y, CURSOR_POS); - break; - case 4: // mouse is below, scroll up - w->scroll(w->mTopLineNum + scroll_amount, w->mHorizOffset); - pos = w->xy_to_position(scroll_x, w->text_area.y + w->text_area.h, CURSOR_POS); - break; - default: - return; - } - fl_text_drag_me(pos, w); - Fl::repeat_timeout(.1, scroll_timer_cb, user_data); -} - - -int Fl_Text_Display_mod::handle(int event) { - if (!buffer()) return 0; - // This isn't very elegant! - if (!Fl::event_inside(text_area.x, text_area.y, text_area.w, text_area.h) && - !dragging && event != FL_LEAVE && event != FL_ENTER && - event != FL_MOVE && event != FL_FOCUS && event != FL_UNFOCUS && - event != FL_KEYBOARD && event != FL_KEYUP) { - return Fl_Group::handle(event); - } - - switch (event) { - case FL_ENTER: - case FL_MOVE: - if (active_r()) { - if (Fl::event_inside(text_area.x, text_area.y, text_area.w, - text_area.h)) window()->cursor(FL_CURSOR_INSERT); - else window()->cursor(FL_CURSOR_DEFAULT); - return 1; - } else { - return 0; - } - - case FL_LEAVE: - case FL_HIDE: - if (active_r() && window()) { - window()->cursor(FL_CURSOR_DEFAULT); - - return 1; - } else { - return 0; - } - - case FL_PUSH: { - if (active_r() && window()) { - if (Fl::event_inside(text_area.x, text_area.y, text_area.w, - text_area.h)) window()->cursor(FL_CURSOR_INSERT); - else window()->cursor(FL_CURSOR_DEFAULT); - } - - if (Fl::focus() != this) { - Fl::focus(this); - handle(FL_FOCUS); - } - if (Fl_Group::handle(event)) return 1; - if (Fl::event_state()&FL_SHIFT) return handle(FL_DRAG); - dragging = 1; - int pos = xy_to_position(Fl::event_x(), Fl::event_y(), CURSOR_POS); - dragType = Fl::event_clicks(); - dragPos = pos; - if (dragType == DRAG_CHAR) - buffer()->unselect(); - else if (dragType == DRAG_WORD) - buffer()->select(word_start(pos), word_end(pos)); - else if (dragType == DRAG_LINE) - buffer()->select(buffer()->line_start(pos), buffer()->line_end(pos)+1); - - if (buffer()->primary_selection()->selected()) - insert_position(buffer()->primary_selection()->end()); - else - insert_position(pos); - show_insert_position(); - return 1; - } - - case FL_DRAG: { - if (dragType < 0) return 1; - int X = Fl::event_x(), Y = Fl::event_y(), pos; - // if we leave the text_area, we start a timer event - // that will take care of scrolling and selecting - if (Y < text_area.y) { - scroll_x = X; - scroll_amount = (Y - text_area.y) / 5 - 1; - if (!scroll_direction) { - Fl::add_timeout(.01, scroll_timer_cb, this); - } - scroll_direction = 3; - } else if (Y >= text_area.y+text_area.h) { - scroll_x = X; - scroll_amount = (Y - text_area.y - text_area.h) / 5 + 1; - if (!scroll_direction) { - Fl::add_timeout(.01, scroll_timer_cb, this); - } - scroll_direction = 4; - } else if (X < text_area.x) { - scroll_y = Y; - scroll_amount = (X - text_area.x) / 2 - 1; - if (!scroll_direction) { - Fl::add_timeout(.01, scroll_timer_cb, this); - } - scroll_direction = 2; - } else if (X >= text_area.x+text_area.w) { - scroll_y = Y; - scroll_amount = (X - text_area.x - text_area.w) / 2 + 1; - if (!scroll_direction) { - Fl::add_timeout(.01, scroll_timer_cb, this); - } - scroll_direction = 1; - } else { - if (scroll_direction) { - Fl::remove_timeout(scroll_timer_cb, this); - scroll_direction = 0; - } - pos = xy_to_position(X, Y, CURSOR_POS); - fl_text_drag_me(pos, this); - } - return 1; - } - - case FL_RELEASE: { - dragging = 0; - if (scroll_direction) { - Fl::remove_timeout(scroll_timer_cb, this); - scroll_direction = 0; - } - - // convert from WORD or LINE selection to CHAR - if (insert_position() >= dragPos) - dragPos = buffer()->primary_selection()->start(); - else - dragPos = buffer()->primary_selection()->end(); - dragType = DRAG_CHAR; - - const char* copy = buffer()->selection_text(); - if (*copy) Fl::copy(copy, strlen(copy), 0); - free((void*)copy); - return 1; - } - - case FL_MOUSEWHEEL: - if (Fl::event_dy()) return mVScrollBar->handle(event); - else return mHScrollBar->handle(event); - - case FL_UNFOCUS: - if (active_r() && window()) window()->cursor(FL_CURSOR_DEFAULT); - case FL_FOCUS: - if (buffer()->selected()) redraw(); - - return 1; - - case FL_KEYBOARD: - // Copy? - if ((Fl::event_state()&(FL_CTRL|FL_COMMAND)) && Fl::event_key()=='c') { - if (!buffer()->selected()) return 1; - const char *copy = buffer()->selection_text(); - if (*copy) Fl::copy(copy, strlen(copy), 1); - free((void*)copy); - return 1; - } - - // Select all ? - if ((Fl::event_state()&(FL_CTRL|FL_COMMAND)) && Fl::event_key()=='a') { - buffer()->select(0,buffer()->length()); - return 1; - } - - if (mVScrollBar->handle(event)) return 1; - if (mHScrollBar->handle(event)) return 1; - - break; - } - - return 0; -} - - -// -// End of "$Id: Fl_Text_Display.cxx 5848 2007-05-20 16:18:31Z mike $". -// diff --git a/src/widgets/Fl_Text_Display_mod_1_3.cxx b/src/widgets/Fl_Text_Display_mod_1_3.cxx deleted file mode 100644 index 3ed2fa3..0000000 --- a/src/widgets/Fl_Text_Display_mod_1_3.cxx +++ /dev/null @@ -1,3796 +0,0 @@ -// "$Id: Fl_Text_Display_mod.cxx 8808 2011-06-16 13:31:25Z manolo $" -// -// Copyright 2001-2010 by Bill Spitzak and others. -// Original code Copyright Mark Edel. Permission to distribute under -// the LGPL for the FLTK library granted by Mark Edel. -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ -// -// This file is part of flmsg -// -// flrig 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. -// -// flrig 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 -#include -#include -#include "missing_strings.h" -#include -#include -#include -#include -#include -#include "Fl_Text_Buffer_mod.H" -#include "Fl_Text_Display_mod.H" - -#undef min -#undef max - -// Text area margins. Left & right margins should be at least 3 so that -// there is some room for the overhanging parts of the cursor! -const int Fl_Text_Display_mod::DEFAULT_TOP_MARGIN = 1; -const int Fl_Text_Display_mod::DEFAULT_BOTTOM_MARGIN = 1; -const int Fl_Text_Display_mod::DEFAULT_LEFT_MARGIN = 3; -const int Fl_Text_Display_mod::DEFAULT_RIGHT_MARGIN = 3; -//#define TOP_MARGIN 1 -//#define BOTTOM_MARGIN 1 -//#define LEFT_MARGIN 3 -//#define RIGHT_MARGIN 3 - -#define NO_HINT -1 - -/* Masks for text drawing methods. These are or'd together to form an - integer which describes what drawing calls to use to draw a std::string */ -#define FILL_MASK 0x0100 -#define SECONDARY_MASK 0x0200 -#define PRIMARY_MASK 0x0400 -#define HIGHLIGHT_MASK 0x0800 -#define BG_ONLY_MASK 0x1000 -#define TEXT_ONLY_MASK 0x2000 -#define STYLE_LOOKUP_MASK 0xff - -/* Maximum displayable line length (how many characters will fit across the - widest window). This amount of memory is temporarily allocated from the - stack in the draw_vline() method for drawing std::strings */ -#define MAX_DISP_LINE_LEN 1000 - -static int max( int i1, int i2 ); -static int min( int i1, int i2 ); -static int countlines( const char *string ); - -/* The variables below are used in a timer event to allow smooth - scrolling of the text area when the pointer has left the area. */ -static int scroll_direction = 0; -static int scroll_amount = 0; -static int scroll_y = 0; -static int scroll_x = 0; - -// CET - FIXME -#define TMPFONTWIDTH 6 - - - -/** - \brief Creates a new text display widget. - - \param X, Y, W, H position and size of widget - \param l label text, defaults to none - */ -Fl_Text_Display_mod::Fl_Text_Display_mod(int X, int Y, int W, int H, const char* l) -: Fl_Group(X, Y, W, H, l) { - int i; - - TOP_MARGIN = DEFAULT_TOP_MARGIN; - BOTTOM_MARGIN = DEFAULT_BOTTOM_MARGIN; - LEFT_MARGIN = DEFAULT_LEFT_MARGIN; - RIGHT_MARGIN = DEFAULT_RIGHT_MARGIN; - - mMaxsize = 0; - damage_range1_start = damage_range1_end = -1; - damage_range2_start = damage_range2_end = -1; - dragPos = dragging = 0; - dragType = DRAG_CHAR; - display_insert_position_hint = 0; - shortcut_ = 0; - - color(FL_BACKGROUND2_COLOR, FL_SELECTION_COLOR); - box(FL_DOWN_FRAME); - textsize(FL_NORMAL_SIZE); - textcolor(FL_FOREGROUND_COLOR); - textfont(FL_HELVETICA); - set_flag(SHORTCUT_LABEL); - - text_area.x = 0; - text_area.y = 0; - text_area.w = 0; - text_area.h = 0; - - mVScrollBar = new Fl_Scrollbar(0,0,1,1); - mVScrollBar->callback((Fl_Callback*)v_scrollbar_cb, this); - mHScrollBar = new Fl_Scrollbar(0,0,1,1); - mHScrollBar->callback((Fl_Callback*)h_scrollbar_cb, this); - mHScrollBar->type(FL_HORIZONTAL); - - end(); - - scrollbar_width(Fl::scrollbar_size()); - scrollbar_align(FL_ALIGN_BOTTOM_RIGHT); - - mCursorOn = 0; - mCursorPos = 0; - mCursorOldY = -100; - mCursorToHint = NO_HINT; - mCursorStyle = NORMAL_CURSOR; - mCursorPreferredXPos = -1; - mBuffer = 0; - mFirstChar = 0; - mLastChar = 0; - mNBufferLines = 0; - mTopLineNum = mTopLineNumHint = 1; - mAbsTopLineNum = 1; - mNeedAbsTopLineNum = 0; - mHorizOffset = mHorizOffsetHint = 0; - - mCursor_color = FL_FOREGROUND_COLOR; - - mStyleBuffer = 0; - mStyleTable = 0; - mNStyles = 0; - mNVisibleLines = 1; - mLineStarts = new int[mNVisibleLines]; - mLineStarts[0] = 0; - for (i=1; iremove_modify_callback(buffer_modified_cb, this); -// mBuffer->remove_predelete_callback(buffer_predelete_cb, this); -// } - if (mLineStarts) delete[] mLineStarts; -} - - - -/** - Attach a text buffer to display, replacing the current buffer (if any) - \param buf attach this text buffer - */ -void Fl_Text_Display_mod::buffer( Fl_Text_Buffer_mod *buf ) { - /* If the text display is already displaying a buffer, clear it off - of the display and remove our callback from it */ - if ( buf == mBuffer) return; - if ( mBuffer != 0 ) { - // we must provide a copy of the buffer that we are deleting! - char *deletedText = mBuffer->text(); - buffer_modified_cb( 0, 0, mBuffer->length(), 0, deletedText, this ); - free(deletedText); - mNBufferLines = 0; - mBuffer->remove_modify_callback( buffer_modified_cb, this ); - mBuffer->remove_predelete_callback( buffer_predelete_cb, this ); - } - - /* Add the buffer to the display, and attach a callback to the buffer for - receiving modification information when the buffer contents change */ - mBuffer = buf; - if (mBuffer) { - mBuffer->add_modify_callback( buffer_modified_cb, this ); - mBuffer->add_predelete_callback( buffer_predelete_cb, this ); - - /* Update the display */ - buffer_modified_cb( 0, buf->length(), 0, 0, 0, this ); - } - - /* Resize the widget to update the screen... */ - resize(x(), y(), w(), h()); -} - - - -/** - \brief Attach (or remove) highlight information in text display and redisplay. - - Highlighting information consists of a style buffer which parallels the - normal text buffer, but codes font and color information for the display; - a style table which translates style buffer codes (indexed by buffer - character - 'A') into fonts and colors; and a callback mechanism for - as-needed highlighting, triggered by a style buffer entry of - "unfinishedStyle". Style buffer can trigger additional redisplay during - a normal buffer modification if the buffer contains a primary Fl_Text_Selection - (see extendRangeForStyleMods for more information on this protocol). - - Style buffers, tables and their associated memory are managed by the caller. - - Styles are ranged from 65 ('A') to 126. - - \param styleBuffer this buffer works in parallel to the text buffer. For every - character in the text buffer, the stye buffer has a byte at the same offset - that contains an index into an array of possible styles. - \param styleTable a list of styles indexed by the style buffer - \param nStyles number of styles in the style table - \param unfinishedStyle if this style is found, the callback below is called - \param unfinishedHighlightCB if a character with an unfinished style is found, - this callback will be called - \param cbArg and optional argument for the callback above, usually a pointer - to the Text Display. - */ -void Fl_Text_Display_mod::highlight_data(Fl_Text_Buffer_mod *styleBuffer, - const Style_Table_Entry *styleTable, - int nStyles, char unfinishedStyle, - Unfinished_Style_Cb unfinishedHighlightCB, - void *cbArg ) { - mStyleBuffer = styleBuffer; - mStyleTable = styleTable; - mNStyles = nStyles; - mUnfinishedStyle = unfinishedStyle; - mUnfinishedHighlightCB = unfinishedHighlightCB; - mHighlightCBArg = cbArg; - mColumnScale = 0; - - mStyleBuffer->canUndo(0); - damage(FL_DAMAGE_EXPOSE); -} - - - -/** - \brief Find the longest line of all visible lines. - \return the width of the longest visible line in pixels - */ -int Fl_Text_Display_mod::longest_vline() const { - int longest = 0; - for (int i = 0; i < mNVisibleLines; i++) - longest = max(longest, measure_vline(i)); - return longest; -} - - - -/** - \brief Change the size of the displayed text area. - Calling this function will trigger a recalculation of all lines visible and - of all scrollbar sizes. - \param X, Y, W, H new position and size of this widget - */ -void Fl_Text_Display_mod::resize(int X, int Y, int W, int H) { -#ifdef DEBUG - printf("Fl_Text_Display_mod::resize(X=%d, Y=%d, W=%d, H=%d)\n", X, Y, W, H); -#endif // DEBUG - const int oldWidth = w(); -#ifdef DEBUG - printf(" oldWidth=%d, mContinuousWrap=%d, mWrapMargin=%d\n", oldWidth, mContinuousWrap, mWrapMargin); -#endif // DEBUG - Fl_Widget::resize(X,Y,W,H); - if (!buffer()) return; - X += Fl::box_dx(box()); - Y += Fl::box_dy(box()); - W -= Fl::box_dw(box()); - H -= Fl::box_dh(box()); - - text_area.x = X+LEFT_MARGIN; - text_area.y = Y+TOP_MARGIN; - text_area.w = W-LEFT_MARGIN-RIGHT_MARGIN - (mVScrollBar->visible() ? scrollbar_width() : 0); - text_area.h = H-TOP_MARGIN-BOTTOM_MARGIN - (mHScrollBar->visible() ? scrollbar_width() : 0); - int i; - - /* Find the new maximum font height for this text display */ - for (i = 0, mMaxsize = fl_height(textfont(), textsize()); i < mNStyles; i++) - mMaxsize = max(mMaxsize, fl_height(mStyleTable[i].font, mStyleTable[i].size)); - - // did we have scrollbars initially? - unsigned int hscrollbarvisible = mHScrollBar->visible(); - unsigned int vscrollbarvisible = mVScrollBar->visible(); - - // try without scrollbars first - mVScrollBar->clear_visible(); - mHScrollBar->clear_visible(); - - for (int again = 1; again;) { - again = 0; - /* In continuous wrap mode, a change in width affects the total number of - lines in the buffer, and can leave the top line number incorrect, and - the top character no longer pointing at a valid line start */ - if (!mFastDisplay && mContinuousWrap && !mWrapMarginPix && W!=oldWidth) { - int oldFirstChar = mFirstChar; - mNBufferLines = count_lines(0, buffer()->length(), true); - mFirstChar = line_start(mFirstChar); - mTopLineNum = count_lines(0, mFirstChar, true)+1; - absolute_top_line_number(oldFirstChar); -#ifdef DEBUG - printf(" mNBufferLines=%d\n", mNBufferLines); -#endif // DEBUG - } - - /* reallocate and update the line starts array, which may have changed - size and / or contents. */ - int nvlines = (text_area.h + mMaxsize - 1) / mMaxsize; - if (nvlines < 1) nvlines = 1; - if (mNVisibleLines != nvlines) { - mNVisibleLines = nvlines; - if (mLineStarts) delete[] mLineStarts; - mLineStarts = new int [mNVisibleLines]; - } - - calc_line_starts(0, mNVisibleLines); - calc_last_char(); - - // figure the scrollbars - if (scrollbar_width()) { - /* Decide if the vertical scrollbar needs to be visible */ -// always display vertical scroll bar -// if (scrollbar_align() & (FL_ALIGN_LEFT|FL_ALIGN_RIGHT) && -// mNBufferLines >= mNVisibleLines - 1) - { - mVScrollBar->set_visible(); - if (scrollbar_align() & FL_ALIGN_LEFT) { - text_area.x = X+scrollbar_width()+LEFT_MARGIN; - text_area.w = W-scrollbar_width()-LEFT_MARGIN-RIGHT_MARGIN - scrollbar_width(); - mVScrollBar->resize(X, text_area.y-TOP_MARGIN, scrollbar_width(), - text_area.h+TOP_MARGIN+BOTTOM_MARGIN); - } else { - text_area.x = X+LEFT_MARGIN; - text_area.w = W-scrollbar_width()-LEFT_MARGIN-RIGHT_MARGIN; - mVScrollBar->resize(X+W-scrollbar_width(), text_area.y-TOP_MARGIN, - scrollbar_width(), text_area.h+TOP_MARGIN+BOTTOM_MARGIN); - } - } - - /* - Decide if the horizontal scrollbar needs to be visible. If there - is a vertical scrollbar, a horizontal is always created too. This - is because the alternatives are unattractive: - * Dynamically creating a horizontal scrollbar based on the currently - visible lines is what the original nedit does, but it always wastes - space for the scrollbar even when it's not used. Since the FLTK - widget dynamically allocates the space for the scrollbar and - rearranges the widget to make room for it, this would create a very - visually displeasing "bounce" effect when the vertical scrollbar is - dragged. Trust me, I tried it and it looks really bad. - * The other alternative would be to keep track of what the longest - line in the entire buffer is and base the scrollbar on that. I - didn't do this because I didn't see any easy way to do that using - the nedit code and this could involve a lengthy calculation for - large buffers. If an efficient and non-costly way of doing this - can be found, this might be a way to go. - */ - /* WAS: Suggestion: Try turning the horizontal scrollbar on when - you first see a line that is too wide in the window, but then - don't turn it off (ie mix both of your solutions). */ - if (!mFastDisplay && !mContinuousWrap && scrollbar_align() & (FL_ALIGN_TOP|FL_ALIGN_BOTTOM) && - (mVScrollBar->visible() || longest_vline() > text_area.w)) - { - if (!mHScrollBar->visible()) { - mHScrollBar->set_visible(); - again = 1; // loop again to see if we now need vert. & recalc sizes - } - if (scrollbar_align() & FL_ALIGN_TOP) { - text_area.y = Y + scrollbar_width()+TOP_MARGIN; - text_area.h = H - scrollbar_width()-TOP_MARGIN-BOTTOM_MARGIN; - mHScrollBar->resize(text_area.x-LEFT_MARGIN, Y, - text_area.w+LEFT_MARGIN+RIGHT_MARGIN, scrollbar_width()); - } else { - text_area.y = Y+TOP_MARGIN; - text_area.h = H - scrollbar_width()-TOP_MARGIN-BOTTOM_MARGIN; - mHScrollBar->resize(text_area.x-LEFT_MARGIN, Y+H-scrollbar_width(), - text_area.w+LEFT_MARGIN+RIGHT_MARGIN, scrollbar_width()); - } - } - } - } - - // user request to change viewport - if (mTopLineNumHint != mTopLineNum || mHorizOffsetHint != mHorizOffset) - scroll_(mTopLineNumHint, mHorizOffsetHint); - - // everything will fit in the viewport - if (mNBufferLines < mNVisibleLines || mBuffer == NULL || mBuffer->length() == 0) { - scroll_(1, mHorizOffset); - /* if empty lines become visible, there may be an opportunity to - display more text by scrolling down */ - } else { - while ( mNVisibleLines>=2 - && (mLineStarts[mNVisibleLines-2]==-1) - && scroll_(mTopLineNum-1, mHorizOffset)) - { } - } - - // user request to display insert position - if (display_insert_position_hint) - display_insert(); - - // in case horizontal offset is now greater than longest line - int maxhoffset = max(0, longest_vline()-text_area.w); - if (mHorizOffset > maxhoffset) - scroll_(mTopLineNumHint, maxhoffset); - - mTopLineNumHint = mTopLineNum; - mHorizOffsetHint = mHorizOffset; - display_insert_position_hint = 0; - - if ((!mFastDisplay && mContinuousWrap) || - hscrollbarvisible != mHScrollBar->visible() || - vscrollbarvisible != mVScrollBar->visible()) - redraw(); - - update_v_scrollbar(); - update_h_scrollbar(); -} - - - -/** - \brief Refresh a rectangle of the text display. - \param left, top are in coordinates of the text drawing window. - \param width, height size in pixels - */ -void Fl_Text_Display_mod::draw_text( int left, int top, int width, int height ) { - int fontHeight, firstLine, lastLine, line; - - /* find the line number range of the display */ - fontHeight = mMaxsize ? mMaxsize : textsize_; - firstLine = ( top - text_area.y - fontHeight + 1 ) / fontHeight; - lastLine = ( top + height - text_area.y ) / fontHeight + 1; - - fl_push_clip( left, top, width, height ); - - /* draw the lines */ - for ( line = firstLine; line <= lastLine; line++ ) - draw_vline( line, left, left + width, 0, INT_MAX ); - - /* draw the line numbers if exposed area includes them */ - if (mLineNumWidth != 0 && left <= mLineNumLeft + mLineNumWidth) - draw_line_numbers(false); - - fl_pop_clip(); -} - - - -/** - \brief Marks text from start to end as needing a redraw. - This function will trigger a damage event and later a redraw of parts of - the widget. - \param startpos index of first character needing redraw - \param endpos index after last character needing redraw - */ -void Fl_Text_Display_mod::redisplay_range(int startpos, int endpos) { - IS_UTF8_ALIGNED2(buffer(), startpos) - IS_UTF8_ALIGNED2(buffer(), endpos) - - if (damage_range1_start == -1 && damage_range1_end == -1) { - damage_range1_start = startpos; - damage_range1_end = endpos; - } else if ((startpos >= damage_range1_start && startpos <= damage_range1_end) || - (endpos >= damage_range1_start && endpos <= damage_range1_end)) { - damage_range1_start = min(damage_range1_start, startpos); - damage_range1_end = max(damage_range1_end, endpos); - } else if (damage_range2_start == -1 && damage_range2_end == -1) { - damage_range2_start = startpos; - damage_range2_end = endpos; - } else { - damage_range2_start = min(damage_range2_start, startpos); - damage_range2_end = max(damage_range2_end, endpos); - } - damage(FL_DAMAGE_SCROLL); -} - - - -/** - \brief Draw a range of text. - - Refresh all of the text between buffer positions \p startpos and - \p endpos not including the character at the position \p endpos. - - If \p endpos points beyond the end of the buffer, refresh the whole display - after \p startpos, including blank lines which are not technically part of - any range of characters. - - \param startpos index of first character to draw - \param endpos index after last character to draw - */ -void Fl_Text_Display_mod::draw_range(int startpos, int endpos) { - startpos = buffer()->utf8_align(startpos); - endpos = buffer()->utf8_align(endpos); - - int i, startLine, lastLine, startIndex, endIndex; - - /* If the range is outside of the displayed text, just return */ - if ( endpos < mFirstChar || ( startpos > mLastChar && !empty_vlines() ) ) - return; - - /* Clean up the starting and ending values */ - if ( startpos < 0 ) startpos = 0; - if ( startpos > mBuffer->length() ) startpos = mBuffer->length(); - if ( endpos < 0 ) endpos = 0; - if ( endpos > mBuffer->length() ) endpos = mBuffer->length(); - - /* Get the starting and ending lines */ - if ( startpos < mFirstChar ) - startpos = mFirstChar; - if ( !position_to_line( startpos, &startLine ) ) - startLine = mNVisibleLines - 1; - if ( endpos >= mLastChar ) { - lastLine = mNVisibleLines - 1; - } else { - if ( !position_to_line( endpos, &lastLine ) ) { - /* shouldn't happen */ - lastLine = mNVisibleLines - 1; - } - } - - /* Get the starting and ending positions within the lines */ - startIndex = mLineStarts[ startLine ] == -1 ? 0 : startpos - mLineStarts[ startLine ]; - if ( endpos >= mLastChar ) - endIndex = INT_MAX; - else if ( mLineStarts[ lastLine ] == -1 ) - endIndex = 0; - else - endIndex = endpos - mLineStarts[ lastLine ]; - - /* If the starting and ending lines are the same, redisplay the single - line between "start" and "end" */ - if ( startLine == lastLine ) { - draw_vline( startLine, 0, INT_MAX, startIndex, endIndex ); - return; - } - - /* Redisplay the first line from "start" */ - draw_vline( startLine, 0, INT_MAX, startIndex, INT_MAX ); - - /* Redisplay the lines in between at their full width */ - for ( i = startLine + 1; i < lastLine; i++ ) - draw_vline( i, 0, INT_MAX, 0, INT_MAX ); - - /* Redisplay the last line to "end" */ - draw_vline( lastLine, 0, INT_MAX, 0, endIndex ); -} - - - -/** - \brief Sets the position of the text insertion cursor for text display. - Move the insertion cursor in front of the character at \p newPos. - This function may trigger a redraw. - \param newPos new caret position - */ -void Fl_Text_Display_mod::insert_position( int newPos ) { - IS_UTF8_ALIGNED2(buffer(), newPos) - - /* make sure new position is ok, do nothing if it hasn't changed */ - if ( newPos == mCursorPos ) return; - if ( newPos < 0 ) newPos = 0; - if ( newPos > mBuffer->length() ) newPos = mBuffer->length(); - - /* cursor movement cancels vertical cursor motion column */ - mCursorPreferredXPos = -1; - - /* erase the cursor at its previous position */ - redisplay_range(buffer()->prev_char_clipped(mCursorPos), buffer()->next_char(mCursorPos)); - - mCursorPos = newPos; - - /* draw cursor at its new position */ - redisplay_range(buffer()->prev_char_clipped(mCursorPos), buffer()->next_char(mCursorPos)); -} - - - -/** - \brief Shows the text cursor. - This function may trigger a redraw. - \param b show(1) or hide(0) the text cursor (caret). - */ -void Fl_Text_Display_mod::show_cursor(int b) { - mCursorOn = b; - redisplay_range(buffer()->prev_char_clipped(mCursorPos), buffer()->next_char(mCursorPos)); -} - - - -/** - \brief Sets the text cursor style. - Sets the text cursor style to one of the following: - - \li Fl_Text_Display_mod::NORMAL_CURSOR - Shows an I beam. - \li Fl_Text_Display_mod::CARET_CURSOR - Shows a caret under the text. - \li Fl_Text_Display_mod::DIM_CURSOR - Shows a dimmed I beam. - \li Fl_Text_Display_mod::BLOCK_CURSOR - Shows an unfilled box around the current - character. - \li Fl_Text_Display_mod::HEAVY_CURSOR - Shows a thick I beam. - - This call also switches the cursor on and may trigger a redraw. - - \param style new cursor style - */ -void Fl_Text_Display_mod::cursor_style(int style) { - mCursorStyle = style; - if (mCursorOn) show_cursor(); -} - - - -/** - \brief Set the new text wrap mode. - - If \p wrap mode is not zero, this call enables automatic word wrapping at column - \p wrapMargin. Word-wrapping does not change the text buffer itself, only the way - the text is displayed. Different Text Displays can have different wrap modes, - even if they share the same Text Buffer. - - \param wrap new wrap mode is WRAP_NONE (don't wrap text at all), WRAP_AT_COLUMN - (wrap text at the given text column), WRAP_AT_PIXEL (wrap text at a pixel - position), or WRAP_AT_BOUNDS (wrap text so that it fits into the - widget width) - \param wrapMargin in WRAP_AT_COLUMN mode, text will wrap at the n'th character. - For variable width fonts, an average character width is calculated. The - column width is calculated using the current textfont or the first style - when this function is called. If the font size changes, this function - must be called again. In WRAP_AT_PIXEL mode, this is the pixel position. - \todo we need new wrap modes to wrap at the window edge and based on pixel width - or average character width. - */ -void Fl_Text_Display_mod::wrap_mode(int wrap, int wrapMargin) { - switch (wrap) { - case WRAP_NONE: - mWrapMarginPix = 0; - mContinuousWrap = 0; - break; - case WRAP_AT_COLUMN: - default: - mWrapMarginPix = int(col_to_x(wrapMargin)); - mContinuousWrap = 1; - break; - case WRAP_AT_PIXEL: - mWrapMarginPix = wrapMargin; - mContinuousWrap = 1; - break; - case WRAP_AT_BOUNDS: - mWrapMarginPix = 0; - mContinuousWrap = 1; - break; - } - - if (buffer()) { - /* wrapping can change the total number of lines, re-count */ - mNBufferLines = count_lines(0, buffer()->length(), true); - - /* changing wrap margins or changing from wrapped mode to non-wrapped - can leave the character at the top no longer at a line start, and/or - change the line number */ - mFirstChar = line_start(mFirstChar); - mTopLineNum = count_lines(0, mFirstChar, true) + 1; - - reset_absolute_top_line_number(); - - /* update the line starts array */ - calc_line_starts(0, mNVisibleLines); - calc_last_char(); - } else { - // No buffer, so just clear the state info for later... - mNBufferLines = 0; - mFirstChar = 0; - mTopLineNum = 1; - mAbsTopLineNum = 0; - } - - resize(x(), y(), w(), h()); -} - - - -/** - \brief Inserts "text" at the current cursor location. - - This has the same effect as inserting the text into the buffer using BufInsert - and then moving the insert position after the newly inserted text, except - that it's optimized to do less redrawing. - - \param text new text in UTF-8 encoding. - */ -void Fl_Text_Display_mod::insert(const char* text) { - IS_UTF8_ALIGNED2(buffer(), mCursorPos) - IS_UTF8_ALIGNED(text) - - int pos = mCursorPos; - - mCursorToHint = pos + strlen( text ); - mBuffer->insert( pos, text ); - mCursorToHint = NO_HINT; -} - - - -/** - \brief Replaces text at the current insert position. - \param text new text in UTF-8 encoding - - \todo Unicode? Find out exactly what we do here and simplify. - */ -void Fl_Text_Display_mod::overstrike(const char* text) { - IS_UTF8_ALIGNED2(buffer(), mCursorPos) - IS_UTF8_ALIGNED(text) - - int startPos = mCursorPos; - Fl_Text_Buffer_mod *buf = mBuffer; - int lineStart = buf->line_start( startPos ); - int textLen = strlen( text ); - int i, p, endPos, indent, startIndent, endIndent; - const char *c; - unsigned int ch; - char *paddedText = NULL; - - /* determine how many displayed character positions are covered */ - startIndent = mBuffer->count_displayed_characters( lineStart, startPos ); - indent = startIndent; - for ( c = text; *c != '\0'; c += fl_utf8len1(*c) ) - indent++; - endIndent = indent; - - /* find which characters to remove, and if necessary generate additional - padding to make up for removed control characters at the end */ - indent = startIndent; - for ( p = startPos; ; p=buffer()->next_char(p) ) { - if ( p == buf->length() ) - break; - ch = buf->char_at( p ); - if ( ch == '\n' ) - break; - indent++; - if ( indent == endIndent ) { - p++; - break; - } else if ( indent > endIndent ) { - if ( ch != '\t' ) { - p++; - paddedText = new char [ textLen + FL_TEXT_MAX_EXP_CHAR_LEN + 1 ]; - strcpy( paddedText, text ); - for ( i = 0; i < indent - endIndent; i++ ) - paddedText[ textLen + i ] = ' '; - paddedText[ textLen + i ] = '\0'; - } - break; - } - } - endPos = p; - - mCursorToHint = startPos + textLen; - buf->replace( startPos, endPos, paddedText == NULL ? text : paddedText ); - mCursorToHint = NO_HINT; - if ( paddedText != NULL ) - delete [] paddedText; -} - - - -/** - \brief Convert a character index into a pixel position. - - Translate a buffer text position to the XY location where the top left of the - cursor would be positioned to point to that character. Returns 0 if the - position is not displayed because it is \e \b vertically out of view. - If the position is horizontally out of view, returns the X coordinate where - the position would be if it were visible. - - \param pos character index - \param[out] X, Y pixel position of character on screen - \return 0 if character vertically out of view, X position otherwise - */ -int Fl_Text_Display_mod::position_to_xy( int pos, int* X, int* Y ) const { - IS_UTF8_ALIGNED2(buffer(), pos) - - int lineStartPos, fontHeight;//, lineLen; - int visLineNum; - - /* If position is not displayed, return false */ - if (pos < mFirstChar || (pos > mLastChar && !empty_vlines())) { - return 0; - } - - /* Calculate Y coordinate */ - if (!position_to_line(pos, &visLineNum)) { - return 0; - } - if (visLineNum < 0 || visLineNum > mNBufferLines) { - return 0; - } - - fontHeight = mMaxsize; - *Y = text_area.y + visLineNum * fontHeight; - - /* Get the text, length, and buffer position of the line. If the position - is beyond the end of the buffer and should be at the first position on - the first empty line, don't try to get or scan the text */ - lineStartPos = mLineStarts[visLineNum]; - if ( lineStartPos == -1 ) { - *X = text_area.x - mHorizOffset; - return 1; - } -// lineLen = vline_length( visLineNum ); - *X = text_area.x + handle_vline(GET_WIDTH, lineStartPos, pos-lineStartPos, 0, 0, 0, 0, 0, 0) - mHorizOffset; - return 1; -} - - - -/** - \brief Find the line and column number of position \p pos. - - This only works for displayed lines. If the line is not displayed, the - function returns 0 (without the mLineStarts array it could turn in to very long - calculation involving scanning large amounts of text in the buffer). - If continuous wrap mode is on, returns the absolute line number (as opposed - to the wrapped line number which is used for scrolling). - - \param pos character index - \param[out] lineNum absolute (unwrapped) line number - \param[out] column character offset to the beginning of the line - \return 0 if \p pos is off screen, line number otherwise - \todo a column number makes little sense in the UTF-8/variable font width - environment. We will have to further define what exactly we want to return. - Please check the functions that call this particular function. - */ -int Fl_Text_Display_mod::position_to_linecol( int pos, int* lineNum, int* column ) const { - IS_UTF8_ALIGNED2(buffer(), pos) - - int retVal; - - /* In continuous wrap mode, the absolute (non-wrapped) line count is - maintained separately, as needed. Only return it if we're actually - keeping track of it and pos is in the displayed text */ - if (!mFastDisplay && mContinuousWrap) { - if (!maintaining_absolute_top_line_number() || pos < mFirstChar || pos > mLastChar) - return 0; - *lineNum = mAbsTopLineNum + buffer()->count_lines(mFirstChar, pos); - *column = buffer()->count_displayed_characters(buffer()->line_start(pos), pos); - return 1; - } - - retVal = position_to_line( pos, lineNum ); - if ( retVal ) { - *column = mBuffer->count_displayed_characters( mLineStarts[ *lineNum ], pos ); - *lineNum += mTopLineNum; - } - return retVal; -} - - - -/** - \brief Check if a pixel position is within the primary selection. - \param X, Y pixel position to test - \return 1 if position (X, Y) is inside of the primary Fl_Text_Selection - */ -int Fl_Text_Display_mod::in_selection( int X, int Y ) const { - int pos = xy_to_position( X, Y, CHARACTER_POS ); - IS_UTF8_ALIGNED2(buffer(), pos) - Fl_Text_Buffer_mod *buf = mBuffer; - return buf->primary_selection()->includes(pos); -} - - - -/** - \brief Nobody knows what this function does. - - Correct a column number based on an unconstrained position (as returned by - TextDXYToUnconstrainedPosition) to be relative to the last actual newline - in the buffer before the row and column position given, rather than the - last line start created by line wrapping. This is an adapter - for rectangular selections and code written before continuous wrap mode, - which thinks that the unconstrained column is the number of characters - from the last newline. Obviously this is time consuming, because it - invloves character re-counting. - - \param row - \param column - \return something unknown - \todo What does this do and how is it useful? Column numbers mean little in - this context. Which functions depend on this one? - - \todo Unicode? - */ -int Fl_Text_Display_mod::wrapped_column(int row, int column) const { - int lineStart, dispLineStart; - - if (mFastDisplay || !mContinuousWrap || row < 0 || row > mNVisibleLines) - return column; - dispLineStart = mLineStarts[row]; - if (dispLineStart == -1) - return column; - lineStart = buffer()->line_start(dispLineStart); - return column + buffer()->count_displayed_characters(lineStart, dispLineStart); -} - - - -/** - \brief Nobody knows what this function does. - - Correct a row number from an unconstrained position (as returned by - TextDXYToUnconstrainedPosition) to a straight number of newlines from the - top line of the display. Because rectangular selections are based on - newlines, rather than display wrapping, and anywhere a rectangular selection - needs a row, it needs it in terms of un-wrapped lines. - - \param row - \return something unknown - \todo What does this do and how is it useful? Column numbers mean little in - this context. Which functions depend on this one? - */ -int Fl_Text_Display_mod::wrapped_row(int row) const { - if (mFastDisplay || !mContinuousWrap || row < 0 || row > mNVisibleLines) - return row; - return buffer()->count_lines(mFirstChar, mLineStarts[row]); -} - - - -/** - \brief Scroll the display to bring insertion cursor into view. - - Note: it would be nice to be able to do this without counting lines twice - (scroll_() counts them too) and/or to count from the most efficient - starting point, but the efficiency of this routine is not as important to - the overall performance of the text display. - - \todo Unicode? - */ -void Fl_Text_Display_mod::display_insert() { - int hOffset, topLine, X, Y; - hOffset = mHorizOffset; - topLine = mTopLineNum; - - if (insert_position() < mFirstChar) { - topLine -= count_lines(insert_position(), mFirstChar, false); - } else if (mNVisibleLines>=2 && mLineStarts[mNVisibleLines-2] != -1) { - int lastChar = line_end(mLineStarts[mNVisibleLines-2],true); - if (insert_position() >= lastChar) - topLine += count_lines(lastChar - (wrap_uses_character(mLastChar) ? 0 : 1), - insert_position(), false); - } - - /* Find the new setting for horizontal offset (this is a bit ungraceful). - If the line is visible, just use PositionToXY to get the position - to scroll to, otherwise, do the vertical scrolling first, then the - horizontal */ - if (!position_to_xy( mCursorPos, &X, &Y )) { - scroll_(topLine, hOffset); - if (!position_to_xy( mCursorPos, &X, &Y )) { -#ifdef DEBUG - printf ("*** display_insert/position_to_xy # GIVE UP !\n"); fflush(stdout); -#endif // DEBUG - return; /* Give up, it's not worth it (but why does it fail?) */ - } - } - if (X > text_area.x + text_area.w) - hOffset += X-(text_area.x + text_area.w); - else if (X < text_area.x) - hOffset += X-text_area.x; - - /* Do the scroll */ - if (topLine != mTopLineNum || hOffset != mHorizOffset) - scroll_(topLine, hOffset); -} - - -/** - \brief Scrolls the text buffer to show the current insert position. - This function triggers a complete recalculation, ending in a call to - Fl_Text_Display_mod::display_insert() - */ -void Fl_Text_Display_mod::show_insert_position() { - display_insert_position_hint = 1; - resize(x(), y(), w(), h()); -} - - -/* - Cursor movement functions - */ - -/** - \brief Moves the current insert position right one character. - \return 1 if the cursor moved, 0 if the end of the text was reached - */ -int Fl_Text_Display_mod::move_right() { - if ( mCursorPos >= mBuffer->length() ) - return 0; - int p = insert_position(); - int q = buffer()->next_char(p); - insert_position(q); - return 1; -} - - - -/** - \brief Moves the current insert position left one character. - \return 1 if the cursor moved, 0 if the beginning of the text was reached - */ -int Fl_Text_Display_mod::move_left() { - if ( mCursorPos <= 0 ) - return 0; - int p = insert_position(); - int q = buffer()->prev_char_clipped(p); - insert_position(q); - return 1; -} - - - -/** - \brief Moves the current insert position up one line. - \return 1 if the cursor moved, 0 if the beginning of the text was reached - */ -int Fl_Text_Display_mod::move_up() { - int lineStartPos, xPos, prevLineStartPos, newPos, visLineNum; - - /* Find the position of the start of the line. Use the line starts array - if possible */ - if ( position_to_line( mCursorPos, &visLineNum ) ) - lineStartPos = mLineStarts[ visLineNum ]; - else { - lineStartPos = line_start( mCursorPos ); - visLineNum = -1; - } - if ( lineStartPos == 0 ) - return 0; - - /* Decide what column to move to, if there's a preferred column use that */ - if (mCursorPreferredXPos >= 0) - xPos = mCursorPreferredXPos; - else - xPos = handle_vline(GET_WIDTH, lineStartPos, mCursorPos-lineStartPos, - 0, 0, 0, 0, 0, INT_MAX); - - /* count forward from the start of the previous line to reach the column */ - if ( visLineNum != -1 && visLineNum != 0 ) - prevLineStartPos = mLineStarts[ visLineNum - 1 ]; - else - prevLineStartPos = rewind_lines( lineStartPos, 1 ); - - int lineEnd = line_end(prevLineStartPos, true); - newPos = handle_vline(FIND_INDEX_FROM_ZERO, prevLineStartPos, lineEnd-prevLineStartPos, - 0, 0, 0, 0, 0, xPos); - - /* move the cursor */ - insert_position( newPos ); - - /* if a preferred column wasn't aleady established, establish it */ - mCursorPreferredXPos = xPos; - return 1; -} - - - -/** - \brief Moves the current insert position down one line. - \return 1 if the cursor moved, 0 if the beginning of the text was reached - */ -int Fl_Text_Display_mod::move_down() { - int lineStartPos, xPos, newPos, visLineNum; - - if ( mCursorPos == mBuffer->length() ) - return 0; - - if ( position_to_line( mCursorPos, &visLineNum ) ) - lineStartPos = mLineStarts[ visLineNum ]; - else { - lineStartPos = line_start( mCursorPos ); - visLineNum = -1; - } - if (mCursorPreferredXPos >= 0) { - xPos = mCursorPreferredXPos; - } else { - xPos = handle_vline(GET_WIDTH, lineStartPos, mCursorPos-lineStartPos, - 0, 0, 0, 0, 0, INT_MAX); - } - - int nextLineStartPos = skip_lines( lineStartPos, 1, true ); - int lineEnd = line_end(nextLineStartPos, true); - newPos = handle_vline(FIND_INDEX_FROM_ZERO, nextLineStartPos, lineEnd-nextLineStartPos, - 0, 0, 0, 0, 0, xPos); - - insert_position( newPos ); - mCursorPreferredXPos = xPos; - return 1; -} - - - -/** - \brief Count the number of lines between two positions. - - Same as BufCountLines, but takes into account wrapping if wrapping is - turned on. If the caller knows that \p startPos is at a line start, it - can pass \p startPosIsLineStart as True to make the call more efficient - by avoiding the additional step of scanning back to the last newline. - - \param startPos index to first character - \param endPos index after last character - \param startPosIsLineStart avoid scanning back to the line start - \return number of lines - */ -int Fl_Text_Display_mod::count_lines(int startPos, int endPos, - bool startPosIsLineStart) const { - IS_UTF8_ALIGNED2(buffer(), startPos) - IS_UTF8_ALIGNED2(buffer(), endPos) - - int retLines, retPos, retLineStart, retLineEnd; - -#ifdef DEBUG - printf("Fl_Text_Display_mod::count_lines(startPos=%d, endPos=%d, startPosIsLineStart=%d\n", - startPos, endPos, startPosIsLineStart); -#endif // DEBUG - - /* If we're not wrapping use simple (and more efficient) BufCountLines */ - if (mFastDisplay || !mContinuousWrap) - return buffer()->count_lines(startPos, endPos); - - wrapped_line_counter(buffer(), startPos, endPos, INT_MAX, - startPosIsLineStart, 0, &retPos, &retLines, &retLineStart, - &retLineEnd); - -#ifdef DEBUG - printf(" # after WLC: retPos=%d, retLines=%d, retLineStart=%d, retLineEnd=%d\n", - retPos, retLines, retLineStart, retLineEnd); -#endif // DEBUG - - return retLines; -} - - - -/** - \brief Skip a number of lines forward. - - Same as BufCountForwardNLines, but takes into account line breaks when - wrapping is turned on. If the caller knows that startPos is at a line start, - it can pass "startPosIsLineStart" as True to make the call more efficient - by avoiding the additional step of scanning back to the last newline. - - \param startPos index to starting character - \param nLines number of lines to skip ahead - \param startPosIsLineStart avoid scanning back to the line start - \return new position as index - */ -int Fl_Text_Display_mod::skip_lines(int startPos, int nLines, - bool startPosIsLineStart) { - IS_UTF8_ALIGNED2(buffer(), startPos) - - int retLines, retPos, retLineStart, retLineEnd; - - /* if we're not wrapping use more efficient BufCountForwardNLines */ - if (mFastDisplay || !mContinuousWrap) - return buffer()->skip_lines(startPos, nLines); - - /* wrappedLineCounter can't handle the 0 lines case */ - if (nLines == 0) - return startPos; - - /* use the common line counting routine to count forward */ - wrapped_line_counter(buffer(), startPos, buffer()->length(), - nLines, startPosIsLineStart, 0, - &retPos, &retLines, &retLineStart, &retLineEnd); - IS_UTF8_ALIGNED2(buffer(), retPos) - return retPos; -} - - - -/** - \brief Returns the end of a line. - - Same as BufEndOfLine, but takes into account line breaks when wrapping - is turned on. If the caller knows that \p startPos is at a line start, it - can pass "startPosIsLineStart" as True to make the call more efficient - by avoiding the additional step of scanning back to the last newline. - - Note that the definition of the end of a line is less clear when continuous - wrap is on. With continuous wrap off, it's just a pointer to the newline - that ends the line. When it's on, it's the character beyond the last - \b displayable character on the line, where a whitespace character which has - been "converted" to a newline for wrapping is not considered displayable. - Also note that a line can be wrapped at a non-whitespace character if the - line had no whitespace. In this case, this routine returns a pointer to - the start of the next line. This is also consistent with the model used by - visLineLength. - - \param startPos index to starting character - \param startPosIsLineStart avoid scanning back to the line start - \return new position as index - */ -int Fl_Text_Display_mod::line_end(int startPos, bool startPosIsLineStart) const { - IS_UTF8_ALIGNED2(buffer(), startPos) - - int retLines, retPos, retLineStart, retLineEnd; - - /* If we're not wrapping use more efficient BufEndOfLine */ - if (mFastDisplay || !mContinuousWrap) - return buffer()->line_end(startPos); - - if (startPos == buffer()->length()) - return startPos; - - wrapped_line_counter(buffer(), startPos, buffer()->length(), 1, - startPosIsLineStart, 0, &retPos, &retLines, &retLineStart, - &retLineEnd); - - IS_UTF8_ALIGNED2(buffer(), retLineEnd) - return retLineEnd; -} - - - -/** - \brief Return the beginning of a line. - - Same as BufStartOfLine, but returns the character after last wrap point - rather than the last newline. - - \param pos index to starting character - \return new position as index - */ -int Fl_Text_Display_mod::line_start(int pos) const { - IS_UTF8_ALIGNED2(buffer(), pos) - - int retLines, retPos, retLineStart, retLineEnd; - - /* If we're not wrapping, use the more efficient BufStartOfLine */ - if (mFastDisplay || !mContinuousWrap) - return buffer()->line_start(pos); - - wrapped_line_counter(buffer(), buffer()->line_start(pos), pos, INT_MAX, true, 0, - &retPos, &retLines, &retLineStart, &retLineEnd); - - IS_UTF8_ALIGNED2(buffer(), retLineStart) - return retLineStart; -} - - - -/** - \brief Skip a number of lines back. - - Same as BufCountBackwardNLines, but takes into account line breaks when - wrapping is turned on. - - \param startPos index to starting character - \param nLines number of lines to skip back - \return new position as index - */ -int Fl_Text_Display_mod::rewind_lines(int startPos, int nLines) { - IS_UTF8_ALIGNED2(buffer(), startPos) - - Fl_Text_Buffer_mod *buf = buffer(); - int pos, lineStart, retLines, retPos, retLineStart, retLineEnd; - - /* If we're not wrapping, use the more efficient BufCountBackwardNLines */ - if (mFastDisplay || !mContinuousWrap) - return buf->rewind_lines(startPos, nLines); - - pos = startPos; - for (;;) { - lineStart = buf->line_start(pos); - wrapped_line_counter(buf, lineStart, pos, INT_MAX, true, 0, - &retPos, &retLines, &retLineStart, &retLineEnd, false); - if (retLines > nLines) - return skip_lines(lineStart, retLines-nLines, true); - nLines -= retLines; - pos = lineStart - 1; - if (pos < 0) - return 0; - nLines -= 1; - } -} - - - -static inline int fl_isseparator(unsigned int c) { - // FIXME: this does not take UCS-4 encoding into account - return c != '$' && c != '_' && (isspace(c) || ispunct(c)); -} - - - -/** - \brief Moves the current insert position right one word. - */ -void Fl_Text_Display_mod::next_word() { - int pos = insert_position(); - - while (pos < buffer()->length() && !fl_isseparator(buffer()->char_at(pos))) { - pos = buffer()->next_char(pos); - } - - while (pos < buffer()->length() && fl_isseparator(buffer()->char_at(pos))) { - pos = buffer()->next_char(pos); - } - - insert_position( pos ); -} - - - -/** - \brief Moves the current insert position left one word. - */ -void Fl_Text_Display_mod::previous_word() { - int pos = insert_position(); - if (pos==0) return; - pos = buffer()->prev_char(pos); - - while (pos && fl_isseparator(buffer()->char_at(pos))) { - pos = buffer()->prev_char(pos); - } - - while (pos && !fl_isseparator(buffer()->char_at(pos))) { - pos = buffer()->prev_char(pos); - } - - if (fl_isseparator(buffer()->char_at(pos))) { - pos = buffer()->next_char(pos); - } - - insert_position( pos ); -} - - - -/** - \brief This is called before any characters are deleted. - - Callback attached to the text buffer to receive delete information before - the modifications are actually made. - - \param pos starting index of deletion - \param nDeleted number of bytes we will delete (must be UTF-8 aligned!) - \param cbArg "this" pointer for static callback function - */ -void Fl_Text_Display_mod::buffer_predelete_cb(int pos, int nDeleted, void *cbArg) { - Fl_Text_Display_mod *textD = (Fl_Text_Display_mod *)cbArg; - if (textD->mContinuousWrap && !textD->mFastDisplay) { - /* Note: we must perform this measurement, even if there is not a - single character deleted; the number of "deleted" lines is the - number of visual lines spanned by the real line in which the - modification takes place. - Also, a modification of the tab distance requires the same - kind of calculations in advance, even if the font width is "fixed", - because when the width of the tab characters changes, the layout - of the text may be completely different. */ - IS_UTF8_ALIGNED2(textD->buffer(), pos) - textD->measure_deleted_lines(pos, nDeleted); - } else { - textD->mSuppressResync = 0; /* Probably not needed, but just in case */ - } -} - - - -/** - \brief This is called whenever the buffer is modified. - - Callback attached to the text buffer to receive modification information - - \param pos starting index of modification - \param nInserted number of bytes we inserted (must be UTF-8 aligned!) - \param nDeleted number of bytes deleted (must be UTF-8 aligned!) - \param nRestyled ?? - \param deletedText this is what was removed, must not be NULL if nDeleted is set - \param cbArg "this" pointer for static callback function - */ -void Fl_Text_Display_mod::buffer_modified_cb( int pos, int nInserted, int nDeleted, - int nRestyled, const char *deletedText, void *cbArg ) { - int linesInserted, linesDeleted, startDispPos, endDispPos; - Fl_Text_Display_mod *textD = ( Fl_Text_Display_mod * ) cbArg; - Fl_Text_Buffer_mod *buf = textD->mBuffer; - int oldFirstChar = textD->mFirstChar; - int scrolled, origCursorPos = textD->mCursorPos; - int wrapModStart = 0, wrapModEnd = 0; - - IS_UTF8_ALIGNED2(buf, pos) - IS_UTF8_ALIGNED2(buf, oldFirstChar) - - /* buffer modification cancels vertical cursor motion column */ - if ( nInserted != 0 || nDeleted != 0 ) - textD->mCursorPreferredXPos = -1; - - /* Count the number of lines inserted and deleted, and in the case - of continuous wrap mode, how much has changed */ - if (textD->mContinuousWrap && !textD->mFastDisplay) { - textD->find_wrap_range(deletedText, pos, nInserted, nDeleted, - &wrapModStart, &wrapModEnd, &linesInserted, &linesDeleted); - } else { - linesInserted = nInserted == 0 ? 0 : buf->count_lines( pos, pos + nInserted ); - linesDeleted = nDeleted == 0 ? 0 : countlines( deletedText ); - } - - /* Update the line starts and mTopLineNum */ - if ( nInserted != 0 || nDeleted != 0 ) { - if (textD->mContinuousWrap && !textD->mFastDisplay) { - textD->update_line_starts( wrapModStart, wrapModEnd-wrapModStart, - nDeleted + pos-wrapModStart + (wrapModEnd-(pos+nInserted)), - linesInserted, linesDeleted, &scrolled ); - } else { - textD->update_line_starts( pos, nInserted, nDeleted, linesInserted, - linesDeleted, &scrolled ); - } - } else - scrolled = 0; - - /* If we're counting non-wrapped lines as well, maintain the absolute - (non-wrapped) line number of the text displayed */ - if (textD->maintaining_absolute_top_line_number() && - (nInserted != 0 || nDeleted != 0)) { - if (deletedText && (pos + nDeleted < oldFirstChar)) - textD->mAbsTopLineNum += buf->count_lines(pos, pos + nInserted) - - countlines(deletedText); - else if (pos < oldFirstChar) - textD->reset_absolute_top_line_number(); - } - - /* Update the line count for the whole buffer */ - textD->mNBufferLines += linesInserted - linesDeleted; - - /* Update the cursor position */ - if ( textD->mCursorToHint != NO_HINT ) { - textD->mCursorPos = textD->mCursorToHint; - textD->mCursorToHint = NO_HINT; - } else if ( textD->mCursorPos > pos ) { - if ( textD->mCursorPos < pos + nDeleted ) - textD->mCursorPos = pos; - else - textD->mCursorPos += nInserted - nDeleted; - } - - // refigure scrollbars & stuff - textD->resize(textD->x(), textD->y(), textD->w(), textD->h()); - - // don't need to do anything else if not visible? - if (!textD->visible_r()) return; - - /* If the changes caused scrolling, re-paint everything and we're done. */ - if ( scrolled ) { - textD->damage(FL_DAMAGE_EXPOSE); - if ( textD->mStyleBuffer ) /* See comments in extendRangeForStyleMods */ - textD->mStyleBuffer->primary_selection()->selected(0); - return; - } - - /* If the changes didn't cause scrolling, decide the range of characters - that need to be re-painted. Also if the cursor position moved, be - sure that the redisplay range covers the old cursor position so the - old cursor gets erased, and erase the bits of the cursor which extend - beyond the left and right edges of the text. */ - startDispPos = (textD->mContinuousWrap && !textD->mFastDisplay) ? wrapModStart : pos; - IS_UTF8_ALIGNED2(buf, startDispPos) - - if ( origCursorPos == startDispPos && textD->mCursorPos != startDispPos ) - startDispPos = min( startDispPos, buf->prev_char_clipped(origCursorPos) ); - IS_UTF8_ALIGNED2(buf, startDispPos) - - if ( linesInserted == linesDeleted ) { - if ( nInserted == 0 && nDeleted == 0 ) - endDispPos = pos + nRestyled; - else { - endDispPos = textD->mContinuousWrap ? wrapModEnd : - buf->line_end( pos + nInserted ) + 1; - if (textD->mContinuousWrap && !textD->mFastDisplay) - endDispPos = wrapModEnd; - else - endDispPos = buf->next_char(buf->line_end( pos + nInserted )); - - // CET - FIXME if ( origCursorPos >= startDispPos && - // ( origCursorPos <= endDispPos || endDispPos == buf->length() ) ) - } - - if (linesInserted > 1) textD->draw_line_numbers(false); - } else { - endDispPos = buf->next_char(textD->mLastChar); - // CET - FIXME if ( origCursorPos >= pos ) - /* If more than one line is inserted/deleted, a line break may have - been inserted or removed in between, and the line numbers may - have changed. If only one line is altered, line numbers cannot - be affected (the insertion or removal of a line break always - results in at least two lines being redrawn). */ - textD->draw_line_numbers(false); - } - IS_UTF8_ALIGNED2(buf, startDispPos) - IS_UTF8_ALIGNED2(buf, endDispPos) - - /* If there is a style buffer, check if the modification caused additional - changes that need to be redisplayed. (Redisplaying separately would - cause double-redraw on almost every modification involving styled - text). Extend the redraw range to incorporate style changes */ - if ( textD->mStyleBuffer ) - textD->extend_range_for_styles( &startDispPos, &endDispPos ); - IS_UTF8_ALIGNED2(buf, startDispPos) - IS_UTF8_ALIGNED2(buf, endDispPos) - - /* Redisplay computed range */ - textD->redisplay_range( startDispPos, endDispPos ); -} - - - -/** - \brief Line numbering stuff, currently unused. - - In continuous wrap mode, internal line numbers are calculated after - wrapping. A separate non-wrapped line count is maintained when line - numbering is turned on. There is some performance cost to maintaining this - line count, so normally absolute line numbers are not tracked if line - numbering is off. This routine allows callers to specify that they still - want this line count maintained (for use via TextDPosToLineAndCol). - More specifically, this allows the line number reported in the statistics - line to be calibrated in absolute lines, rather than post-wrapped lines. - */ -void Fl_Text_Display_mod::maintain_absolute_top_line_number(int state) { - mNeedAbsTopLineNum = state; - reset_absolute_top_line_number(); -} - - - -/** - \brief Line numbering stuff, currently unused. - - Returns the absolute (non-wrapped) line number of the first line displayed. - Returns 0 if the absolute top line number is not being maintained. - */ -int Fl_Text_Display_mod::get_absolute_top_line_number() const { - if (mFastDisplay || !mContinuousWrap) - return mTopLineNum; - if (maintaining_absolute_top_line_number()) - return mAbsTopLineNum; - return 0; -} - - - -/** - \brief Line numbering stuff, currently unused. - - Re-calculate absolute top line number for a change in scroll position. - */ -void Fl_Text_Display_mod::absolute_top_line_number(int oldFirstChar) { - if (maintaining_absolute_top_line_number()) { - if (mFirstChar < oldFirstChar) - mAbsTopLineNum -= buffer()->count_lines(mFirstChar, oldFirstChar); - else - mAbsTopLineNum += buffer()->count_lines(oldFirstChar, mFirstChar); - } -} - - - -/** - \brief Line numbering stuff, currently unused. - - Return true if a separate absolute top line number is being maintained - (for displaying line numbers or showing in the statistics line). - */ -int Fl_Text_Display_mod::maintaining_absolute_top_line_number() const { - return (!mFastDisplay && mContinuousWrap && (mLineNumWidth != 0 || mNeedAbsTopLineNum)); -} - - - -/** - \brief Line numbering stuff, probably unused. - - Count lines from the beginning of the buffer to reestablish the - absolute (non-wrapped) top line number. If mode is not continuous wrap, - or the number is not being maintained, does nothing. - */ -void Fl_Text_Display_mod::reset_absolute_top_line_number() { - mAbsTopLineNum = 1; - absolute_top_line_number(0); -} - - - -/** - \brief Convert a position index into a line number offset. - - Find the line number of position \p pos relative to the first line of - displayed text. Returns 0 if the line is not displayed. - - \param pos ?? - \param[out] lineNum ?? - \return ?? - \todo What does this do? - */ -int Fl_Text_Display_mod::position_to_line( int pos, int *lineNum ) const { - IS_UTF8_ALIGNED2(buffer(), pos) - - int i; - - *lineNum = 0; - if ( pos < mFirstChar ) return 0; - if ( pos > mLastChar ) { - if ( empty_vlines() ) { - if ( mLastChar < mBuffer->length() ) { - if ( !position_to_line( mLastChar, lineNum ) ) { - Fl::error("Fl_Text_Display_mod::position_to_line(): Consistency check ptvl failed"); - return 0; - } - return ++( *lineNum ) <= mNVisibleLines - 1; - } else { - position_to_line( buffer()->prev_char_clipped(mLastChar), lineNum ); - return 1; - } - } - return 0; - } - - for ( i = mNVisibleLines - 1; i >= 0; i-- ) { - if ( mLineStarts[ i ] != -1 && pos >= mLineStarts[ i ] ) { - *lineNum = i; - return 1; - } - } - return 0; /* probably never be reached */ -} - - -/** - Universal pixel machine. - - We use a single function that handles all line layout, measuring, and drawing - \li draw a text range - \li return the width of a text range in pixels - \li return the index of a character that is at a pixel position - - \param[in] mode DRAW_LINE, GET_WIDTH, FIND_INDEX - \param[in] lineStartPos index of first character - \param[in] lineLen size of std::string in bytes - \param[in] leftChar, rightChar - \param[in] Y drawing position - \param[in] bottomClip, leftClip, rightClip stop work when we reach the clipped - area. rightClip is the X position that we search in FIND_INDEX. - \retval DRAW_LINE index of last drawn character - \retval GET_WIDTH width in pixels of text segment if we would draw it - \retval FIND_INDEX index of character at given x position in window coordinates - \retval FIND_INDEX_FROM_ZERO index of character at given x position without scrolling and widget offsets - \todo we need to handle hidden hyphens and tabs here! - \todo we handle all styles and selections - \todo we must provide code to get pixel positions of the middle of a character as well - */ -int Fl_Text_Display_mod::handle_vline( - int mode, - int lineStartPos, int lineLen, int leftChar, int rightChar, - int Y, int bottomClip, - int leftClip, int rightClip) const -{ - IS_UTF8_ALIGNED2(buffer(), lineStartPos) - - // FIXME: we need to allow two modes for FIND_INDEX: one on the edge of the - // FIXME: character for selection, and one on the character center for cursors. - int i, X, startX, startIndex, style, charStyle; - char *lineStr; - - if ( lineStartPos == -1 ) { - lineStr = NULL; - } else { - lineStr = mBuffer->text_range( lineStartPos, lineStartPos + lineLen ); - } - - if (mode==GET_WIDTH) { - X = 0; - } else if (mode==FIND_INDEX_FROM_ZERO) { - X = 0; - mode = FIND_INDEX; - } else { - X = text_area.x - mHorizOffset; - } - - startX = X; - startIndex = 0; - if (!lineStr) { - // just clear the background - if (mode==DRAW_LINE) { - style = position_style(lineStartPos, lineLen, -1); - draw_string( style|BG_ONLY_MASK, text_area.x, Y, text_area.x+text_area.w, lineStr, lineLen ); - } - if (mode==FIND_INDEX) { - IS_UTF8_ALIGNED2(buffer(), lineStartPos) - return lineStartPos; - } - return 0; - } - - char currChar = 0, prevChar = 0; - // draw the line - style = position_style(lineStartPos, lineLen, 0); - for (i=0; itab_distance()); - int xAbs = (mode==GET_WIDTH) ? startX : startX+mHorizOffset-text_area.x; - w = (((xAbs/tab)+1)*tab) - xAbs; - if (mode==DRAW_LINE) - draw_string( style|BG_ONLY_MASK, startX, Y, startX+w, 0, 0 ); - if (mode==FIND_INDEX && startX+w>rightClip) { - // find x pos inside block - free(lineStr); - return lineStartPos + startIndex; - } - } else { - // draw a text segment - w = int( string_width( lineStr+startIndex, i-startIndex, style ) ); - if (mode==DRAW_LINE) - draw_string( style, startX, Y, startX+w, lineStr+startIndex, i-startIndex ); - if (mode==FIND_INDEX && startX+w>rightClip) { - // find x pos inside block - int di = find_x(lineStr+startIndex, i-startIndex, style, rightClip-startX); - free(lineStr); - IS_UTF8_ALIGNED2(buffer(), (lineStartPos+startIndex+di)) - return lineStartPos + startIndex + di; - } - } - style = charStyle; - startX += w; - startIndex = i; - } - i += len; - prevChar = currChar; - } - int w = 0; - if (currChar=='\t') { - // draw a single Tab space - int tab = (int)col_to_x(mBuffer->tab_distance()); - int xAbs = (mode==GET_WIDTH) ? startX : startX+mHorizOffset-text_area.x; - w = (((xAbs/tab)+1)*tab) - xAbs; - if (mode==DRAW_LINE) - draw_string( style|BG_ONLY_MASK, startX, Y, startX+w, 0, 0 ); - if (mode==FIND_INDEX) { - // find x pos inside block - free(lineStr); - return lineStartPos + startIndex + ( rightClip-startX>w ? 1 : 0 ); - } - } else { - w = int( string_width( lineStr+startIndex, i-startIndex, style ) ); - if (mode==DRAW_LINE) - draw_string( style, startX, Y, startX+w, lineStr+startIndex, i-startIndex ); - if (mode==FIND_INDEX) { - // find x pos inside block - int di = find_x(lineStr+startIndex, i-startIndex, style, rightClip-startX); - free(lineStr); - IS_UTF8_ALIGNED2(buffer(), (lineStartPos+startIndex+di)) - return lineStartPos + startIndex + di; - } - } - if (mode==GET_WIDTH) { - free(lineStr); - return startX+w; - } - - // clear the rest of the line - startX += w; - style = position_style(lineStartPos, lineLen, i); - if (mode==DRAW_LINE) - draw_string( style|BG_ONLY_MASK, startX, Y, text_area.x+text_area.w, lineStr, lineLen ); - - free(lineStr); - IS_UTF8_ALIGNED2(buffer(), (lineStartPos+lineLen)) - return lineStartPos + lineLen; -} - - -/** - \brief Find the index of the character that lies at the given x position. - \param s UTF-8 text std::string - \param len length of std::string - \param style index into style lookup table - \param x position in pixels - \return index into buffer - */ -int Fl_Text_Display_mod::find_x(const char *s, int len, int style, int x) const { - IS_UTF8_ALIGNED(s) - - // TODO: use binary search which may be quicker. - int i = 0; - while (ix) - return i; - i += cl; - } - return len; -} - - - -/** - \brief Draw a single line of text. - - Draw the text on a single line represented by \p visLineNum (the - number of lines down from the top of the display), limited by - \p leftClip and \p rightClip window coordinates and \p leftCharIndex and - \p rightCharIndex character positions (not including the character at - position \p rightCharIndex). - - \param visLineNum index of line in the visible line number lookup - \param leftClip, rightClip pixel position of clipped area - \param leftCharIndex, rightCharIndex index into line of segment that we want to draw - */ -void Fl_Text_Display_mod::draw_vline(int visLineNum, int leftClip, int rightClip, - int leftCharIndex, int rightCharIndex) { - int Y, lineStartPos, lineLen, fontHeight; - - // printf("draw_vline(visLineNum=%d, leftClip=%d, rightClip=%d, leftCharIndex=%d, rightCharIndex=%d)\n", - // visLineNum, leftClip, rightClip, leftCharIndex, rightCharIndex); - // printf("nNVisibleLines=%d\n", mNVisibleLines); - - /* If line is not displayed, skip it */ - if ( visLineNum < 0 || visLineNum >= mNVisibleLines ) - return; - - /* Calculate Y coordinate of the std::string to draw */ - fontHeight = mMaxsize; - Y = text_area.y + visLineNum * fontHeight; - - /* Get the text, length, and buffer position of the line to display */ - lineStartPos = mLineStarts[ visLineNum ]; - if ( lineStartPos == -1 ) { - lineLen = 0; - } else { - lineLen = vline_length( visLineNum ); - } - - /* Shrink the clipping range to the active display area */ - leftClip = max( text_area.x, leftClip ); - rightClip = min( rightClip, text_area.x + text_area.w ); - - handle_vline(DRAW_LINE, - lineStartPos, lineLen, leftCharIndex, rightCharIndex, - Y, Y+fontHeight, leftClip, rightClip); - return; -} - - - -/** - \brief Draw a text segment in a single style. - - Draw a std::string or blank area according to parameter \p style, using the - appropriate colors and drawing method for that style, with top left - corner at \p X, \p Y. If style says to draw text, use \p std::string as - source of characters, and draw \p nChars, if style is FILL, erase - rectangle where text would have drawn from \p X to \p toX and from - \p Y to the maximum y extent of the current font(s). - - \param style index into style lookup table - \param X, Y drawing origin - \param toX rightmost position if this is a fill operation - \param std::string text if this is a drawing operation - \param nChars number of characters to draw - */ -void Fl_Text_Display_mod::draw_string(int style, - int X, int Y, int toX, - const char *drwstring, int nChars) const { - IS_UTF8_ALIGNED(std::string) - - const Style_Table_Entry * styleRec; - - /* Draw blank area rather than text, if that was the request */ - if ( style & FILL_MASK ) { - if (style & TEXT_ONLY_MASK) return; - clear_rect( style, X, Y, toX - X, mMaxsize ); - return; - } - /* Set font, color, and gc depending on style. For normal text, GCs - for normal drawing, or drawing within a Fl_Text_Selection or highlight are - pre-allocated and pre-configured. For syntax highlighting, GCs are - configured here, on the fly. */ - - Fl_Font font = textfont(); - int fsize = textsize(); - Fl_Color foreground; - Fl_Color background; - - if ( style & STYLE_LOOKUP_MASK ) { - int si = (style & STYLE_LOOKUP_MASK) - 'A'; - if (si < 0) si = 0; - else if (si >= mNStyles) si = mNStyles - 1; - - styleRec = mStyleTable + si; - font = styleRec->font; - fsize = styleRec->size; - - if (style & PRIMARY_MASK) { - if (Fl::focus() == (Fl_Widget*)this) background = selection_color(); - else background = fl_color_average(color(), selection_color(), 0.4f); - } else if (style & HIGHLIGHT_MASK) { - if (Fl::focus() == (Fl_Widget*)this) background = fl_color_average(color(), selection_color(), 0.5f); - else background = fl_color_average(color(), selection_color(), 0.6f); - } else background = color(); - foreground = fl_contrast(styleRec->color, background); - } else if (style & PRIMARY_MASK) { - if (Fl::focus() == (Fl_Widget*)this) background = selection_color(); - else background = fl_color_average(color(), selection_color(), 0.4f); - foreground = fl_contrast(textcolor(), background); - } else if (style & HIGHLIGHT_MASK) { - if (Fl::focus() == (Fl_Widget*)this) background = fl_color_average(color(), selection_color(), 0.5f); - else background = fl_color_average(color(), selection_color(), 0.6f); - foreground = fl_contrast(textcolor(), background); - } else { - foreground = textcolor(); - background = color(); - } - - if (!(style & TEXT_ONLY_MASK)) { - fl_color( background ); - fl_rectf( X, Y, toX - X, mMaxsize ); - } - if (!(style & BG_ONLY_MASK)) { - fl_color( foreground ); - fl_font( font, fsize ); -#if !(defined(__APPLE__) || defined(WIN32)) && USE_XFT - // makes sure antialiased ÄÖÜ do not leak on line above - fl_push_clip(X, Y, toX - X, mMaxsize); -#endif - fl_draw( drwstring, nChars, X, Y + mMaxsize - fl_descent()); -#if !(defined(__APPLE__) || defined(WIN32)) && USE_XFT - fl_pop_clip(); -#endif - } - - // CET - FIXME - /* If any space around the character remains unfilled (due to use of - different sized fonts for highlighting), fill in above or below - to erase previously drawn characters */ - /* - if (fs->ascent < mAscent) - clear_rect( style, X, Y, toX - X, mAscent - fs->ascent); - if (fs->descent < mDescent) - clear_rect( style, X, Y + mAscent + fs->descent, toX - x, - mDescent - fs->descent); - */ - /* Underline if style is secondary Fl_Text_Selection */ - - /* - if (style & SECONDARY_MASK) - XDrawLine(XtDisplay(mW), XtWindow(mW), gc, x, - y + mAscent, toX - 1, Y + fs->ascent); - */ -} - - - -/** - \brief Clear a rectangle with the appropriate background color for \p style. - - \param style index into style table - \param X, Y, width, height size and position of background area - */ -void Fl_Text_Display_mod::clear_rect(int style, - int X, int Y, - int width, int height) const { - /* A width of zero means "clear to end of window" to XClearArea */ - if ( width == 0 ) - return; - - if (style & PRIMARY_MASK) { - if (Fl::focus()==(Fl_Widget*)this) { - fl_color(selection_color()); - } else { - fl_color(fl_color_average(color(), selection_color(), 0.4f)); - } - } else if (style & HIGHLIGHT_MASK) { - if (Fl::focus()==(Fl_Widget*)this) { - fl_color(fl_color_average(color(), selection_color(), 0.5f)); - } else { - fl_color(fl_color_average(color(), selection_color(), 0.6f)); - } - } else { - fl_color( color() ); - } - fl_rectf( X, Y, width, height ); -} - - - -/** - \brief Draw a cursor with top center at \p X, \p Y. - - \param X, Y cursor position in pixels - */ -void Fl_Text_Display_mod::draw_cursor( int X, int Y ) { - - typedef struct { - int x1, y1, x2, y2; - } - Segment; - - Segment segs[ 5 ]; - int left, right, cursorWidth, midY; - // int fontWidth = mFontStruct->min_bounds.width, nSegs = 0; - int fontWidth = TMPFONTWIDTH; // CET - FIXME - int nSegs = 0; - int fontHeight = mMaxsize; - int bot = Y + fontHeight - 1; - - if ( X < text_area.x - 1 || X > text_area.x + text_area.w ) - return; - - /* For cursors other than the block, make them around 2/3 of a character - width, rounded to an even number of pixels so that X will draw an - odd number centered on the stem at x. */ - cursorWidth = 4; //(fontWidth/3) * 2; - left = X - cursorWidth / 2; - right = left + cursorWidth; - - /* Create segments and draw cursor */ - if ( mCursorStyle == CARET_CURSOR ) { - midY = bot - fontHeight / 5; - segs[ 0 ].x1 = left; segs[ 0 ].y1 = bot; segs[ 0 ].x2 = X; segs[ 0 ].y2 = midY; - segs[ 1 ].x1 = X; segs[ 1 ].y1 = midY; segs[ 1 ].x2 = right; segs[ 1 ].y2 = bot; - segs[ 2 ].x1 = left; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = X; segs[ 2 ].y2 = midY - 1; - segs[ 3 ].x1 = X; segs[ 3 ].y1 = midY - 1; segs[ 3 ].x2 = right; segs[ 3 ].y2 = bot; - nSegs = 4; - } else if ( mCursorStyle == NORMAL_CURSOR ) { - segs[ 0 ].x1 = left; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = right; segs[ 0 ].y2 = Y; - segs[ 1 ].x1 = X; segs[ 1 ].y1 = Y; segs[ 1 ].x2 = X; segs[ 1 ].y2 = bot; - segs[ 2 ].x1 = left; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = right; segs[ 2 ].y2 = bot; - nSegs = 3; - } else if ( mCursorStyle == HEAVY_CURSOR ) { - segs[ 0 ].x1 = X - 1; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = X - 1; segs[ 0 ].y2 = bot; - segs[ 1 ].x1 = X; segs[ 1 ].y1 = Y; segs[ 1 ].x2 = X; segs[ 1 ].y2 = bot; - segs[ 2 ].x1 = X + 1; segs[ 2 ].y1 = Y; segs[ 2 ].x2 = X + 1; segs[ 2 ].y2 = bot; - segs[ 3 ].x1 = left; segs[ 3 ].y1 = Y; segs[ 3 ].x2 = right; segs[ 3 ].y2 = Y; - segs[ 4 ].x1 = left; segs[ 4 ].y1 = bot; segs[ 4 ].x2 = right; segs[ 4 ].y2 = bot; - nSegs = 5; - } else if ( mCursorStyle == DIM_CURSOR ) { - midY = Y + fontHeight / 2; - segs[ 0 ].x1 = X; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = X; segs[ 0 ].y2 = Y; - segs[ 1 ].x1 = X; segs[ 1 ].y1 = midY; segs[ 1 ].x2 = X; segs[ 1 ].y2 = midY; - segs[ 2 ].x1 = X; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = X; segs[ 2 ].y2 = bot; - nSegs = 3; - } else if ( mCursorStyle == BLOCK_CURSOR ) { - right = X + fontWidth; - segs[ 0 ].x1 = X; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = right; segs[ 0 ].y2 = Y; - segs[ 1 ].x1 = right; segs[ 1 ].y1 = Y; segs[ 1 ].x2 = right; segs[ 1 ].y2 = bot; - segs[ 2 ].x1 = right; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = X; segs[ 2 ].y2 = bot; - segs[ 3 ].x1 = X; segs[ 3 ].y1 = bot; segs[ 3 ].x2 = X; segs[ 3 ].y2 = Y; - nSegs = 4; - } - fl_color( mCursor_color ); - - for ( int k = 0; k < nSegs; k++ ) { - fl_line( segs[ k ].x1, segs[ k ].y1, segs[ k ].x2, segs[ k ].y2 ); - } -} - - - -/** - \brief Find the correct style for a character. - - Determine the drawing method to use to draw a specific character from "buf". - \p lineStartPos gives the character index where the line begins, \p lineIndex, - the number of characters past the beginning of the line, and \p lineIndex - the number of displayed characters past the beginning of the line. Passing - \p lineStartPos of -1 returns the drawing style for "no text". - - Why not just: position_style(pos)? Because style applies to blank areas - of the window beyond the text boundaries, and because this routine must also - decide whether a position is inside of a rectangular Fl_Text_Selection, and do - so efficiently, without re-counting character positions from the start of the - line. - - Note that style is a somewhat incorrect name, drawing method would - be more appropriate. - - \param lineStartPos beginning of this line - \param lineLen number of bytes in line - \param lineIndex position of character within line - \return style for the given character - */ -int Fl_Text_Display_mod::position_style( int lineStartPos, int lineLen, int lineIndex) const -{ - IS_UTF8_ALIGNED2(buffer(), lineStartPos) - - Fl_Text_Buffer_mod * buf = mBuffer; - Fl_Text_Buffer_mod *styleBuf = mStyleBuffer; - int pos, style = 0; - - if ( lineStartPos == -1 || buf == NULL ) - return FILL_MASK; - - pos = lineStartPos + min( lineIndex, lineLen ); - - if ( lineIndex >= lineLen ) - style = FILL_MASK; - else if ( styleBuf != NULL ) { - style = ( unsigned char ) styleBuf->byte_at( pos ); - if (style == mUnfinishedStyle && mUnfinishedHighlightCB) { - /* encountered "unfinished" style, trigger parsing */ - (mUnfinishedHighlightCB)( pos, mHighlightCBArg); - style = (unsigned char) styleBuf->byte_at( pos); - } - } - if (buf->primary_selection()->includes(pos)) - style |= PRIMARY_MASK; - if (buf->highlight_selection()->includes(pos)) - style |= HIGHLIGHT_MASK; - if (buf->secondary_selection()->includes(pos)) - style |= SECONDARY_MASK; - return style; -} - - -/** - \brief Find the width of a std::string in the font of a particular style. - - \param std::string the text - \param length number of bytes in std::string - \param style index into style table - \return width of text segment in pixels - */ -double Fl_Text_Display_mod::string_width( const char *dspstring, int length, int style ) const { - IS_UTF8_ALIGNED(std::string) - - Fl_Font font; - Fl_Fontsize fsize; - - if ( mNStyles && (style & STYLE_LOOKUP_MASK) ) { - int si = (style & STYLE_LOOKUP_MASK) - 'A'; - if (si < 0) si = 0; - else if (si >= mNStyles) si = mNStyles - 1; - - font = mStyleTable[si].font; - fsize = mStyleTable[si].size; - } else { - font = textfont(); - fsize = textsize(); - } - fl_font( font, fsize ); - return fl_width( dspstring, length ); -} - - - -/** - \brief Translate a pixel position into a character index. - - Translate window coordinates to the nearest (insert cursor or character - cell) text position. The parameter \p posType specifies how to interpret the - position: CURSOR_POS means translate the coordinates to the nearest cursor - position, and CHARACTER_POS means return the position of the character - closest to (\p X, \p Y). - - \param X, Y pixel position - \param posType CURSOR_POS or CHARACTER_POS - \return index into text buffer - */ -int Fl_Text_Display_mod::xy_to_position( int X, int Y, int posType ) const { - int lineStart, lineLen, fontHeight; - int visLineNum; - - /* Find the visible line number corresponding to the Y coordinate */ - fontHeight = mMaxsize; - visLineNum = ( Y - text_area.y ) / fontHeight; - if ( visLineNum < 0 ) - return mFirstChar; - if ( visLineNum >= mNVisibleLines ) - visLineNum = mNVisibleLines - 1; - - /* Find the position at the start of the line */ - lineStart = mLineStarts[ visLineNum ]; - - /* If the line start was empty, return the last position in the buffer */ - if ( lineStart == -1 ) - return mBuffer->length(); - - /* Get the line text and its length */ - lineLen = vline_length( visLineNum ); - - return handle_vline(FIND_INDEX, - lineStart, lineLen, 0, 0, - 0, 0, - text_area.x, X); -} - - - -/** - \brief Translate pixel coordinates into row and column. - - Translate window coordinates to the nearest row and column number for - positioning the cursor. This, of course, makes no sense when the font is - proportional, since there are no absolute columns. The parameter posType - specifies how to interpret the position: CURSOR_POS means translate the - coordinates to the nearest position between characters, and CHARACTER_POS - means translate the position to the nearest character cell. - - \param X, Y pixel coordinates - \param[out] row, column neares row and column - \param posType CURSOR_POS or CHARACTER_POS - */ -void Fl_Text_Display_mod::xy_to_rowcol( int X, int Y, int *row, - int *column, int posType ) const { - int fontHeight = mMaxsize; - int fontWidth = TMPFONTWIDTH; //mFontStruct->max_bounds.width; - - /* Find the visible line number corresponding to the Y coordinate */ - *row = ( Y - text_area.y ) / fontHeight; - if ( *row < 0 ) *row = 0; - if ( *row >= mNVisibleLines ) *row = mNVisibleLines - 1; - - *column = ( ( X - text_area.x ) + mHorizOffset + - ( posType == CURSOR_POS ? fontWidth / 2 : 0 ) ) / fontWidth; - if ( *column < 0 ) * column = 0; -} - - - -/** - \brief Offset line start counters for a new vertical scroll position. - - Offset the line starts array, mTopLineNum, mFirstChar and lastChar, for a new - vertical scroll position given by newTopLineNum. If any currently displayed - lines will still be visible, salvage the line starts values, otherwise, - count lines from the nearest known line start (start or end of buffer, or - the closest value in the mLineStarts array) - - \param newTopLineNum index into buffer - */ -void Fl_Text_Display_mod::offset_line_starts( int newTopLineNum ) { - int oldTopLineNum = mTopLineNum; - int oldFirstChar = mFirstChar; - int lineDelta = newTopLineNum - oldTopLineNum; - int nVisLines = mNVisibleLines; - int *lineStarts = mLineStarts; - int i, lastLineNum; - Fl_Text_Buffer_mod *buf = mBuffer; - - /* If there was no offset, nothing needs to be changed */ - if ( lineDelta == 0 ) - return; - - /* Find the new value for mFirstChar by counting lines from the nearest - known line start (start or end of buffer, or the closest value in the - lineStarts array) */ - lastLineNum = oldTopLineNum + nVisLines - 1; - if ( newTopLineNum < oldTopLineNum && newTopLineNum < -lineDelta ) { - mFirstChar = skip_lines( 0, newTopLineNum - 1, true ); - } else if ( newTopLineNum < oldTopLineNum ) { - mFirstChar = rewind_lines( mFirstChar, -lineDelta ); - } else if ( newTopLineNum < lastLineNum ) { - mFirstChar = lineStarts[ newTopLineNum - oldTopLineNum ]; - } else if ( newTopLineNum - lastLineNum < mNBufferLines - newTopLineNum ) { - mFirstChar = skip_lines( lineStarts[ nVisLines - 1 ], - newTopLineNum - lastLineNum, true ); - } else { - mFirstChar = rewind_lines( buf->length(), mNBufferLines - newTopLineNum + 1 ); - } - - /* Fill in the line starts array */ - if ( lineDelta < 0 && -lineDelta < nVisLines ) { - for ( i = nVisLines - 1; i >= -lineDelta; i-- ) - lineStarts[ i ] = lineStarts[ i + lineDelta ]; - calc_line_starts( 0, -lineDelta ); - } else if ( lineDelta > 0 && lineDelta < nVisLines ) { - for ( i = 0; i < nVisLines - lineDelta; i++ ) - lineStarts[ i ] = lineStarts[ i + lineDelta ]; - calc_line_starts( nVisLines - lineDelta, nVisLines - 1 ); - } else - calc_line_starts( 0, nVisLines ); - - /* Set lastChar and mTopLineNum */ - calc_last_char(); - mTopLineNum = newTopLineNum; - - /* If we're numbering lines or being asked to maintain an absolute line - number, re-calculate the absolute line number */ - absolute_top_line_number(oldFirstChar); -} - - - -/** - \brief Update line start arrays and variables. - - Update the line starts array, mTopLineNum, mFirstChar and lastChar for this - text display after a modification to the text buffer, given by the - position \p pos where the change began, and the numbers of characters - and lines inserted and deleted. - - \param pos index into buffer of recent changes - \param charsInserted number of bytes(!) inserted - \param charsDeleted number of bytes(!) deleted - \param linesInserted number of lines - \param linesDeleted number of lines - \param[out] scrolled set to 1 if the text display needs to be scrolled - */ -void Fl_Text_Display_mod::update_line_starts(int pos, int charsInserted, - int charsDeleted, int linesInserted, - int linesDeleted, int *scrolled ) { - IS_UTF8_ALIGNED2(buffer(), pos) - - int *lineStarts = mLineStarts; - int i, lineOfPos, lineOfEnd, nVisLines = mNVisibleLines; - int charDelta = charsInserted - charsDeleted; - int lineDelta = linesInserted - linesDeleted; - - /* If all of the changes were before the displayed text, the display - doesn't change, just update the top line num and offset the line - start entries and first and last characters */ - if ( pos + charsDeleted < mFirstChar ) { - mTopLineNum += lineDelta; - for ( i = 0; i < nVisLines && lineStarts[i] != -1; i++ ) - lineStarts[ i ] += charDelta; - mFirstChar += charDelta; - mLastChar += charDelta; - *scrolled = 0; - return; - } - - /* The change began before the beginning of the displayed text, but - part or all of the displayed text was deleted */ - if ( pos < mFirstChar ) { - /* If some text remains in the window, anchor on that */ - if ( position_to_line( pos + charsDeleted, &lineOfEnd ) && - ++lineOfEnd < nVisLines && lineStarts[ lineOfEnd ] != -1 ) { - mTopLineNum = max( 1, mTopLineNum + lineDelta ); - mFirstChar = rewind_lines(lineStarts[ lineOfEnd ] + charDelta, lineOfEnd ); - /* Otherwise anchor on original line number and recount everything */ - } else { - if ( mTopLineNum > mNBufferLines + lineDelta ) { - mTopLineNum = 1; - mFirstChar = 0; - } else - mFirstChar = skip_lines( 0, mTopLineNum - 1, true ); - } - calc_line_starts( 0, nVisLines - 1 ); - /* calculate lastChar by finding the end of the last displayed line */ - calc_last_char(); - *scrolled = 1; - return; - } - - /* If the change was in the middle of the displayed text (it usually is), - salvage as much of the line starts array as possible by moving and - offsetting the entries after the changed area, and re-counting the - added lines or the lines beyond the salvaged part of the line starts - array */ - if ( pos <= mLastChar ) { - /* find line on which the change began */ - position_to_line( pos, &lineOfPos ); - /* salvage line starts after the changed area */ - if ( lineDelta == 0 ) { - for ( i = lineOfPos + 1; i < nVisLines && lineStarts[ i ] != -1; i++ ) - lineStarts[ i ] += charDelta; - } else if ( lineDelta > 0 ) { - for ( i = nVisLines - 1; i >= lineOfPos + lineDelta + 1; i-- ) - lineStarts[ i ] = lineStarts[ i - lineDelta ] + - ( lineStarts[ i - lineDelta ] == -1 ? 0 : charDelta ); - } else /* (lineDelta < 0) */ { - for ( i = max( 0, lineOfPos + 1 ); i < nVisLines + lineDelta; i++ ) - lineStarts[ i ] = lineStarts[ i - lineDelta ] + - ( lineStarts[ i - lineDelta ] == -1 ? 0 : charDelta ); - } - /* fill in the missing line starts */ - if ( linesInserted >= 0 ) - calc_line_starts( lineOfPos + 1, lineOfPos + linesInserted ); - if ( lineDelta < 0 ) - calc_line_starts( nVisLines + lineDelta, nVisLines ); - /* calculate lastChar by finding the end of the last displayed line */ - calc_last_char(); - *scrolled = 0; - return; - } - - /* Change was past the end of the displayed text, but displayable by virtue - of being an insert at the end of the buffer into visible blank lines */ - if ( empty_vlines() ) { - position_to_line( pos, &lineOfPos ); - calc_line_starts( lineOfPos, lineOfPos + linesInserted ); - calc_last_char(); - *scrolled = 0; - return; - } - - /* Change was beyond the end of the buffer and not visible, do nothing */ - *scrolled = 0; -} - - - -/** - \brief Update the line start arrays. - - Scan through the text in the "textD"'s buffer and recalculate the line - starts array values beginning at index "startLine" and continuing through - (including) "endLine". It assumes that the line starts entry preceding - "startLine" (or mFirstChar if startLine is 0) is good, and re-counts - newlines to fill in the requested entries. Out of range values for - "startLine" and "endLine" are acceptable. - - \param startLine, endLine range of lines to scan as line numbers - */ -void Fl_Text_Display_mod::calc_line_starts( int startLine, int endLine ) { - int startPos, bufLen = mBuffer->length(); - int line, lineEnd, nextLineStart, nVis = mNVisibleLines; - int *lineStarts = mLineStarts; - - /* Clean up (possibly) messy input parameters */ - if ( endLine < 0 ) endLine = 0; - if ( endLine >= nVis ) endLine = nVis - 1; - if ( startLine < 0 ) startLine = 0; - if ( startLine >= nVis ) startLine = nVis - 1; - if ( startLine > endLine ) - return; - - /* Find the last known good line number -> position mapping */ - if ( startLine == 0 ) { - lineStarts[ 0 ] = mFirstChar; - startLine = 1; - } - startPos = lineStarts[ startLine - 1 ]; - - /* If the starting position is already past the end of the text, - fill in -1's (means no text on line) and return */ - if ( startPos == -1 ) { - for ( line = startLine; line <= endLine; line++ ) - lineStarts[ line ] = -1; - return; - } - - /* Loop searching for ends of lines and storing the positions of the - start of the next line in lineStarts */ - for ( line = startLine; line <= endLine; line++ ) { - find_line_end(startPos, true, &lineEnd, &nextLineStart); - startPos = nextLineStart; - if ( startPos >= bufLen ) { - /* If the buffer ends with a newline or line break, put - buf->length() in the next line start position (instead of - a -1 which is the normal marker for an empty line) to - indicate that the cursor may safely be displayed there */ - if ( line == 0 || ( lineStarts[ line - 1 ] != bufLen && - lineEnd != nextLineStart ) ) { - lineStarts[ line ] = bufLen; - line++; - } - break; - } - lineStarts[ line ] = startPos; - } - - /* Set any entries beyond the end of the text to -1 */ - for ( ; line <= endLine; line++ ) - lineStarts[ line ] = -1; -} - - - -/** - \brief Update last display character index. - - Given a Fl_Text_Display_mod with a complete, up-to-date lineStarts array, update - the lastChar entry to point to the last buffer position displayed. - */ -void Fl_Text_Display_mod::calc_last_char() { - int i; - for (i = mNVisibleLines - 1; i >= 0 && mLineStarts[i] == -1; i--) ; - mLastChar = i < 0 ? 0 : line_end(mLineStarts[i], true); -} - - - -/** - \brief Scrolls the current buffer to start at the specified line and column. - \param topLineNum top line number - \param horizOffset column number - \todo Column numbers make little sense here. - */ -void Fl_Text_Display_mod::scroll(int topLineNum, int horizOffset) { - mTopLineNumHint = topLineNum; - mHorizOffsetHint = horizOffset; - resize(x(), y(), w(), h()); -} - - - -/** - \brief Scrolls the current buffer to start at the specified line and column. - \param topLineNum top line number - \param horizOffset in pixels - \return 0 if nothing changed, 1 if we scrolled - */ -int Fl_Text_Display_mod::scroll_(int topLineNum, int horizOffset) { - /* Limit the requested scroll position to allowable values */ - if (topLineNum > mNBufferLines + 3 - mNVisibleLines) - topLineNum = mNBufferLines + 3 - mNVisibleLines; - if (topLineNum < 1) topLineNum = 1; - - if (horizOffset > longest_vline() - text_area.w) - horizOffset = longest_vline() - text_area.w; - if (horizOffset < 0) horizOffset = 0; - - /* Do nothing if scroll position hasn't actually changed or there's no - window to draw in yet */ - if (mHorizOffset == horizOffset && mTopLineNum == topLineNum) - return 0; - - /* If the vertical scroll position has changed, update the line - starts array and related counters in the text display */ - offset_line_starts(topLineNum); - - /* Just setting mHorizOffset is enough information for redisplay */ - mHorizOffset = horizOffset; - - // redraw all text - damage(FL_DAMAGE_EXPOSE); - return 1; -} - - - -/** - \brief Update vertical scrollbar. - - Update the minimum, maximum, slider size, page increment, and value - for vertical scrollbar. - */ -void Fl_Text_Display_mod::update_v_scrollbar() { - /* The vertical scrollbar value and slider size directly represent the top - line number, and the number of visible lines respectively. The scroll - bar maximum value is chosen to generally represent the size of the whole - buffer, with minor adjustments to keep the scrollbar widget happy */ -#ifdef DEBUG - printf("Fl_Text_Display_mod::update_v_scrollbar():\n" - " mTopLineNum=%d, mNVisibleLines=%d, mNBufferLines=%d\n", - mTopLineNum, mNVisibleLines, mNBufferLines); -#endif // DEBUG - - mVScrollBar->value(mTopLineNum, mNVisibleLines, 1, mNBufferLines + 2); - mVScrollBar->linesize(3); -} - - -/** - \brief Update vertical scrollbar. - - Update the minimum, maximum, slider size, page increment, and value - for the horizontal scrollbar. - */ -void Fl_Text_Display_mod::update_h_scrollbar() { - int sliderMax = max(longest_vline(), text_area.w + mHorizOffset); - mHScrollBar->value( mHorizOffset, text_area.w, 0, sliderMax ); -} - - - -/** - \brief Callbacks for drag or valueChanged on scrollbars. - */ -void Fl_Text_Display_mod::v_scrollbar_cb(Fl_Scrollbar* b, Fl_Text_Display_mod* textD) { - if (b->value() == textD->mTopLineNum) return; - textD->scroll(b->value(), textD->mHorizOffset); -} - - - -/** - \brief Callbacks for drag or valueChanged on scrollbars. - */ -void Fl_Text_Display_mod::h_scrollbar_cb(Fl_Scrollbar* b, Fl_Text_Display_mod* textD) { - if (b->value() == textD->mHorizOffset) return; - textD->scroll(textD->mTopLineNum, b->value()); -} - - - -/** - \brief Refresh the line number area. - - If clearAll is False, writes only over the character cell areas. Setting - clearAll to True will clear out any stray marks outside of the character cell - area, which might have been left from before a resize or font change. - - This function is not used. - */ -void Fl_Text_Display_mod::draw_line_numbers(bool /*clearAll*/) { -#if 0 - int y, line, visLine, nCols, lineStart; - char lineNumstd::string[12]; - int lineHeight = mMaxsize ? mMaxsize : textsize_; - int charWidth = TMPFONTWIDTH; //mFontStruct->max_bounds.width; - - /* Don't draw if mLineNumWidth == 0 (line numbers are hidden), or widget is - not yet realized */ - if (mLineNumWidth == 0 || visible_r()) - return; - - /* GC is allocated on demand, since not everyone will use line numbering */ - if (textD->lineNumGC == NULL) { - XGCValues values; - values.foreground = textD->lineNumFGPixel; - values.background = textD->bgPixel; - values.font = textD->fontStruct->fid; - textD->lineNumGC = XtGetGC(textD->w, - GCFont| GCForeground | GCBackground, &values); - } - - /* Erase the previous contents of the line number area, if requested */ - if (clearAll) - XClearArea(XtDisplay(textD->w), XtWindow(textD->w), textD->lineNumLeft, - textD->top, textD->lineNumWidth, textD->height, False); - - /* Draw the line numbers, aligned to the text */ - nCols = min(11, textD->lineNumWidth / charWidth); - y = textD->top; - line = getAbsTopLineNum(textD); - for (visLine=0; visLine < textD->nVisibleLines; visLine++) { - lineStart = textD->lineStarts[visLine]; - if (lineStart != -1 && (lineStart==0 || - BufGetCharacter(textD->buffer, lineStart-1)=='\n')) { - sprintf(lineNumstd::string, "%*d", nCols, line); - XDrawImagestd::string(XtDisplay(textD->w), XtWindow(textD->w), - textD->lineNumGC, textD->lineNumLeft, y + textD->ascent, - lineNumstd::string, strlen(lineNumstd::string)); - line++; - } else { - XClearArea(XtDisplay(textD->w), XtWindow(textD->w), - textD->lineNumLeft, y, textD->lineNumWidth, - textD->ascent + textD->descent, False); - if (visLine == 0) - line++; - } - y += lineHeight; - } -#endif -} - -static int max( int i1, int i2 ) { - return i1 >= i2 ? i1 : i2; -} - -static int min( int i1, int i2 ) { - return i1 <= i2 ? i1 : i2; -} - - - -/** - Count the number of newlines in a null-terminated text std::string; - */ -static int countlines( const char *cntstring ) { - IS_UTF8_ALIGNED(std::string) - - const char * c; - int lineCount = 0; - - if (!cntstring) return 0; - - for ( c = cntstring; *c != '\0'; c++ ) - if ( *c == '\n' ) lineCount++; - return lineCount; -} - - - - -/** - \brief Returns the width in pixels of the displayed line pointed to by "visLineNum". - \param visLineNum index into visible lines array - \return width of line in pixels - */ -int Fl_Text_Display_mod::measure_vline( int visLineNum ) const { - int lineLen = vline_length( visLineNum ); - int lineStartPos = mLineStarts[ visLineNum ]; - if (lineStartPos < 0 || lineLen == 0) return 0; - return handle_vline(GET_WIDTH, lineStartPos, lineLen, 0, 0, 0, 0, 0, 0); -} - - - -/** - \brief Return true if there are lines visible with no corresponding buffer text. - \return 1 if there are empty lines - */ -int Fl_Text_Display_mod::empty_vlines() const { - return (mNVisibleLines > 0) && (mLineStarts[ mNVisibleLines - 1 ] == -1); -} - - - -/** - \brief Count number of bytes in a visible line. - - Return the length of a line (number of bytes) by examining - entries in the line starts array rather than by scanning for newlines. - - \param visLineNum index of line in visible line array - \return number of bytes in this line - */ -int Fl_Text_Display_mod::vline_length( int visLineNum ) const { - int nextLineStart, lineStartPos; - - if (visLineNum < 0 || visLineNum >= mNVisibleLines) - return (0); - - lineStartPos = mLineStarts[ visLineNum ]; - - if ( lineStartPos == -1 ) - return 0; - - if ( visLineNum + 1 >= mNVisibleLines ) - return mLastChar - lineStartPos; - - nextLineStart = mLineStarts[ visLineNum + 1 ]; - if ( nextLineStart == -1 ) - return mLastChar - lineStartPos; - - int nextLineStartMinus1 = buffer()->prev_char(nextLineStart); - if (wrap_uses_character(nextLineStartMinus1)) - return nextLineStartMinus1 - lineStartPos; - - return nextLineStart - lineStartPos; -} - - - -/** - \brief Wrapping calculations. - - When continuous wrap is on, and the user inserts or deletes characters, - wrapping can happen before and beyond the changed position. This routine - finds the extent of the changes, and counts the deleted and inserted lines - over that range. It also attempts to minimize the size of the range to - what has to be counted and re-displayed, so the results can be useful - both for delimiting where the line starts need to be recalculated, and - for deciding what part of the text to redisplay. - - \param deletedText - \param pos - \param nInserted - \param nDeleted - \param modRangeStart - \param modRangeEnd - \param linesInserted - \param linesDeleted - */ -void Fl_Text_Display_mod::find_wrap_range(const char *deletedText, int pos, - int nInserted, int nDeleted, - int *modRangeStart, int *modRangeEnd, - int *linesInserted, int *linesDeleted) { - IS_UTF8_ALIGNED(deletedText) - IS_UTF8_ALIGNED2(buffer(), pos) - - int length, retPos, retLines, retLineStart, retLineEnd; - Fl_Text_Buffer_mod *deletedTextBuf, *buf = buffer(); - int nVisLines = mNVisibleLines; - int *lineStarts = mLineStarts; - int countFrom, countTo, lineStart, adjLineStart, i; - int visLineNum = 0, nLines = 0; - - /* - ** Determine where to begin searching: either the previous newline, or - ** if possible, limit to the start of the (original) previous displayed - ** line, using information from the existing line starts array - */ - if (pos >= mFirstChar && pos <= mLastChar) { - for (i=nVisLines-1; i>0; i--) { - if (lineStarts[i] != -1 && pos >= lineStarts[i]) { - break; - } - } - if (i > 0) { - countFrom = lineStarts[i-1]; - visLineNum = i-1; - } else { - countFrom = buf->line_start(pos); - } - } else { - countFrom = buf->line_start(pos); - } - - IS_UTF8_ALIGNED2(buf, countFrom) - - /* - ** Move forward through the (new) text one line at a time, counting - ** displayed lines, and looking for either a real newline, or for the - ** line starts to re-sync with the original line starts array - */ - lineStart = countFrom; - *modRangeStart = countFrom; - for (;;) { - - /* advance to the next line. If the line ended in a real newline - or the end of the buffer, that's far enough */ - wrapped_line_counter(buf, lineStart, buf->length(), 1, true, 0, - &retPos, &retLines, &retLineStart, &retLineEnd); - if (retPos >= buf->length()) { - countTo = buf->length(); - *modRangeEnd = countTo; - if (retPos != retLineEnd) - nLines++; - break; - } else { - lineStart = retPos; - } - nLines++; - if (lineStart > pos + nInserted && buf->char_at(buf->prev_char(lineStart)) == '\n') { - countTo = lineStart; - *modRangeEnd = lineStart; - break; - } - - /* Don't try to resync in continuous wrap mode with non-fixed font - sizes; it would result in a chicken-and-egg dependency between - the calculations for the inserted and the deleted lines. - If we're in that mode, the number of deleted lines is calculated in - advance, without resynchronization, so we shouldn't resynchronize - for the inserted lines either. */ - if (mSuppressResync) - continue; - - /* check for synchronization with the original line starts array - before pos, if so, the modified range can begin later */ - if (lineStart <= pos) { - while (visLineNumprev_char(lineStarts[visLineNum+1])); - else - *modRangeStart = countFrom; - } else - *modRangeStart = min(*modRangeStart, buf->prev_char(lineStart)); - } - - /* check for synchronization with the original line starts array - after pos, if so, the modified range can end early */ - else if (lineStart > pos + nInserted) { - adjLineStart = lineStart - nInserted + nDeleted; - while (visLineNumcopy(buffer(), countFrom, pos, 0); - if (nDeleted != 0) - deletedTextBuf->insert(pos-countFrom, deletedText); - deletedTextBuf->copy(buffer(), pos+nInserted, countTo, pos-countFrom+nDeleted); - /* Note that we need to take into account an offset for the style buffer: - the deletedTextBuf can be out of sync with the style buffer. */ - wrapped_line_counter(deletedTextBuf, 0, length, INT_MAX, true, countFrom, - &retPos, &retLines, &retLineStart, &retLineEnd, false); - delete deletedTextBuf; - *linesDeleted = retLines; - mSuppressResync = 0; -} - - - -/** - \brief Wrapping calculations. - - This is a stripped-down version of the findWrapRange() function above, - intended to be used to calculate the number of "deleted" lines during - a buffer modification. It is called _before_ the modification takes place. - - This function should only be called in continuous wrap mode with a - non-fixed font width. In that case, it is impossible to calculate - the number of deleted lines, because the necessary style information - is no longer available _after_ the modification. In other cases, we - can still perform the calculation afterwards (possibly even more - efficiently). - - \param pos - \param nDeleted - */ -void Fl_Text_Display_mod::measure_deleted_lines(int pos, int nDeleted) { - IS_UTF8_ALIGNED2(buffer(), pos) - - int retPos, retLines, retLineStart, retLineEnd; - Fl_Text_Buffer_mod *buf = buffer(); - int nVisLines = mNVisibleLines; - int *lineStarts = mLineStarts; - int countFrom, lineStart; -// int visLineNum = 0; - int nLines = 0, i; - /* - ** Determine where to begin searching: either the previous newline, or - ** if possible, limit to the start of the (original) previous displayed - ** line, using information from the existing line starts array - */ - if (pos >= mFirstChar && pos <= mLastChar) { - for (i=nVisLines-1; i>0; i--) - if (lineStarts[i] != -1 && pos >= lineStarts[i]) - break; - if (i > 0) { - countFrom = lineStarts[i-1]; -// visLineNum = i-1; - } else - countFrom = buf->line_start(pos); - } else - countFrom = buf->line_start(pos); - - /* - ** Move forward through the (new) text one line at a time, counting - ** displayed lines, and looking for either a real newline, or for the - ** line starts to re-sync with the original line starts array - */ - lineStart = countFrom; - for (;;) { - /* advance to the next line. If the line ended in a real newline - or the end of the buffer, that's far enough */ - wrapped_line_counter(buf, lineStart, buf->length(), 1, true, 0, - &retPos, &retLines, &retLineStart, &retLineEnd); - if (retPos >= buf->length()) { - if (retPos != retLineEnd) - nLines++; - break; - } else - lineStart = retPos; - nLines++; - if (lineStart > pos + nDeleted && buf->char_at(lineStart-1) == '\n') { - break; - } - - /* Unlike in the findWrapRange() function above, we don't try to - resync with the line starts, because we don't know the length - of the inserted text yet, nor the updated style information. - - Because of that, we also shouldn't resync with the line starts - after the modification either, because we must perform the - calculations for the deleted and inserted lines in the same way. - - This can result in some unnecessary recalculation and redrawing - overhead, and therefore we should only use this two-phase mode - of calculation when it's really needed (continuous wrap + variable - font width). */ - } - mNLinesDeleted = nLines; - mSuppressResync = 1; -} - - - -/** - \brief Wrapping calculations. - - Count forward from startPos to either maxPos or maxLines (whichever is - reached first), and return all relevant positions and line count. - The provided textBuffer may differ from the actual text buffer of the - widget. In that case it must be a (partial) copy of the actual text buffer - and the styleBufOffset argument must indicate the starting position of the - copy, to take into account the correct style information. - - \param buf - \param startPos - \param maxPos - \param maxLines - \param startPosIsLineStart - \param styleBufOffset - - \param[out] retPos Position where counting ended. When counting lines, the - position returned is the start of the line "maxLines" lines - beyond "startPos". - \param[out] retLines Number of line breaks counted - \param[out] retLineStart Start of the line where counting ended - \param[out] retLineEnd End position of the last line traversed - \param[out] countLastLineMissingNewLine - */ -void Fl_Text_Display_mod::wrapped_line_counter(Fl_Text_Buffer_mod *buf, int startPos, - int maxPos, int maxLines, bool startPosIsLineStart, int styleBufOffset, - int *retPos, int *retLines, int *retLineStart, int *retLineEnd, - bool countLastLineMissingNewLine) const { - IS_UTF8_ALIGNED2(buf, startPos) - IS_UTF8_ALIGNED2(buf, maxPos) - - int lineStart, newLineStart = 0, b, p, colNum, wrapMarginPix; - int i, foundBreak; - double width; - int nLines = 0; - unsigned int c; - - /* Set the wrap margin to the wrap column or the view width */ - if (mWrapMarginPix != 0) { - wrapMarginPix = mWrapMarginPix; - } else { - wrapMarginPix = text_area.w; - } - - /* Find the start of the line if the start pos is not marked as a - line start. */ - if (startPosIsLineStart) - lineStart = startPos; - else - lineStart = line_start(startPos); - - /* - ** Loop until position exceeds maxPos or line count exceeds maxLines. - ** (actually, continues beyond maxPos to end of line containing maxPos, - ** in case later characters cause a word wrap back before maxPos) - */ - colNum = 0; - width = 0; - for (p=lineStart; plength(); p=buf->next_char(p)) { - c = buf->char_at(p); // UCS-4 - - /* If the character was a newline, count the line and start over, - otherwise, add it to the width and column counts */ - if (c == '\n') { - if (p >= maxPos) { - *retPos = maxPos; - *retLines = nLines; - *retLineStart = lineStart; - *retLineEnd = maxPos; - return; - } - nLines++; - int p1 = buf->next_char(p); - if (nLines >= maxLines) { - *retPos = p1; - *retLines = nLines; - *retLineStart = p1; - *retLineEnd = p; - return; - } - lineStart = p1; - colNum = 0; - width = 0; - } else { - const char *s = buf->address(p); - colNum++; - // FIXME: it is not a good idea to simply add character widths because on - // some platforms, the width is a floating point value and depends on the - // previous character as well. - width += measure_proportional_character(s, (int)width, p+styleBufOffset); - } - - /* If character exceeded wrap margin, find the break point and wrap there */ - if (width > wrapMarginPix) { - foundBreak = false; - for (b=p; b>=lineStart; b=buf->prev_char(b)) { - c = buf->char_at(b); - if (c == '\t' || c == ' ') { - newLineStart = buf->next_char(b); - colNum = 0; - width = 0; - int iMax = buf->next_char(p); - for (i=buf->next_char(b); inext_char(i)) { - width += measure_proportional_character(buf->address(i), (int)width, - i+styleBufOffset); - colNum++; - } - foundBreak = true; - break; - } - } - if (!foundBreak) { /* no whitespace, just break at margin */ - newLineStart = max(p, buf->next_char(lineStart)); - const char *s = buf->address(b); - colNum++; - width = measure_proportional_character(s, 0, p+styleBufOffset); - } - if (p >= maxPos) { - *retPos = maxPos; - *retLines = maxPos < newLineStart ? nLines : nLines + 1; - *retLineStart = maxPos < newLineStart ? lineStart : newLineStart; - *retLineEnd = maxPos; - return; - } - nLines++; - if (nLines >= maxLines) { - *retPos = foundBreak ? buf->next_char(b) : max(p, buf->next_char(lineStart)); - *retLines = nLines; - *retLineStart = lineStart; - *retLineEnd = foundBreak ? b : p; - return; - } - lineStart = newLineStart; - } - } - - /* reached end of buffer before reaching pos or line target */ - *retPos = buf->length(); - *retLines = nLines; - if (countLastLineMissingNewLine && colNum > 0) - *retLines = buf->next_char(*retLines); - *retLineStart = lineStart; - *retLineEnd = buf->length(); -} - - - -/** - \brief Wrapping calculations. - - Measure the width in pixels of the first character of std::string "s" at a - particular column "colNum" and buffer position "pos". This is for measuring - characters in proportional or mixed-width highlighting fonts. - - A note about proportional and mixed-width fonts: the mixed width and - proportional font code in nedit does not get much use in general editing, - because nedit doesn't allow per-language-mode fonts, and editing programs - in a proportional font is usually a bad idea, so very few users would - choose a proportional font as a default. There are still probably mixed- - width syntax highlighting cases where things don't redraw properly for - insertion/deletion, though static display and wrapping and resizing - should now be solid because they are now used for online help display. - - \param s text std::string - \param xPix x pixel position needed for calculating tab widths - \param pos offset within std::string - \return width of character in pixels - */ -double Fl_Text_Display_mod::measure_proportional_character(const char *s, int xPix, int pos) const { - IS_UTF8_ALIGNED(s) - - if (*s=='\t') { - int tab = (int)col_to_x(mBuffer->tab_distance()); - return (((xPix/tab)+1)*tab) - xPix; - } - - int charLen = fl_utf8len1(*s), style = 0; - if (mStyleBuffer) { - style = mStyleBuffer->byte_at(pos); - } - return string_width(s, charLen, style); -} - - - -/** - \brief Finds both the end of the current line and the start of the next line. - - Why? - In continuous wrap mode, if you need to know both, figuring out one from the - other can be expensive or error prone. The problem comes when there's a - trailing space or tab just before the end of the buffer. To translate an - end of line value to or from the next lines start value, you need to know - whether the trailing space or tab is being used as a line break or just a - normal character, and to find that out would otherwise require counting all - the way back to the beginning of the line. - - \param startPos - \param startPosIsLineStart - \param[out] lineEnd - \param[out] nextLineStart - */ -void Fl_Text_Display_mod::find_line_end(int startPos, bool startPosIsLineStart, - int *lineEnd, int *nextLineStart) const { - IS_UTF8_ALIGNED2(buffer(), startPos) - - int retLines, retLineStart; - - /* if we're not wrapping use more efficient BufEndOfLine */ - if (mFastDisplay || !mContinuousWrap) { - int le = buffer()->line_end(startPos); - int ls = buffer()->next_char(le); - *lineEnd = le; - *nextLineStart = min(buffer()->length(), ls); - return; - } - - /* use the wrapped line counter routine to count forward one line */ - wrapped_line_counter(buffer(), startPos, buffer()->length(), - 1, startPosIsLineStart, 0, nextLineStart, &retLines, - &retLineStart, lineEnd); -} - - - -/** - \brief Check if the line break is caused by a \\n or by line wrapping. - - Line breaks in continuous wrap mode usually happen at newlines or - whitespace. This line-terminating character is not included in line - width measurements and has a special status as a non-visible character. - However, lines with no whitespace are wrapped without the benefit of a - line terminating character, and this distinction causes endless trouble - with all of the text display code which was originally written without - continuous wrap mode and always expects to wrap at a newline character. - - Given the position of the end of the line, as returned by TextDEndOfLine - or BufEndOfLine, this returns true if there is a line terminating - character, and false if there's not. On the last character in the - buffer, this function can't tell for certain whether a trailing space was - used as a wrap point, and just guesses that it wasn't. So if an exact - accounting is necessary, don't use this function. - - \param lineEndPos index of character where the line wraps - \return 1 if a \\n character causes the line wrap - */ -int Fl_Text_Display_mod::wrap_uses_character(int lineEndPos) const { - IS_UTF8_ALIGNED2(buffer(), lineEndPos) - - unsigned int c; - - if (mFastDisplay || !mContinuousWrap || lineEndPos == buffer()->length()) - return 1; - - c = buffer()->char_at(lineEndPos); - return c == '\n' || ((c == '\t' || c == ' ') && - lineEndPos + 1 < buffer()->length()); -} - -/** - \brief I don't know what this does! - - Extend the range of a redraw request (from *start to *end) with additional - redraw requests resulting from changes to the attached style buffer (which - contains auxiliary information for coloring or styling text). - - \param startpos ?? - \param endpos ?? - - \todo Unicode? - */ -void Fl_Text_Display_mod::extend_range_for_styles( int *startpos, int *endpos ) { - IS_UTF8_ALIGNED2(buffer(), (*startpos)) - IS_UTF8_ALIGNED2(buffer(), (*endpos)) - - Fl_Text_Selection_mod * sel = mStyleBuffer->primary_selection(); - int extended = 0; - - /* The peculiar protocol used here is that modifications to the style - buffer are marked by selecting them with the buffer's primary Fl_Text_Selection. - The style buffer is usually modified in response to a modify callback on - the text buffer BEFORE Fl_Text_Display_mod.c's modify callback, so that it can keep - the style buffer in step with the text buffer. The style-update - callback can't just call for a redraw, because Fl_Text_Display_mod hasn't processed - the original text changes yet. Anyhow, to minimize redrawing and to - avoid the complexity of scheduling redraws later, this simple protocol - tells the text display's buffer modify callback to extend its redraw - range to show the text color/and font changes as well. */ - if ( sel->selected() ) { - if ( sel->start() < *startpos ) { - *startpos = sel->start(); - // somewhere while deleting, alignment is lost. We do this just to be sure. - *startpos = buffer()->utf8_align(*startpos); - IS_UTF8_ALIGNED2(buffer(), (*startpos)) - extended = 1; - } - if ( sel->end() > *endpos ) { - *endpos = sel->end(); - *endpos = buffer()->utf8_align(*endpos); - IS_UTF8_ALIGNED2(buffer(), (*endpos)) - extended = 1; - } - } - - /* If the Fl_Text_Selection was extended due to a style change, and some of the - fonts don't match in spacing, extend redraw area to end of line to - redraw characters exposed by possible font size changes */ - if ( extended ) - *endpos = mBuffer->line_end( *endpos ) + 1; - - IS_UTF8_ALIGNED2(buffer(), (*endpos)) -} - - - -/** - \brief Draw the widget. - - This function tries to limit drawing to smaller areas if possible. - */ -void Fl_Text_Display_mod::draw(void) { - // don't even try if there is no associated text buffer! - if (!buffer()) { draw_box(); return; } - - fl_push_clip(x(),y(),w(),h()); // prevent drawing outside widget area - - // draw the non-text, non-scrollbar areas. - if (damage() & FL_DAMAGE_ALL) { - // draw the box() - int W = w(), H = h(); - draw_box(box(), x(), y(), W, H, color()); - - if (mHScrollBar->visible()) - W -= scrollbar_width(); - if (mVScrollBar->visible()) - H -= scrollbar_width(); - - // left margin - fl_rectf(text_area.x-LEFT_MARGIN, text_area.y-TOP_MARGIN, - LEFT_MARGIN, text_area.h+TOP_MARGIN+BOTTOM_MARGIN, - color()); - - // right margin - fl_rectf(text_area.x+text_area.w, text_area.y-TOP_MARGIN, - RIGHT_MARGIN, text_area.h+TOP_MARGIN+BOTTOM_MARGIN, - color()); - - // top margin - fl_rectf(text_area.x, text_area.y-TOP_MARGIN, - text_area.w, TOP_MARGIN, color()); - - // bottom margin - fl_rectf(text_area.x, text_area.y+text_area.h, - text_area.w, BOTTOM_MARGIN, color()); - - // draw that little box in the corner of the scrollbars - if (mVScrollBar->visible() && mHScrollBar->visible()) - fl_rectf(mVScrollBar->x(), mHScrollBar->y(), - mVScrollBar->w(), mHScrollBar->h(), - FL_GRAY); - - // blank the previous cursor protrusions - } - else if (damage() & (FL_DAMAGE_SCROLL | FL_DAMAGE_EXPOSE)) { - // printf("blanking previous cursor extrusions at Y: %d\n", mCursorOldY); - // CET - FIXME - save old cursor position instead and just draw side needed? - fl_push_clip(text_area.x-LEFT_MARGIN, - text_area.y, - text_area.w+LEFT_MARGIN+RIGHT_MARGIN, - text_area.h); - fl_rectf(text_area.x-LEFT_MARGIN, mCursorOldY, - LEFT_MARGIN, mMaxsize, color()); - fl_rectf(text_area.x+text_area.w, mCursorOldY, - RIGHT_MARGIN, mMaxsize, color()); - fl_pop_clip(); - } - - // draw the scrollbars - if (damage() & (FL_DAMAGE_ALL | FL_DAMAGE_CHILD)) { - mVScrollBar->damage(FL_DAMAGE_ALL); - mHScrollBar->damage(FL_DAMAGE_ALL); - } - update_child(*mVScrollBar); - update_child(*mHScrollBar); - - // draw all of the text - if (damage() & (FL_DAMAGE_ALL | FL_DAMAGE_EXPOSE)) { - //printf("drawing all text\n"); - int X, Y, W, H; - if (fl_clip_box(text_area.x, text_area.y, text_area.w, text_area.h, - X, Y, W, H)) { - // Draw text using the intersected clipping box... - // (this sets the clipping internally) - draw_text(X, Y, W, H); - } else { - // Draw the whole area... - draw_text(text_area.x, text_area.y, text_area.w, text_area.h); - } - } - else if (damage() & FL_DAMAGE_SCROLL) { - // draw some lines of text - fl_push_clip(text_area.x, text_area.y, - text_area.w, text_area.h); - //printf("drawing text from %d to %d\n", damage_range1_start, damage_range1_end); - draw_range(damage_range1_start, damage_range1_end); - if (damage_range2_end != -1) { - //printf("drawing text from %d to %d\n", damage_range2_start, damage_range2_end); - draw_range(damage_range2_start, damage_range2_end); - } - damage_range1_start = damage_range1_end = -1; - damage_range2_start = damage_range2_end = -1; - fl_pop_clip(); - } - - // draw the text cursor - if (damage() & (FL_DAMAGE_ALL | FL_DAMAGE_SCROLL | FL_DAMAGE_EXPOSE) - && !buffer()->primary_selection()->selected() && - mCursorOn && Fl::focus() == (Fl_Widget*)this ) { - fl_push_clip(text_area.x-LEFT_MARGIN, - text_area.y, - text_area.w+LEFT_MARGIN+RIGHT_MARGIN, - text_area.h); - - int X, Y; - if (position_to_xy(mCursorPos, &X, &Y)) draw_cursor(X, Y); - // else puts("position_to_xy() failed - unable to draw cursor!"); - //printf("drew cursor at pos: %d (%d,%d)\n", mCursorPos, X, Y); - mCursorOldY = Y; - fl_pop_clip(); - } - fl_pop_clip(); -} - - - -// this processes drag events due to mouse for Fl_Text_Display_mod and -// also drags due to cursor movement with shift held down for -// Fl_Text_Editor_mod -void fl_text_drag_me(int pos, Fl_Text_Display_mod* d) { - if (d->dragType == Fl_Text_Display_mod::DRAG_CHAR) { - if (pos >= d->dragPos) { - d->buffer()->select(d->dragPos, pos); - } else { - d->buffer()->select(pos, d->dragPos); - } - d->insert_position(pos); - } else if (d->dragType == Fl_Text_Display_mod::DRAG_WORD) { - if (pos >= d->dragPos) { - d->insert_position(d->word_end(pos)); - d->buffer()->select(d->word_start(d->dragPos), d->word_end(pos)); - } else { - d->insert_position(d->word_start(pos)); - d->buffer()->select(d->word_start(pos), d->word_end(d->dragPos)); - } - } else if (d->dragType == Fl_Text_Display_mod::DRAG_LINE) { - if (pos >= d->dragPos) { - d->insert_position(d->buffer()->line_end(pos)+1); - d->buffer()->select(d->buffer()->line_start(d->dragPos), - d->buffer()->line_end(pos)+1); - } else { - d->insert_position(d->buffer()->line_start(pos)); - d->buffer()->select(d->buffer()->line_start(pos), - d->buffer()->line_end(d->dragPos)+1); - } - } -} - - - -/** - \brief Timer callback for scroll events. - - This timer event scrolls the text view proportionally to - how far the mouse pointer has left the text area. This - allows for smooth scrolling without "wiggeling" the mouse. - */ -void Fl_Text_Display_mod::scroll_timer_cb(void *user_data) { - Fl_Text_Display_mod *w = (Fl_Text_Display_mod*)user_data; - int pos; - switch (scroll_direction) { - case 1: // mouse is to the right, scroll left - w->scroll(w->mTopLineNum, w->mHorizOffset + scroll_amount); - pos = w->xy_to_position(w->text_area.x + w->text_area.w, scroll_y, CURSOR_POS); - break; - case 2: // mouse is to the left, scroll right - w->scroll(w->mTopLineNum, w->mHorizOffset + scroll_amount); - pos = w->xy_to_position(w->text_area.x, scroll_y, CURSOR_POS); - break; - case 3: // mouse is above, scroll down - w->scroll(w->mTopLineNum + scroll_amount, w->mHorizOffset); - pos = w->xy_to_position(scroll_x, w->text_area.y, CURSOR_POS); - break; - case 4: // mouse is below, scroll up - w->scroll(w->mTopLineNum + scroll_amount, w->mHorizOffset); - pos = w->xy_to_position(scroll_x, w->text_area.y + w->text_area.h, CURSOR_POS); - break; - default: - return; - } - fl_text_drag_me(pos, w); - Fl::repeat_timeout(.1, scroll_timer_cb, user_data); -} - - - -/** - \brief Event handling. - */ -int Fl_Text_Display_mod::handle(int event) { - if (!buffer()) return 0; - // This isn't very elegant! - if (!Fl::event_inside(text_area.x, text_area.y, text_area.w, text_area.h) && - !dragging && event != FL_LEAVE && event != FL_ENTER && - event != FL_MOVE && event != FL_FOCUS && event != FL_UNFOCUS && - event != FL_KEYBOARD && event != FL_KEYUP) { - return Fl_Group::handle(event); - } - - switch (event) { - case FL_ENTER: - case FL_MOVE: - if (active_r()) { - if (Fl::event_inside(text_area.x, text_area.y, text_area.w, - text_area.h)) window()->cursor(FL_CURSOR_INSERT); - else window()->cursor(FL_CURSOR_DEFAULT); - return 1; - } else { - return 0; - } - - case FL_LEAVE: - case FL_HIDE: - if (active_r() && window()) { - window()->cursor(FL_CURSOR_DEFAULT); - - return 1; - } else { - return 0; - } - - case FL_PUSH: { - if (active_r() && window()) { - if (Fl::event_inside(text_area.x, text_area.y, text_area.w, - text_area.h)) window()->cursor(FL_CURSOR_INSERT); - else window()->cursor(FL_CURSOR_DEFAULT); - } - - if (Fl::focus() != this) { - Fl::focus(this); - handle(FL_FOCUS); - } - if (Fl_Group::handle(event)) return 1; - if (Fl::event_state()&FL_SHIFT) return handle(FL_DRAG); - dragging = 1; - int pos = xy_to_position(Fl::event_x(), Fl::event_y(), CURSOR_POS); - dragPos = pos; - if (buffer()->primary_selection()->includes(pos)) { - dragType = DRAG_START_DND; - return 1; - } - dragType = Fl::event_clicks(); - if (dragType == DRAG_CHAR) { - buffer()->unselect(); -// Fl::copy("", 0, 0); /* removed for STR 2668 */ - } - else if (dragType == DRAG_WORD) { - buffer()->select(word_start(pos), word_end(pos)); - dragPos = word_start(pos); - } - - if (buffer()->primary_selection()->selected()) - insert_position(buffer()->primary_selection()->end()); - else - insert_position(pos); - show_insert_position(); - return 1; - } - - case FL_DRAG: { - if (dragType==DRAG_NONE) - return 1; - if (dragType==DRAG_START_DND) { - if (!Fl::event_is_click() && Fl::dnd_text_ops()) { - const char* copy = buffer()->selection_text(); - Fl::dnd(); - free((void*)copy); - } - return 1; - } - int X = Fl::event_x(), Y = Fl::event_y(), pos = insert_position(); - // if we leave the text_area, we start a timer event - // that will take care of scrolling and selecting - if (Y < text_area.y) { - scroll_x = X; - scroll_amount = (Y - text_area.y) / 5 - 1; - if (!scroll_direction) { - Fl::add_timeout(.01, scroll_timer_cb, this); - } - scroll_direction = 3; - } else if (Y >= text_area.y+text_area.h) { - scroll_x = X; - scroll_amount = (Y - text_area.y - text_area.h) / 5 + 1; - if (!scroll_direction) { - Fl::add_timeout(.01, scroll_timer_cb, this); - } - scroll_direction = 4; - } else if (X < text_area.x) { - scroll_y = Y; - scroll_amount = (X - text_area.x) / 2 - 1; - if (!scroll_direction) { - Fl::add_timeout(.01, scroll_timer_cb, this); - } - scroll_direction = 2; - } else if (X >= text_area.x+text_area.w) { - scroll_y = Y; - scroll_amount = (X - text_area.x - text_area.w) / 2 + 1; - if (!scroll_direction) { - Fl::add_timeout(.01, scroll_timer_cb, this); - } - scroll_direction = 1; - } else { - if (scroll_direction) { - Fl::remove_timeout(scroll_timer_cb, this); - scroll_direction = 0; - } - pos = xy_to_position(X, Y, CURSOR_POS); - pos = buffer()->next_char(pos); - } - fl_text_drag_me(pos, this); - return 1; - } - - case FL_RELEASE: { - if (Fl::event_is_click() && (! Fl::event_clicks()) && - buffer()->primary_selection()->includes(dragPos) && !(Fl::event_state()&FL_SHIFT) ) { - buffer()->unselect(); // clicking in the selection: unselect and move cursor - insert_position(dragPos); - return 1; - } else if (Fl::event_clicks() == DRAG_LINE && Fl::event_button() == FL_LEFT_MOUSE) { - buffer()->select(buffer()->line_start(dragPos), buffer()->next_char(buffer()->line_end(dragPos))); - dragPos = line_start(dragPos); - dragType = DRAG_CHAR; - } else { - dragging = 0; - if (scroll_direction) { - Fl::remove_timeout(scroll_timer_cb, this); - scroll_direction = 0; - } - - // convert from WORD or LINE selection to CHAR - /*if (insert_position() >= dragPos) - dragPos = buffer()->primary_selection()->start(); - else - dragPos = buffer()->primary_selection()->end();*/ - dragType = DRAG_CHAR; - } - - const char* copy = buffer()->selection_text(); - if (*copy) Fl::copy(copy, strlen(copy), 0); - free((void*)copy); - return 1; - } - - case FL_MOUSEWHEEL: - if (Fl::event_dy()) return mVScrollBar->handle(event); - else return mHScrollBar->handle(event); - - case FL_UNFOCUS: - if (active_r() && window()) window()->cursor(FL_CURSOR_DEFAULT); - case FL_FOCUS: - if (buffer()->selected()) { - int start, end; - if (buffer()->selection_position(&start, &end)) - redisplay_range(start, end); - } - if (buffer()->secondary_selected()) { - int start, end; - if (buffer()->secondary_selection_position(&start, &end)) - redisplay_range(start, end); - } - if (buffer()->highlight()) { - int start, end; - if (buffer()->highlight_position(&start, &end)) - redisplay_range(start, end); - } - return 1; - - case FL_KEYBOARD: - // Copy? - if ((Fl::event_state()&(FL_CTRL|FL_COMMAND)) && Fl::event_key()=='c') { - if (!buffer()->selected()) return 1; - const char *copy = buffer()->selection_text(); - if (*copy) Fl::copy(copy, strlen(copy), 1); - free((void*)copy); - return 1; - } - - // Select all ? - if ((Fl::event_state()&(FL_CTRL|FL_COMMAND)) && Fl::event_key()=='a') { - buffer()->select(0,buffer()->length()); - const char *copy = buffer()->selection_text(); - if (*copy) Fl::copy(copy, strlen(copy), 0); - free((void*)copy); - return 1; - } - - if (mVScrollBar->handle(event)) return 1; - if (mHScrollBar->handle(event)) return 1; - - break; - - case FL_SHORTCUT: - if (!(shortcut() ? Fl::test_shortcut(shortcut()) : test_shortcut())) - return 0; - if (Fl::visible_focus() && handle(FL_FOCUS)) { - Fl::focus(this); - return 1; - } - break; - - } - - return 0; -} - - -/* - Convert an x pixel position into a column number. - */ -double Fl_Text_Display_mod::x_to_col(double y) const -{ - if (!mColumnScale) { - mColumnScale = string_width("Mitg", 4, 'A') / 4.0; - } - return (y/mColumnScale)+0.5; -} - - -/** - Convert a column number into an x pixel position. - */ -double Fl_Text_Display_mod::col_to_x(double col) const -{ - if (!mColumnScale) { - // recalculate column scale value - x_to_col(0); - } - return col*mColumnScale; -} - -// -// End of "$Id: Fl_Text_Display_mod.cxx 8808 2011-06-16 13:31:25Z manolo $". -// diff --git a/src/widgets/Fl_Text_Editor_mod.cxx b/src/widgets/Fl_Text_Editor_mod.cxx index df7ab1b..8265127 100644 --- a/src/widgets/Fl_Text_Editor_mod.cxx +++ b/src/widgets/Fl_Text_Editor_mod.cxx @@ -1,27 +1,667 @@ -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ // -// This file is part of flmsg +// "$Id: Fl_Text_Editor_mod.cxx 8034 2010-12-15 12:21:55Z AlbrechtS $" // -// flrig 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. +// Copyright 2001-2010 by Bill Spitzak and others. +// Original code Copyright Mark Edel. Permission to distribute under +// the LGPL for the FLTK library granted by Mark Edel. // -// flrig is distributed in the hope that it will be useful, +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Library General Public +// License as published by the Free Software Foundation; either +// version 2 of the License, or (at your option) any later version. +// +// This library 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. +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Library 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 . -// ---------------------------------------------------------------------------- +// You should have received a copy of the GNU Library General Public +// License along with this library; if not, write to the +// +// Free Software Foundation, Inc. +// 51 Franklin Street, Fifth Floor +// Boston, MA 02110-1301 USA. +// +// Please report all bugs and problems on the following page: +// +// http://www.fltk.org/str.php +// + +#include +#include +#include "missing_strings.h" +#include +#include +#include +#include +#include "Fl_Text_Editor_mod.H" #include +#include "debug.h" -#if FLMSG_FLTK_API_MINOR < 3 -# include "Fl_Text_Editor_mod_1_1.cxx" -#else -# include "Fl_Text_Editor_mod_1_3.cxx" +#if FLCLUSTER_FLTK_API_MAJOR == 1 && FLCLUSTER_FLTK_API_MINOR < 3 +# error "FLTK versions less then 1.3 are no longer supported" #endif + +/* Keyboard Control Matrix + + key\modifier plain Ctrl Alt Meta + --------------------------------------- + left 1/1 13/9 0/13 0/9 + right 2/2 14/10 0/14 0/10 + up 3/19 21/7 0/15 0/17 + down 4/20 22/8 0/16 0/18 + home 9/5 17/0 0/0 0/0 + end 10/6 18/0 0/0 0/0 + page up 11/7 23/0 0/11 0/0 + page down 12/8 24/0 0/12 0/0 + + (FLTK action / OS X action) + (adding the shift key extends the selection, all other combinations are no-op) + + 0: no-op + 1: move cursor to the left, at line beginning wrap to end of prev line, at doc start no-op + 2: move cursor to the right, at line end move to beginning of the next line, at doc end no-op + 3: move cursor up, at doc top no-op + 4: move cursor down, at doc bottom no-op + 5: scroll display to top of text (cursor unchanged) + 6: scroll display to end of text (cursor unchanged) + 7: scroll text down one page (cursor unchanged) + 8: scroll text up one page (cursor unchanged) + 9: move cursor to beginning of line + 10: move cursor to end of line + 11: move cursor up one page and scroll down + 12: move cursor down one page and scroll up + 13: move to the beginning of the word or the previous word + 14: move to the end of the word or the next word + 15: if start of line: start of prev line, else start of this line + 16: if end of line: end of next line, else end of this line + 17: move cursor to the beginning of the document + 18: move cursor to the end of the document + 19: move cursor up, at doc top: home, at doc start: no-op) + 20: move cursor down, at doc bot: end, at doc end: no-op) + 21: scroll text down one line (cursor unchanged) + 22: scroll text up one line (cursor unchanged) + 23: move cursor to the beginning of the top of the screen + 24: move cursor to the beginning of the bottom of the window + */ + +/** The constructor creates a new text editor widget.*/ +Fl_Text_Editor_mod::Fl_Text_Editor_mod(int X, int Y, int W, int H, const char* l) +: Fl_Text_Display_mod(X, Y, W, H, l) { + mCursorOn = 1; + insert_mode_ = 1; + key_bindings = 0; + + // handle the default key bindings + add_default_key_bindings(&key_bindings); + + // handle everything else + default_key_function(kf_default); +} + +#ifndef FL_DOXYGEN +Fl_Text_Editor_mod::Key_Binding* Fl_Text_Editor_mod::global_key_bindings = 0; +#endif + +// These are the default key bindings every widget should start with +static struct { + int key; + int state; + Fl_Text_Editor_mod::Key_Func func; +} default_key_bindings[] = { + { FL_Escape, Fl_Text_Editor_mod_ANY_STATE, Fl_Text_Editor_mod::kf_ignore }, + { FL_Enter, Fl_Text_Editor_mod_ANY_STATE, Fl_Text_Editor_mod::kf_enter }, + { FL_KP_Enter, Fl_Text_Editor_mod_ANY_STATE, Fl_Text_Editor_mod::kf_enter }, + { FL_BackSpace, Fl_Text_Editor_mod_ANY_STATE, Fl_Text_Editor_mod::kf_backspace }, + { FL_Insert, Fl_Text_Editor_mod_ANY_STATE, Fl_Text_Editor_mod::kf_insert }, + { FL_Delete, Fl_Text_Editor_mod_ANY_STATE, Fl_Text_Editor_mod::kf_delete }, + { FL_Home, 0, Fl_Text_Editor_mod::kf_move }, + { FL_End, 0, Fl_Text_Editor_mod::kf_move }, + { FL_Left, 0, Fl_Text_Editor_mod::kf_move }, + { FL_Up, 0, Fl_Text_Editor_mod::kf_move }, + { FL_Right, 0, Fl_Text_Editor_mod::kf_move }, + { FL_Down, 0, Fl_Text_Editor_mod::kf_move }, + { FL_Page_Up, 0, Fl_Text_Editor_mod::kf_move }, + { FL_Page_Down, 0, Fl_Text_Editor_mod::kf_move }, + { FL_Home, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, + { FL_End, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, + { FL_Left, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, + { FL_Up, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, + { FL_Right, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, + { FL_Down, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, + { FL_Page_Up, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, + { FL_Page_Down, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, + { FL_Home, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, + { FL_End, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, + { FL_Left, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, + { FL_Up, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, + { FL_Right, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, + { FL_Down, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, + { FL_Page_Up, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, + { FL_Page_Down, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, + { FL_Home, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, + { FL_End, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, + { FL_Left, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, + { FL_Up, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, + { FL_Right, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, + { FL_Down, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, + { FL_Page_Up, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, + { FL_Page_Down, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, + //{ FL_Clear, 0, Fl_Text_Editor_mod::delete_to_eol }, + { 'z', FL_CTRL, Fl_Text_Editor_mod::kf_undo }, + { '/', FL_CTRL, Fl_Text_Editor_mod::kf_undo }, + { FL_Home, FL_SHIFT, Fl_Text_Editor_mod::kf_undo }, + { 'x', FL_CTRL, Fl_Text_Editor_mod::kf_cut }, + { FL_Delete, FL_SHIFT, Fl_Text_Editor_mod::kf_cut }, + { 'c', FL_CTRL, Fl_Text_Editor_mod::kf_copy }, + { FL_Insert, FL_CTRL, Fl_Text_Editor_mod::kf_copy }, + { 'v', FL_CTRL, Fl_Text_Editor_mod::kf_paste }, + { FL_Insert, FL_SHIFT, Fl_Text_Editor_mod::kf_paste }, + { 'a', FL_CTRL, Fl_Text_Editor_mod::kf_select_all }, + +#ifdef __APPLE__ + // Define CMD+key accelerators... + { 'z', FL_COMMAND, Fl_Text_Editor_mod::kf_undo }, + { 'x', FL_COMMAND, Fl_Text_Editor_mod::kf_cut }, + { 'c', FL_COMMAND, Fl_Text_Editor_mod::kf_copy }, + { 'v', FL_COMMAND, Fl_Text_Editor_mod::kf_paste }, + { 'a', FL_COMMAND, Fl_Text_Editor_mod::kf_select_all }, + { FL_Left, FL_COMMAND, Fl_Text_Editor_mod::kf_meta_move }, + { FL_Right, FL_COMMAND, Fl_Text_Editor_mod::kf_meta_move }, + { FL_Up, FL_COMMAND, Fl_Text_Editor_mod::kf_meta_move }, + { FL_Down, FL_COMMAND, Fl_Text_Editor_mod::kf_meta_move }, + { FL_Left, FL_COMMAND|FL_SHIFT, Fl_Text_Editor_mod::kf_m_s_move }, + { FL_Right, FL_COMMAND|FL_SHIFT, Fl_Text_Editor_mod::kf_m_s_move }, + { FL_Up, FL_COMMAND|FL_SHIFT, Fl_Text_Editor_mod::kf_m_s_move }, + { FL_Down, FL_COMMAND|FL_SHIFT, Fl_Text_Editor_mod::kf_m_s_move }, +#endif // __APPLE__ + + { 0, 0, 0 } +}; + +/** Adds all of the default editor key bindings to the specified key binding list.*/ +void Fl_Text_Editor_mod::add_default_key_bindings(Key_Binding** list) { + for (int i = 0; default_key_bindings[i].key; i++) { + add_key_binding(default_key_bindings[i].key, + default_key_bindings[i].state, + default_key_bindings[i].func, + list); + } +} + +/** Returns the function associated with a key binding.*/ +Fl_Text_Editor_mod::Key_Func Fl_Text_Editor_mod::bound_key_function(int key, int state, Key_Binding* list) { + Key_Binding* cur; + if (!list) return 0; + for (cur = list; cur; cur = cur->next) + if (cur->key == key) + if (cur->state == Fl_Text_Editor_mod_ANY_STATE || cur->state == state) + break; + if (!cur) return 0; + return cur->function; +} + +/** Removes all of the key bindings associated with the text editor or list.*/ +void Fl_Text_Editor_mod::remove_all_key_bindings(Key_Binding** list) { + Key_Binding *cur, *next; + for (cur = *list; cur; cur = next) { + next = cur->next; + delete cur; + } + *list = 0; +} + +/** Removes the key binding associated with the key "key" of state "state" */ +void Fl_Text_Editor_mod::remove_key_binding(int key, int state, Key_Binding** list) { + Key_Binding *cur, *last = 0; + for (cur = *list; cur; last = cur, cur = cur->next) + if (cur->key == key && cur->state == state) break; + if (!cur) return; + if (last) last->next = cur->next; + else *list = cur->next; + delete cur; +} +/** Adds a key of state "state" with the function "function" */ +void Fl_Text_Editor_mod::add_key_binding(int key, int state, Key_Func function, + Key_Binding** list) { + Key_Binding* kb = new Key_Binding; + kb->key = key; + kb->state = state; + kb->function = function; + kb->next = *list; + *list = kb; +} + +//////////////////////////////////////////////////////////////// + +static void kill_selection(Fl_Text_Editor_mod* e) { + if (e->buffer()->selected()) { + e->insert_position(e->buffer()->primary_selection()->start()); + e->buffer()->remove_selection(); + } +} + +/** Inserts the text associated with the key */ +int Fl_Text_Editor_mod::kf_default(int c, Fl_Text_Editor_mod* e) { + // FIXME: this function is a mess! Fix this! + if (!c || (!isprint(c) && c != '\t')) return 0; + char s[2] = "\0"; + s[0] = (char)c; + kill_selection(e); + if (e->insert_mode()) e->insert(s); + else e->overstrike(s); + e->show_insert_position(); + e->set_changed(); + if (e->when()&FL_WHEN_CHANGED) e->do_callback(); + return 1; +} + +/** Ignores the keypress */ +int Fl_Text_Editor_mod::kf_ignore(int, Fl_Text_Editor_mod*) { + return 0; // don't handle +} +/** Does a backspace in the current buffer.*/ +int Fl_Text_Editor_mod::kf_backspace(int, Fl_Text_Editor_mod* e) { + if (!e->buffer()->selected() && e->move_left()) { + int p1 = e->insert_position(); + int p2 = e->buffer()->next_char(p1); + e->buffer()->select(p1, p2); + } + kill_selection(e); + e->show_insert_position(); + e->set_changed(); + if (e->when()&FL_WHEN_CHANGED) e->do_callback(); + return 1; +} + +/** Inserts a newline at the current cursor position */ +int Fl_Text_Editor_mod::kf_enter(int, Fl_Text_Editor_mod* e) { + kill_selection(e); + e->insert("\n"); + e->show_insert_position(); + e->set_changed(); + if (e->when()&FL_WHEN_CHANGED) e->do_callback(); + return 1; +} + +extern void fl_text_drag_me(int pos, Fl_Text_Display_mod* d); +/** Moves the text cursor in the direction indicated by key c.*/ +int Fl_Text_Editor_mod::kf_move(int c, Fl_Text_Editor_mod* e) { + int i; + int selected = e->buffer()->selected(); + if (!selected) + e->dragPos = e->insert_position(); + e->buffer()->unselect(); + Fl::copy("", 0, 0); + switch (c) { + case FL_Home: + e->insert_position(e->buffer()->line_start(e->insert_position())); + break; + case FL_End: + e->insert_position(e->buffer()->line_end(e->insert_position())); + break; + case FL_Left: + e->move_left(); + break; + case FL_Right: + e->move_right(); + break; + case FL_Up: + e->move_up(); + break; + case FL_Down: + e->move_down(); + break; + case FL_Page_Up: + for (i = 0; i < e->mNVisibleLines - 1; i++) e->move_up(); + break; + case FL_Page_Down: + for (i = 0; i < e->mNVisibleLines - 1; i++) e->move_down(); + break; + } + e->show_insert_position(); + return 1; +} + +/** Extends the current selection in the direction of key c.*/ +int Fl_Text_Editor_mod::kf_shift_move(int c, Fl_Text_Editor_mod* e) { + kf_move(c, e); + fl_text_drag_me(e->insert_position(), e); + char *copy = e->buffer()->selection_text(); + if (copy) { + Fl::copy(copy, strlen(copy), 0); + free(copy); + } + return 1; +} +/** Moves the current text cursor in the direction indicated by control key */ +int Fl_Text_Editor_mod::kf_ctrl_move(int c, Fl_Text_Editor_mod* e) { + if (!e->buffer()->selected()) + e->dragPos = e->insert_position(); + if (c != FL_Up && c != FL_Down) { + e->buffer()->unselect(); + Fl::copy("", 0, 0); + e->show_insert_position(); + } + switch (c) { + case FL_Home: + e->insert_position(0); + e->scroll(0, 0); + break; + case FL_End: + e->insert_position(e->buffer()->length()); + e->scroll(e->count_lines(0, e->buffer()->length(), 1), 0); + break; + case FL_Left: + e->previous_word(); + break; + case FL_Right: + e->next_word(); + break; + case FL_Up: + e->scroll(e->mTopLineNum-1, e->mHorizOffset); + break; + case FL_Down: + e->scroll(e->mTopLineNum+1, e->mHorizOffset); + break; + case FL_Page_Up: + e->insert_position(e->mLineStarts[0]); + break; + case FL_Page_Down: + e->insert_position(e->mLineStarts[e->mNVisibleLines-2]); + break; + } + return 1; +} + +/** Moves the current text cursor in the direction indicated by meta key */ +int Fl_Text_Editor_mod::kf_meta_move(int c, Fl_Text_Editor_mod* e) { + if (!e->buffer()->selected()) + e->dragPos = e->insert_position(); + if (c != FL_Up && c != FL_Down) { + e->buffer()->unselect(); + Fl::copy("", 0, 0); + e->show_insert_position(); + } + switch (c) { + case FL_Up: // top of buffer + e->insert_position(0); + e->scroll(0, 0); + break; + case FL_Down: // end of buffer + e->insert_position(e->buffer()->length()); + e->scroll(e->count_lines(0, e->buffer()->length(), 1), 0); + break; + case FL_Left: // beginning of line + kf_move(FL_Home, e); + break; + case FL_Right: // end of line + kf_move(FL_End, e); + break; + } + return 1; +} + +/** Extends the current selection in the direction indicated by meta key c. */ +int Fl_Text_Editor_mod::kf_m_s_move(int c, Fl_Text_Editor_mod* e) { + kf_meta_move(c, e); + fl_text_drag_me(e->insert_position(), e); + return 1; +} + +/** Extends the current selection in the direction indicated by control key c. */ +int Fl_Text_Editor_mod::kf_c_s_move(int c, Fl_Text_Editor_mod* e) { + kf_ctrl_move(c, e); + fl_text_drag_me(e->insert_position(), e); + return 1; +} + +/** Moves the text cursor to the beginning of the current line.*/ +int Fl_Text_Editor_mod::kf_home(int, Fl_Text_Editor_mod* e) { + return kf_move(FL_Home, e); +} + +/** Moves the text cursor to the end of the current line.*/ +int Fl_Text_Editor_mod::kf_end(int, Fl_Text_Editor_mod* e) { + return kf_move(FL_End, e); +} + +/** Moves the text cursor one character to the left.*/ +int Fl_Text_Editor_mod::kf_left(int, Fl_Text_Editor_mod* e) { + return kf_move(FL_Left, e); +} + +/** Moves the text cursor one line up.*/ +int Fl_Text_Editor_mod::kf_up(int, Fl_Text_Editor_mod* e) { + return kf_move(FL_Up, e); +} + +/** Moves the text cursor one character to the right.*/ +int Fl_Text_Editor_mod::kf_right(int, Fl_Text_Editor_mod* e) { + return kf_move(FL_Right, e); +} +/** Moves the text cursor one line down.*/ +int Fl_Text_Editor_mod::kf_down(int, Fl_Text_Editor_mod* e) { + return kf_move(FL_Down, e); +} + +/** Moves the text cursor up one page.*/ +int Fl_Text_Editor_mod::kf_page_up(int, Fl_Text_Editor_mod* e) { + return kf_move(FL_Page_Up, e); +} + +/** Moves the text cursor down one page.*/ +int Fl_Text_Editor_mod::kf_page_down(int, Fl_Text_Editor_mod* e) { + return kf_move(FL_Page_Down, e); +} +/** Toggles the insert mode in the text editor.*/ +int Fl_Text_Editor_mod::kf_insert(int, Fl_Text_Editor_mod* e) { + e->insert_mode(e->insert_mode() ? 0 : 1); + return 1; +} + +/** Does a delete of selected text or the current character in the current buffer.*/ +int Fl_Text_Editor_mod::kf_delete(int, Fl_Text_Editor_mod* e) { + if (!e->buffer()->selected()) { + int p1 = e->insert_position(); + int p2 = e->buffer()->next_char(p1); + e->buffer()->select(p1, p2); + } + + kill_selection(e); + e->show_insert_position(); + e->set_changed(); + if (e->when()&FL_WHEN_CHANGED) e->do_callback(); + return 1; +} + +/** Does a copy of selected text or the current character in the current buffer.*/ +int Fl_Text_Editor_mod::kf_copy(int, Fl_Text_Editor_mod* e) { + if (!e->buffer()->selected()) return 1; + const char *copy = e->buffer()->selection_text(); + if (*copy) Fl::copy(copy, strlen(copy), 1); + free((void*)copy); + e->show_insert_position(); + return 1; +} + +/** Does a cut of selected text in the current buffer.*/ +int Fl_Text_Editor_mod::kf_cut(int c, Fl_Text_Editor_mod* e) { + kf_copy(c, e); + kill_selection(e); + e->set_changed(); + if (e->when()&FL_WHEN_CHANGED) e->do_callback(); + return 1; +} + +/** Does a paste of selected text in the current buffer.*/ +int Fl_Text_Editor_mod::kf_paste(int, Fl_Text_Editor_mod* e) { + kill_selection(e); + Fl::paste(*e, 1); + e->show_insert_position(); + e->set_changed(); + if (e->when()&FL_WHEN_CHANGED) e->do_callback(); + return 1; +} + +/** Selects all text in the current buffer.*/ +int Fl_Text_Editor_mod::kf_select_all(int, Fl_Text_Editor_mod* e) { + e->buffer()->select(0, e->buffer()->length()); + const char *copy = e->buffer()->selection_text(); + if (*copy) Fl::copy(copy, strlen(copy), 0); + free((void*)copy); + return 1; +} +/** Undo last edit in the current buffer. Also deselect previous selection. */ +int Fl_Text_Editor_mod::kf_undo(int , Fl_Text_Editor_mod* e) { + e->buffer()->unselect(); + Fl::copy("", 0, 0); + int crsr; + int ret = e->buffer()->undo(&crsr); + e->insert_position(crsr); + e->show_insert_position(); + e->set_changed(); + if (e->when()&FL_WHEN_CHANGED) e->do_callback(); + return ret; +} + +/** Handles a key press in the editor */ +int Fl_Text_Editor_mod::handle_key() { + // Call FLTK's rules to try to turn this into a printing character. + // This uses the right-hand ctrl key as a "compose prefix" and returns + // the changes that should be made to the text, as a number of + // bytes to delete and a string to insert: + + int del = 0; + int key = Fl::event_key(), state = Fl::event_state();//, c = Fl::event_text()[0]; + if (key == FL_Caps_Lock) return 0; + + if (Fl::compose(del)) { + if (del) { + int dp = insert_position(), di = del; + while (di--) dp = buffer()->prev_char_clipped(dp); + buffer()->select(dp, insert_position()); + } + kill_selection(this); + if (Fl::event_length()) { + if (insert_mode()) insert(Fl::event_text()); + else overstrike(Fl::event_text()); + } + show_insert_position(); + set_changed(); + if (when()&FL_WHEN_CHANGED) do_callback(); + return 1; + } + + state &= FL_SHIFT|FL_CTRL|FL_ALT|FL_META; // only care about these states + Key_Func f; + f = bound_key_function(key, state, global_key_bindings); + + if (!f && key_bindings) f = bound_key_function(key, state, key_bindings); + + if (f) return f(key, this); + if (default_key_function_ && !state) return default_key_function_(key, this); + return 0; +} + +/** does or does not a callback according to changed() and when() settings */ +void Fl_Text_Editor_mod::maybe_do_callback() { + if (changed() || (when()&FL_WHEN_NOT_CHANGED)) do_callback(); +} + +int Fl_Text_Editor_mod::handle(int event) { + static int dndCursorPos; + + if (!buffer()) return 0; + + switch (event) { + case FL_FOCUS: + show_cursor(mCursorOn); // redraws the cursor + if (buffer()->selected()) redraw(); // Redraw selections... + Fl::focus(this); + return 1; + + case FL_UNFOCUS: + show_cursor(mCursorOn); // redraws the cursor + if (buffer()->selected()) redraw(); // Redraw selections... + case FL_HIDE: + if (when() & FL_WHEN_RELEASE) maybe_do_callback(); + return 1; + + case FL_KEYBOARD: + if (active_r() && window() && this == Fl::belowmouse()) + window()->cursor(FL_CURSOR_NONE); + return handle_key(); + + case FL_PASTE: + if (!Fl::event_text()) { + fl_beep(); + return 1; + } + buffer()->remove_selection(); + if (insert_mode()) insert(Fl::event_text()); + else overstrike(Fl::event_text()); + show_insert_position(); + set_changed(); + if (when()&FL_WHEN_CHANGED) do_callback(); + return 1; + + case FL_ENTER: + // MRS: WIN32 only? Need to test! + // case FL_MOVE: + show_cursor(mCursorOn); + return 1; + + case FL_PUSH: + if (Fl::event_button() == 2) { + // don't let the text_display see this event + if (Fl_Group::handle(event)) return 1; + dragType = DRAG_NONE; + if(buffer()->selected()) { + buffer()->unselect(); + } + int pos = xy_to_position(Fl::event_x(), Fl::event_y(), CURSOR_POS); + insert_position(pos); + Fl::paste(*this, 0); + Fl::focus(this); + set_changed(); + if (when()&FL_WHEN_CHANGED) do_callback(); + return 1; + } + break; + + case FL_SHORTCUT: + if (!(shortcut() ? Fl::test_shortcut(shortcut()) : test_shortcut())) + return 0; + if (Fl::visible_focus() && handle(FL_FOCUS)) { + Fl::focus(this); + return 1; + } + break; + + // Handle drag'n'drop attempt by the user. This is a simplified + // implementation which allows dnd operations onto the scroll bars. + case FL_DND_ENTER: // save the current cursor position + if (Fl::visible_focus() && handle(FL_FOCUS)) + Fl::focus(this); + show_cursor(mCursorOn); + dndCursorPos = insert_position(); + /* fall through */ + case FL_DND_DRAG: // show a temporary insertion cursor + insert_position(xy_to_position(Fl::event_x(), Fl::event_y(), CURSOR_POS)); + return 1; + case FL_DND_LEAVE: // restore original cursor + insert_position(dndCursorPos); + return 1; + case FL_DND_RELEASE: // keep insertion cursor and wait for the FL_PASTE event + buffer()->unselect(); // FL_PASTE must not destroy current selection! + return 1; + } + + return Fl_Text_Display_mod::handle(event); +} + +// +// End of "$Id: Fl_Text_Editor_mod.cxx 8034 2010-12-15 12:21:55Z AlbrechtS $". +// diff --git a/src/widgets/Fl_Text_Editor_mod_1_1.cxx b/src/widgets/Fl_Text_Editor_mod_1_1.cxx deleted file mode 100644 index 0f5b6f2..0000000 --- a/src/widgets/Fl_Text_Editor_mod_1_1.cxx +++ /dev/null @@ -1,494 +0,0 @@ -// "$Id: Fl_Text_Editor.cxx 5671 2007-02-08 07:58:47Z matt $" -// -// Copyright 2001-2006 by Bill Spitzak and others. -// Original code Copyright Mark Edel. Permission to distribute under -// the LGPL for the FLTK library granted by Mark Edel. -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ -// -// This file is part of flmsg -// -// flrig 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. -// -// flrig 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 - -#include -#include -#include -#include -#include -#include -#include "Fl_Text_Editor_mod.H" -#include -#include "missing_strings.h" - - -Fl_Text_Editor_mod::Fl_Text_Editor_mod(int X, int Y, int W, int H, const char* l) - : Fl_Text_Display_mod(X, Y, W, H, l) { - mCursorOn = 1; - insert_mode_ = 1; - key_bindings = 0; - - // handle the default key bindings - add_default_key_bindings(&key_bindings); - - // handle everything else - default_key_function(kf_default); -} - -Fl_Text_Editor_mod::Key_Binding* Fl_Text_Editor_mod::global_key_bindings = 0; - -// These are the default key bindings every widget should start with -static struct { - int key; - int state; - Fl_Text_Editor_mod::Key_Func func; -} default_key_bindings[] = { - { FL_Escape, FL_TEXT_EDITOR_ANY_STATE, Fl_Text_Editor_mod::kf_ignore }, - { FL_Enter, FL_TEXT_EDITOR_ANY_STATE, Fl_Text_Editor_mod::kf_enter }, - { FL_KP_Enter, FL_TEXT_EDITOR_ANY_STATE, Fl_Text_Editor_mod::kf_enter }, - { FL_BackSpace, FL_TEXT_EDITOR_ANY_STATE, Fl_Text_Editor_mod::kf_backspace }, - { FL_Insert, FL_TEXT_EDITOR_ANY_STATE, Fl_Text_Editor_mod::kf_insert }, - { FL_Delete, FL_TEXT_EDITOR_ANY_STATE, Fl_Text_Editor_mod::kf_delete }, - { FL_Home, 0, Fl_Text_Editor_mod::kf_move }, - { FL_End, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Left, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Up, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Right, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Down, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Page_Up, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Page_Down, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Home, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_End, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Left, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Up, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Right, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Down, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Page_Up, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Page_Down, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Home, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_End, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Left, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Up, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Right, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Down, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Page_Up, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Page_Down, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Home, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_End, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_Left, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_Up, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_Right, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_Down, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_Page_Up, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_Page_Down, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, -//{ FL_Clear, 0, Fl_Text_Editor_mod::delete_to_eol }, - { 'z', FL_CTRL, Fl_Text_Editor_mod::kf_undo }, - { '/', FL_CTRL, Fl_Text_Editor_mod::kf_undo }, - { 'x', FL_CTRL, Fl_Text_Editor_mod::kf_cut }, - { FL_Delete, FL_SHIFT, Fl_Text_Editor_mod::kf_cut }, - { 'c', FL_CTRL, Fl_Text_Editor_mod::kf_copy }, - { FL_Insert, FL_CTRL, Fl_Text_Editor_mod::kf_copy }, - { 'v', FL_CTRL, Fl_Text_Editor_mod::kf_paste }, - { FL_Insert, FL_SHIFT, Fl_Text_Editor_mod::kf_paste }, - { 'a', FL_CTRL, Fl_Text_Editor_mod::kf_select_all }, - -#ifdef __APPLE__ - // Define CMD+key accelerators... - { 'z', FL_COMMAND, Fl_Text_Editor_mod::kf_undo }, - { 'x', FL_COMMAND, Fl_Text_Editor_mod::kf_cut }, - { 'c', FL_COMMAND, Fl_Text_Editor_mod::kf_copy }, - { 'v', FL_COMMAND, Fl_Text_Editor_mod::kf_paste }, - { 'a', FL_COMMAND, Fl_Text_Editor_mod::kf_select_all }, -#endif // __APPLE__ - - { 0, 0, 0 } -}; - -void Fl_Text_Editor_mod::add_default_key_bindings(Key_Binding** list) { - for (int i = 0; default_key_bindings[i].key; i++) { - add_key_binding(default_key_bindings[i].key, - default_key_bindings[i].state, - default_key_bindings[i].func, - list); - } -} - -Fl_Text_Editor_mod::Key_Func -Fl_Text_Editor_mod::bound_key_function(int key, int state, Key_Binding* list) { - Key_Binding* cur; - if (!list) return 0; - for (cur = list; cur; cur = cur->next) - if (cur->key == key) - if (cur->state == FL_TEXT_EDITOR_ANY_STATE || cur->state == state) - break; - if (!cur) return 0; - return cur->function; -} - -void -Fl_Text_Editor_mod::remove_all_key_bindings(Key_Binding** list) { - Key_Binding *cur, *next; - for (cur = *list; cur; cur = next) { - next = cur->next; - delete cur; - } - *list = 0; -} - -void -Fl_Text_Editor_mod::remove_key_binding(int key, int state, Key_Binding** list) { - Key_Binding *cur, *last = 0; - for (cur = *list; cur; last = cur, cur = cur->next) - if (cur->key == key && cur->state == state) break; - if (!cur) return; - if (last) last->next = cur->next; - else *list = cur->next; - delete cur; -} - -void -Fl_Text_Editor_mod::add_key_binding(int key, int state, Key_Func function, - Key_Binding** list) { - Key_Binding* kb = new Key_Binding; - kb->key = key; - kb->state = state; - kb->function = function; - kb->next = *list; - *list = kb; -} - -//////////////////////////////////////////////////////////////// - -#define NORMAL_INPUT_MOVE 0 - -static void kill_selection(Fl_Text_Editor_mod* e) { - if (e->buffer()->selected()) { - e->insert_position(e->buffer()->primary_selection()->start()); - e->buffer()->remove_selection(); - } -} - -int Fl_Text_Editor_mod::kf_default(int c, Fl_Text_Editor_mod* e) { - if (!c || (!isprint(c) && c != '\t')) return 0; - char s[2] = "\0"; - s[0] = (char)c; - kill_selection(e); - if (e->insert_mode()) e->insert(s); - else e->overstrike(s); - e->show_insert_position(); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return 1; -} - -int Fl_Text_Editor_mod::kf_ignore(int, Fl_Text_Editor_mod*) { - return 0; // don't handle -} - -int Fl_Text_Editor_mod::kf_backspace(int, Fl_Text_Editor_mod* e) { - if (!e->buffer()->selected() && e->move_left()) - e->buffer()->select(e->insert_position(), e->insert_position()+1); - kill_selection(e); - e->show_insert_position(); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return 1; -} - -int Fl_Text_Editor_mod::kf_enter(int, Fl_Text_Editor_mod* e) { - kill_selection(e); - e->insert("\n"); - e->show_insert_position(); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return 1; -} - -extern void fl_text_drag_me(int pos, Fl_Text_Display_mod* d); - -int Fl_Text_Editor_mod::kf_move(int c, Fl_Text_Editor_mod* e) { - int i; - int selected = e->buffer()->selected(); - if (!selected) - e->dragPos = e->insert_position(); - e->buffer()->unselect(); - switch (c) { - case FL_Home: - e->insert_position(e->buffer()->line_start(e->insert_position())); - break; - case FL_End: - e->insert_position(e->buffer()->line_end(e->insert_position())); - break; - case FL_Left: - e->move_left(); - break; - case FL_Right: - e->move_right(); - break; - case FL_Up: - e->move_up(); - break; - case FL_Down: - e->move_down(); - break; - case FL_Page_Up: - for (i = 0; i < e->mNVisibleLines - 1; i++) e->move_up(); - break; - case FL_Page_Down: - for (i = 0; i < e->mNVisibleLines - 1; i++) e->move_down(); - break; - } - e->show_insert_position(); - return 1; -} - -int Fl_Text_Editor_mod::kf_shift_move(int c, Fl_Text_Editor_mod* e) { - kf_move(c, e); - fl_text_drag_me(e->insert_position(), e); - return 1; -} - -int Fl_Text_Editor_mod::kf_ctrl_move(int c, Fl_Text_Editor_mod* e) { - if (!e->buffer()->selected()) - e->dragPos = e->insert_position(); - if (c != FL_Up && c != FL_Down) { - e->buffer()->unselect(); - e->show_insert_position(); - } - switch (c) { - case FL_Home: - e->insert_position(0); - e->scroll(0, 0); - break; - case FL_End: - e->insert_position(e->buffer()->length()); - e->scroll(e->count_lines(0, e->buffer()->length(), 1), 0); - break; - case FL_Left: - e->previous_word(); - break; - case FL_Right: - e->next_word(); - break; - case FL_Up: - e->scroll(e->mTopLineNum-1, e->mHorizOffset); - break; - case FL_Down: - e->scroll(e->mTopLineNum+1, e->mHorizOffset); - break; - case FL_Page_Up: - e->insert_position(e->mLineStarts[0]); - break; - case FL_Page_Down: - e->insert_position(e->mLineStarts[e->mNVisibleLines-2]); - break; - } - return 1; -} - -int Fl_Text_Editor_mod::kf_c_s_move(int c, Fl_Text_Editor_mod* e) { - kf_ctrl_move(c, e); - fl_text_drag_me(e->insert_position(), e); - return 1; -} - -int Fl_Text_Editor_mod::kf_home(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Home, e); -} - -int Fl_Text_Editor_mod::kf_end(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_End, e); -} - -int Fl_Text_Editor_mod::kf_left(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Left, e); -} - -int Fl_Text_Editor_mod::kf_up(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Up, e); -} - -int Fl_Text_Editor_mod::kf_right(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Right, e); -} - -int Fl_Text_Editor_mod::kf_down(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Down, e); -} - -int Fl_Text_Editor_mod::kf_page_up(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Page_Up, e); -} - -int Fl_Text_Editor_mod::kf_page_down(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Page_Down, e); -} - - -int Fl_Text_Editor_mod::kf_insert(int, Fl_Text_Editor_mod* e) { - e->insert_mode(e->insert_mode() ? 0 : 1); - return 1; -} - -int Fl_Text_Editor_mod::kf_delete(int, Fl_Text_Editor_mod* e) { - if (!e->buffer()->selected()) - e->buffer()->select(e->insert_position(), e->insert_position()+1); - kill_selection(e); - e->show_insert_position(); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return 1; -} - -int Fl_Text_Editor_mod::kf_copy(int, Fl_Text_Editor_mod* e) { - if (!e->buffer()->selected()) return 1; - const char *copy = e->buffer()->selection_text(); - if (*copy) Fl::copy(copy, strlen(copy), 1); - free((void*)copy); - e->show_insert_position(); - return 1; -} - -int Fl_Text_Editor_mod::kf_cut(int c, Fl_Text_Editor_mod* e) { - kf_copy(c, e); - kill_selection(e); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return 1; -} - -int Fl_Text_Editor_mod::kf_paste(int, Fl_Text_Editor_mod* e) { - kill_selection(e); - Fl::paste(*e, 1); - e->show_insert_position(); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return 1; -} - -int Fl_Text_Editor_mod::kf_select_all(int, Fl_Text_Editor_mod* e) { - e->buffer()->select(0, e->buffer()->length()); - return 1; -} - -int Fl_Text_Editor_mod::kf_undo(int , Fl_Text_Editor_mod* e) { - e->buffer()->unselect(); - int crsr; - int ret = e->buffer()->undo(&crsr); - e->insert_position(crsr); - e->show_insert_position(); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return ret; -} - -int Fl_Text_Editor_mod::handle_key() { - // Call FLTK's rules to try to turn this into a printing character. - // This uses the right-hand ctrl key as a "compose prefix" and returns - // the changes that should be made to the text, as a number of - // bytes to delete and a std::string to insert: - int del; - if (Fl::compose(del)) { - if (del) buffer()->select(insert_position()-del, insert_position()); - kill_selection(this); - if (Fl::event_length()) { - if (insert_mode()) insert(Fl::event_text()); - else overstrike(Fl::event_text()); - } - show_insert_position(); - set_changed(); - if (when()&FL_WHEN_CHANGED) do_callback(); - return 1; - } - - int key = Fl::event_key(), state = Fl::event_state(), c = Fl::event_text()[0]; - state &= FL_SHIFT|FL_CTRL|FL_ALT|FL_META; // only care about these states - Key_Func f; - f = bound_key_function(key, state, global_key_bindings); - if (!f) f = bound_key_function(key, state, key_bindings); - if (f) return f(key, this); - if (default_key_function_ && !state) return default_key_function_(c, this); - return 0; -} - -void Fl_Text_Editor_mod::maybe_do_callback() { -// printf("Fl_Text_Editor_mod::maybe_do_callback()\n"); -// printf("changed()=%d, when()=%x\n", changed(), when()); - if (changed() || (when()&FL_WHEN_NOT_CHANGED)) do_callback(); -} - -int Fl_Text_Editor_mod::handle(int event) { - if (!buffer()) return 0; - - switch (event) { - case FL_FOCUS: - show_cursor(mCursorOn); // redraws the cursor - if (buffer()->selected()) redraw(); // Redraw selections... - Fl::focus(this); - return 1; - - case FL_UNFOCUS: - show_cursor(mCursorOn); // redraws the cursor - if (buffer()->selected()) redraw(); // Redraw selections... - case FL_HIDE: - if (when() & FL_WHEN_RELEASE) maybe_do_callback(); - return 1; - - case FL_KEYBOARD: - if (active_r() && window() && this == Fl::belowmouse()) - window()->cursor(FL_CURSOR_NONE); - return handle_key(); - - case FL_PASTE: - if (!Fl::event_text()) { - fl_beep(); - return 1; - } - buffer()->remove_selection(); - if (insert_mode()) insert(Fl::event_text()); - else overstrike(Fl::event_text()); - show_insert_position(); - set_changed(); - if (when()&FL_WHEN_CHANGED) do_callback(); - return 1; - - case FL_ENTER: -// MRS: WIN32 only? Need to test! -// case FL_MOVE: - show_cursor(mCursorOn); - return 1; - - case FL_PUSH: - if (Fl::event_button() == 2) { - // don't let the text_display see this event - if (Fl_Group::handle(event)) return 1; - dragType = -1; - Fl::paste(*this, 0); - Fl::focus(this); - set_changed(); - if (when()&FL_WHEN_CHANGED) do_callback(); - return 1; - } - break; - } - - return Fl_Text_Display_mod::handle(event); -} - -// -// End of "$Id: Fl_Text_Editor.cxx 5671 2007-02-08 07:58:47Z matt $". -// diff --git a/src/widgets/Fl_Text_Editor_mod_1_3.cxx b/src/widgets/Fl_Text_Editor_mod_1_3.cxx deleted file mode 100644 index 43c0f1a..0000000 --- a/src/widgets/Fl_Text_Editor_mod_1_3.cxx +++ /dev/null @@ -1,656 +0,0 @@ -// "$Id: Fl_Text_Editor_mod.cxx 8034 2010-12-15 12:21:55Z AlbrechtS $" -// -// Copyright 2001-2010 by Bill Spitzak and others. -// Original code Copyright Mark Edel. Permission to distribute under -// the LGPL for the FLTK library granted by Mark Edel. -// ---------------------------------------------------------------------------- -// Copyright (C) 2014 -// David Freese, W1HKJ -// -// This file is part of flmsg -// -// flrig 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. -// -// flrig 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 -#include -#include "missing_strings.h" -#include -#include -#include -#include -#include "Fl_Text_Editor_mod.H" - -#include "debug.h" - -/* Keyboard Control Matrix - -key\modifier plain Ctrl Alt Meta - left 1/1 13/9 0/13 0/9 - right 2/2 14/10 0/14 0/10 - up 3/19 21/7 0/15 0/17 - down 4/20 22/8 0/16 0/18 - home 9/5 17/0 0/0 0/0 - end 10/6 18/0 0/0 0/0 - page up 11/7 23/0 0/11 0/0 - page down 12/8 24/0 0/12 0/0 - (FLTK action / OS X action) - (adding the shift key extends the selection, all other combinations are no-op) - - 0: no-op - 1: move cursor to the left, at line beginning wrap to end of prev line, at doc start no-op - 2: move cursor to the right, at line end move to beginning of the next line, at doc end no-op - 3: move cursor up, at doc top no-op - 4: move cursor down, at doc bottom no-op - 5: scroll display to top of text (cursor unchanged) - 6: scroll display to end of text (cursor unchanged) - 7: scroll text down one page (cursor unchanged) - 8: scroll text up one page (cursor unchanged) - 9: move cursor to beginning of line - 10: move cursor to end of line - 11: move cursor up one page and scroll down - 12: move cursor down one page and scroll up - 13: move to the beginning of the word or the previous word - 14: move to the end of the word or the next word - 15: if start of line: start of prev line, else start of this line - 16: if end of line: end of next line, else end of this line - 17: move cursor to the beginning of the document - 18: move cursor to the end of the document - 19: move cursor up, at doc top: home, at doc start: no-op) - 20: move cursor down, at doc bot: end, at doc end: no-op) - 21: scroll text down one line (cursor unchanged) - 22: scroll text up one line (cursor unchanged) - 23: move cursor to the beginning of the top of the screen - 24: move cursor to the beginning of the bottom of the window -*/ - -/** The constructor creates a new text editor widget.*/ -Fl_Text_Editor_mod::Fl_Text_Editor_mod(int X, int Y, int W, int H, const char* l) - : Fl_Text_Display_mod(X, Y, W, H, l) { - mCursorOn = 1; - insert_mode_ = 1; - key_bindings = 0; - - // handle the default key bindings - add_default_key_bindings(&key_bindings); - - // handle everything else - default_key_function(kf_default); -} - -#ifndef FL_DOXYGEN -Fl_Text_Editor_mod::Key_Binding* Fl_Text_Editor_mod::global_key_bindings = 0; -#endif - -// These are the default key bindings every widget should start with -static struct { - int key; - int state; - Fl_Text_Editor_mod::Key_Func func; -} default_key_bindings[] = { - { FL_Escape, Fl_Text_Editor_mod_ANY_STATE, Fl_Text_Editor_mod::kf_ignore }, - { FL_Enter, Fl_Text_Editor_mod_ANY_STATE, Fl_Text_Editor_mod::kf_enter }, - { FL_KP_Enter, Fl_Text_Editor_mod_ANY_STATE, Fl_Text_Editor_mod::kf_enter }, - { FL_BackSpace, Fl_Text_Editor_mod_ANY_STATE, Fl_Text_Editor_mod::kf_backspace }, - { FL_Insert, Fl_Text_Editor_mod_ANY_STATE, Fl_Text_Editor_mod::kf_insert }, - { FL_Delete, Fl_Text_Editor_mod_ANY_STATE, Fl_Text_Editor_mod::kf_delete }, - { FL_Home, 0, Fl_Text_Editor_mod::kf_move }, - { FL_End, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Left, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Up, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Right, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Down, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Page_Up, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Page_Down, 0, Fl_Text_Editor_mod::kf_move }, - { FL_Home, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_End, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Left, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Up, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Right, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Down, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Page_Up, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Page_Down, FL_SHIFT, Fl_Text_Editor_mod::kf_shift_move }, - { FL_Home, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_End, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Left, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Up, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Right, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Down, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Page_Up, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Page_Down, FL_CTRL, Fl_Text_Editor_mod::kf_ctrl_move }, - { FL_Home, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_End, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_Left, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_Up, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_Right, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_Down, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_Page_Up, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, - { FL_Page_Down, FL_CTRL|FL_SHIFT, Fl_Text_Editor_mod::kf_c_s_move }, -//{ FL_Clear, 0, Fl_Text_Editor_mod::delete_to_eol }, - { 'z', FL_CTRL, Fl_Text_Editor_mod::kf_undo }, - { '/', FL_CTRL, Fl_Text_Editor_mod::kf_undo }, - { FL_Home, FL_SHIFT, Fl_Text_Editor_mod::kf_undo }, - { 'x', FL_CTRL, Fl_Text_Editor_mod::kf_cut }, - { FL_Delete, FL_SHIFT, Fl_Text_Editor_mod::kf_cut }, - { 'c', FL_CTRL, Fl_Text_Editor_mod::kf_copy }, - { FL_Insert, FL_CTRL, Fl_Text_Editor_mod::kf_copy }, - { 'v', FL_CTRL, Fl_Text_Editor_mod::kf_paste }, - { FL_Insert, FL_SHIFT, Fl_Text_Editor_mod::kf_paste }, - { 'a', FL_CTRL, Fl_Text_Editor_mod::kf_select_all }, - -#ifdef __APPLE__ - // Define CMD+key accelerators... - { 'z', FL_COMMAND, Fl_Text_Editor_mod::kf_undo }, - { 'x', FL_COMMAND, Fl_Text_Editor_mod::kf_cut }, - { 'c', FL_COMMAND, Fl_Text_Editor_mod::kf_copy }, - { 'v', FL_COMMAND, Fl_Text_Editor_mod::kf_paste }, - { 'a', FL_COMMAND, Fl_Text_Editor_mod::kf_select_all }, - { FL_Left, FL_COMMAND, Fl_Text_Editor_mod::kf_meta_move }, - { FL_Right, FL_COMMAND, Fl_Text_Editor_mod::kf_meta_move }, - { FL_Up, FL_COMMAND, Fl_Text_Editor_mod::kf_meta_move }, - { FL_Down, FL_COMMAND, Fl_Text_Editor_mod::kf_meta_move }, - { FL_Left, FL_COMMAND|FL_SHIFT, Fl_Text_Editor_mod::kf_m_s_move }, - { FL_Right, FL_COMMAND|FL_SHIFT, Fl_Text_Editor_mod::kf_m_s_move }, - { FL_Up, FL_COMMAND|FL_SHIFT, Fl_Text_Editor_mod::kf_m_s_move }, - { FL_Down, FL_COMMAND|FL_SHIFT, Fl_Text_Editor_mod::kf_m_s_move }, -#endif // __APPLE__ - - { 0, 0, 0 } -}; - -/** Adds all of the default editor key bindings to the specified key binding list.*/ -void Fl_Text_Editor_mod::add_default_key_bindings(Key_Binding** list) { - for (int i = 0; default_key_bindings[i].key; i++) { - add_key_binding(default_key_bindings[i].key, - default_key_bindings[i].state, - default_key_bindings[i].func, - list); - } -} - -/** Returns the function associated with a key binding.*/ -Fl_Text_Editor_mod::Key_Func Fl_Text_Editor_mod::bound_key_function(int key, int state, Key_Binding* list) { - Key_Binding* cur; - if (!list) return 0; - for (cur = list; cur; cur = cur->next) - if (cur->key == key) - if (cur->state == Fl_Text_Editor_mod_ANY_STATE || cur->state == state) - break; - if (!cur) return 0; - return cur->function; -} - -/** Removes all of the key bindings associated with the text editor or list.*/ -void Fl_Text_Editor_mod::remove_all_key_bindings(Key_Binding** list) { - Key_Binding *cur, *next; - for (cur = *list; cur; cur = next) { - next = cur->next; - delete cur; - } - *list = 0; -} - -/** Removes the key binding associated with the key "key" of state "state" */ -void Fl_Text_Editor_mod::remove_key_binding(int key, int state, Key_Binding** list) { - Key_Binding *cur, *last = 0; - for (cur = *list; cur; last = cur, cur = cur->next) - if (cur->key == key && cur->state == state) break; - if (!cur) return; - if (last) last->next = cur->next; - else *list = cur->next; - delete cur; -} -/** Adds a key of state "state" with the function "function" */ -void Fl_Text_Editor_mod::add_key_binding(int key, int state, Key_Func function, - Key_Binding** list) { - Key_Binding* kb = new Key_Binding; - kb->key = key; - kb->state = state; - kb->function = function; - kb->next = *list; - *list = kb; -} - -//////////////////////////////////////////////////////////////// - -static void kill_selection(Fl_Text_Editor_mod* e) { - if (e->buffer()->selected()) { - e->insert_position(e->buffer()->primary_selection()->start()); - e->buffer()->remove_selection(); - } -} - -/** Inserts the text associated with the key */ -int Fl_Text_Editor_mod::kf_default(int c, Fl_Text_Editor_mod* e) { - // FIXME: this function is a mess! Fix this! - if (!c || (!isprint(c) && c != '\t')) return 0; - char s[2] = "\0"; - s[0] = (char)c; - kill_selection(e); - if (e->insert_mode()) e->insert(s); - else e->overstrike(s); - e->show_insert_position(); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return 1; -} - -/** Ignores the keypress */ -int Fl_Text_Editor_mod::kf_ignore(int, Fl_Text_Editor_mod*) { - return 0; // don't handle -} -/** Does a backspace in the current buffer.*/ -int Fl_Text_Editor_mod::kf_backspace(int, Fl_Text_Editor_mod* e) { - if (!e->buffer()->selected() && e->move_left()) { - int p1 = e->insert_position(); - int p2 = e->buffer()->next_char(p1); - e->buffer()->select(p1, p2); - } - kill_selection(e); - e->show_insert_position(); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return 1; -} - -/** Inserts a newline at the current cursor position */ -int Fl_Text_Editor_mod::kf_enter(int, Fl_Text_Editor_mod* e) { - kill_selection(e); - e->insert("\n"); - e->show_insert_position(); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return 1; -} - -extern void fl_text_drag_me(int pos, Fl_Text_Display_mod* d); -/** Moves the text cursor in the direction indicated by key c.*/ -int Fl_Text_Editor_mod::kf_move(int c, Fl_Text_Editor_mod* e) { - int i; - int selected = e->buffer()->selected(); - if (!selected) - e->dragPos = e->insert_position(); - e->buffer()->unselect(); - Fl::copy("", 0, 0); - switch (c) { - case FL_Home: - e->insert_position(e->buffer()->line_start(e->insert_position())); - break; - case FL_End: - e->insert_position(e->buffer()->line_end(e->insert_position())); - break; - case FL_Left: - e->move_left(); - break; - case FL_Right: - e->move_right(); - break; - case FL_Up: - e->move_up(); - break; - case FL_Down: - e->move_down(); - break; - case FL_Page_Up: - for (i = 0; i < e->mNVisibleLines - 1; i++) e->move_up(); - break; - case FL_Page_Down: - for (i = 0; i < e->mNVisibleLines - 1; i++) e->move_down(); - break; - } - e->show_insert_position(); - return 1; -} - -/** Extends the current selection in the direction of key c.*/ -int Fl_Text_Editor_mod::kf_shift_move(int c, Fl_Text_Editor_mod* e) { - kf_move(c, e); - fl_text_drag_me(e->insert_position(), e); - char *copy = e->buffer()->selection_text(); - if (copy) { - Fl::copy(copy, strlen(copy), 0); - free(copy); - } - return 1; -} -/** Moves the current text cursor in the direction indicated by control key */ -int Fl_Text_Editor_mod::kf_ctrl_move(int c, Fl_Text_Editor_mod* e) { - if (!e->buffer()->selected()) - e->dragPos = e->insert_position(); - if (c != FL_Up && c != FL_Down) { - e->buffer()->unselect(); - Fl::copy("", 0, 0); - e->show_insert_position(); - } - switch (c) { - case FL_Home: - e->insert_position(0); - e->scroll(0, 0); - break; - case FL_End: - e->insert_position(e->buffer()->length()); - e->scroll(e->count_lines(0, e->buffer()->length(), 1), 0); - break; - case FL_Left: - e->previous_word(); - break; - case FL_Right: - e->next_word(); - break; - case FL_Up: - e->scroll(e->mTopLineNum-1, e->mHorizOffset); - break; - case FL_Down: - e->scroll(e->mTopLineNum+1, e->mHorizOffset); - break; - case FL_Page_Up: - e->insert_position(e->mLineStarts[0]); - break; - case FL_Page_Down: - e->insert_position(e->mLineStarts[e->mNVisibleLines-2]); - break; - } - return 1; -} - -/** Moves the current text cursor in the direction indicated by meta key */ -int Fl_Text_Editor_mod::kf_meta_move(int c, Fl_Text_Editor_mod* e) { - if (!e->buffer()->selected()) - e->dragPos = e->insert_position(); - if (c != FL_Up && c != FL_Down) { - e->buffer()->unselect(); - Fl::copy("", 0, 0); - e->show_insert_position(); - } - switch (c) { - case FL_Up: // top of buffer - e->insert_position(0); - e->scroll(0, 0); - break; - case FL_Down: // end of buffer - e->insert_position(e->buffer()->length()); - e->scroll(e->count_lines(0, e->buffer()->length(), 1), 0); - break; - case FL_Left: // beginning of line - kf_move(FL_Home, e); - break; - case FL_Right: // end of line - kf_move(FL_End, e); - break; - } - return 1; -} - -/** Extends the current selection in the direction indicated by meta key c. */ -int Fl_Text_Editor_mod::kf_m_s_move(int c, Fl_Text_Editor_mod* e) { - kf_meta_move(c, e); - fl_text_drag_me(e->insert_position(), e); - return 1; -} - -/** Extends the current selection in the direction indicated by control key c. */ -int Fl_Text_Editor_mod::kf_c_s_move(int c, Fl_Text_Editor_mod* e) { - kf_ctrl_move(c, e); - fl_text_drag_me(e->insert_position(), e); - return 1; -} - -/** Moves the text cursor to the beginning of the current line.*/ -int Fl_Text_Editor_mod::kf_home(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Home, e); -} - -/** Moves the text cursor to the end of the current line.*/ -int Fl_Text_Editor_mod::kf_end(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_End, e); -} - -/** Moves the text cursor one character to the left.*/ -int Fl_Text_Editor_mod::kf_left(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Left, e); -} - -/** Moves the text cursor one line up.*/ -int Fl_Text_Editor_mod::kf_up(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Up, e); -} - -/** Moves the text cursor one character to the right.*/ -int Fl_Text_Editor_mod::kf_right(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Right, e); -} -/** Moves the text cursor one line down.*/ -int Fl_Text_Editor_mod::kf_down(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Down, e); -} - -/** Moves the text cursor up one page.*/ -int Fl_Text_Editor_mod::kf_page_up(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Page_Up, e); -} - -/** Moves the text cursor down one page.*/ -int Fl_Text_Editor_mod::kf_page_down(int, Fl_Text_Editor_mod* e) { - return kf_move(FL_Page_Down, e); -} -/** Toggles the insert mode in the text editor.*/ -int Fl_Text_Editor_mod::kf_insert(int, Fl_Text_Editor_mod* e) { - e->insert_mode(e->insert_mode() ? 0 : 1); - return 1; -} - -/** Does a delete of selected text or the current character in the current buffer.*/ -int Fl_Text_Editor_mod::kf_delete(int, Fl_Text_Editor_mod* e) { - if (!e->buffer()->selected()) { - int p1 = e->insert_position(); - int p2 = e->buffer()->next_char(p1); - e->buffer()->select(p1, p2); - } - - kill_selection(e); - e->show_insert_position(); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return 1; -} - -/** Does a copy of selected text or the current character in the current buffer.*/ -int Fl_Text_Editor_mod::kf_copy(int, Fl_Text_Editor_mod* e) { - if (!e->buffer()->selected()) return 1; - const char *copy = e->buffer()->selection_text(); - if (*copy) Fl::copy(copy, strlen(copy), 1); - free((void*)copy); - e->show_insert_position(); - return 1; -} - -/** Does a cut of selected text in the current buffer.*/ -int Fl_Text_Editor_mod::kf_cut(int c, Fl_Text_Editor_mod* e) { - kf_copy(c, e); - kill_selection(e); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return 1; -} - -/** Does a paste of selected text in the current buffer.*/ -int Fl_Text_Editor_mod::kf_paste(int, Fl_Text_Editor_mod* e) { - kill_selection(e); - Fl::paste(*e, 1); - e->show_insert_position(); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return 1; -} - -/** Selects all text in the current buffer.*/ -int Fl_Text_Editor_mod::kf_select_all(int, Fl_Text_Editor_mod* e) { - e->buffer()->select(0, e->buffer()->length()); - const char *copy = e->buffer()->selection_text(); - if (*copy) Fl::copy(copy, strlen(copy), 0); - free((void*)copy); - return 1; -} -/** Undo last edit in the current buffer. Also deselect previous selection. */ -int Fl_Text_Editor_mod::kf_undo(int , Fl_Text_Editor_mod* e) { - e->buffer()->unselect(); - Fl::copy("", 0, 0); - int crsr; - int ret = e->buffer()->undo(&crsr); - e->insert_position(crsr); - e->show_insert_position(); - e->set_changed(); - if (e->when()&FL_WHEN_CHANGED) e->do_callback(); - return ret; -} - -/** Handles a key press in the editor */ -int Fl_Text_Editor_mod::handle_key() { - // Call FLTK's rules to try to turn this into a printing character. - // This uses the right-hand ctrl key as a "compose prefix" and returns - // the changes that should be made to the text, as a number of - // bytes to delete and a std::string to insert: - - int del = 0; - int key = Fl::event_key(), state = Fl::event_state();//, c = Fl::event_text()[0]; - if (key == FL_Caps_Lock) return 0; - - if (Fl::compose(del)) { - if (del) { - int dp = insert_position(), di = del; - while (di--) dp = buffer()->prev_char_clipped(dp); - buffer()->select(dp, insert_position()); - } - kill_selection(this); - if (Fl::event_length()) { - if (insert_mode()) insert(Fl::event_text()); - else overstrike(Fl::event_text()); - } - show_insert_position(); - set_changed(); - if (when()&FL_WHEN_CHANGED) do_callback(); - return 1; - } - - state &= FL_SHIFT|FL_CTRL|FL_ALT|FL_META; // only care about these states - Key_Func f; - f = bound_key_function(key, state, global_key_bindings); - - if (!f && key_bindings) f = bound_key_function(key, state, key_bindings); - - if (f) return f(key, this); - if (default_key_function_ && !state) return default_key_function_(key, this); - return 0; -} - -/** does or does not a callback according to changed() and when() settings */ -void Fl_Text_Editor_mod::maybe_do_callback() { - if (changed() || (when()&FL_WHEN_NOT_CHANGED)) do_callback(); -} - -int Fl_Text_Editor_mod::handle(int event) { - static int dndCursorPos; - - if (!buffer()) return 0; - - switch (event) { - case FL_FOCUS: - show_cursor(mCursorOn); // redraws the cursor - if (buffer()->selected()) redraw(); // Redraw selections... - Fl::focus(this); - return 1; - - case FL_UNFOCUS: - show_cursor(mCursorOn); // redraws the cursor - if (buffer()->selected()) redraw(); // Redraw selections... - case FL_HIDE: - if (when() & FL_WHEN_RELEASE) maybe_do_callback(); - return 1; - - case FL_KEYBOARD: - if (active_r() && window() && this == Fl::belowmouse()) - window()->cursor(FL_CURSOR_NONE); - return handle_key(); - - case FL_PASTE: - if (!Fl::event_text()) { - fl_beep(); - return 1; - } - buffer()->remove_selection(); - if (insert_mode()) insert(Fl::event_text()); - else overstrike(Fl::event_text()); - show_insert_position(); - set_changed(); - if (when()&FL_WHEN_CHANGED) do_callback(); - return 1; - - case FL_ENTER: -// MRS: WIN32 only? Need to test! -// case FL_MOVE: - show_cursor(mCursorOn); - return 1; - - case FL_PUSH: - if (Fl::event_button() == 2) { - // don't let the text_display see this event - if (Fl_Group::handle(event)) return 1; - dragType = DRAG_NONE; - if(buffer()->selected()) { - buffer()->unselect(); - } - int pos = xy_to_position(Fl::event_x(), Fl::event_y(), CURSOR_POS); - insert_position(pos); - Fl::paste(*this, 0); - Fl::focus(this); - set_changed(); - if (when()&FL_WHEN_CHANGED) do_callback(); - return 1; - } - break; - - case FL_SHORTCUT: - if (!(shortcut() ? Fl::test_shortcut(shortcut()) : test_shortcut())) - return 0; - if (Fl::visible_focus() && handle(FL_FOCUS)) { - Fl::focus(this); - return 1; - } - break; - - // Handle drag'n'drop attempt by the user. This is a simplified - // implementation which allows dnd operations onto the scroll bars. - case FL_DND_ENTER: // save the current cursor position - if (Fl::visible_focus() && handle(FL_FOCUS)) - Fl::focus(this); - show_cursor(mCursorOn); - dndCursorPos = insert_position(); - /* fall through */ - case FL_DND_DRAG: // show a temporary insertion cursor - insert_position(xy_to_position(Fl::event_x(), Fl::event_y(), CURSOR_POS)); - return 1; - case FL_DND_LEAVE: // restore original cursor - insert_position(dndCursorPos); - return 1; - case FL_DND_RELEASE: // keep insertion cursor and wait for the FL_PASTE event - buffer()->unselect(); // FL_PASTE must not destroy current selection! - return 1; - } - - return Fl_Text_Display_mod::handle(event); -} - -// -// End of "$Id: Fl_Text_Editor_mod.cxx 8034 2010-12-15 12:21:55Z AlbrechtS $". -// diff --git a/src/widgets/icons.cxx b/src/widgets/icons.cxx index f6ddcd5..184c2c1 100644 --- a/src/widgets/icons.cxx +++ b/src/widgets/icons.cxx @@ -255,7 +255,12 @@ void set_message_icon(const char** pixmap) Fl_Widget* msg = fl_message_icon(); msg->label(""); msg->align(FL_ALIGN_TOP_LEFT | FL_ALIGN_INSIDE); - msg->color(msg->parent()->color()); + + if (!msg->parent()) + msg->color(FL_BACKGROUND_COLOR); + else + msg->color(msg->parent()->color()); + msg->box(FL_NO_BOX); msg->image(msg_icon = new Fl_Pixmap(pixmap)); }