You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3796 lines
126KB

  1. //
  2. // "$Id: Fl_Text_Display.cxx 8808 2011-06-16 13:31:25Z manolo $"
  3. //
  4. // Copyright 2001-2010 by Bill Spitzak and others.
  5. // Original code Copyright Mark Edel. Permission to distribute under
  6. // the LGPL for the FLTK library granted by Mark Edel.
  7. //
  8. // This library is free software; you can redistribute it and/or
  9. // modify it under the terms of the GNU Library General Public
  10. // License as published by the Free Software Foundation; either
  11. // version 2 of the License, or (at your option) any later version.
  12. //
  13. // This library is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. // Library General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Library General Public
  19. // License along with this library; if not, write to the Free Software
  20. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  21. // USA.
  22. //
  23. // Please report all bugs and problems on the following page:
  24. //
  25. // http://www.fltk.org/str.php
  26. //
  27. // TODO: rendering of the "optional hyphen"
  28. // TODO: make line numbering work again
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <FL/fl_utf8.h>
  32. #include "flstring.h"
  33. #include <limits.h>
  34. #include <ctype.h>
  35. #include <FL/Fl.H>
  36. #include <FL/Fl_Text_Buffer.H>
  37. #include <FL/Fl_Text_Display.H>
  38. #include <FL/Fl_Window.H>
  39. #include <FL/Fl_Printer.H>
  40. #undef min
  41. #undef max
  42. // Text area margins. Left & right margins should be at least 3 so that
  43. // there is some room for the overhanging parts of the cursor!
  44. #define TOP_MARGIN 1
  45. #define BOTTOM_MARGIN 1
  46. #define LEFT_MARGIN 3
  47. #define RIGHT_MARGIN 3
  48. #define NO_HINT -1
  49. /* Masks for text drawing methods. These are or'd together to form an
  50. integer which describes what drawing calls to use to draw a string */
  51. #define FILL_MASK 0x0100
  52. #define SECONDARY_MASK 0x0200
  53. #define PRIMARY_MASK 0x0400
  54. #define HIGHLIGHT_MASK 0x0800
  55. #define BG_ONLY_MASK 0x1000
  56. #define TEXT_ONLY_MASK 0x2000
  57. #define STYLE_LOOKUP_MASK 0xff
  58. /* Maximum displayable line length (how many characters will fit across the
  59. widest window). This amount of memory is temporarily allocated from the
  60. stack in the draw_vline() method for drawing strings */
  61. #define MAX_DISP_LINE_LEN 1000
  62. static int max( int i1, int i2 );
  63. static int min( int i1, int i2 );
  64. static int countlines( const char *string );
  65. /* The variables below are used in a timer event to allow smooth
  66. scrolling of the text area when the pointer has left the area. */
  67. static int scroll_direction = 0;
  68. static int scroll_amount = 0;
  69. static int scroll_y = 0;
  70. static int scroll_x = 0;
  71. // CET - FIXME
  72. #define TMPFONTWIDTH 6
  73. /**
  74. \brief Creates a new text display widget.
  75. \param X, Y, W, H position and size of widget
  76. \param l label text, defaults to none
  77. */
  78. Fl_Text_Display::Fl_Text_Display(int X, int Y, int W, int H, const char* l)
  79. : Fl_Group(X, Y, W, H, l) {
  80. int i;
  81. mMaxsize = 0;
  82. damage_range1_start = damage_range1_end = -1;
  83. damage_range2_start = damage_range2_end = -1;
  84. dragPos = dragging = 0;
  85. dragType = DRAG_CHAR;
  86. display_insert_position_hint = 0;
  87. shortcut_ = 0;
  88. color(FL_BACKGROUND2_COLOR, FL_SELECTION_COLOR);
  89. box(FL_DOWN_FRAME);
  90. textsize(FL_NORMAL_SIZE);
  91. textcolor(FL_FOREGROUND_COLOR);
  92. textfont(FL_HELVETICA);
  93. set_flag(SHORTCUT_LABEL);
  94. text_area.x = 0;
  95. text_area.y = 0;
  96. text_area.w = 0;
  97. text_area.h = 0;
  98. mVScrollBar = new Fl_Scrollbar(0,0,1,1);
  99. mVScrollBar->callback((Fl_Callback*)v_scrollbar_cb, this);
  100. mHScrollBar = new Fl_Scrollbar(0,0,1,1);
  101. mHScrollBar->callback((Fl_Callback*)h_scrollbar_cb, this);
  102. mHScrollBar->type(FL_HORIZONTAL);
  103. end();
  104. scrollbar_width(Fl::scrollbar_size());
  105. scrollbar_align(FL_ALIGN_BOTTOM_RIGHT);
  106. mCursorOn = 0;
  107. mCursorPos = 0;
  108. mCursorOldY = -100;
  109. mCursorToHint = NO_HINT;
  110. mCursorStyle = NORMAL_CURSOR;
  111. mCursorPreferredXPos = -1;
  112. mBuffer = 0;
  113. mFirstChar = 0;
  114. mLastChar = 0;
  115. mNBufferLines = 0;
  116. mTopLineNum = mTopLineNumHint = 1;
  117. mAbsTopLineNum = 1;
  118. mNeedAbsTopLineNum = 0;
  119. mHorizOffset = mHorizOffsetHint = 0;
  120. mCursor_color = FL_FOREGROUND_COLOR;
  121. mStyleBuffer = 0;
  122. mStyleTable = 0;
  123. mNStyles = 0;
  124. mNVisibleLines = 1;
  125. mLineStarts = new int[mNVisibleLines];
  126. mLineStarts[0] = 0;
  127. for (i=1; i<mNVisibleLines; i++)
  128. mLineStarts[i] = -1;
  129. mSuppressResync = 0;
  130. mNLinesDeleted = 0;
  131. mModifyingTabDistance = 0;
  132. mUnfinishedStyle = 0;
  133. mUnfinishedHighlightCB = 0;
  134. mHighlightCBArg = 0;
  135. mLineNumLeft = mLineNumWidth = 0;
  136. mContinuousWrap = 0;
  137. mWrapMarginPix = 0;
  138. mSuppressResync = mNLinesDeleted = mModifyingTabDistance = 0;
  139. }
  140. /**
  141. Free a text display and release its associated memory.
  142. Note, the text BUFFER that the text display displays is a separate
  143. entity and is not freed, nor are the style buffer or style table.
  144. */
  145. Fl_Text_Display::~Fl_Text_Display() {
  146. if (scroll_direction) {
  147. Fl::remove_timeout(scroll_timer_cb, this);
  148. scroll_direction = 0;
  149. }
  150. if (mBuffer) {
  151. mBuffer->remove_modify_callback(buffer_modified_cb, this);
  152. mBuffer->remove_predelete_callback(buffer_predelete_cb, this);
  153. }
  154. if (mLineStarts) delete[] mLineStarts;
  155. }
  156. /**
  157. Attach a text buffer to display, replacing the current buffer (if any)
  158. \param buf attach this text buffer
  159. */
  160. void Fl_Text_Display::buffer( Fl_Text_Buffer *buf ) {
  161. /* If the text display is already displaying a buffer, clear it off
  162. of the display and remove our callback from it */
  163. if ( buf == mBuffer) return;
  164. if ( mBuffer != 0 ) {
  165. // we must provide a copy of the buffer that we are deleting!
  166. char *deletedText = mBuffer->text();
  167. buffer_modified_cb( 0, 0, mBuffer->length(), 0, deletedText, this );
  168. free(deletedText);
  169. mNBufferLines = 0;
  170. mBuffer->remove_modify_callback( buffer_modified_cb, this );
  171. mBuffer->remove_predelete_callback( buffer_predelete_cb, this );
  172. }
  173. /* Add the buffer to the display, and attach a callback to the buffer for
  174. receiving modification information when the buffer contents change */
  175. mBuffer = buf;
  176. if (mBuffer) {
  177. mBuffer->add_modify_callback( buffer_modified_cb, this );
  178. mBuffer->add_predelete_callback( buffer_predelete_cb, this );
  179. /* Update the display */
  180. buffer_modified_cb( 0, buf->length(), 0, 0, 0, this );
  181. }
  182. /* Resize the widget to update the screen... */
  183. resize(x(), y(), w(), h());
  184. }
  185. /**
  186. \brief Attach (or remove) highlight information in text display and redisplay.
  187. Highlighting information consists of a style buffer which parallels the
  188. normal text buffer, but codes font and color information for the display;
  189. a style table which translates style buffer codes (indexed by buffer
  190. character - 'A') into fonts and colors; and a callback mechanism for
  191. as-needed highlighting, triggered by a style buffer entry of
  192. "unfinishedStyle". Style buffer can trigger additional redisplay during
  193. a normal buffer modification if the buffer contains a primary Fl_Text_Selection
  194. (see extendRangeForStyleMods for more information on this protocol).
  195. Style buffers, tables and their associated memory are managed by the caller.
  196. Styles are ranged from 65 ('A') to 126.
  197. \param styleBuffer this buffer works in parallel to the text buffer. For every
  198. character in the text buffer, the stye buffer has a byte at the same offset
  199. that contains an index into an array of possible styles.
  200. \param styleTable a list of styles indexed by the style buffer
  201. \param nStyles number of styles in the style table
  202. \param unfinishedStyle if this style is found, the callback below is called
  203. \param unfinishedHighlightCB if a character with an unfinished style is found,
  204. this callback will be called
  205. \param cbArg and optional argument for the callback above, usually a pointer
  206. to the Text Display.
  207. */
  208. void Fl_Text_Display::highlight_data(Fl_Text_Buffer *styleBuffer,
  209. const Style_Table_Entry *styleTable,
  210. int nStyles, char unfinishedStyle,
  211. Unfinished_Style_Cb unfinishedHighlightCB,
  212. void *cbArg ) {
  213. mStyleBuffer = styleBuffer;
  214. mStyleTable = styleTable;
  215. mNStyles = nStyles;
  216. mUnfinishedStyle = unfinishedStyle;
  217. mUnfinishedHighlightCB = unfinishedHighlightCB;
  218. mHighlightCBArg = cbArg;
  219. mColumnScale = 0;
  220. mStyleBuffer->canUndo(0);
  221. damage(FL_DAMAGE_EXPOSE);
  222. }
  223. /**
  224. \brief Find the longest line of all visible lines.
  225. \return the width of the longest visible line in pixels
  226. */
  227. int Fl_Text_Display::longest_vline() const {
  228. int longest = 0;
  229. for (int i = 0; i < mNVisibleLines; i++)
  230. longest = max(longest, measure_vline(i));
  231. return longest;
  232. }
  233. /**
  234. \brief Change the size of the displayed text area.
  235. Calling this function will trigger a recalculation of all lines visible and
  236. of all scrollbar sizes.
  237. \param X, Y, W, H new position and size of this widget
  238. */
  239. void Fl_Text_Display::resize(int X, int Y, int W, int H) {
  240. #ifdef DEBUG
  241. printf("Fl_Text_Display::resize(X=%d, Y=%d, W=%d, H=%d)\n", X, Y, W, H);
  242. #endif // DEBUG
  243. const int oldWidth = w();
  244. #ifdef DEBUG
  245. printf(" oldWidth=%d, mContinuousWrap=%d, mWrapMargin=%d\n", oldWidth, mContinuousWrap, mWrapMargin);
  246. #endif // DEBUG
  247. Fl_Widget::resize(X,Y,W,H);
  248. if (!buffer()) return;
  249. X += Fl::box_dx(box());
  250. Y += Fl::box_dy(box());
  251. W -= Fl::box_dw(box());
  252. H -= Fl::box_dh(box());
  253. text_area.x = X+LEFT_MARGIN;
  254. text_area.y = Y+TOP_MARGIN;
  255. text_area.w = W-LEFT_MARGIN-RIGHT_MARGIN;
  256. text_area.h = H-TOP_MARGIN-BOTTOM_MARGIN;
  257. int i;
  258. /* Find the new maximum font height for this text display */
  259. for (i = 0, mMaxsize = fl_height(textfont(), textsize()); i < mNStyles; i++)
  260. mMaxsize = max(mMaxsize, fl_height(mStyleTable[i].font, mStyleTable[i].size));
  261. // did we have scrollbars initially?
  262. unsigned int hscrollbarvisible = mHScrollBar->visible();
  263. unsigned int vscrollbarvisible = mVScrollBar->visible();
  264. // try without scrollbars first
  265. mVScrollBar->clear_visible();
  266. mHScrollBar->clear_visible();
  267. for (int again = 1; again;) {
  268. again = 0;
  269. /* In continuous wrap mode, a change in width affects the total number of
  270. lines in the buffer, and can leave the top line number incorrect, and
  271. the top character no longer pointing at a valid line start */
  272. if (mContinuousWrap && !mWrapMarginPix && W!=oldWidth) {
  273. int oldFirstChar = mFirstChar;
  274. mNBufferLines = count_lines(0, buffer()->length(), true);
  275. mFirstChar = line_start(mFirstChar);
  276. mTopLineNum = count_lines(0, mFirstChar, true)+1;
  277. absolute_top_line_number(oldFirstChar);
  278. #ifdef DEBUG
  279. printf(" mNBufferLines=%d\n", mNBufferLines);
  280. #endif // DEBUG
  281. }
  282. /* reallocate and update the line starts array, which may have changed
  283. size and / or contents. */
  284. int nvlines = (text_area.h + mMaxsize - 1) / mMaxsize;
  285. if (nvlines < 1) nvlines = 1;
  286. if (mNVisibleLines != nvlines) {
  287. mNVisibleLines = nvlines;
  288. if (mLineStarts) delete[] mLineStarts;
  289. mLineStarts = new int [mNVisibleLines];
  290. }
  291. calc_line_starts(0, mNVisibleLines);
  292. calc_last_char();
  293. // figure the scrollbars
  294. if (scrollbar_width()) {
  295. /* Decide if the vertical scrollbar needs to be visible */
  296. if (scrollbar_align() & (FL_ALIGN_LEFT|FL_ALIGN_RIGHT) &&
  297. mNBufferLines >= mNVisibleLines - 1)
  298. {
  299. mVScrollBar->set_visible();
  300. if (scrollbar_align() & FL_ALIGN_LEFT) {
  301. text_area.x = X+scrollbar_width()+LEFT_MARGIN;
  302. text_area.w = W-scrollbar_width()-LEFT_MARGIN-RIGHT_MARGIN;
  303. mVScrollBar->resize(X, text_area.y-TOP_MARGIN, scrollbar_width(),
  304. text_area.h+TOP_MARGIN+BOTTOM_MARGIN);
  305. } else {
  306. text_area.x = X+LEFT_MARGIN;
  307. text_area.w = W-scrollbar_width()-LEFT_MARGIN-RIGHT_MARGIN;
  308. mVScrollBar->resize(X+W-scrollbar_width(), text_area.y-TOP_MARGIN,
  309. scrollbar_width(), text_area.h+TOP_MARGIN+BOTTOM_MARGIN);
  310. }
  311. }
  312. /*
  313. Decide if the horizontal scrollbar needs to be visible. If there
  314. is a vertical scrollbar, a horizontal is always created too. This
  315. is because the alternatives are unattractive:
  316. * Dynamically creating a horizontal scrollbar based on the currently
  317. visible lines is what the original nedit does, but it always wastes
  318. space for the scrollbar even when it's not used. Since the FLTK
  319. widget dynamically allocates the space for the scrollbar and
  320. rearranges the widget to make room for it, this would create a very
  321. visually displeasing "bounce" effect when the vertical scrollbar is
  322. dragged. Trust me, I tried it and it looks really bad.
  323. * The other alternative would be to keep track of what the longest
  324. line in the entire buffer is and base the scrollbar on that. I
  325. didn't do this because I didn't see any easy way to do that using
  326. the nedit code and this could involve a lengthy calculation for
  327. large buffers. If an efficient and non-costly way of doing this
  328. can be found, this might be a way to go.
  329. */
  330. /* WAS: Suggestion: Try turning the horizontal scrollbar on when
  331. you first see a line that is too wide in the window, but then
  332. don't turn it off (ie mix both of your solutions). */
  333. if (scrollbar_align() & (FL_ALIGN_TOP|FL_ALIGN_BOTTOM) &&
  334. (longest_vline() > text_area.w))
  335. {
  336. if (!mHScrollBar->visible()) {
  337. mHScrollBar->set_visible();
  338. again = 1; // loop again to see if we now need vert. & recalc sizes
  339. }
  340. if (scrollbar_align() & FL_ALIGN_TOP) {
  341. text_area.y = Y + scrollbar_width()+TOP_MARGIN;
  342. text_area.h = H - scrollbar_width()-TOP_MARGIN-BOTTOM_MARGIN;
  343. mHScrollBar->resize(text_area.x-LEFT_MARGIN, Y,
  344. text_area.w+LEFT_MARGIN+RIGHT_MARGIN, scrollbar_width());
  345. } else {
  346. text_area.y = Y+TOP_MARGIN;
  347. text_area.h = H - scrollbar_width()-TOP_MARGIN-BOTTOM_MARGIN;
  348. mHScrollBar->resize(text_area.x-LEFT_MARGIN, Y+H-scrollbar_width(),
  349. text_area.w+LEFT_MARGIN+RIGHT_MARGIN, scrollbar_width());
  350. }
  351. }
  352. }
  353. }
  354. // user request to change viewport
  355. if (mTopLineNumHint != mTopLineNum || mHorizOffsetHint != mHorizOffset)
  356. scroll_(mTopLineNumHint, mHorizOffsetHint);
  357. // everything will fit in the viewport
  358. if (mNBufferLines < mNVisibleLines || mBuffer == NULL || mBuffer->length() == 0) {
  359. scroll_(1, mHorizOffset);
  360. /* if empty lines become visible, there may be an opportunity to
  361. display more text by scrolling down */
  362. } else {
  363. while ( mNVisibleLines>=2
  364. && (mLineStarts[mNVisibleLines-2]==-1)
  365. && scroll_(mTopLineNum-1, mHorizOffset))
  366. { }
  367. }
  368. // user request to display insert position
  369. if (display_insert_position_hint)
  370. display_insert();
  371. // in case horizontal offset is now greater than longest line
  372. int maxhoffset = max(0, longest_vline()-text_area.w);
  373. if (mHorizOffset > maxhoffset)
  374. scroll_(mTopLineNumHint, maxhoffset);
  375. mTopLineNumHint = mTopLineNum;
  376. mHorizOffsetHint = mHorizOffset;
  377. display_insert_position_hint = 0;
  378. if (mContinuousWrap ||
  379. hscrollbarvisible != mHScrollBar->visible() ||
  380. vscrollbarvisible != mVScrollBar->visible())
  381. redraw();
  382. update_v_scrollbar();
  383. update_h_scrollbar();
  384. }
  385. /**
  386. \brief Refresh a rectangle of the text display.
  387. \param left, top are in coordinates of the text drawing window.
  388. \param width, height size in pixels
  389. */
  390. void Fl_Text_Display::draw_text( int left, int top, int width, int height ) {
  391. int fontHeight, firstLine, lastLine, line;
  392. /* find the line number range of the display */
  393. fontHeight = mMaxsize ? mMaxsize : textsize_;
  394. firstLine = ( top - text_area.y - fontHeight + 1 ) / fontHeight;
  395. lastLine = ( top + height - text_area.y ) / fontHeight + 1;
  396. fl_push_clip( left, top, width, height );
  397. /* draw the lines */
  398. for ( line = firstLine; line <= lastLine; line++ )
  399. draw_vline( line, left, left + width, 0, INT_MAX );
  400. /* draw the line numbers if exposed area includes them */
  401. if (mLineNumWidth != 0 && left <= mLineNumLeft + mLineNumWidth)
  402. draw_line_numbers(false);
  403. fl_pop_clip();
  404. }
  405. /**
  406. \brief Marks text from start to end as needing a redraw.
  407. This function will trigger a damage event and later a redraw of parts of
  408. the widget.
  409. \param startpos index of first character needing redraw
  410. \param endpos index after last character needing redraw
  411. */
  412. void Fl_Text_Display::redisplay_range(int startpos, int endpos) {
  413. IS_UTF8_ALIGNED2(buffer(), startpos)
  414. IS_UTF8_ALIGNED2(buffer(), endpos)
  415. if (damage_range1_start == -1 && damage_range1_end == -1) {
  416. damage_range1_start = startpos;
  417. damage_range1_end = endpos;
  418. } else if ((startpos >= damage_range1_start && startpos <= damage_range1_end) ||
  419. (endpos >= damage_range1_start && endpos <= damage_range1_end)) {
  420. damage_range1_start = min(damage_range1_start, startpos);
  421. damage_range1_end = max(damage_range1_end, endpos);
  422. } else if (damage_range2_start == -1 && damage_range2_end == -1) {
  423. damage_range2_start = startpos;
  424. damage_range2_end = endpos;
  425. } else {
  426. damage_range2_start = min(damage_range2_start, startpos);
  427. damage_range2_end = max(damage_range2_end, endpos);
  428. }
  429. damage(FL_DAMAGE_SCROLL);
  430. }
  431. /**
  432. \brief Draw a range of text.
  433. Refresh all of the text between buffer positions \p startpos and
  434. \p endpos not including the character at the position \p endpos.
  435. If \p endpos points beyond the end of the buffer, refresh the whole display
  436. after \p startpos, including blank lines which are not technically part of
  437. any range of characters.
  438. \param startpos index of first character to draw
  439. \param endpos index after last character to draw
  440. */
  441. void Fl_Text_Display::draw_range(int startpos, int endpos) {
  442. startpos = buffer()->utf8_align(startpos);
  443. endpos = buffer()->utf8_align(endpos);
  444. int i, startLine, lastLine, startIndex, endIndex;
  445. /* If the range is outside of the displayed text, just return */
  446. if ( endpos < mFirstChar || ( startpos > mLastChar && !empty_vlines() ) )
  447. return;
  448. /* Clean up the starting and ending values */
  449. if ( startpos < 0 ) startpos = 0;
  450. if ( startpos > mBuffer->length() ) startpos = mBuffer->length();
  451. if ( endpos < 0 ) endpos = 0;
  452. if ( endpos > mBuffer->length() ) endpos = mBuffer->length();
  453. /* Get the starting and ending lines */
  454. if ( startpos < mFirstChar )
  455. startpos = mFirstChar;
  456. if ( !position_to_line( startpos, &startLine ) )
  457. startLine = mNVisibleLines - 1;
  458. if ( endpos >= mLastChar ) {
  459. lastLine = mNVisibleLines - 1;
  460. } else {
  461. if ( !position_to_line( endpos, &lastLine ) ) {
  462. /* shouldn't happen */
  463. lastLine = mNVisibleLines - 1;
  464. }
  465. }
  466. /* Get the starting and ending positions within the lines */
  467. startIndex = mLineStarts[ startLine ] == -1 ? 0 : startpos - mLineStarts[ startLine ];
  468. if ( endpos >= mLastChar )
  469. endIndex = INT_MAX;
  470. else if ( mLineStarts[ lastLine ] == -1 )
  471. endIndex = 0;
  472. else
  473. endIndex = endpos - mLineStarts[ lastLine ];
  474. /* If the starting and ending lines are the same, redisplay the single
  475. line between "start" and "end" */
  476. if ( startLine == lastLine ) {
  477. draw_vline( startLine, 0, INT_MAX, startIndex, endIndex );
  478. return;
  479. }
  480. /* Redisplay the first line from "start" */
  481. draw_vline( startLine, 0, INT_MAX, startIndex, INT_MAX );
  482. /* Redisplay the lines in between at their full width */
  483. for ( i = startLine + 1; i < lastLine; i++ )
  484. draw_vline( i, 0, INT_MAX, 0, INT_MAX );
  485. /* Redisplay the last line to "end" */
  486. draw_vline( lastLine, 0, INT_MAX, 0, endIndex );
  487. }
  488. /**
  489. \brief Sets the position of the text insertion cursor for text display.
  490. Move the insertion cursor in front of the character at \p newPos.
  491. This function may trigger a redraw.
  492. \param newPos new caret position
  493. */
  494. void Fl_Text_Display::insert_position( int newPos ) {
  495. IS_UTF8_ALIGNED2(buffer(), newPos)
  496. /* make sure new position is ok, do nothing if it hasn't changed */
  497. if ( newPos == mCursorPos ) return;
  498. if ( newPos < 0 ) newPos = 0;
  499. if ( newPos > mBuffer->length() ) newPos = mBuffer->length();
  500. /* cursor movement cancels vertical cursor motion column */
  501. mCursorPreferredXPos = -1;
  502. /* erase the cursor at its previous position */
  503. redisplay_range(buffer()->prev_char_clipped(mCursorPos), buffer()->next_char(mCursorPos));
  504. mCursorPos = newPos;
  505. /* draw cursor at its new position */
  506. redisplay_range(buffer()->prev_char_clipped(mCursorPos), buffer()->next_char(mCursorPos));
  507. }
  508. /**
  509. \brief Shows the text cursor.
  510. This function may trigger a redraw.
  511. \param b show(1) or hide(0) the text cursor (caret).
  512. */
  513. void Fl_Text_Display::show_cursor(int b) {
  514. mCursorOn = b;
  515. redisplay_range(buffer()->prev_char_clipped(mCursorPos), buffer()->next_char(mCursorPos));
  516. }
  517. /**
  518. \brief Sets the text cursor style.
  519. Sets the text cursor style to one of the following:
  520. \li Fl_Text_Display::NORMAL_CURSOR - Shows an I beam.
  521. \li Fl_Text_Display::CARET_CURSOR - Shows a caret under the text.
  522. \li Fl_Text_Display::DIM_CURSOR - Shows a dimmed I beam.
  523. \li Fl_Text_Display::BLOCK_CURSOR - Shows an unfilled box around the current
  524. character.
  525. \li Fl_Text_Display::HEAVY_CURSOR - Shows a thick I beam.
  526. This call also switches the cursor on and may trigger a redraw.
  527. \param style new cursor style
  528. */
  529. void Fl_Text_Display::cursor_style(int style) {
  530. mCursorStyle = style;
  531. if (mCursorOn) show_cursor();
  532. }
  533. /**
  534. \brief Set the new text wrap mode.
  535. If \p wrap mode is not zero, this call enables automatic word wrapping at column
  536. \p wrapMargin. Word-wrapping does not change the text buffer itself, only the way
  537. the text is displayed. Different Text Displays can have different wrap modes,
  538. even if they share the same Text Buffer.
  539. \param wrap new wrap mode is WRAP_NONE (don't wrap text at all), WRAP_AT_COLUMN
  540. (wrap text at the given text column), WRAP_AT_PIXEL (wrap text at a pixel
  541. position), or WRAP_AT_BOUNDS (wrap text so that it fits into the
  542. widget width)
  543. \param wrapMargin in WRAP_AT_COLUMN mode, text will wrap at the n'th character.
  544. For variable width fonts, an average character width is calculated. The
  545. column width is calculated using the current textfont or the first style
  546. when this function is called. If the font size changes, this function
  547. must be called again. In WRAP_AT_PIXEL mode, this is the pixel position.
  548. \todo we need new wrap modes to wrap at the window edge and based on pixel width
  549. or average character width.
  550. */
  551. void Fl_Text_Display::wrap_mode(int wrap, int wrapMargin) {
  552. switch (wrap) {
  553. case WRAP_NONE:
  554. mWrapMarginPix = 0;
  555. mContinuousWrap = 0;
  556. break;
  557. case WRAP_AT_COLUMN:
  558. default:
  559. mWrapMarginPix = int(col_to_x(wrapMargin));
  560. mContinuousWrap = 1;
  561. break;
  562. case WRAP_AT_PIXEL:
  563. mWrapMarginPix = wrapMargin;
  564. mContinuousWrap = 1;
  565. break;
  566. case WRAP_AT_BOUNDS:
  567. mWrapMarginPix = 0;
  568. mContinuousWrap = 1;
  569. break;
  570. }
  571. if (buffer()) {
  572. /* wrapping can change the total number of lines, re-count */
  573. mNBufferLines = count_lines(0, buffer()->length(), true);
  574. /* changing wrap margins or changing from wrapped mode to non-wrapped
  575. can leave the character at the top no longer at a line start, and/or
  576. change the line number */
  577. mFirstChar = line_start(mFirstChar);
  578. mTopLineNum = count_lines(0, mFirstChar, true) + 1;
  579. reset_absolute_top_line_number();
  580. /* update the line starts array */
  581. calc_line_starts(0, mNVisibleLines);
  582. calc_last_char();
  583. } else {
  584. // No buffer, so just clear the state info for later...
  585. mNBufferLines = 0;
  586. mFirstChar = 0;
  587. mTopLineNum = 1;
  588. mAbsTopLineNum = 0;
  589. }
  590. resize(x(), y(), w(), h());
  591. }
  592. /**
  593. \brief Inserts "text" at the current cursor location.
  594. This has the same effect as inserting the text into the buffer using BufInsert
  595. and then moving the insert position after the newly inserted text, except
  596. that it's optimized to do less redrawing.
  597. \param text new text in UTF-8 encoding.
  598. */
  599. void Fl_Text_Display::insert(const char* text) {
  600. IS_UTF8_ALIGNED2(buffer(), mCursorPos)
  601. IS_UTF8_ALIGNED(text)
  602. int pos = mCursorPos;
  603. mCursorToHint = pos + strlen( text );
  604. mBuffer->insert( pos, text );
  605. mCursorToHint = NO_HINT;
  606. }
  607. /**
  608. \brief Replaces text at the current insert position.
  609. \param text new text in UTF-8 encoding
  610. \todo Unicode? Find out exactly what we do here and simplify.
  611. */
  612. void Fl_Text_Display::overstrike(const char* text) {
  613. IS_UTF8_ALIGNED2(buffer(), mCursorPos)
  614. IS_UTF8_ALIGNED(text)
  615. int startPos = mCursorPos;
  616. Fl_Text_Buffer *buf = mBuffer;
  617. int lineStart = buf->line_start( startPos );
  618. int textLen = strlen( text );
  619. int i, p, endPos, indent, startIndent, endIndent;
  620. const char *c;
  621. unsigned int ch;
  622. char *paddedText = NULL;
  623. /* determine how many displayed character positions are covered */
  624. startIndent = mBuffer->count_displayed_characters( lineStart, startPos );
  625. indent = startIndent;
  626. for ( c = text; *c != '\0'; c += fl_utf8len1(*c) )
  627. indent++;
  628. endIndent = indent;
  629. /* find which characters to remove, and if necessary generate additional
  630. padding to make up for removed control characters at the end */
  631. indent = startIndent;
  632. for ( p = startPos; ; p=buffer()->next_char(p) ) {
  633. if ( p == buf->length() )
  634. break;
  635. ch = buf->char_at( p );
  636. if ( ch == '\n' )
  637. break;
  638. indent++;
  639. if ( indent == endIndent ) {
  640. p++;
  641. break;
  642. } else if ( indent > endIndent ) {
  643. if ( ch != '\t' ) {
  644. p++;
  645. paddedText = new char [ textLen + FL_TEXT_MAX_EXP_CHAR_LEN + 1 ];
  646. strcpy( paddedText, text );
  647. for ( i = 0; i < indent - endIndent; i++ )
  648. paddedText[ textLen + i ] = ' ';
  649. paddedText[ textLen + i ] = '\0';
  650. }
  651. break;
  652. }
  653. }
  654. endPos = p;
  655. mCursorToHint = startPos + textLen;
  656. buf->replace( startPos, endPos, paddedText == NULL ? text : paddedText );
  657. mCursorToHint = NO_HINT;
  658. if ( paddedText != NULL )
  659. delete [] paddedText;
  660. }
  661. /**
  662. \brief Convert a character index into a pixel position.
  663. Translate a buffer text position to the XY location where the top left of the
  664. cursor would be positioned to point to that character. Returns 0 if the
  665. position is not displayed because it is \e \b vertically out of view.
  666. If the position is horizontally out of view, returns the X coordinate where
  667. the position would be if it were visible.
  668. \param pos character index
  669. \param[out] X, Y pixel position of character on screen
  670. \return 0 if character vertically out of view, X position otherwise
  671. */
  672. int Fl_Text_Display::position_to_xy( int pos, int* X, int* Y ) const {
  673. IS_UTF8_ALIGNED2(buffer(), pos)
  674. int lineStartPos, fontHeight, lineLen;
  675. int visLineNum;
  676. /* If position is not displayed, return false */
  677. if (pos < mFirstChar || (pos > mLastChar && !empty_vlines())) {
  678. return 0;
  679. }
  680. /* Calculate Y coordinate */
  681. if (!position_to_line(pos, &visLineNum)) {
  682. return 0;
  683. }
  684. if (visLineNum < 0 || visLineNum > mNBufferLines) {
  685. return 0;
  686. }
  687. fontHeight = mMaxsize;
  688. *Y = text_area.y + visLineNum * fontHeight;
  689. /* Get the text, length, and buffer position of the line. If the position
  690. is beyond the end of the buffer and should be at the first position on
  691. the first empty line, don't try to get or scan the text */
  692. lineStartPos = mLineStarts[visLineNum];
  693. if ( lineStartPos == -1 ) {
  694. *X = text_area.x - mHorizOffset;
  695. return 1;
  696. }
  697. lineLen = vline_length( visLineNum );
  698. *X = text_area.x + handle_vline(GET_WIDTH, lineStartPos, pos-lineStartPos, 0, 0, 0, 0, 0, 0) - mHorizOffset;
  699. return 1;
  700. }
  701. /**
  702. \brief Find the line and column number of position \p pos.
  703. This only works for displayed lines. If the line is not displayed, the
  704. function returns 0 (without the mLineStarts array it could turn in to very long
  705. calculation involving scanning large amounts of text in the buffer).
  706. If continuous wrap mode is on, returns the absolute line number (as opposed
  707. to the wrapped line number which is used for scrolling).
  708. \param pos character index
  709. \param[out] lineNum absolute (unwrapped) line number
  710. \param[out] column character offset to the beginning of the line
  711. \return 0 if \p pos is off screen, line number otherwise
  712. \todo a column number makes little sense in the UTF-8/variable font width
  713. environment. We will have to further define what exactly we want to return.
  714. Please check the functions that call this particular function.
  715. */
  716. int Fl_Text_Display::position_to_linecol( int pos, int* lineNum, int* column ) const {
  717. IS_UTF8_ALIGNED2(buffer(), pos)
  718. int retVal;
  719. /* In continuous wrap mode, the absolute (non-wrapped) line count is
  720. maintained separately, as needed. Only return it if we're actually
  721. keeping track of it and pos is in the displayed text */
  722. if (mContinuousWrap) {
  723. if (!maintaining_absolute_top_line_number() || pos < mFirstChar || pos > mLastChar)
  724. return 0;
  725. *lineNum = mAbsTopLineNum + buffer()->count_lines(mFirstChar, pos);
  726. *column = buffer()->count_displayed_characters(buffer()->line_start(pos), pos);
  727. return 1;
  728. }
  729. retVal = position_to_line( pos, lineNum );
  730. if ( retVal ) {
  731. *column = mBuffer->count_displayed_characters( mLineStarts[ *lineNum ], pos );
  732. *lineNum += mTopLineNum;
  733. }
  734. return retVal;
  735. }
  736. /**
  737. \brief Check if a pixel position is within the primary selection.
  738. \param X, Y pixel position to test
  739. \return 1 if position (X, Y) is inside of the primary Fl_Text_Selection
  740. */
  741. int Fl_Text_Display::in_selection( int X, int Y ) const {
  742. int pos = xy_to_position( X, Y, CHARACTER_POS );
  743. IS_UTF8_ALIGNED2(buffer(), pos)
  744. Fl_Text_Buffer *buf = mBuffer;
  745. return buf->primary_selection()->includes(pos);
  746. }
  747. /**
  748. \brief Nobody knows what this function does.
  749. Correct a column number based on an unconstrained position (as returned by
  750. TextDXYToUnconstrainedPosition) to be relative to the last actual newline
  751. in the buffer before the row and column position given, rather than the
  752. last line start created by line wrapping. This is an adapter
  753. for rectangular selections and code written before continuous wrap mode,
  754. which thinks that the unconstrained column is the number of characters
  755. from the last newline. Obviously this is time consuming, because it
  756. invloves character re-counting.
  757. \param row
  758. \param column
  759. \return something unknown
  760. \todo What does this do and how is it useful? Column numbers mean little in
  761. this context. Which functions depend on this one?
  762. \todo Unicode?
  763. */
  764. int Fl_Text_Display::wrapped_column(int row, int column) const {
  765. int lineStart, dispLineStart;
  766. if (!mContinuousWrap || row < 0 || row > mNVisibleLines)
  767. return column;
  768. dispLineStart = mLineStarts[row];
  769. if (dispLineStart == -1)
  770. return column;
  771. lineStart = buffer()->line_start(dispLineStart);
  772. return column + buffer()->count_displayed_characters(lineStart, dispLineStart);
  773. }
  774. /**
  775. \brief Nobody knows what this function does.
  776. Correct a row number from an unconstrained position (as returned by
  777. TextDXYToUnconstrainedPosition) to a straight number of newlines from the
  778. top line of the display. Because rectangular selections are based on
  779. newlines, rather than display wrapping, and anywhere a rectangular selection
  780. needs a row, it needs it in terms of un-wrapped lines.
  781. \param row
  782. \return something unknown
  783. \todo What does this do and how is it useful? Column numbers mean little in
  784. this context. Which functions depend on this one?
  785. */
  786. int Fl_Text_Display::wrapped_row(int row) const {
  787. if (!mContinuousWrap || row < 0 || row > mNVisibleLines)
  788. return row;
  789. return buffer()->count_lines(mFirstChar, mLineStarts[row]);
  790. }
  791. /**
  792. \brief Scroll the display to bring insertion cursor into view.
  793. Note: it would be nice to be able to do this without counting lines twice
  794. (scroll_() counts them too) and/or to count from the most efficient
  795. starting point, but the efficiency of this routine is not as important to
  796. the overall performance of the text display.
  797. \todo Unicode?
  798. */
  799. void Fl_Text_Display::display_insert() {
  800. int hOffset, topLine, X, Y;
  801. hOffset = mHorizOffset;
  802. topLine = mTopLineNum;
  803. if (insert_position() < mFirstChar) {
  804. topLine -= count_lines(insert_position(), mFirstChar, false);
  805. } else if (mNVisibleLines>=2 && mLineStarts[mNVisibleLines-2] != -1) {
  806. int lastChar = line_end(mLineStarts[mNVisibleLines-2],true);
  807. if (insert_position() >= lastChar)
  808. topLine += count_lines(lastChar - (wrap_uses_character(mLastChar) ? 0 : 1),
  809. insert_position(), false);
  810. }
  811. /* Find the new setting for horizontal offset (this is a bit ungraceful).
  812. If the line is visible, just use PositionToXY to get the position
  813. to scroll to, otherwise, do the vertical scrolling first, then the
  814. horizontal */
  815. if (!position_to_xy( mCursorPos, &X, &Y )) {
  816. scroll_(topLine, hOffset);
  817. if (!position_to_xy( mCursorPos, &X, &Y )) {
  818. #ifdef DEBUG
  819. printf ("*** display_insert/position_to_xy # GIVE UP !\n"); fflush(stdout);
  820. #endif // DEBUG
  821. return; /* Give up, it's not worth it (but why does it fail?) */
  822. }
  823. }
  824. if (X > text_area.x + text_area.w)
  825. hOffset += X-(text_area.x + text_area.w);
  826. else if (X < text_area.x)
  827. hOffset += X-text_area.x;
  828. /* Do the scroll */
  829. if (topLine != mTopLineNum || hOffset != mHorizOffset)
  830. scroll_(topLine, hOffset);
  831. }
  832. /**
  833. \brief Scrolls the text buffer to show the current insert position.
  834. This function triggers a complete recalculation, ending in a call to
  835. Fl_Text_Display::display_insert()
  836. */
  837. void Fl_Text_Display::show_insert_position() {
  838. display_insert_position_hint = 1;
  839. resize(x(), y(), w(), h());
  840. }
  841. /*
  842. Cursor movement functions
  843. */
  844. /**
  845. \brief Moves the current insert position right one character.
  846. \return 1 if the cursor moved, 0 if the end of the text was reached
  847. */
  848. int Fl_Text_Display::move_right() {
  849. if ( mCursorPos >= mBuffer->length() )
  850. return 0;
  851. int p = insert_position();
  852. int q = buffer()->next_char(p);
  853. insert_position(q);
  854. return 1;
  855. }
  856. /**
  857. \brief Moves the current insert position left one character.
  858. \return 1 if the cursor moved, 0 if the beginning of the text was reached
  859. */
  860. int Fl_Text_Display::move_left() {
  861. if ( mCursorPos <= 0 )
  862. return 0;
  863. int p = insert_position();
  864. int q = buffer()->prev_char_clipped(p);
  865. insert_position(q);
  866. return 1;
  867. }
  868. /**
  869. \brief Moves the current insert position up one line.
  870. \return 1 if the cursor moved, 0 if the beginning of the text was reached
  871. */
  872. int Fl_Text_Display::move_up() {
  873. int lineStartPos, xPos, prevLineStartPos, newPos, visLineNum;
  874. /* Find the position of the start of the line. Use the line starts array
  875. if possible */
  876. if ( position_to_line( mCursorPos, &visLineNum ) )
  877. lineStartPos = mLineStarts[ visLineNum ];
  878. else {
  879. lineStartPos = line_start( mCursorPos );
  880. visLineNum = -1;
  881. }
  882. if ( lineStartPos == 0 )
  883. return 0;
  884. /* Decide what column to move to, if there's a preferred column use that */
  885. if (mCursorPreferredXPos >= 0)
  886. xPos = mCursorPreferredXPos;
  887. else
  888. xPos = handle_vline(GET_WIDTH, lineStartPos, mCursorPos-lineStartPos,
  889. 0, 0, 0, 0, 0, INT_MAX);
  890. /* count forward from the start of the previous line to reach the column */
  891. if ( visLineNum != -1 && visLineNum != 0 )
  892. prevLineStartPos = mLineStarts[ visLineNum - 1 ];
  893. else
  894. prevLineStartPos = rewind_lines( lineStartPos, 1 );
  895. int lineEnd = line_end(prevLineStartPos, true);
  896. newPos = handle_vline(FIND_INDEX_FROM_ZERO, prevLineStartPos, lineEnd-prevLineStartPos,
  897. 0, 0, 0, 0, 0, xPos);
  898. /* move the cursor */
  899. insert_position( newPos );
  900. /* if a preferred column wasn't aleady established, establish it */
  901. mCursorPreferredXPos = xPos;
  902. return 1;
  903. }
  904. /**
  905. \brief Moves the current insert position down one line.
  906. \return 1 if the cursor moved, 0 if the beginning of the text was reached
  907. */
  908. int Fl_Text_Display::move_down() {
  909. int lineStartPos, xPos, newPos, visLineNum;
  910. if ( mCursorPos == mBuffer->length() )
  911. return 0;
  912. if ( position_to_line( mCursorPos, &visLineNum ) )
  913. lineStartPos = mLineStarts[ visLineNum ];
  914. else {
  915. lineStartPos = line_start( mCursorPos );
  916. visLineNum = -1;
  917. }
  918. if (mCursorPreferredXPos >= 0) {
  919. xPos = mCursorPreferredXPos;
  920. } else {
  921. xPos = handle_vline(GET_WIDTH, lineStartPos, mCursorPos-lineStartPos,
  922. 0, 0, 0, 0, 0, INT_MAX);
  923. }
  924. int nextLineStartPos = skip_lines( lineStartPos, 1, true );
  925. int lineEnd = line_end(nextLineStartPos, true);
  926. newPos = handle_vline(FIND_INDEX_FROM_ZERO, nextLineStartPos, lineEnd-nextLineStartPos,
  927. 0, 0, 0, 0, 0, xPos);
  928. insert_position( newPos );
  929. mCursorPreferredXPos = xPos;
  930. return 1;
  931. }
  932. /**
  933. \brief Count the number of lines between two positions.
  934. Same as BufCountLines, but takes into account wrapping if wrapping is
  935. turned on. If the caller knows that \p startPos is at a line start, it
  936. can pass \p startPosIsLineStart as True to make the call more efficient
  937. by avoiding the additional step of scanning back to the last newline.
  938. \param startPos index to first character
  939. \param endPos index after last character
  940. \param startPosIsLineStart avoid scanning back to the line start
  941. \return number of lines
  942. */
  943. int Fl_Text_Display::count_lines(int startPos, int endPos,
  944. bool startPosIsLineStart) const {
  945. IS_UTF8_ALIGNED2(buffer(), startPos)
  946. IS_UTF8_ALIGNED2(buffer(), endPos)
  947. int retLines, retPos, retLineStart, retLineEnd;
  948. #ifdef DEBUG
  949. printf("Fl_Text_Display::count_lines(startPos=%d, endPos=%d, startPosIsLineStart=%d\n",
  950. startPos, endPos, startPosIsLineStart);
  951. #endif // DEBUG
  952. /* If we're not wrapping use simple (and more efficient) BufCountLines */
  953. if (!mContinuousWrap)
  954. return buffer()->count_lines(startPos, endPos);
  955. wrapped_line_counter(buffer(), startPos, endPos, INT_MAX,
  956. startPosIsLineStart, 0, &retPos, &retLines, &retLineStart,
  957. &retLineEnd);
  958. #ifdef DEBUG
  959. printf(" # after WLC: retPos=%d, retLines=%d, retLineStart=%d, retLineEnd=%d\n",
  960. retPos, retLines, retLineStart, retLineEnd);
  961. #endif // DEBUG
  962. return retLines;
  963. }
  964. /**
  965. \brief Skip a number of lines forward.
  966. Same as BufCountForwardNLines, but takes into account line breaks when
  967. wrapping is turned on. If the caller knows that startPos is at a line start,
  968. it can pass "startPosIsLineStart" as True to make the call more efficient
  969. by avoiding the additional step of scanning back to the last newline.
  970. \param startPos index to starting character
  971. \param nLines number of lines to skip ahead
  972. \param startPosIsLineStart avoid scanning back to the line start
  973. \return new position as index
  974. */
  975. int Fl_Text_Display::skip_lines(int startPos, int nLines,
  976. bool startPosIsLineStart) {
  977. IS_UTF8_ALIGNED2(buffer(), startPos)
  978. int retLines, retPos, retLineStart, retLineEnd;
  979. /* if we're not wrapping use more efficient BufCountForwardNLines */
  980. if (!mContinuousWrap)
  981. return buffer()->skip_lines(startPos, nLines);
  982. /* wrappedLineCounter can't handle the 0 lines case */
  983. if (nLines == 0)
  984. return startPos;
  985. /* use the common line counting routine to count forward */
  986. wrapped_line_counter(buffer(), startPos, buffer()->length(),
  987. nLines, startPosIsLineStart, 0,
  988. &retPos, &retLines, &retLineStart, &retLineEnd);
  989. IS_UTF8_ALIGNED2(buffer(), retPos)
  990. return retPos;
  991. }
  992. /**
  993. \brief Returns the end of a line.
  994. Same as BufEndOfLine, but takes into account line breaks when wrapping
  995. is turned on. If the caller knows that \p startPos is at a line start, it
  996. can pass "startPosIsLineStart" as True to make the call more efficient
  997. by avoiding the additional step of scanning back to the last newline.
  998. Note that the definition of the end of a line is less clear when continuous
  999. wrap is on. With continuous wrap off, it's just a pointer to the newline
  1000. that ends the line. When it's on, it's the character beyond the last
  1001. \b displayable character on the line, where a whitespace character which has
  1002. been "converted" to a newline for wrapping is not considered displayable.
  1003. Also note that a line can be wrapped at a non-whitespace character if the
  1004. line had no whitespace. In this case, this routine returns a pointer to
  1005. the start of the next line. This is also consistent with the model used by
  1006. visLineLength.
  1007. \param startPos index to starting character
  1008. \param startPosIsLineStart avoid scanning back to the line start
  1009. \return new position as index
  1010. */
  1011. int Fl_Text_Display::line_end(int startPos, bool startPosIsLineStart) const {
  1012. IS_UTF8_ALIGNED2(buffer(), startPos)
  1013. int retLines, retPos, retLineStart, retLineEnd;
  1014. /* If we're not wrapping use more efficient BufEndOfLine */
  1015. if (!mContinuousWrap)
  1016. return buffer()->line_end(startPos);
  1017. if (startPos == buffer()->length())
  1018. return startPos;
  1019. wrapped_line_counter(buffer(), startPos, buffer()->length(), 1,
  1020. startPosIsLineStart, 0, &retPos, &retLines, &retLineStart,
  1021. &retLineEnd);
  1022. IS_UTF8_ALIGNED2(buffer(), retLineEnd)
  1023. return retLineEnd;
  1024. }
  1025. /**
  1026. \brief Return the beginning of a line.
  1027. Same as BufStartOfLine, but returns the character after last wrap point
  1028. rather than the last newline.
  1029. \param pos index to starting character
  1030. \return new position as index
  1031. */
  1032. int Fl_Text_Display::line_start(int pos) const {
  1033. IS_UTF8_ALIGNED2(buffer(), pos)
  1034. int retLines, retPos, retLineStart, retLineEnd;
  1035. /* If we're not wrapping, use the more efficient BufStartOfLine */
  1036. if (!mContinuousWrap)
  1037. return buffer()->line_start(pos);
  1038. wrapped_line_counter(buffer(), buffer()->line_start(pos), pos, INT_MAX, true, 0,
  1039. &retPos, &retLines, &retLineStart, &retLineEnd);
  1040. IS_UTF8_ALIGNED2(buffer(), retLineStart)
  1041. return retLineStart;
  1042. }
  1043. /**
  1044. \brief Skip a number of lines back.
  1045. Same as BufCountBackwardNLines, but takes into account line breaks when
  1046. wrapping is turned on.
  1047. \param startPos index to starting character
  1048. \param nLines number of lines to skip back
  1049. \return new position as index
  1050. */
  1051. int Fl_Text_Display::rewind_lines(int startPos, int nLines) {
  1052. IS_UTF8_ALIGNED2(buffer(), startPos)
  1053. Fl_Text_Buffer *buf = buffer();
  1054. int pos, lineStart, retLines, retPos, retLineStart, retLineEnd;
  1055. /* If we're not wrapping, use the more efficient BufCountBackwardNLines */
  1056. if (!mContinuousWrap)
  1057. return buf->rewind_lines(startPos, nLines);
  1058. pos = startPos;
  1059. for (;;) {
  1060. lineStart = buf->line_start(pos);
  1061. wrapped_line_counter(buf, lineStart, pos, INT_MAX, true, 0,
  1062. &retPos, &retLines, &retLineStart, &retLineEnd, false);
  1063. if (retLines > nLines)
  1064. return skip_lines(lineStart, retLines-nLines, true);
  1065. nLines -= retLines;
  1066. pos = lineStart - 1;
  1067. if (pos < 0)
  1068. return 0;
  1069. nLines -= 1;
  1070. }
  1071. }
  1072. static inline int fl_isseparator(unsigned int c) {
  1073. // FIXME: this does not take UCS-4 encoding into account
  1074. return c != '$' && c != '_' && (isspace(c) || ispunct(c));
  1075. }
  1076. /**
  1077. \brief Moves the current insert position right one word.
  1078. */
  1079. void Fl_Text_Display::next_word() {
  1080. int pos = insert_position();
  1081. while (pos < buffer()->length() && !fl_isseparator(buffer()->char_at(pos))) {
  1082. pos = buffer()->next_char(pos);
  1083. }
  1084. while (pos < buffer()->length() && fl_isseparator(buffer()->char_at(pos))) {
  1085. pos = buffer()->next_char(pos);
  1086. }
  1087. insert_position( pos );
  1088. }
  1089. /**
  1090. \brief Moves the current insert position left one word.
  1091. */
  1092. void Fl_Text_Display::previous_word() {
  1093. int pos = insert_position();
  1094. if (pos==0) return;
  1095. pos = buffer()->prev_char(pos);
  1096. while (pos && fl_isseparator(buffer()->char_at(pos))) {
  1097. pos = buffer()->prev_char(pos);
  1098. }
  1099. while (pos && !fl_isseparator(buffer()->char_at(pos))) {
  1100. pos = buffer()->prev_char(pos);
  1101. }
  1102. if (fl_isseparator(buffer()->char_at(pos))) {
  1103. pos = buffer()->next_char(pos);
  1104. }
  1105. insert_position( pos );
  1106. }
  1107. /**
  1108. \brief This is called before any characters are deleted.
  1109. Callback attached to the text buffer to receive delete information before
  1110. the modifications are actually made.
  1111. \param pos starting index of deletion
  1112. \param nDeleted number of bytes we will delete (must be UTF-8 aligned!)
  1113. \param cbArg "this" pointer for static callback function
  1114. */
  1115. void Fl_Text_Display::buffer_predelete_cb(int pos, int nDeleted, void *cbArg) {
  1116. Fl_Text_Display *textD = (Fl_Text_Display *)cbArg;
  1117. if (textD->mContinuousWrap) {
  1118. /* Note: we must perform this measurement, even if there is not a
  1119. single character deleted; the number of "deleted" lines is the
  1120. number of visual lines spanned by the real line in which the
  1121. modification takes place.
  1122. Also, a modification of the tab distance requires the same
  1123. kind of calculations in advance, even if the font width is "fixed",
  1124. because when the width of the tab characters changes, the layout
  1125. of the text may be completely different. */
  1126. IS_UTF8_ALIGNED2(textD->buffer(), pos)
  1127. textD->measure_deleted_lines(pos, nDeleted);
  1128. } else {
  1129. textD->mSuppressResync = 0; /* Probably not needed, but just in case */
  1130. }
  1131. }
  1132. /**
  1133. \brief This is called whenever the buffer is modified.
  1134. Callback attached to the text buffer to receive modification information
  1135. \param pos starting index of modification
  1136. \param nInserted number of bytes we inserted (must be UTF-8 aligned!)
  1137. \param nDeleted number of bytes deleted (must be UTF-8 aligned!)
  1138. \param nRestyled ??
  1139. \param deletedText this is what was removed, must not be NULL if nDeleted is set
  1140. \param cbArg "this" pointer for static callback function
  1141. */
  1142. void Fl_Text_Display::buffer_modified_cb( int pos, int nInserted, int nDeleted,
  1143. int nRestyled, const char *deletedText, void *cbArg ) {
  1144. int linesInserted, linesDeleted, startDispPos, endDispPos;
  1145. Fl_Text_Display *textD = ( Fl_Text_Display * ) cbArg;
  1146. Fl_Text_Buffer *buf = textD->mBuffer;
  1147. int oldFirstChar = textD->mFirstChar;
  1148. int scrolled, origCursorPos = textD->mCursorPos;
  1149. int wrapModStart = 0, wrapModEnd = 0;
  1150. IS_UTF8_ALIGNED2(buf, pos)
  1151. IS_UTF8_ALIGNED2(buf, oldFirstChar)
  1152. /* buffer modification cancels vertical cursor motion column */
  1153. if ( nInserted != 0 || nDeleted != 0 )
  1154. textD->mCursorPreferredXPos = -1;
  1155. /* Count the number of lines inserted and deleted, and in the case
  1156. of continuous wrap mode, how much has changed */
  1157. if (textD->mContinuousWrap) {
  1158. textD->find_wrap_range(deletedText, pos, nInserted, nDeleted,
  1159. &wrapModStart, &wrapModEnd, &linesInserted, &linesDeleted);
  1160. } else {
  1161. linesInserted = nInserted == 0 ? 0 : buf->count_lines( pos, pos + nInserted );
  1162. linesDeleted = nDeleted == 0 ? 0 : countlines( deletedText );
  1163. }
  1164. /* Update the line starts and mTopLineNum */
  1165. if ( nInserted != 0 || nDeleted != 0 ) {
  1166. if (textD->mContinuousWrap) {
  1167. textD->update_line_starts( wrapModStart, wrapModEnd-wrapModStart,
  1168. nDeleted + pos-wrapModStart + (wrapModEnd-(pos+nInserted)),
  1169. linesInserted, linesDeleted, &scrolled );
  1170. } else {
  1171. textD->update_line_starts( pos, nInserted, nDeleted, linesInserted,
  1172. linesDeleted, &scrolled );
  1173. }
  1174. } else
  1175. scrolled = 0;
  1176. /* If we're counting non-wrapped lines as well, maintain the absolute
  1177. (non-wrapped) line number of the text displayed */
  1178. if (textD->maintaining_absolute_top_line_number() &&
  1179. (nInserted != 0 || nDeleted != 0)) {
  1180. if (deletedText && (pos + nDeleted < oldFirstChar))
  1181. textD->mAbsTopLineNum += buf->count_lines(pos, pos + nInserted) -
  1182. countlines(deletedText);
  1183. else if (pos < oldFirstChar)
  1184. textD->reset_absolute_top_line_number();
  1185. }
  1186. /* Update the line count for the whole buffer */
  1187. textD->mNBufferLines += linesInserted - linesDeleted;
  1188. /* Update the cursor position */
  1189. if ( textD->mCursorToHint != NO_HINT ) {
  1190. textD->mCursorPos = textD->mCursorToHint;
  1191. textD->mCursorToHint = NO_HINT;
  1192. } else if ( textD->mCursorPos > pos ) {
  1193. if ( textD->mCursorPos < pos + nDeleted )
  1194. textD->mCursorPos = pos;
  1195. else
  1196. textD->mCursorPos += nInserted - nDeleted;
  1197. }
  1198. // refigure scrollbars & stuff
  1199. textD->resize(textD->x(), textD->y(), textD->w(), textD->h());
  1200. // don't need to do anything else if not visible?
  1201. if (!textD->visible_r()) return;
  1202. /* If the changes caused scrolling, re-paint everything and we're done. */
  1203. if ( scrolled ) {
  1204. textD->damage(FL_DAMAGE_EXPOSE);
  1205. if ( textD->mStyleBuffer ) /* See comments in extendRangeForStyleMods */
  1206. textD->mStyleBuffer->primary_selection()->selected(0);
  1207. return;
  1208. }
  1209. /* If the changes didn't cause scrolling, decide the range of characters
  1210. that need to be re-painted. Also if the cursor position moved, be
  1211. sure that the redisplay range covers the old cursor position so the
  1212. old cursor gets erased, and erase the bits of the cursor which extend
  1213. beyond the left and right edges of the text. */
  1214. startDispPos = textD->mContinuousWrap ? wrapModStart : pos;
  1215. IS_UTF8_ALIGNED2(buf, startDispPos)
  1216. if ( origCursorPos == startDispPos && textD->mCursorPos != startDispPos )
  1217. startDispPos = min( startDispPos, buf->prev_char_clipped(origCursorPos) );
  1218. IS_UTF8_ALIGNED2(buf, startDispPos)
  1219. if ( linesInserted == linesDeleted ) {
  1220. if ( nInserted == 0 && nDeleted == 0 )
  1221. endDispPos = pos + nRestyled;
  1222. else {
  1223. if (textD->mContinuousWrap)
  1224. endDispPos = wrapModEnd;
  1225. else
  1226. endDispPos = buf->next_char(buf->line_end( pos + nInserted ));
  1227. // CET - FIXME if ( origCursorPos >= startDispPos &&
  1228. // ( origCursorPos <= endDispPos || endDispPos == buf->length() ) )
  1229. }
  1230. if (linesInserted > 1) textD->draw_line_numbers(false);
  1231. } else {
  1232. endDispPos = buf->next_char(textD->mLastChar);
  1233. // CET - FIXME if ( origCursorPos >= pos )
  1234. /* If more than one line is inserted/deleted, a line break may have
  1235. been inserted or removed in between, and the line numbers may
  1236. have changed. If only one line is altered, line numbers cannot
  1237. be affected (the insertion or removal of a line break always
  1238. results in at least two lines being redrawn). */
  1239. textD->draw_line_numbers(false);
  1240. }
  1241. IS_UTF8_ALIGNED2(buf, startDispPos)
  1242. IS_UTF8_ALIGNED2(buf, endDispPos)
  1243. /* If there is a style buffer, check if the modification caused additional
  1244. changes that need to be redisplayed. (Redisplaying separately would
  1245. cause double-redraw on almost every modification involving styled
  1246. text). Extend the redraw range to incorporate style changes */
  1247. if ( textD->mStyleBuffer )
  1248. textD->extend_range_for_styles( &startDispPos, &endDispPos );
  1249. IS_UTF8_ALIGNED2(buf, startDispPos)
  1250. IS_UTF8_ALIGNED2(buf, endDispPos)
  1251. /* Redisplay computed range */
  1252. textD->redisplay_range( startDispPos, endDispPos );
  1253. }
  1254. /**
  1255. \brief Line numbering stuff, currently unused.
  1256. In continuous wrap mode, internal line numbers are calculated after
  1257. wrapping. A separate non-wrapped line count is maintained when line
  1258. numbering is turned on. There is some performance cost to maintaining this
  1259. line count, so normally absolute line numbers are not tracked if line
  1260. numbering is off. This routine allows callers to specify that they still
  1261. want this line count maintained (for use via TextDPosToLineAndCol).
  1262. More specifically, this allows the line number reported in the statistics
  1263. line to be calibrated in absolute lines, rather than post-wrapped lines.
  1264. */
  1265. void Fl_Text_Display::maintain_absolute_top_line_number(int state) {
  1266. mNeedAbsTopLineNum = state;
  1267. reset_absolute_top_line_number();
  1268. }
  1269. /**
  1270. \brief Line numbering stuff, currently unused.
  1271. Returns the absolute (non-wrapped) line number of the first line displayed.
  1272. Returns 0 if the absolute top line number is not being maintained.
  1273. */
  1274. int Fl_Text_Display::get_absolute_top_line_number() const {
  1275. if (!mContinuousWrap)
  1276. return mTopLineNum;
  1277. if (maintaining_absolute_top_line_number())
  1278. return mAbsTopLineNum;
  1279. return 0;
  1280. }
  1281. /**
  1282. \brief Line numbering stuff, currently unused.
  1283. Re-calculate absolute top line number for a change in scroll position.
  1284. */
  1285. void Fl_Text_Display::absolute_top_line_number(int oldFirstChar) {
  1286. if (maintaining_absolute_top_line_number()) {
  1287. if (mFirstChar < oldFirstChar)
  1288. mAbsTopLineNum -= buffer()->count_lines(mFirstChar, oldFirstChar);
  1289. else
  1290. mAbsTopLineNum += buffer()->count_lines(oldFirstChar, mFirstChar);
  1291. }
  1292. }
  1293. /**
  1294. \brief Line numbering stuff, currently unused.
  1295. Return true if a separate absolute top line number is being maintained
  1296. (for displaying line numbers or showing in the statistics line).
  1297. */
  1298. int Fl_Text_Display::maintaining_absolute_top_line_number() const {
  1299. return mContinuousWrap &&
  1300. (mLineNumWidth != 0 || mNeedAbsTopLineNum);
  1301. }
  1302. /**
  1303. \brief Line numbering stuff, probably unused.
  1304. Count lines from the beginning of the buffer to reestablish the
  1305. absolute (non-wrapped) top line number. If mode is not continuous wrap,
  1306. or the number is not being maintained, does nothing.
  1307. */
  1308. void Fl_Text_Display::reset_absolute_top_line_number() {
  1309. mAbsTopLineNum = 1;
  1310. absolute_top_line_number(0);
  1311. }
  1312. /**
  1313. \brief Convert a position index into a line number offset.
  1314. Find the line number of position \p pos relative to the first line of
  1315. displayed text. Returns 0 if the line is not displayed.
  1316. \param pos ??
  1317. \param[out] lineNum ??
  1318. \return ??
  1319. \todo What does this do?
  1320. */
  1321. int Fl_Text_Display::position_to_line( int pos, int *lineNum ) const {
  1322. IS_UTF8_ALIGNED2(buffer(), pos)
  1323. int i;
  1324. *lineNum = 0;
  1325. if ( pos < mFirstChar ) return 0;
  1326. if ( pos > mLastChar ) {
  1327. if ( empty_vlines() ) {
  1328. if ( mLastChar < mBuffer->length() ) {
  1329. if ( !position_to_line( mLastChar, lineNum ) ) {
  1330. Fl::error("Fl_Text_Display::position_to_line(): Consistency check ptvl failed");
  1331. return 0;
  1332. }
  1333. return ++( *lineNum ) <= mNVisibleLines - 1;
  1334. } else {
  1335. position_to_line( buffer()->prev_char_clipped(mLastChar), lineNum );
  1336. return 1;
  1337. }
  1338. }
  1339. return 0;
  1340. }
  1341. for ( i = mNVisibleLines - 1; i >= 0; i-- ) {
  1342. if ( mLineStarts[ i ] != -1 && pos >= mLineStarts[ i ] ) {
  1343. *lineNum = i;
  1344. return 1;
  1345. }
  1346. }
  1347. return 0; /* probably never be reached */
  1348. }
  1349. /**
  1350. Universal pixel machine.
  1351. We use a single function that handles all line layout, measuring, and drawing
  1352. \li draw a text range
  1353. \li return the width of a text range in pixels
  1354. \li return the index of a character that is at a pixel position
  1355. \param[in] mode DRAW_LINE, GET_WIDTH, FIND_INDEX
  1356. \param[in] lineStartPos index of first character
  1357. \param[in] lineLen size of string in bytes
  1358. \param[in] leftChar, rightChar
  1359. \param[in] Y drawing position
  1360. \param[in] bottomClip, leftClip, rightClip stop work when we reach the clipped
  1361. area. rightClip is the X position that we search in FIND_INDEX.
  1362. \retval DRAW_LINE index of last drawn character
  1363. \retval GET_WIDTH width in pixels of text segment if we would draw it
  1364. \retval FIND_INDEX index of character at given x position in window coordinates
  1365. \retval FIND_INDEX_FROM_ZERO index of character at given x position without scrolling and widget offsets
  1366. \todo we need to handle hidden hyphens and tabs here!
  1367. \todo we handle all styles and selections
  1368. \todo we must provide code to get pixel positions of the middle of a character as well
  1369. */
  1370. int Fl_Text_Display::handle_vline(
  1371. int mode,
  1372. int lineStartPos, int lineLen, int leftChar, int rightChar,
  1373. int Y, int bottomClip,
  1374. int leftClip, int rightClip) const
  1375. {
  1376. IS_UTF8_ALIGNED2(buffer(), lineStartPos)
  1377. // FIXME: we need to allow two modes for FIND_INDEX: one on the edge of the
  1378. // FIXME: character for selection, and one on the character center for cursors.
  1379. int i, X, startX, startIndex, style, charStyle;
  1380. char *lineStr;
  1381. if ( lineStartPos == -1 ) {
  1382. lineStr = NULL;
  1383. } else {
  1384. lineStr = mBuffer->text_range( lineStartPos, lineStartPos + lineLen );
  1385. }
  1386. if (mode==GET_WIDTH) {
  1387. X = 0;
  1388. } else if (mode==FIND_INDEX_FROM_ZERO) {
  1389. X = 0;
  1390. mode = FIND_INDEX;
  1391. } else {
  1392. X = text_area.x - mHorizOffset;
  1393. }
  1394. startX = X;
  1395. startIndex = 0;
  1396. if (!lineStr) {
  1397. // just clear the background
  1398. if (mode==DRAW_LINE) {
  1399. style = position_style(lineStartPos, lineLen, -1);
  1400. draw_string( style|BG_ONLY_MASK, text_area.x, Y, text_area.x+text_area.w, lineStr, lineLen );
  1401. }
  1402. if (mode==FIND_INDEX) {
  1403. IS_UTF8_ALIGNED2(buffer(), lineStartPos)
  1404. return lineStartPos;
  1405. }
  1406. return 0;
  1407. }
  1408. char currChar = 0, prevChar = 0;
  1409. // draw the line
  1410. style = position_style(lineStartPos, lineLen, 0);
  1411. for (i=0; i<lineLen; ) {
  1412. currChar = lineStr[i]; // one byte is enough to handele tabs and other cases
  1413. int len = fl_utf8len1(currChar);
  1414. if (len<=0) len = 1; // OUCH!
  1415. charStyle = position_style(lineStartPos, lineLen, i);
  1416. if (charStyle!=style || currChar=='\t' || prevChar=='\t') {
  1417. // draw a segment whenever the style changes or a Tab is found
  1418. int w = 0;
  1419. if (prevChar=='\t') {
  1420. // draw a single Tab space
  1421. int tab = (int)col_to_x(mBuffer->tab_distance());
  1422. int xAbs = (mode==GET_WIDTH) ? startX : startX+mHorizOffset-text_area.x;
  1423. w = (((xAbs/tab)+1)*tab) - xAbs;
  1424. if (mode==DRAW_LINE)
  1425. draw_string( style|BG_ONLY_MASK, startX, Y, startX+w, 0, 0 );
  1426. if (mode==FIND_INDEX && startX+w>rightClip) {
  1427. // find x pos inside block
  1428. free(lineStr);
  1429. return lineStartPos + startIndex;
  1430. }
  1431. } else {
  1432. // draw a text segment
  1433. w = int( string_width( lineStr+startIndex, i-startIndex, style ) );
  1434. if (mode==DRAW_LINE)
  1435. draw_string( style, startX, Y, startX+w, lineStr+startIndex, i-startIndex );
  1436. if (mode==FIND_INDEX && startX+w>rightClip) {
  1437. // find x pos inside block
  1438. int di = find_x(lineStr+startIndex, i-startIndex, style, rightClip-startX);
  1439. free(lineStr);
  1440. IS_UTF8_ALIGNED2(buffer(), (lineStartPos+startIndex+di))
  1441. return lineStartPos + startIndex + di;
  1442. }
  1443. }
  1444. style = charStyle;
  1445. startX += w;
  1446. startIndex = i;
  1447. }
  1448. i += len;
  1449. prevChar = currChar;
  1450. }
  1451. int w = 0;
  1452. if (currChar=='\t') {
  1453. // draw a single Tab space
  1454. int tab = (int)col_to_x(mBuffer->tab_distance());
  1455. int xAbs = (mode==GET_WIDTH) ? startX : startX+mHorizOffset-text_area.x;
  1456. w = (((xAbs/tab)+1)*tab) - xAbs;
  1457. if (mode==DRAW_LINE)
  1458. draw_string( style|BG_ONLY_MASK, startX, Y, startX+w, 0, 0 );
  1459. if (mode==FIND_INDEX) {
  1460. // find x pos inside block
  1461. free(lineStr);
  1462. return lineStartPos + startIndex + ( rightClip-startX>w ? 1 : 0 );
  1463. }
  1464. } else {
  1465. w = int( string_width( lineStr+startIndex, i-startIndex, style ) );
  1466. if (mode==DRAW_LINE)
  1467. draw_string( style, startX, Y, startX+w, lineStr+startIndex, i-startIndex );
  1468. if (mode==FIND_INDEX) {
  1469. // find x pos inside block
  1470. int di = find_x(lineStr+startIndex, i-startIndex, style, rightClip-startX);
  1471. free(lineStr);
  1472. IS_UTF8_ALIGNED2(buffer(), (lineStartPos+startIndex+di))
  1473. return lineStartPos + startIndex + di;
  1474. }
  1475. }
  1476. if (mode==GET_WIDTH) {
  1477. free(lineStr);
  1478. return startX+w;
  1479. }
  1480. // clear the rest of the line
  1481. startX += w;
  1482. style = position_style(lineStartPos, lineLen, i);
  1483. if (mode==DRAW_LINE)
  1484. draw_string( style|BG_ONLY_MASK, startX, Y, text_area.x+text_area.w, lineStr, lineLen );
  1485. free(lineStr);
  1486. IS_UTF8_ALIGNED2(buffer(), (lineStartPos+lineLen))
  1487. return lineStartPos + lineLen;
  1488. }
  1489. /**
  1490. \brief Find the index of the character that lies at the given x position.
  1491. \param s UTF-8 text string
  1492. \param len length of string
  1493. \param style index into style lookup table
  1494. \param x position in pixels
  1495. \return index into buffer
  1496. */
  1497. int Fl_Text_Display::find_x(const char *s, int len, int style, int x) const {
  1498. IS_UTF8_ALIGNED(s)
  1499. // TODO: use binary search which may be quicker.
  1500. int i = 0;
  1501. while (i<len) {
  1502. int cl = fl_utf8len1(s[i]);
  1503. int w = int( string_width(s, i+cl, style) );
  1504. if (w>x)
  1505. return i;
  1506. i += cl;
  1507. }
  1508. return len;
  1509. }
  1510. /**
  1511. \brief Draw a single line of text.
  1512. Draw the text on a single line represented by \p visLineNum (the
  1513. number of lines down from the top of the display), limited by
  1514. \p leftClip and \p rightClip window coordinates and \p leftCharIndex and
  1515. \p rightCharIndex character positions (not including the character at
  1516. position \p rightCharIndex).
  1517. \param visLineNum index of line in the visible line number lookup
  1518. \param leftClip, rightClip pixel position of clipped area
  1519. \param leftCharIndex, rightCharIndex index into line of segment that we want to draw
  1520. */
  1521. void Fl_Text_Display::draw_vline(int visLineNum, int leftClip, int rightClip,
  1522. int leftCharIndex, int rightCharIndex) {
  1523. int Y, lineStartPos, lineLen, fontHeight;
  1524. // printf("draw_vline(visLineNum=%d, leftClip=%d, rightClip=%d, leftCharIndex=%d, rightCharIndex=%d)\n",
  1525. // visLineNum, leftClip, rightClip, leftCharIndex, rightCharIndex);
  1526. // printf("nNVisibleLines=%d\n", mNVisibleLines);
  1527. /* If line is not displayed, skip it */
  1528. if ( visLineNum < 0 || visLineNum >= mNVisibleLines )
  1529. return;
  1530. /* Calculate Y coordinate of the string to draw */
  1531. fontHeight = mMaxsize;
  1532. Y = text_area.y + visLineNum * fontHeight;
  1533. /* Get the text, length, and buffer position of the line to display */
  1534. lineStartPos = mLineStarts[ visLineNum ];
  1535. if ( lineStartPos == -1 ) {
  1536. lineLen = 0;
  1537. } else {
  1538. lineLen = vline_length( visLineNum );
  1539. }
  1540. /* Shrink the clipping range to the active display area */
  1541. leftClip = max( text_area.x, leftClip );
  1542. rightClip = min( rightClip, text_area.x + text_area.w );
  1543. handle_vline(DRAW_LINE,
  1544. lineStartPos, lineLen, leftCharIndex, rightCharIndex,
  1545. Y, Y+fontHeight, leftClip, rightClip);
  1546. return;
  1547. }
  1548. /**
  1549. \brief Draw a text segment in a single style.
  1550. Draw a string or blank area according to parameter \p style, using the
  1551. appropriate colors and drawing method for that style, with top left
  1552. corner at \p X, \p Y. If style says to draw text, use \p string as
  1553. source of characters, and draw \p nChars, if style is FILL, erase
  1554. rectangle where text would have drawn from \p X to \p toX and from
  1555. \p Y to the maximum y extent of the current font(s).
  1556. \param style index into style lookup table
  1557. \param X, Y drawing origin
  1558. \param toX rightmost position if this is a fill operation
  1559. \param string text if this is a drawing operation
  1560. \param nChars number of characters to draw
  1561. */
  1562. void Fl_Text_Display::draw_string(int style,
  1563. int X, int Y, int toX,
  1564. const char *string, int nChars) const {
  1565. IS_UTF8_ALIGNED(string)
  1566. const Style_Table_Entry * styleRec;
  1567. /* Draw blank area rather than text, if that was the request */
  1568. if ( style & FILL_MASK ) {
  1569. if (style & TEXT_ONLY_MASK) return;
  1570. clear_rect( style, X, Y, toX - X, mMaxsize );
  1571. return;
  1572. }
  1573. /* Set font, color, and gc depending on style. For normal text, GCs
  1574. for normal drawing, or drawing within a Fl_Text_Selection or highlight are
  1575. pre-allocated and pre-configured. For syntax highlighting, GCs are
  1576. configured here, on the fly. */
  1577. Fl_Font font = textfont();
  1578. int fsize = textsize();
  1579. Fl_Color foreground;
  1580. Fl_Color background;
  1581. if ( style & STYLE_LOOKUP_MASK ) {
  1582. int si = (style & STYLE_LOOKUP_MASK) - 'A';
  1583. if (si < 0) si = 0;
  1584. else if (si >= mNStyles) si = mNStyles - 1;
  1585. styleRec = mStyleTable + si;
  1586. font = styleRec->font;
  1587. fsize = styleRec->size;
  1588. if (style & PRIMARY_MASK) {
  1589. if (Fl::focus() == (Fl_Widget*)this) background = selection_color();
  1590. else background = fl_color_average(color(), selection_color(), 0.4f);
  1591. } else if (style & HIGHLIGHT_MASK) {
  1592. if (Fl::focus() == (Fl_Widget*)this) background = fl_color_average(color(), selection_color(), 0.5f);
  1593. else background = fl_color_average(color(), selection_color(), 0.6f);
  1594. } else background = color();
  1595. foreground = fl_contrast(styleRec->color, background);
  1596. } else if (style & PRIMARY_MASK) {
  1597. if (Fl::focus() == (Fl_Widget*)this) background = selection_color();
  1598. else background = fl_color_average(color(), selection_color(), 0.4f);
  1599. foreground = fl_contrast(textcolor(), background);
  1600. } else if (style & HIGHLIGHT_MASK) {
  1601. if (Fl::focus() == (Fl_Widget*)this) background = fl_color_average(color(), selection_color(), 0.5f);
  1602. else background = fl_color_average(color(), selection_color(), 0.6f);
  1603. foreground = fl_contrast(textcolor(), background);
  1604. } else {
  1605. foreground = textcolor();
  1606. background = color();
  1607. }
  1608. if (!(style & TEXT_ONLY_MASK)) {
  1609. fl_color( background );
  1610. fl_rectf( X, Y, toX - X, mMaxsize );
  1611. }
  1612. if (!(style & BG_ONLY_MASK)) {
  1613. fl_color( foreground );
  1614. fl_font( font, fsize );
  1615. #if !(defined(__APPLE__) || defined(WIN32)) && USE_XFT
  1616. // makes sure antialiased ÄÖÜ do not leak on line above
  1617. fl_push_clip(X, Y, toX - X, mMaxsize);
  1618. #endif
  1619. fl_draw( string, nChars, X, Y + mMaxsize - fl_descent());
  1620. #if !(defined(__APPLE__) || defined(WIN32)) && USE_XFT
  1621. fl_pop_clip();
  1622. #endif
  1623. }
  1624. // CET - FIXME
  1625. /* If any space around the character remains unfilled (due to use of
  1626. different sized fonts for highlighting), fill in above or below
  1627. to erase previously drawn characters */
  1628. /*
  1629. if (fs->ascent < mAscent)
  1630. clear_rect( style, X, Y, toX - X, mAscent - fs->ascent);
  1631. if (fs->descent < mDescent)
  1632. clear_rect( style, X, Y + mAscent + fs->descent, toX - x,
  1633. mDescent - fs->descent);
  1634. */
  1635. /* Underline if style is secondary Fl_Text_Selection */
  1636. /*
  1637. if (style & SECONDARY_MASK)
  1638. XDrawLine(XtDisplay(mW), XtWindow(mW), gc, x,
  1639. y + mAscent, toX - 1, Y + fs->ascent);
  1640. */
  1641. }
  1642. /**
  1643. \brief Clear a rectangle with the appropriate background color for \p style.
  1644. \param style index into style table
  1645. \param X, Y, width, height size and position of background area
  1646. */
  1647. void Fl_Text_Display::clear_rect(int style,
  1648. int X, int Y,
  1649. int width, int height) const {
  1650. /* A width of zero means "clear to end of window" to XClearArea */
  1651. if ( width == 0 )
  1652. return;
  1653. if (style & PRIMARY_MASK) {
  1654. if (Fl::focus()==(Fl_Widget*)this) {
  1655. fl_color(selection_color());
  1656. } else {
  1657. fl_color(fl_color_average(color(), selection_color(), 0.4f));
  1658. }
  1659. } else if (style & HIGHLIGHT_MASK) {
  1660. if (Fl::focus()==(Fl_Widget*)this) {
  1661. fl_color(fl_color_average(color(), selection_color(), 0.5f));
  1662. } else {
  1663. fl_color(fl_color_average(color(), selection_color(), 0.6f));
  1664. }
  1665. } else {
  1666. fl_color( color() );
  1667. }
  1668. fl_rectf( X, Y, width, height );
  1669. }
  1670. /**
  1671. \brief Draw a cursor with top center at \p X, \p Y.
  1672. \param X, Y cursor position in pixels
  1673. */
  1674. void Fl_Text_Display::draw_cursor( int X, int Y ) {
  1675. typedef struct {
  1676. int x1, y1, x2, y2;
  1677. }
  1678. Segment;
  1679. Segment segs[ 5 ];
  1680. int left, right, cursorWidth, midY;
  1681. // int fontWidth = mFontStruct->min_bounds.width, nSegs = 0;
  1682. int fontWidth = TMPFONTWIDTH; // CET - FIXME
  1683. int nSegs = 0;
  1684. int fontHeight = mMaxsize;
  1685. int bot = Y + fontHeight - 1;
  1686. if ( X < text_area.x - 1 || X > text_area.x + text_area.w )
  1687. return;
  1688. /* For cursors other than the block, make them around 2/3 of a character
  1689. width, rounded to an even number of pixels so that X will draw an
  1690. odd number centered on the stem at x. */
  1691. cursorWidth = 4; //(fontWidth/3) * 2;
  1692. left = X - cursorWidth / 2;
  1693. right = left + cursorWidth;
  1694. /* Create segments and draw cursor */
  1695. if ( mCursorStyle == CARET_CURSOR ) {
  1696. midY = bot - fontHeight / 5;
  1697. segs[ 0 ].x1 = left; segs[ 0 ].y1 = bot; segs[ 0 ].x2 = X; segs[ 0 ].y2 = midY;
  1698. segs[ 1 ].x1 = X; segs[ 1 ].y1 = midY; segs[ 1 ].x2 = right; segs[ 1 ].y2 = bot;
  1699. segs[ 2 ].x1 = left; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = X; segs[ 2 ].y2 = midY - 1;
  1700. segs[ 3 ].x1 = X; segs[ 3 ].y1 = midY - 1; segs[ 3 ].x2 = right; segs[ 3 ].y2 = bot;
  1701. nSegs = 4;
  1702. } else if ( mCursorStyle == NORMAL_CURSOR ) {
  1703. segs[ 0 ].x1 = left; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = right; segs[ 0 ].y2 = Y;
  1704. segs[ 1 ].x1 = X; segs[ 1 ].y1 = Y; segs[ 1 ].x2 = X; segs[ 1 ].y2 = bot;
  1705. segs[ 2 ].x1 = left; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = right; segs[ 2 ].y2 = bot;
  1706. nSegs = 3;
  1707. } else if ( mCursorStyle == HEAVY_CURSOR ) {
  1708. segs[ 0 ].x1 = X - 1; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = X - 1; segs[ 0 ].y2 = bot;
  1709. segs[ 1 ].x1 = X; segs[ 1 ].y1 = Y; segs[ 1 ].x2 = X; segs[ 1 ].y2 = bot;
  1710. segs[ 2 ].x1 = X + 1; segs[ 2 ].y1 = Y; segs[ 2 ].x2 = X + 1; segs[ 2 ].y2 = bot;
  1711. segs[ 3 ].x1 = left; segs[ 3 ].y1 = Y; segs[ 3 ].x2 = right; segs[ 3 ].y2 = Y;
  1712. segs[ 4 ].x1 = left; segs[ 4 ].y1 = bot; segs[ 4 ].x2 = right; segs[ 4 ].y2 = bot;
  1713. nSegs = 5;
  1714. } else if ( mCursorStyle == DIM_CURSOR ) {
  1715. midY = Y + fontHeight / 2;
  1716. segs[ 0 ].x1 = X; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = X; segs[ 0 ].y2 = Y;
  1717. segs[ 1 ].x1 = X; segs[ 1 ].y1 = midY; segs[ 1 ].x2 = X; segs[ 1 ].y2 = midY;
  1718. segs[ 2 ].x1 = X; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = X; segs[ 2 ].y2 = bot;
  1719. nSegs = 3;
  1720. } else if ( mCursorStyle == BLOCK_CURSOR ) {
  1721. right = X + fontWidth;
  1722. segs[ 0 ].x1 = X; segs[ 0 ].y1 = Y; segs[ 0 ].x2 = right; segs[ 0 ].y2 = Y;
  1723. segs[ 1 ].x1 = right; segs[ 1 ].y1 = Y; segs[ 1 ].x2 = right; segs[ 1 ].y2 = bot;
  1724. segs[ 2 ].x1 = right; segs[ 2 ].y1 = bot; segs[ 2 ].x2 = X; segs[ 2 ].y2 = bot;
  1725. segs[ 3 ].x1 = X; segs[ 3 ].y1 = bot; segs[ 3 ].x2 = X; segs[ 3 ].y2 = Y;
  1726. nSegs = 4;
  1727. }
  1728. fl_color( mCursor_color );
  1729. for ( int k = 0; k < nSegs; k++ ) {
  1730. fl_line( segs[ k ].x1, segs[ k ].y1, segs[ k ].x2, segs[ k ].y2 );
  1731. }
  1732. }
  1733. /**
  1734. \brief Find the correct style for a character.
  1735. Determine the drawing method to use to draw a specific character from "buf".
  1736. \p lineStartPos gives the character index where the line begins, \p lineIndex,
  1737. the number of characters past the beginning of the line, and \p lineIndex
  1738. the number of displayed characters past the beginning of the line. Passing
  1739. \p lineStartPos of -1 returns the drawing style for "no text".
  1740. Why not just: position_style(pos)? Because style applies to blank areas
  1741. of the window beyond the text boundaries, and because this routine must also
  1742. decide whether a position is inside of a rectangular Fl_Text_Selection, and do
  1743. so efficiently, without re-counting character positions from the start of the
  1744. line.
  1745. Note that style is a somewhat incorrect name, drawing method would
  1746. be more appropriate.
  1747. \param lineStartPos beginning of this line
  1748. \param lineLen number of bytes in line
  1749. \param lineIndex position of character within line
  1750. \return style for the given character
  1751. */
  1752. int Fl_Text_Display::position_style( int lineStartPos, int lineLen, int lineIndex) const
  1753. {
  1754. IS_UTF8_ALIGNED2(buffer(), lineStartPos)
  1755. Fl_Text_Buffer * buf = mBuffer;
  1756. Fl_Text_Buffer *styleBuf = mStyleBuffer;
  1757. int pos, style = 0;
  1758. if ( lineStartPos == -1 || buf == NULL )
  1759. return FILL_MASK;
  1760. pos = lineStartPos + min( lineIndex, lineLen );
  1761. if ( lineIndex >= lineLen )
  1762. style = FILL_MASK;
  1763. else if ( styleBuf != NULL ) {
  1764. style = ( unsigned char ) styleBuf->byte_at( pos );
  1765. if (style == mUnfinishedStyle && mUnfinishedHighlightCB) {
  1766. /* encountered "unfinished" style, trigger parsing */
  1767. (mUnfinishedHighlightCB)( pos, mHighlightCBArg);
  1768. style = (unsigned char) styleBuf->byte_at( pos);
  1769. }
  1770. }
  1771. if (buf->primary_selection()->includes(pos))
  1772. style |= PRIMARY_MASK;
  1773. if (buf->highlight_selection()->includes(pos))
  1774. style |= HIGHLIGHT_MASK;
  1775. if (buf->secondary_selection()->includes(pos))
  1776. style |= SECONDARY_MASK;
  1777. return style;
  1778. }
  1779. /**
  1780. \brief Find the width of a string in the font of a particular style.
  1781. \param string the text
  1782. \param length number of bytes in string
  1783. \param style index into style table
  1784. \return width of text segment in pixels
  1785. */
  1786. double Fl_Text_Display::string_width( const char *string, int length, int style ) const {
  1787. IS_UTF8_ALIGNED(string)
  1788. Fl_Font font;
  1789. Fl_Fontsize fsize;
  1790. if ( mNStyles && (style & STYLE_LOOKUP_MASK) ) {
  1791. int si = (style & STYLE_LOOKUP_MASK) - 'A';
  1792. if (si < 0) si = 0;
  1793. else if (si >= mNStyles) si = mNStyles - 1;
  1794. font = mStyleTable[si].font;
  1795. fsize = mStyleTable[si].size;
  1796. } else {
  1797. font = textfont();
  1798. fsize = textsize();
  1799. }
  1800. fl_font( font, fsize );
  1801. return fl_width( string, length );
  1802. }
  1803. /**
  1804. \brief Translate a pixel position into a character index.
  1805. Translate window coordinates to the nearest (insert cursor or character
  1806. cell) text position. The parameter \p posType specifies how to interpret the
  1807. position: CURSOR_POS means translate the coordinates to the nearest cursor
  1808. position, and CHARACTER_POS means return the position of the character
  1809. closest to (\p X, \p Y).
  1810. \param X, Y pixel position
  1811. \param posType CURSOR_POS or CHARACTER_POS
  1812. \return index into text buffer
  1813. */
  1814. int Fl_Text_Display::xy_to_position( int X, int Y, int posType ) const {
  1815. int lineStart, lineLen, fontHeight;
  1816. int visLineNum;
  1817. /* Find the visible line number corresponding to the Y coordinate */
  1818. fontHeight = mMaxsize;
  1819. visLineNum = ( Y - text_area.y ) / fontHeight;
  1820. if ( visLineNum < 0 )
  1821. return mFirstChar;
  1822. if ( visLineNum >= mNVisibleLines )
  1823. visLineNum = mNVisibleLines - 1;
  1824. /* Find the position at the start of the line */
  1825. lineStart = mLineStarts[ visLineNum ];
  1826. /* If the line start was empty, return the last position in the buffer */
  1827. if ( lineStart == -1 )
  1828. return mBuffer->length();
  1829. /* Get the line text and its length */
  1830. lineLen = vline_length( visLineNum );
  1831. return handle_vline(FIND_INDEX,
  1832. lineStart, lineLen, 0, 0,
  1833. 0, 0,
  1834. text_area.x, X);
  1835. }
  1836. /**
  1837. \brief Translate pixel coordinates into row and column.
  1838. Translate window coordinates to the nearest row and column number for
  1839. positioning the cursor. This, of course, makes no sense when the font is
  1840. proportional, since there are no absolute columns. The parameter posType
  1841. specifies how to interpret the position: CURSOR_POS means translate the
  1842. coordinates to the nearest position between characters, and CHARACTER_POS
  1843. means translate the position to the nearest character cell.
  1844. \param X, Y pixel coordinates
  1845. \param[out] row, column neares row and column
  1846. \param posType CURSOR_POS or CHARACTER_POS
  1847. */
  1848. void Fl_Text_Display::xy_to_rowcol( int X, int Y, int *row,
  1849. int *column, int posType ) const {
  1850. int fontHeight = mMaxsize;
  1851. int fontWidth = TMPFONTWIDTH; //mFontStruct->max_bounds.width;
  1852. /* Find the visible line number corresponding to the Y coordinate */
  1853. *row = ( Y - text_area.y ) / fontHeight;
  1854. if ( *row < 0 ) *row = 0;
  1855. if ( *row >= mNVisibleLines ) *row = mNVisibleLines - 1;
  1856. *column = ( ( X - text_area.x ) + mHorizOffset +
  1857. ( posType == CURSOR_POS ? fontWidth / 2 : 0 ) ) / fontWidth;
  1858. if ( *column < 0 ) * column = 0;
  1859. }
  1860. /**
  1861. \brief Offset line start counters for a new vertical scroll position.
  1862. Offset the line starts array, mTopLineNum, mFirstChar and lastChar, for a new
  1863. vertical scroll position given by newTopLineNum. If any currently displayed
  1864. lines will still be visible, salvage the line starts values, otherwise,
  1865. count lines from the nearest known line start (start or end of buffer, or
  1866. the closest value in the mLineStarts array)
  1867. \param newTopLineNum index into buffer
  1868. */
  1869. void Fl_Text_Display::offset_line_starts( int newTopLineNum ) {
  1870. int oldTopLineNum = mTopLineNum;
  1871. int oldFirstChar = mFirstChar;
  1872. int lineDelta = newTopLineNum - oldTopLineNum;
  1873. int nVisLines = mNVisibleLines;
  1874. int *lineStarts = mLineStarts;
  1875. int i, lastLineNum;
  1876. Fl_Text_Buffer *buf = mBuffer;
  1877. /* If there was no offset, nothing needs to be changed */
  1878. if ( lineDelta == 0 )
  1879. return;
  1880. /* Find the new value for mFirstChar by counting lines from the nearest
  1881. known line start (start or end of buffer, or the closest value in the
  1882. lineStarts array) */
  1883. lastLineNum = oldTopLineNum + nVisLines - 1;
  1884. if ( newTopLineNum < oldTopLineNum && newTopLineNum < -lineDelta ) {
  1885. mFirstChar = skip_lines( 0, newTopLineNum - 1, true );
  1886. } else if ( newTopLineNum < oldTopLineNum ) {
  1887. mFirstChar = rewind_lines( mFirstChar, -lineDelta );
  1888. } else if ( newTopLineNum < lastLineNum ) {
  1889. mFirstChar = lineStarts[ newTopLineNum - oldTopLineNum ];
  1890. } else if ( newTopLineNum - lastLineNum < mNBufferLines - newTopLineNum ) {
  1891. mFirstChar = skip_lines( lineStarts[ nVisLines - 1 ],
  1892. newTopLineNum - lastLineNum, true );
  1893. } else {
  1894. mFirstChar = rewind_lines( buf->length(), mNBufferLines - newTopLineNum + 1 );
  1895. }
  1896. /* Fill in the line starts array */
  1897. if ( lineDelta < 0 && -lineDelta < nVisLines ) {
  1898. for ( i = nVisLines - 1; i >= -lineDelta; i-- )
  1899. lineStarts[ i ] = lineStarts[ i + lineDelta ];
  1900. calc_line_starts( 0, -lineDelta );
  1901. } else if ( lineDelta > 0 && lineDelta < nVisLines ) {
  1902. for ( i = 0; i < nVisLines - lineDelta; i++ )
  1903. lineStarts[ i ] = lineStarts[ i + lineDelta ];
  1904. calc_line_starts( nVisLines - lineDelta, nVisLines - 1 );
  1905. } else
  1906. calc_line_starts( 0, nVisLines );
  1907. /* Set lastChar and mTopLineNum */
  1908. calc_last_char();
  1909. mTopLineNum = newTopLineNum;
  1910. /* If we're numbering lines or being asked to maintain an absolute line
  1911. number, re-calculate the absolute line number */
  1912. absolute_top_line_number(oldFirstChar);
  1913. }
  1914. /**
  1915. \brief Update line start arrays and variables.
  1916. Update the line starts array, mTopLineNum, mFirstChar and lastChar for this
  1917. text display after a modification to the text buffer, given by the
  1918. position \p pos where the change began, and the numbers of characters
  1919. and lines inserted and deleted.
  1920. \param pos index into buffer of recent changes
  1921. \param charsInserted number of bytes(!) inserted
  1922. \param charsDeleted number of bytes(!) deleted
  1923. \param linesInserted number of lines
  1924. \param linesDeleted number of lines
  1925. \param[out] scrolled set to 1 if the text display needs to be scrolled
  1926. */
  1927. void Fl_Text_Display::update_line_starts(int pos, int charsInserted,
  1928. int charsDeleted, int linesInserted,
  1929. int linesDeleted, int *scrolled ) {
  1930. IS_UTF8_ALIGNED2(buffer(), pos)
  1931. int *lineStarts = mLineStarts;
  1932. int i, lineOfPos, lineOfEnd, nVisLines = mNVisibleLines;
  1933. int charDelta = charsInserted - charsDeleted;
  1934. int lineDelta = linesInserted - linesDeleted;
  1935. /* If all of the changes were before the displayed text, the display
  1936. doesn't change, just update the top line num and offset the line
  1937. start entries and first and last characters */
  1938. if ( pos + charsDeleted < mFirstChar ) {
  1939. mTopLineNum += lineDelta;
  1940. for ( i = 0; i < nVisLines && lineStarts[i] != -1; i++ )
  1941. lineStarts[ i ] += charDelta;
  1942. mFirstChar += charDelta;
  1943. mLastChar += charDelta;
  1944. *scrolled = 0;
  1945. return;
  1946. }
  1947. /* The change began before the beginning of the displayed text, but
  1948. part or all of the displayed text was deleted */
  1949. if ( pos < mFirstChar ) {
  1950. /* If some text remains in the window, anchor on that */
  1951. if ( position_to_line( pos + charsDeleted, &lineOfEnd ) &&
  1952. ++lineOfEnd < nVisLines && lineStarts[ lineOfEnd ] != -1 ) {
  1953. mTopLineNum = max( 1, mTopLineNum + lineDelta );
  1954. mFirstChar = rewind_lines(lineStarts[ lineOfEnd ] + charDelta, lineOfEnd );
  1955. /* Otherwise anchor on original line number and recount everything */
  1956. } else {
  1957. if ( mTopLineNum > mNBufferLines + lineDelta ) {
  1958. mTopLineNum = 1;
  1959. mFirstChar = 0;
  1960. } else
  1961. mFirstChar = skip_lines( 0, mTopLineNum - 1, true );
  1962. }
  1963. calc_line_starts( 0, nVisLines - 1 );
  1964. /* calculate lastChar by finding the end of the last displayed line */
  1965. calc_last_char();
  1966. *scrolled = 1;
  1967. return;
  1968. }
  1969. /* If the change was in the middle of the displayed text (it usually is),
  1970. salvage as much of the line starts array as possible by moving and
  1971. offsetting the entries after the changed area, and re-counting the
  1972. added lines or the lines beyond the salvaged part of the line starts
  1973. array */
  1974. if ( pos <= mLastChar ) {
  1975. /* find line on which the change began */
  1976. position_to_line( pos, &lineOfPos );
  1977. /* salvage line starts after the changed area */
  1978. if ( lineDelta == 0 ) {
  1979. for ( i = lineOfPos + 1; i < nVisLines && lineStarts[ i ] != -1; i++ )
  1980. lineStarts[ i ] += charDelta;
  1981. } else if ( lineDelta > 0 ) {
  1982. for ( i = nVisLines - 1; i >= lineOfPos + lineDelta + 1; i-- )
  1983. lineStarts[ i ] = lineStarts[ i - lineDelta ] +
  1984. ( lineStarts[ i - lineDelta ] == -1 ? 0 : charDelta );
  1985. } else /* (lineDelta < 0) */ {
  1986. for ( i = max( 0, lineOfPos + 1 ); i < nVisLines + lineDelta; i++ )
  1987. lineStarts[ i ] = lineStarts[ i - lineDelta ] +
  1988. ( lineStarts[ i - lineDelta ] == -1 ? 0 : charDelta );
  1989. }
  1990. /* fill in the missing line starts */
  1991. if ( linesInserted >= 0 )
  1992. calc_line_starts( lineOfPos + 1, lineOfPos + linesInserted );
  1993. if ( lineDelta < 0 )
  1994. calc_line_starts( nVisLines + lineDelta, nVisLines );
  1995. /* calculate lastChar by finding the end of the last displayed line */
  1996. calc_last_char();
  1997. *scrolled = 0;
  1998. return;
  1999. }
  2000. /* Change was past the end of the displayed text, but displayable by virtue
  2001. of being an insert at the end of the buffer into visible blank lines */
  2002. if ( empty_vlines() ) {
  2003. position_to_line( pos, &lineOfPos );
  2004. calc_line_starts( lineOfPos, lineOfPos + linesInserted );
  2005. calc_last_char();
  2006. *scrolled = 0;
  2007. return;
  2008. }
  2009. /* Change was beyond the end of the buffer and not visible, do nothing */
  2010. *scrolled = 0;
  2011. }
  2012. /**
  2013. \brief Update the line start arrays.
  2014. Scan through the text in the "textD"'s buffer and recalculate the line
  2015. starts array values beginning at index "startLine" and continuing through
  2016. (including) "endLine". It assumes that the line starts entry preceding
  2017. "startLine" (or mFirstChar if startLine is 0) is good, and re-counts
  2018. newlines to fill in the requested entries. Out of range values for
  2019. "startLine" and "endLine" are acceptable.
  2020. \param startLine, endLine range of lines to scan as line numbers
  2021. */
  2022. void Fl_Text_Display::calc_line_starts( int startLine, int endLine ) {
  2023. int startPos, bufLen = mBuffer->length();
  2024. int line, lineEnd, nextLineStart, nVis = mNVisibleLines;
  2025. int *lineStarts = mLineStarts;
  2026. /* Clean up (possibly) messy input parameters */
  2027. if ( endLine < 0 ) endLine = 0;
  2028. if ( endLine >= nVis ) endLine = nVis - 1;
  2029. if ( startLine < 0 ) startLine = 0;
  2030. if ( startLine >= nVis ) startLine = nVis - 1;
  2031. if ( startLine > endLine )
  2032. return;
  2033. /* Find the last known good line number -> position mapping */
  2034. if ( startLine == 0 ) {
  2035. lineStarts[ 0 ] = mFirstChar;
  2036. startLine = 1;
  2037. }
  2038. startPos = lineStarts[ startLine - 1 ];
  2039. /* If the starting position is already past the end of the text,
  2040. fill in -1's (means no text on line) and return */
  2041. if ( startPos == -1 ) {
  2042. for ( line = startLine; line <= endLine; line++ )
  2043. lineStarts[ line ] = -1;
  2044. return;
  2045. }
  2046. /* Loop searching for ends of lines and storing the positions of the
  2047. start of the next line in lineStarts */
  2048. for ( line = startLine; line <= endLine; line++ ) {
  2049. find_line_end(startPos, true, &lineEnd, &nextLineStart);
  2050. startPos = nextLineStart;
  2051. if ( startPos >= bufLen ) {
  2052. /* If the buffer ends with a newline or line break, put
  2053. buf->length() in the next line start position (instead of
  2054. a -1 which is the normal marker for an empty line) to
  2055. indicate that the cursor may safely be displayed there */
  2056. if ( line == 0 || ( lineStarts[ line - 1 ] != bufLen &&
  2057. lineEnd != nextLineStart ) ) {
  2058. lineStarts[ line ] = bufLen;
  2059. line++;
  2060. }
  2061. break;
  2062. }
  2063. lineStarts[ line ] = startPos;
  2064. }
  2065. /* Set any entries beyond the end of the text to -1 */
  2066. for ( ; line <= endLine; line++ )
  2067. lineStarts[ line ] = -1;
  2068. }
  2069. /**
  2070. \brief Update last display character index.
  2071. Given a Fl_Text_Display with a complete, up-to-date lineStarts array, update
  2072. the lastChar entry to point to the last buffer position displayed.
  2073. */
  2074. void Fl_Text_Display::calc_last_char() {
  2075. int i;
  2076. for (i = mNVisibleLines - 1; i >= 0 && mLineStarts[i] == -1; i--) ;
  2077. mLastChar = i < 0 ? 0 : line_end(mLineStarts[i], true);
  2078. }
  2079. /**
  2080. \brief Scrolls the current buffer to start at the specified line and column.
  2081. \param topLineNum top line number
  2082. \param horizOffset column number
  2083. \todo Column numbers make little sense here.
  2084. */
  2085. void Fl_Text_Display::scroll(int topLineNum, int horizOffset) {
  2086. mTopLineNumHint = topLineNum;
  2087. mHorizOffsetHint = horizOffset;
  2088. resize(x(), y(), w(), h());
  2089. }
  2090. /**
  2091. \brief Scrolls the current buffer to start at the specified line and column.
  2092. \param topLineNum top line number
  2093. \param horizOffset in pixels
  2094. \return 0 if nothing changed, 1 if we scrolled
  2095. */
  2096. int Fl_Text_Display::scroll_(int topLineNum, int horizOffset) {
  2097. /* Limit the requested scroll position to allowable values */
  2098. if (topLineNum > mNBufferLines + 3 - mNVisibleLines)
  2099. topLineNum = mNBufferLines + 3 - mNVisibleLines;
  2100. if (topLineNum < 1) topLineNum = 1;
  2101. if (horizOffset > longest_vline() - text_area.w)
  2102. horizOffset = longest_vline() - text_area.w;
  2103. if (horizOffset < 0) horizOffset = 0;
  2104. /* Do nothing if scroll position hasn't actually changed or there's no
  2105. window to draw in yet */
  2106. if (mHorizOffset == horizOffset && mTopLineNum == topLineNum)
  2107. return 0;
  2108. /* If the vertical scroll position has changed, update the line
  2109. starts array and related counters in the text display */
  2110. offset_line_starts(topLineNum);
  2111. /* Just setting mHorizOffset is enough information for redisplay */
  2112. mHorizOffset = horizOffset;
  2113. // redraw all text
  2114. damage(FL_DAMAGE_EXPOSE);
  2115. return 1;
  2116. }
  2117. /**
  2118. \brief Update vertical scrollbar.
  2119. Update the minimum, maximum, slider size, page increment, and value
  2120. for vertical scrollbar.
  2121. */
  2122. void Fl_Text_Display::update_v_scrollbar() {
  2123. /* The vertical scrollbar value and slider size directly represent the top
  2124. line number, and the number of visible lines respectively. The scroll
  2125. bar maximum value is chosen to generally represent the size of the whole
  2126. buffer, with minor adjustments to keep the scrollbar widget happy */
  2127. #ifdef DEBUG
  2128. printf("Fl_Text_Display::update_v_scrollbar():\n"
  2129. " mTopLineNum=%d, mNVisibleLines=%d, mNBufferLines=%d\n",
  2130. mTopLineNum, mNVisibleLines, mNBufferLines);
  2131. #endif // DEBUG
  2132. mVScrollBar->value(mTopLineNum, mNVisibleLines, 1, mNBufferLines+2);
  2133. mVScrollBar->linesize(3);
  2134. }
  2135. /**
  2136. \brief Update vertical scrollbar.
  2137. Update the minimum, maximum, slider size, page increment, and value
  2138. for the horizontal scrollbar.
  2139. */
  2140. void Fl_Text_Display::update_h_scrollbar() {
  2141. int sliderMax = max(longest_vline(), text_area.w + mHorizOffset);
  2142. mHScrollBar->value( mHorizOffset, text_area.w, 0, sliderMax );
  2143. }
  2144. /**
  2145. \brief Callbacks for drag or valueChanged on scrollbars.
  2146. */
  2147. void Fl_Text_Display::v_scrollbar_cb(Fl_Scrollbar* b, Fl_Text_Display* textD) {
  2148. if (b->value() == textD->mTopLineNum) return;
  2149. textD->scroll(b->value(), textD->mHorizOffset);
  2150. }
  2151. /**
  2152. \brief Callbacks for drag or valueChanged on scrollbars.
  2153. */
  2154. void Fl_Text_Display::h_scrollbar_cb(Fl_Scrollbar* b, Fl_Text_Display* textD) {
  2155. if (b->value() == textD->mHorizOffset) return;
  2156. textD->scroll(textD->mTopLineNum, b->value());
  2157. }
  2158. /**
  2159. \brief Refresh the line number area.
  2160. If clearAll is False, writes only over the character cell areas. Setting
  2161. clearAll to True will clear out any stray marks outside of the character cell
  2162. area, which might have been left from before a resize or font change.
  2163. This function is not used.
  2164. */
  2165. void Fl_Text_Display::draw_line_numbers(bool /*clearAll*/) {
  2166. #if 0
  2167. int y, line, visLine, nCols, lineStart;
  2168. char lineNumString[12];
  2169. int lineHeight = mMaxsize ? mMaxsize : textsize_;
  2170. int charWidth = TMPFONTWIDTH; //mFontStruct->max_bounds.width;
  2171. /* Don't draw if mLineNumWidth == 0 (line numbers are hidden), or widget is
  2172. not yet realized */
  2173. if (mLineNumWidth == 0 || visible_r())
  2174. return;
  2175. /* GC is allocated on demand, since not everyone will use line numbering */
  2176. if (textD->lineNumGC == NULL) {
  2177. XGCValues values;
  2178. values.foreground = textD->lineNumFGPixel;
  2179. values.background = textD->bgPixel;
  2180. values.font = textD->fontStruct->fid;
  2181. textD->lineNumGC = XtGetGC(textD->w,
  2182. GCFont| GCForeground | GCBackground, &values);
  2183. }
  2184. /* Erase the previous contents of the line number area, if requested */
  2185. if (clearAll)
  2186. XClearArea(XtDisplay(textD->w), XtWindow(textD->w), textD->lineNumLeft,
  2187. textD->top, textD->lineNumWidth, textD->height, False);
  2188. /* Draw the line numbers, aligned to the text */
  2189. nCols = min(11, textD->lineNumWidth / charWidth);
  2190. y = textD->top;
  2191. line = getAbsTopLineNum(textD);
  2192. for (visLine=0; visLine < textD->nVisibleLines; visLine++) {
  2193. lineStart = textD->lineStarts[visLine];
  2194. if (lineStart != -1 && (lineStart==0 ||
  2195. BufGetCharacter(textD->buffer, lineStart-1)=='\n')) {
  2196. sprintf(lineNumString, "%*d", nCols, line);
  2197. XDrawImageString(XtDisplay(textD->w), XtWindow(textD->w),
  2198. textD->lineNumGC, textD->lineNumLeft, y + textD->ascent,
  2199. lineNumString, strlen(lineNumString));
  2200. line++;
  2201. } else {
  2202. XClearArea(XtDisplay(textD->w), XtWindow(textD->w),
  2203. textD->lineNumLeft, y, textD->lineNumWidth,
  2204. textD->ascent + textD->descent, False);
  2205. if (visLine == 0)
  2206. line++;
  2207. }
  2208. y += lineHeight;
  2209. }
  2210. #endif
  2211. }
  2212. static int max( int i1, int i2 ) {
  2213. return i1 >= i2 ? i1 : i2;
  2214. }
  2215. static int min( int i1, int i2 ) {
  2216. return i1 <= i2 ? i1 : i2;
  2217. }
  2218. /**
  2219. Count the number of newlines in a null-terminated text string;
  2220. */
  2221. static int countlines( const char *string ) {
  2222. IS_UTF8_ALIGNED(string)
  2223. const char * c;
  2224. int lineCount = 0;
  2225. if (!string) return 0;
  2226. for ( c = string; *c != '\0'; c++ )
  2227. if ( *c == '\n' ) lineCount++;
  2228. return lineCount;
  2229. }
  2230. /**
  2231. \brief Returns the width in pixels of the displayed line pointed to by "visLineNum".
  2232. \param visLineNum index into visible lines array
  2233. \return width of line in pixels
  2234. */
  2235. int Fl_Text_Display::measure_vline( int visLineNum ) const {
  2236. int lineLen = vline_length( visLineNum );
  2237. int lineStartPos = mLineStarts[ visLineNum ];
  2238. if (lineStartPos < 0 || lineLen == 0) return 0;
  2239. return handle_vline(GET_WIDTH, lineStartPos, lineLen, 0, 0, 0, 0, 0, 0);
  2240. }
  2241. /**
  2242. \brief Return true if there are lines visible with no corresponding buffer text.
  2243. \return 1 if there are empty lines
  2244. */
  2245. int Fl_Text_Display::empty_vlines() const {
  2246. return (mNVisibleLines > 0) && (mLineStarts[ mNVisibleLines - 1 ] == -1);
  2247. }
  2248. /**
  2249. \brief Count number of bytes in a visible line.
  2250. Return the length of a line (number of bytes) by examining
  2251. entries in the line starts array rather than by scanning for newlines.
  2252. \param visLineNum index of line in visible line array
  2253. \return number of bytes in this line
  2254. */
  2255. int Fl_Text_Display::vline_length( int visLineNum ) const {
  2256. int nextLineStart, lineStartPos;
  2257. if (visLineNum < 0 || visLineNum >= mNVisibleLines)
  2258. return (0);
  2259. lineStartPos = mLineStarts[ visLineNum ];
  2260. if ( lineStartPos == -1 )
  2261. return 0;
  2262. if ( visLineNum + 1 >= mNVisibleLines )
  2263. return mLastChar - lineStartPos;
  2264. nextLineStart = mLineStarts[ visLineNum + 1 ];
  2265. if ( nextLineStart == -1 )
  2266. return mLastChar - lineStartPos;
  2267. int nextLineStartMinus1 = buffer()->prev_char(nextLineStart);
  2268. if (wrap_uses_character(nextLineStartMinus1))
  2269. return nextLineStartMinus1 - lineStartPos;
  2270. return nextLineStart - lineStartPos;
  2271. }
  2272. /**
  2273. \brief Wrapping calculations.
  2274. When continuous wrap is on, and the user inserts or deletes characters,
  2275. wrapping can happen before and beyond the changed position. This routine
  2276. finds the extent of the changes, and counts the deleted and inserted lines
  2277. over that range. It also attempts to minimize the size of the range to
  2278. what has to be counted and re-displayed, so the results can be useful
  2279. both for delimiting where the line starts need to be recalculated, and
  2280. for deciding what part of the text to redisplay.
  2281. \param deletedText
  2282. \param pos
  2283. \param nInserted
  2284. \param nDeleted
  2285. \param modRangeStart
  2286. \param modRangeEnd
  2287. \param linesInserted
  2288. \param linesDeleted
  2289. */
  2290. void Fl_Text_Display::find_wrap_range(const char *deletedText, int pos,
  2291. int nInserted, int nDeleted,
  2292. int *modRangeStart, int *modRangeEnd,
  2293. int *linesInserted, int *linesDeleted) {
  2294. IS_UTF8_ALIGNED(deletedText)
  2295. IS_UTF8_ALIGNED2(buffer(), pos)
  2296. int length, retPos, retLines, retLineStart, retLineEnd;
  2297. Fl_Text_Buffer *deletedTextBuf, *buf = buffer();
  2298. int nVisLines = mNVisibleLines;
  2299. int *lineStarts = mLineStarts;
  2300. int countFrom, countTo, lineStart, adjLineStart, i;
  2301. int visLineNum = 0, nLines = 0;
  2302. /*
  2303. ** Determine where to begin searching: either the previous newline, or
  2304. ** if possible, limit to the start of the (original) previous displayed
  2305. ** line, using information from the existing line starts array
  2306. */
  2307. if (pos >= mFirstChar && pos <= mLastChar) {
  2308. for (i=nVisLines-1; i>0; i--) {
  2309. if (lineStarts[i] != -1 && pos >= lineStarts[i]) {
  2310. break;
  2311. }
  2312. }
  2313. if (i > 0) {
  2314. countFrom = lineStarts[i-1];
  2315. visLineNum = i-1;
  2316. } else {
  2317. countFrom = buf->line_start(pos);
  2318. }
  2319. } else {
  2320. countFrom = buf->line_start(pos);
  2321. }
  2322. IS_UTF8_ALIGNED2(buf, countFrom)
  2323. /*
  2324. ** Move forward through the (new) text one line at a time, counting
  2325. ** displayed lines, and looking for either a real newline, or for the
  2326. ** line starts to re-sync with the original line starts array
  2327. */
  2328. lineStart = countFrom;
  2329. *modRangeStart = countFrom;
  2330. for (;;) {
  2331. /* advance to the next line. If the line ended in a real newline
  2332. or the end of the buffer, that's far enough */
  2333. wrapped_line_counter(buf, lineStart, buf->length(), 1, true, 0,
  2334. &retPos, &retLines, &retLineStart, &retLineEnd);
  2335. if (retPos >= buf->length()) {
  2336. countTo = buf->length();
  2337. *modRangeEnd = countTo;
  2338. if (retPos != retLineEnd)
  2339. nLines++;
  2340. break;
  2341. } else {
  2342. lineStart = retPos;
  2343. }
  2344. nLines++;
  2345. if (lineStart > pos + nInserted && buf->char_at(buf->prev_char(lineStart)) == '\n') {
  2346. countTo = lineStart;
  2347. *modRangeEnd = lineStart;
  2348. break;
  2349. }
  2350. /* Don't try to resync in continuous wrap mode with non-fixed font
  2351. sizes; it would result in a chicken-and-egg dependency between
  2352. the calculations for the inserted and the deleted lines.
  2353. If we're in that mode, the number of deleted lines is calculated in
  2354. advance, without resynchronization, so we shouldn't resynchronize
  2355. for the inserted lines either. */
  2356. if (mSuppressResync)
  2357. continue;
  2358. /* check for synchronization with the original line starts array
  2359. before pos, if so, the modified range can begin later */
  2360. if (lineStart <= pos) {
  2361. while (visLineNum<nVisLines && lineStarts[visLineNum] < lineStart)
  2362. visLineNum++;
  2363. if (visLineNum < nVisLines && lineStarts[visLineNum] == lineStart) {
  2364. countFrom = lineStart;
  2365. nLines = 0;
  2366. if (visLineNum+1 < nVisLines && lineStarts[visLineNum+1] != -1)
  2367. *modRangeStart = min(pos, buf->prev_char(lineStarts[visLineNum+1]));
  2368. else
  2369. *modRangeStart = countFrom;
  2370. } else
  2371. *modRangeStart = min(*modRangeStart, buf->prev_char(lineStart));
  2372. }
  2373. /* check for synchronization with the original line starts array
  2374. after pos, if so, the modified range can end early */
  2375. else if (lineStart > pos + nInserted) {
  2376. adjLineStart = lineStart - nInserted + nDeleted;
  2377. while (visLineNum<nVisLines && lineStarts[visLineNum]<adjLineStart)
  2378. visLineNum++;
  2379. if (visLineNum < nVisLines && lineStarts[visLineNum] != -1 &&
  2380. lineStarts[visLineNum] == adjLineStart) {
  2381. countTo = line_end(lineStart, true);
  2382. *modRangeEnd = lineStart;
  2383. break;
  2384. }
  2385. }
  2386. }
  2387. *linesInserted = nLines;
  2388. /* Count deleted lines between countFrom and countTo as the text existed
  2389. before the modification (that is, as if the text between pos and
  2390. pos+nInserted were replaced by "deletedText"). This extra context is
  2391. necessary because wrapping can occur outside of the modified region
  2392. as a result of adding or deleting text in the region. This is done by
  2393. creating a textBuffer containing the deleted text and the necessary
  2394. additional context, and calling the wrappedLineCounter on it.
  2395. NOTE: This must not be done in continuous wrap mode when the font
  2396. width is not fixed. In that case, the calculation would try
  2397. to access style information that is no longer available (deleted
  2398. text), or out of date (updated highlighting), possibly leading
  2399. to completely wrong calculations and/or even crashes eventually.
  2400. (This is not theoretical; it really happened.)
  2401. In that case, the calculation of the number of deleted lines
  2402. has happened before the buffer was modified (only in that case,
  2403. because resynchronization of the line starts is impossible
  2404. in that case, which makes the whole calculation less efficient).
  2405. */
  2406. if (mSuppressResync) {
  2407. *linesDeleted = mNLinesDeleted;
  2408. mSuppressResync = 0;
  2409. return;
  2410. }
  2411. length = (pos-countFrom) + nDeleted +(countTo-(pos+nInserted));
  2412. deletedTextBuf = new Fl_Text_Buffer(length);
  2413. deletedTextBuf->copy(buffer(), countFrom, pos, 0);
  2414. if (nDeleted != 0)
  2415. deletedTextBuf->insert(pos-countFrom, deletedText);
  2416. deletedTextBuf->copy(buffer(), pos+nInserted, countTo, pos-countFrom+nDeleted);
  2417. /* Note that we need to take into account an offset for the style buffer:
  2418. the deletedTextBuf can be out of sync with the style buffer. */
  2419. wrapped_line_counter(deletedTextBuf, 0, length, INT_MAX, true, countFrom,
  2420. &retPos, &retLines, &retLineStart, &retLineEnd, false);
  2421. delete deletedTextBuf;
  2422. *linesDeleted = retLines;
  2423. mSuppressResync = 0;
  2424. }
  2425. /**
  2426. \brief Wrapping calculations.
  2427. This is a stripped-down version of the findWrapRange() function above,
  2428. intended to be used to calculate the number of "deleted" lines during
  2429. a buffer modification. It is called _before_ the modification takes place.
  2430. This function should only be called in continuous wrap mode with a
  2431. non-fixed font width. In that case, it is impossible to calculate
  2432. the number of deleted lines, because the necessary style information
  2433. is no longer available _after_ the modification. In other cases, we
  2434. can still perform the calculation afterwards (possibly even more
  2435. efficiently).
  2436. \param pos
  2437. \param nDeleted
  2438. */
  2439. void Fl_Text_Display::measure_deleted_lines(int pos, int nDeleted) {
  2440. IS_UTF8_ALIGNED2(buffer(), pos)
  2441. int retPos, retLines, retLineStart, retLineEnd;
  2442. Fl_Text_Buffer *buf = buffer();
  2443. int nVisLines = mNVisibleLines;
  2444. int *lineStarts = mLineStarts;
  2445. int countFrom, lineStart;
  2446. int visLineNum = 0, nLines = 0, i;
  2447. /*
  2448. ** Determine where to begin searching: either the previous newline, or
  2449. ** if possible, limit to the start of the (original) previous displayed
  2450. ** line, using information from the existing line starts array
  2451. */
  2452. if (pos >= mFirstChar && pos <= mLastChar) {
  2453. for (i=nVisLines-1; i>0; i--)
  2454. if (lineStarts[i] != -1 && pos >= lineStarts[i])
  2455. break;
  2456. if (i > 0) {
  2457. countFrom = lineStarts[i-1];
  2458. visLineNum = i-1;
  2459. } else
  2460. countFrom = buf->line_start(pos);
  2461. } else
  2462. countFrom = buf->line_start(pos);
  2463. /*
  2464. ** Move forward through the (new) text one line at a time, counting
  2465. ** displayed lines, and looking for either a real newline, or for the
  2466. ** line starts to re-sync with the original line starts array
  2467. */
  2468. lineStart = countFrom;
  2469. for (;;) {
  2470. /* advance to the next line. If the line ended in a real newline
  2471. or the end of the buffer, that's far enough */
  2472. wrapped_line_counter(buf, lineStart, buf->length(), 1, true, 0,
  2473. &retPos, &retLines, &retLineStart, &retLineEnd);
  2474. if (retPos >= buf->length()) {
  2475. if (retPos != retLineEnd)
  2476. nLines++;
  2477. break;
  2478. } else
  2479. lineStart = retPos;
  2480. nLines++;
  2481. if (lineStart > pos + nDeleted && buf->char_at(lineStart-1) == '\n') {
  2482. break;
  2483. }
  2484. /* Unlike in the findWrapRange() function above, we don't try to
  2485. resync with the line starts, because we don't know the length
  2486. of the inserted text yet, nor the updated style information.
  2487. Because of that, we also shouldn't resync with the line starts
  2488. after the modification either, because we must perform the
  2489. calculations for the deleted and inserted lines in the same way.
  2490. This can result in some unnecessary recalculation and redrawing
  2491. overhead, and therefore we should only use this two-phase mode
  2492. of calculation when it's really needed (continuous wrap + variable
  2493. font width). */
  2494. }
  2495. mNLinesDeleted = nLines;
  2496. mSuppressResync = 1;
  2497. }
  2498. /**
  2499. \brief Wrapping calculations.
  2500. Count forward from startPos to either maxPos or maxLines (whichever is
  2501. reached first), and return all relevant positions and line count.
  2502. The provided textBuffer may differ from the actual text buffer of the
  2503. widget. In that case it must be a (partial) copy of the actual text buffer
  2504. and the styleBufOffset argument must indicate the starting position of the
  2505. copy, to take into account the correct style information.
  2506. \param buf
  2507. \param startPos
  2508. \param maxPos
  2509. \param maxLines
  2510. \param startPosIsLineStart
  2511. \param styleBufOffset
  2512. \param[out] retPos Position where counting ended. When counting lines, the
  2513. position returned is the start of the line "maxLines" lines
  2514. beyond "startPos".
  2515. \param[out] retLines Number of line breaks counted
  2516. \param[out] retLineStart Start of the line where counting ended
  2517. \param[out] retLineEnd End position of the last line traversed
  2518. \param[out] countLastLineMissingNewLine
  2519. */
  2520. void Fl_Text_Display::wrapped_line_counter(Fl_Text_Buffer *buf, int startPos,
  2521. int maxPos, int maxLines, bool startPosIsLineStart, int styleBufOffset,
  2522. int *retPos, int *retLines, int *retLineStart, int *retLineEnd,
  2523. bool countLastLineMissingNewLine) const {
  2524. IS_UTF8_ALIGNED2(buf, startPos)
  2525. IS_UTF8_ALIGNED2(buf, maxPos)
  2526. int lineStart, newLineStart = 0, b, p, colNum, wrapMarginPix;
  2527. int i, foundBreak;
  2528. double width;
  2529. int nLines = 0;
  2530. unsigned int c;
  2531. /* Set the wrap margin to the wrap column or the view width */
  2532. if (mWrapMarginPix != 0) {
  2533. wrapMarginPix = mWrapMarginPix;
  2534. } else {
  2535. wrapMarginPix = text_area.w;
  2536. }
  2537. /* Find the start of the line if the start pos is not marked as a
  2538. line start. */
  2539. if (startPosIsLineStart)
  2540. lineStart = startPos;
  2541. else
  2542. lineStart = line_start(startPos);
  2543. /*
  2544. ** Loop until position exceeds maxPos or line count exceeds maxLines.
  2545. ** (actually, continues beyond maxPos to end of line containing maxPos,
  2546. ** in case later characters cause a word wrap back before maxPos)
  2547. */
  2548. colNum = 0;
  2549. width = 0;
  2550. for (p=lineStart; p<buf->length(); p=buf->next_char(p)) {
  2551. c = buf->char_at(p); // UCS-4
  2552. /* If the character was a newline, count the line and start over,
  2553. otherwise, add it to the width and column counts */
  2554. if (c == '\n') {
  2555. if (p >= maxPos) {
  2556. *retPos = maxPos;
  2557. *retLines = nLines;
  2558. *retLineStart = lineStart;
  2559. *retLineEnd = maxPos;
  2560. return;
  2561. }
  2562. nLines++;
  2563. int p1 = buf->next_char(p);
  2564. if (nLines >= maxLines) {
  2565. *retPos = p1;
  2566. *retLines = nLines;
  2567. *retLineStart = p1;
  2568. *retLineEnd = p;
  2569. return;
  2570. }
  2571. lineStart = p1;
  2572. colNum = 0;
  2573. width = 0;
  2574. } else {
  2575. const char *s = buf->address(p);
  2576. colNum++;
  2577. // FIXME: it is not a good idea to simply add character widths because on
  2578. // some platforms, the width is a floating point value and depends on the
  2579. // previous character as well.
  2580. width += measure_proportional_character(s, (int)width, p+styleBufOffset);
  2581. }
  2582. /* If character exceeded wrap margin, find the break point and wrap there */
  2583. if (width > wrapMarginPix) {
  2584. foundBreak = false;
  2585. for (b=p; b>=lineStart; b=buf->prev_char(b)) {
  2586. c = buf->char_at(b);
  2587. if (c == '\t' || c == ' ') {
  2588. newLineStart = buf->next_char(b);
  2589. colNum = 0;
  2590. width = 0;
  2591. int iMax = buf->next_char(p);
  2592. for (i=buf->next_char(b); i<iMax; i = buf->next_char(i)) {
  2593. width += measure_proportional_character(buf->address(i), (int)width,
  2594. i+styleBufOffset);
  2595. colNum++;
  2596. }
  2597. foundBreak = true;
  2598. break;
  2599. }
  2600. }
  2601. if (!foundBreak) { /* no whitespace, just break at margin */
  2602. newLineStart = max(p, buf->next_char(lineStart));
  2603. const char *s = buf->address(b);
  2604. colNum++;
  2605. width = measure_proportional_character(s, 0, p+styleBufOffset);
  2606. }
  2607. if (p >= maxPos) {
  2608. *retPos = maxPos;
  2609. *retLines = maxPos < newLineStart ? nLines : nLines + 1;
  2610. *retLineStart = maxPos < newLineStart ? lineStart : newLineStart;
  2611. *retLineEnd = maxPos;
  2612. return;
  2613. }
  2614. nLines++;
  2615. if (nLines >= maxLines) {
  2616. *retPos = foundBreak ? buf->next_char(b) : max(p, buf->next_char(lineStart));
  2617. *retLines = nLines;
  2618. *retLineStart = lineStart;
  2619. *retLineEnd = foundBreak ? b : p;
  2620. return;
  2621. }
  2622. lineStart = newLineStart;
  2623. }
  2624. }
  2625. /* reached end of buffer before reaching pos or line target */
  2626. *retPos = buf->length();
  2627. *retLines = nLines;
  2628. if (countLastLineMissingNewLine && colNum > 0)
  2629. *retLines = buf->next_char(*retLines);
  2630. *retLineStart = lineStart;
  2631. *retLineEnd = buf->length();
  2632. }
  2633. /**
  2634. \brief Wrapping calculations.
  2635. Measure the width in pixels of the first character of string "s" at a
  2636. particular column "colNum" and buffer position "pos". This is for measuring
  2637. characters in proportional or mixed-width highlighting fonts.
  2638. A note about proportional and mixed-width fonts: the mixed width and
  2639. proportional font code in nedit does not get much use in general editing,
  2640. because nedit doesn't allow per-language-mode fonts, and editing programs
  2641. in a proportional font is usually a bad idea, so very few users would
  2642. choose a proportional font as a default. There are still probably mixed-
  2643. width syntax highlighting cases where things don't redraw properly for
  2644. insertion/deletion, though static display and wrapping and resizing
  2645. should now be solid because they are now used for online help display.
  2646. \param s text string
  2647. \param xPix x pixel position needed for calculating tab widths
  2648. \param pos offset within string
  2649. \return width of character in pixels
  2650. */
  2651. double Fl_Text_Display::measure_proportional_character(const char *s, int xPix, int pos) const {
  2652. IS_UTF8_ALIGNED(s)
  2653. if (*s=='\t') {
  2654. int tab = (int)col_to_x(mBuffer->tab_distance());
  2655. return (((xPix/tab)+1)*tab) - xPix;
  2656. }
  2657. int charLen = fl_utf8len1(*s), style = 0;
  2658. if (mStyleBuffer) {
  2659. style = mStyleBuffer->byte_at(pos);
  2660. }
  2661. return string_width(s, charLen, style);
  2662. }
  2663. /**
  2664. \brief Finds both the end of the current line and the start of the next line.
  2665. Why?
  2666. In continuous wrap mode, if you need to know both, figuring out one from the
  2667. other can be expensive or error prone. The problem comes when there's a
  2668. trailing space or tab just before the end of the buffer. To translate an
  2669. end of line value to or from the next lines start value, you need to know
  2670. whether the trailing space or tab is being used as a line break or just a
  2671. normal character, and to find that out would otherwise require counting all
  2672. the way back to the beginning of the line.
  2673. \param startPos
  2674. \param startPosIsLineStart
  2675. \param[out] lineEnd
  2676. \param[out] nextLineStart
  2677. */
  2678. void Fl_Text_Display::find_line_end(int startPos, bool startPosIsLineStart,
  2679. int *lineEnd, int *nextLineStart) const {
  2680. IS_UTF8_ALIGNED2(buffer(), startPos)
  2681. int retLines, retLineStart;
  2682. /* if we're not wrapping use more efficient BufEndOfLine */
  2683. if (!mContinuousWrap) {
  2684. int le = buffer()->line_end(startPos);
  2685. int ls = buffer()->next_char(le);
  2686. *lineEnd = le;
  2687. *nextLineStart = min(buffer()->length(), ls);
  2688. return;
  2689. }
  2690. /* use the wrapped line counter routine to count forward one line */
  2691. wrapped_line_counter(buffer(), startPos, buffer()->length(),
  2692. 1, startPosIsLineStart, 0, nextLineStart, &retLines,
  2693. &retLineStart, lineEnd);
  2694. }
  2695. /**
  2696. \brief Check if the line break is caused by a \\n or by line wrapping.
  2697. Line breaks in continuous wrap mode usually happen at newlines or
  2698. whitespace. This line-terminating character is not included in line
  2699. width measurements and has a special status as a non-visible character.
  2700. However, lines with no whitespace are wrapped without the benefit of a
  2701. line terminating character, and this distinction causes endless trouble
  2702. with all of the text display code which was originally written without
  2703. continuous wrap mode and always expects to wrap at a newline character.
  2704. Given the position of the end of the line, as returned by TextDEndOfLine
  2705. or BufEndOfLine, this returns true if there is a line terminating
  2706. character, and false if there's not. On the last character in the
  2707. buffer, this function can't tell for certain whether a trailing space was
  2708. used as a wrap point, and just guesses that it wasn't. So if an exact
  2709. accounting is necessary, don't use this function.
  2710. \param lineEndPos index of character where the line wraps
  2711. \return 1 if a \\n character causes the line wrap
  2712. */
  2713. int Fl_Text_Display::wrap_uses_character(int lineEndPos) const {
  2714. IS_UTF8_ALIGNED2(buffer(), lineEndPos)
  2715. unsigned int c;
  2716. if (!mContinuousWrap || lineEndPos == buffer()->length())
  2717. return 1;
  2718. c = buffer()->char_at(lineEndPos);
  2719. return c == '\n' || ((c == '\t' || c == ' ') &&
  2720. lineEndPos + 1 < buffer()->length());
  2721. }
  2722. /**
  2723. \brief I don't know what this does!
  2724. Extend the range of a redraw request (from *start to *end) with additional
  2725. redraw requests resulting from changes to the attached style buffer (which
  2726. contains auxiliary information for coloring or styling text).
  2727. \param startpos ??
  2728. \param endpos ??
  2729. \todo Unicode?
  2730. */
  2731. void Fl_Text_Display::extend_range_for_styles( int *startpos, int *endpos ) {
  2732. IS_UTF8_ALIGNED2(buffer(), (*startpos))
  2733. IS_UTF8_ALIGNED2(buffer(), (*endpos))
  2734. Fl_Text_Selection * sel = mStyleBuffer->primary_selection();
  2735. int extended = 0;
  2736. /* The peculiar protocol used here is that modifications to the style
  2737. buffer are marked by selecting them with the buffer's primary Fl_Text_Selection.
  2738. The style buffer is usually modified in response to a modify callback on
  2739. the text buffer BEFORE Fl_Text_Display.c's modify callback, so that it can keep
  2740. the style buffer in step with the text buffer. The style-update
  2741. callback can't just call for a redraw, because Fl_Text_Display hasn't processed
  2742. the original text changes yet. Anyhow, to minimize redrawing and to
  2743. avoid the complexity of scheduling redraws later, this simple protocol
  2744. tells the text display's buffer modify callback to extend its redraw
  2745. range to show the text color/and font changes as well. */
  2746. if ( sel->selected() ) {
  2747. if ( sel->start() < *startpos ) {
  2748. *startpos = sel->start();
  2749. // somewhere while deleting, alignment is lost. We do this just to be sure.
  2750. *startpos = buffer()->utf8_align(*startpos);
  2751. IS_UTF8_ALIGNED2(buffer(), (*startpos))
  2752. extended = 1;
  2753. }
  2754. if ( sel->end() > *endpos ) {
  2755. *endpos = sel->end();
  2756. *endpos = buffer()->utf8_align(*endpos);
  2757. IS_UTF8_ALIGNED2(buffer(), (*endpos))
  2758. extended = 1;
  2759. }
  2760. }
  2761. /* If the Fl_Text_Selection was extended due to a style change, and some of the
  2762. fonts don't match in spacing, extend redraw area to end of line to
  2763. redraw characters exposed by possible font size changes */
  2764. if ( extended )
  2765. *endpos = mBuffer->line_end( *endpos ) + 1;
  2766. IS_UTF8_ALIGNED2(buffer(), (*endpos))
  2767. }
  2768. /**
  2769. \brief Draw the widget.
  2770. This function tries to limit drawing to smaller areas if possible.
  2771. */
  2772. void Fl_Text_Display::draw(void) {
  2773. // don't even try if there is no associated text buffer!
  2774. if (!buffer()) { draw_box(); return; }
  2775. fl_push_clip(x(),y(),w(),h()); // prevent drawing outside widget area
  2776. // draw the non-text, non-scrollbar areas.
  2777. if (damage() & FL_DAMAGE_ALL) {
  2778. // printf("drawing all (box = %d)\n", box());
  2779. if (Fl_Surface_Device::surface()->class_name() == Fl_Printer::class_id) {
  2780. // if to printer, draw the background
  2781. fl_rectf(text_area.x, text_area.y, text_area.w, text_area.h, color() );
  2782. }
  2783. // draw the box()
  2784. int W = w(), H = h();
  2785. draw_box(box(), x(), y(), W, H, color());
  2786. if (mHScrollBar->visible())
  2787. W -= scrollbar_width();
  2788. if (mVScrollBar->visible())
  2789. H -= scrollbar_width();
  2790. // left margin
  2791. fl_rectf(text_area.x-LEFT_MARGIN, text_area.y-TOP_MARGIN,
  2792. LEFT_MARGIN, text_area.h+TOP_MARGIN+BOTTOM_MARGIN,
  2793. color());
  2794. // right margin
  2795. fl_rectf(text_area.x+text_area.w, text_area.y-TOP_MARGIN,
  2796. RIGHT_MARGIN, text_area.h+TOP_MARGIN+BOTTOM_MARGIN,
  2797. color());
  2798. // top margin
  2799. fl_rectf(text_area.x, text_area.y-TOP_MARGIN,
  2800. text_area.w, TOP_MARGIN, color());
  2801. // bottom margin
  2802. fl_rectf(text_area.x, text_area.y+text_area.h,
  2803. text_area.w, BOTTOM_MARGIN, color());
  2804. // draw that little box in the corner of the scrollbars
  2805. if (mVScrollBar->visible() && mHScrollBar->visible())
  2806. fl_rectf(mVScrollBar->x(), mHScrollBar->y(),
  2807. mVScrollBar->w(), mHScrollBar->h(),
  2808. FL_GRAY);
  2809. // blank the previous cursor protrusions
  2810. }
  2811. else if (damage() & (FL_DAMAGE_SCROLL | FL_DAMAGE_EXPOSE)) {
  2812. // printf("blanking previous cursor extrusions at Y: %d\n", mCursorOldY);
  2813. // CET - FIXME - save old cursor position instead and just draw side needed?
  2814. fl_push_clip(text_area.x-LEFT_MARGIN,
  2815. text_area.y,
  2816. text_area.w+LEFT_MARGIN+RIGHT_MARGIN,
  2817. text_area.h);
  2818. fl_rectf(text_area.x-LEFT_MARGIN, mCursorOldY,
  2819. LEFT_MARGIN, mMaxsize, color());
  2820. fl_rectf(text_area.x+text_area.w, mCursorOldY,
  2821. RIGHT_MARGIN, mMaxsize, color());
  2822. fl_pop_clip();
  2823. }
  2824. // draw the scrollbars
  2825. if (damage() & (FL_DAMAGE_ALL | FL_DAMAGE_CHILD)) {
  2826. mVScrollBar->damage(FL_DAMAGE_ALL);
  2827. mHScrollBar->damage(FL_DAMAGE_ALL);
  2828. }
  2829. update_child(*mVScrollBar);
  2830. update_child(*mHScrollBar);
  2831. // draw all of the text
  2832. if (damage() & (FL_DAMAGE_ALL | FL_DAMAGE_EXPOSE)) {
  2833. //printf("drawing all text\n");
  2834. int X, Y, W, H;
  2835. if (fl_clip_box(text_area.x, text_area.y, text_area.w, text_area.h,
  2836. X, Y, W, H)) {
  2837. // Draw text using the intersected clipping box...
  2838. // (this sets the clipping internally)
  2839. draw_text(X, Y, W, H);
  2840. } else {
  2841. // Draw the whole area...
  2842. draw_text(text_area.x, text_area.y, text_area.w, text_area.h);
  2843. }
  2844. }
  2845. else if (damage() & FL_DAMAGE_SCROLL) {
  2846. // draw some lines of text
  2847. fl_push_clip(text_area.x, text_area.y,
  2848. text_area.w, text_area.h);
  2849. //printf("drawing text from %d to %d\n", damage_range1_start, damage_range1_end);
  2850. draw_range(damage_range1_start, damage_range1_end);
  2851. if (damage_range2_end != -1) {
  2852. //printf("drawing text from %d to %d\n", damage_range2_start, damage_range2_end);
  2853. draw_range(damage_range2_start, damage_range2_end);
  2854. }
  2855. damage_range1_start = damage_range1_end = -1;
  2856. damage_range2_start = damage_range2_end = -1;
  2857. fl_pop_clip();
  2858. }
  2859. // draw the text cursor
  2860. if (damage() & (FL_DAMAGE_ALL | FL_DAMAGE_SCROLL | FL_DAMAGE_EXPOSE)
  2861. && !buffer()->primary_selection()->selected() &&
  2862. mCursorOn && Fl::focus() == (Fl_Widget*)this ) {
  2863. fl_push_clip(text_area.x-LEFT_MARGIN,
  2864. text_area.y,
  2865. text_area.w+LEFT_MARGIN+RIGHT_MARGIN,
  2866. text_area.h);
  2867. int X, Y;
  2868. if (position_to_xy(mCursorPos, &X, &Y)) draw_cursor(X, Y);
  2869. // else puts("position_to_xy() failed - unable to draw cursor!");
  2870. //printf("drew cursor at pos: %d (%d,%d)\n", mCursorPos, X, Y);
  2871. mCursorOldY = Y;
  2872. fl_pop_clip();
  2873. }
  2874. fl_pop_clip();
  2875. }
  2876. // this processes drag events due to mouse for Fl_Text_Display and
  2877. // also drags due to cursor movement with shift held down for
  2878. // Fl_Text_Editor
  2879. void fl_text_drag_me(int pos, Fl_Text_Display* d) {
  2880. if (d->dragType == Fl_Text_Display::DRAG_CHAR) {
  2881. if (pos >= d->dragPos) {
  2882. d->buffer()->select(d->dragPos, pos);
  2883. } else {
  2884. d->buffer()->select(pos, d->dragPos);
  2885. }
  2886. d->insert_position(pos);
  2887. } else if (d->dragType == Fl_Text_Display::DRAG_WORD) {
  2888. if (pos >= d->dragPos) {
  2889. d->insert_position(d->word_end(pos));
  2890. d->buffer()->select(d->word_start(d->dragPos), d->word_end(pos));
  2891. } else {
  2892. d->insert_position(d->word_start(pos));
  2893. d->buffer()->select(d->word_start(pos), d->word_end(d->dragPos));
  2894. }
  2895. } else if (d->dragType == Fl_Text_Display::DRAG_LINE) {
  2896. if (pos >= d->dragPos) {
  2897. d->insert_position(d->buffer()->line_end(pos)+1);
  2898. d->buffer()->select(d->buffer()->line_start(d->dragPos),
  2899. d->buffer()->line_end(pos)+1);
  2900. } else {
  2901. d->insert_position(d->buffer()->line_start(pos));
  2902. d->buffer()->select(d->buffer()->line_start(pos),
  2903. d->buffer()->line_end(d->dragPos)+1);
  2904. }
  2905. }
  2906. }
  2907. /**
  2908. \brief Timer callback for scroll events.
  2909. This timer event scrolls the text view proportionally to
  2910. how far the mouse pointer has left the text area. This
  2911. allows for smooth scrolling without "wiggeling" the mouse.
  2912. */
  2913. void Fl_Text_Display::scroll_timer_cb(void *user_data) {
  2914. Fl_Text_Display *w = (Fl_Text_Display*)user_data;
  2915. int pos;
  2916. switch (scroll_direction) {
  2917. case 1: // mouse is to the right, scroll left
  2918. w->scroll(w->mTopLineNum, w->mHorizOffset + scroll_amount);
  2919. pos = w->xy_to_position(w->text_area.x + w->text_area.w, scroll_y, CURSOR_POS);
  2920. break;
  2921. case 2: // mouse is to the left, scroll right
  2922. w->scroll(w->mTopLineNum, w->mHorizOffset + scroll_amount);
  2923. pos = w->xy_to_position(w->text_area.x, scroll_y, CURSOR_POS);
  2924. break;
  2925. case 3: // mouse is above, scroll down
  2926. w->scroll(w->mTopLineNum + scroll_amount, w->mHorizOffset);
  2927. pos = w->xy_to_position(scroll_x, w->text_area.y, CURSOR_POS);
  2928. break;
  2929. case 4: // mouse is below, scroll up
  2930. w->scroll(w->mTopLineNum + scroll_amount, w->mHorizOffset);
  2931. pos = w->xy_to_position(scroll_x, w->text_area.y + w->text_area.h, CURSOR_POS);
  2932. break;
  2933. default:
  2934. return;
  2935. }
  2936. fl_text_drag_me(pos, w);
  2937. Fl::repeat_timeout(.1, scroll_timer_cb, user_data);
  2938. }
  2939. /**
  2940. \brief Event handling.
  2941. */
  2942. int Fl_Text_Display::handle(int event) {
  2943. if (!buffer()) return 0;
  2944. // This isn't very elegant!
  2945. if (!Fl::event_inside(text_area.x, text_area.y, text_area.w, text_area.h) &&
  2946. !dragging && event != FL_LEAVE && event != FL_ENTER &&
  2947. event != FL_MOVE && event != FL_FOCUS && event != FL_UNFOCUS &&
  2948. event != FL_KEYBOARD && event != FL_KEYUP) {
  2949. return Fl_Group::handle(event);
  2950. }
  2951. switch (event) {
  2952. case FL_ENTER:
  2953. case FL_MOVE:
  2954. if (active_r()) {
  2955. if (Fl::event_inside(text_area.x, text_area.y, text_area.w,
  2956. text_area.h)) window()->cursor(FL_CURSOR_INSERT);
  2957. else window()->cursor(FL_CURSOR_DEFAULT);
  2958. return 1;
  2959. } else {
  2960. return 0;
  2961. }
  2962. case FL_LEAVE:
  2963. case FL_HIDE:
  2964. if (active_r() && window()) {
  2965. window()->cursor(FL_CURSOR_DEFAULT);
  2966. return 1;
  2967. } else {
  2968. return 0;
  2969. }
  2970. case FL_PUSH: {
  2971. if (active_r() && window()) {
  2972. if (Fl::event_inside(text_area.x, text_area.y, text_area.w,
  2973. text_area.h)) window()->cursor(FL_CURSOR_INSERT);
  2974. else window()->cursor(FL_CURSOR_DEFAULT);
  2975. }
  2976. if (Fl::focus() != this) {
  2977. Fl::focus(this);
  2978. handle(FL_FOCUS);
  2979. }
  2980. if (Fl_Group::handle(event)) return 1;
  2981. if (Fl::event_state()&FL_SHIFT) return handle(FL_DRAG);
  2982. dragging = 1;
  2983. int pos = xy_to_position(Fl::event_x(), Fl::event_y(), CURSOR_POS);
  2984. dragPos = pos;
  2985. if (buffer()->primary_selection()->includes(pos)) {
  2986. dragType = DRAG_START_DND;
  2987. return 1;
  2988. }
  2989. dragType = Fl::event_clicks();
  2990. if (dragType == DRAG_CHAR) {
  2991. buffer()->unselect();
  2992. // Fl::copy("", 0, 0); /* removed for STR 2668 */
  2993. }
  2994. else if (dragType == DRAG_WORD) {
  2995. buffer()->select(word_start(pos), word_end(pos));
  2996. dragPos = word_start(pos);
  2997. }
  2998. if (buffer()->primary_selection()->selected())
  2999. insert_position(buffer()->primary_selection()->end());
  3000. else
  3001. insert_position(pos);
  3002. show_insert_position();
  3003. return 1;
  3004. }
  3005. case FL_DRAG: {
  3006. if (dragType==DRAG_NONE)
  3007. return 1;
  3008. if (dragType==DRAG_START_DND) {
  3009. if (!Fl::event_is_click() && Fl::dnd_text_ops()) {
  3010. const char* copy = buffer()->selection_text();
  3011. Fl::dnd();
  3012. free((void*)copy);
  3013. }
  3014. return 1;
  3015. }
  3016. int X = Fl::event_x(), Y = Fl::event_y(), pos = insert_position();
  3017. // if we leave the text_area, we start a timer event
  3018. // that will take care of scrolling and selecting
  3019. if (Y < text_area.y) {
  3020. scroll_x = X;
  3021. scroll_amount = (Y - text_area.y) / 5 - 1;
  3022. if (!scroll_direction) {
  3023. Fl::add_timeout(.01, scroll_timer_cb, this);
  3024. }
  3025. scroll_direction = 3;
  3026. } else if (Y >= text_area.y+text_area.h) {
  3027. scroll_x = X;
  3028. scroll_amount = (Y - text_area.y - text_area.h) / 5 + 1;
  3029. if (!scroll_direction) {
  3030. Fl::add_timeout(.01, scroll_timer_cb, this);
  3031. }
  3032. scroll_direction = 4;
  3033. } else if (X < text_area.x) {
  3034. scroll_y = Y;
  3035. scroll_amount = (X - text_area.x) / 2 - 1;
  3036. if (!scroll_direction) {
  3037. Fl::add_timeout(.01, scroll_timer_cb, this);
  3038. }
  3039. scroll_direction = 2;
  3040. } else if (X >= text_area.x+text_area.w) {
  3041. scroll_y = Y;
  3042. scroll_amount = (X - text_area.x - text_area.w) / 2 + 1;
  3043. if (!scroll_direction) {
  3044. Fl::add_timeout(.01, scroll_timer_cb, this);
  3045. }
  3046. scroll_direction = 1;
  3047. } else {
  3048. if (scroll_direction) {
  3049. Fl::remove_timeout(scroll_timer_cb, this);
  3050. scroll_direction = 0;
  3051. }
  3052. pos = xy_to_position(X, Y, CURSOR_POS);
  3053. pos = buffer()->next_char(pos);
  3054. }
  3055. fl_text_drag_me(pos, this);
  3056. return 1;
  3057. }
  3058. case FL_RELEASE: {
  3059. if (Fl::event_is_click() && (! Fl::event_clicks()) &&
  3060. buffer()->primary_selection()->includes(dragPos) && !(Fl::event_state()&FL_SHIFT) ) {
  3061. buffer()->unselect(); // clicking in the selection: unselect and move cursor
  3062. insert_position(dragPos);
  3063. return 1;
  3064. } else if (Fl::event_clicks() == DRAG_LINE && Fl::event_button() == FL_LEFT_MOUSE) {
  3065. buffer()->select(buffer()->line_start(dragPos), buffer()->next_char(buffer()->line_end(dragPos)));
  3066. dragPos = line_start(dragPos);
  3067. dragType = DRAG_CHAR;
  3068. } else {
  3069. dragging = 0;
  3070. if (scroll_direction) {
  3071. Fl::remove_timeout(scroll_timer_cb, this);
  3072. scroll_direction = 0;
  3073. }
  3074. // convert from WORD or LINE selection to CHAR
  3075. /*if (insert_position() >= dragPos)
  3076. dragPos = buffer()->primary_selection()->start();
  3077. else
  3078. dragPos = buffer()->primary_selection()->end();*/
  3079. dragType = DRAG_CHAR;
  3080. }
  3081. const char* copy = buffer()->selection_text();
  3082. if (*copy) Fl::copy(copy, strlen(copy), 0);
  3083. free((void*)copy);
  3084. return 1;
  3085. }
  3086. case FL_MOUSEWHEEL:
  3087. if (Fl::event_dy()) return mVScrollBar->handle(event);
  3088. else return mHScrollBar->handle(event);
  3089. case FL_UNFOCUS:
  3090. if (active_r() && window()) window()->cursor(FL_CURSOR_DEFAULT);
  3091. case FL_FOCUS:
  3092. if (buffer()->selected()) {
  3093. int start, end;
  3094. if (buffer()->selection_position(&start, &end))
  3095. redisplay_range(start, end);
  3096. }
  3097. if (buffer()->secondary_selected()) {
  3098. int start, end;
  3099. if (buffer()->secondary_selection_position(&start, &end))
  3100. redisplay_range(start, end);
  3101. }
  3102. if (buffer()->highlight()) {
  3103. int start, end;
  3104. if (buffer()->highlight_position(&start, &end))
  3105. redisplay_range(start, end);
  3106. }
  3107. return 1;
  3108. case FL_KEYBOARD:
  3109. // Copy?
  3110. if ((Fl::event_state()&(FL_CTRL|FL_COMMAND)) && Fl::event_key()=='c') {
  3111. if (!buffer()->selected()) return 1;
  3112. const char *copy = buffer()->selection_text();
  3113. if (*copy) Fl::copy(copy, strlen(copy), 1);
  3114. free((void*)copy);
  3115. return 1;
  3116. }
  3117. // Select all ?
  3118. if ((Fl::event_state()&(FL_CTRL|FL_COMMAND)) && Fl::event_key()=='a') {
  3119. buffer()->select(0,buffer()->length());
  3120. const char *copy = buffer()->selection_text();
  3121. if (*copy) Fl::copy(copy, strlen(copy), 0);
  3122. free((void*)copy);
  3123. return 1;
  3124. }
  3125. if (mVScrollBar->handle(event)) return 1;
  3126. if (mHScrollBar->handle(event)) return 1;
  3127. break;
  3128. case FL_SHORTCUT:
  3129. if (!(shortcut() ? Fl::test_shortcut(shortcut()) : test_shortcut()))
  3130. return 0;
  3131. if (Fl::visible_focus() && handle(FL_FOCUS)) {
  3132. Fl::focus(this);
  3133. return 1;
  3134. }
  3135. break;
  3136. }
  3137. return 0;
  3138. }
  3139. /*
  3140. Convert an x pixel position into a column number.
  3141. */
  3142. double Fl_Text_Display::x_to_col(double y) const
  3143. {
  3144. if (!mColumnScale) {
  3145. mColumnScale = string_width("Mitg", 4, 'A') / 4.0;
  3146. }
  3147. return (y/mColumnScale)+0.5;
  3148. }
  3149. /**
  3150. Convert a column number into an x pixel position.
  3151. */
  3152. double Fl_Text_Display::col_to_x(double col) const
  3153. {
  3154. if (!mColumnScale) {
  3155. // recalculate column scale value
  3156. x_to_col(0);
  3157. }
  3158. return col*mColumnScale;
  3159. }
  3160. //
  3161. // End of "$Id: Fl_Text_Display.cxx 8808 2011-06-16 13:31:25Z manolo $".
  3162. //