Fl_Text_Display.cxx 124 KB

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