kateviewinternal.cpp

00001 /* This file is part of the KDE libraries
00002    Copyright (C) 2002 John Firebaugh <jfirebaugh@kde.org>
00003    Copyright (C) 2002 Joseph Wenninger <jowenn@kde.org>
00004    Copyright (C) 2002,2003 Christoph Cullmann <cullmann@kde.org>
00005    Copyright (C) 2002,2003 Hamish Rodda <rodda@kde.org>
00006    Copyright (C) 2003 Anakim Border <aborder@sources.sourceforge.net>
00007 
00008    Based on:
00009      KWriteView : Copyright (C) 1999 Jochen Wilhelmy <digisnap@cs.tu-berlin.de>
00010 
00011    This library is free software; you can redistribute it and/or
00012    modify it under the terms of the GNU Library General Public
00013    License version 2 as published by the Free Software Foundation.
00014 
00015    This library is distributed in the hope that it will be useful,
00016    but WITHOUT ANY WARRANTY; without even the implied warranty of
00017    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00018    Library General Public License for more details.
00019 
00020    You should have received a copy of the GNU Library General Public License
00021    along with this library; see the file COPYING.LIB.  If not, write to
00022    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00023    Boston, MA 02110-1301, USA.
00024 */
00025 
00026 #include "kateviewinternal.h"
00027 #include "kateviewinternal.moc"
00028 
00029 #include "kateview.h"
00030 #include "katecodefoldinghelpers.h"
00031 #include "kateviewhelpers.h"
00032 #include "katehighlight.h"
00033 #include "katesupercursor.h"
00034 #include "katerenderer.h"
00035 #include "katecodecompletion.h"
00036 #include "kateconfig.h"
00037 
00038 #include <kcursor.h>
00039 #include <kdebug.h>
00040 #include <kapplication.h>
00041 #include <kglobalsettings.h>
00042 #include <kurldrag.h>
00043 
00044 #include <qstyle.h>
00045 #include <qdragobject.h>
00046 #include <qpopupmenu.h>
00047 #include <qdropsite.h>
00048 #include <qpainter.h>
00049 #include <qlayout.h>
00050 #include <qclipboard.h>
00051 #include <qpixmap.h>
00052 #include <qvbox.h>
00053 
00054 KateViewInternal::KateViewInternal(KateView *view, KateDocument *doc)
00055   : QWidget (view, "", Qt::WStaticContents | Qt::WRepaintNoErase | Qt::WResizeNoErase )
00056   , editSessionNumber (0)
00057   , editIsRunning (false)
00058   , m_view (view)
00059   , m_doc (doc)
00060   , cursor (doc, true, 0, 0, this)
00061   , possibleTripleClick (false)
00062   , m_dummy (0)
00063   , m_startPos(doc, true, 0,0)
00064   , m_madeVisible(false)
00065   , m_shiftKeyPressed (false)
00066   , m_autoCenterLines (false)
00067   , m_selChangedByUser (false)
00068   , selectAnchor (-1, -1)
00069   , m_selectionMode( Default )
00070   , m_preserveMaxX(false)
00071   , m_currentMaxX(0)
00072   , m_usePlainLines(false)
00073   , m_updatingView(true)
00074   , m_cachedMaxStartPos(-1, -1)
00075   , m_dragScrollTimer(this)
00076   , m_scrollTimer (this)
00077   , m_cursorTimer (this)
00078   , m_textHintTimer (this)
00079   , m_textHintEnabled(false)
00080   , m_textHintMouseX(-1)
00081   , m_textHintMouseY(-1)
00082   , m_imPreeditStartLine(0)
00083   , m_imPreeditStart(0)
00084   , m_imPreeditLength(0)
00085   , m_imPreeditSelStart(0)
00086 {
00087   setMinimumSize (0,0);
00088 
00089   // cursor
00090   cursor.setMoveOnInsert (true);
00091 
00092   // invalidate selStartCached, or keyb selection is screwed initially
00093   selStartCached.setLine( -1 );
00094   //
00095   // scrollbar for lines
00096   //
00097   m_lineScroll = new KateScrollBar(QScrollBar::Vertical, this);
00098   m_lineScroll->show();
00099   m_lineScroll->setTracking (true);
00100 
00101   m_lineLayout = new QVBoxLayout();
00102   m_colLayout = new QHBoxLayout();
00103 
00104   m_colLayout->addWidget(m_lineScroll);
00105   m_lineLayout->addLayout(m_colLayout);
00106 
00107   // bottom corner box
00108   m_dummy = new QWidget(m_view);
00109   m_dummy->setFixedHeight(style().scrollBarExtent().width());
00110 
00111   if (m_view->dynWordWrap())
00112     m_dummy->hide();
00113   else
00114     m_dummy->show();
00115 
00116   m_lineLayout->addWidget(m_dummy);
00117 
00118   // Hijack the line scroller's controls, so we can scroll nicely for word-wrap
00119   connect(m_lineScroll, SIGNAL(prevPage()), SLOT(scrollPrevPage()));
00120   connect(m_lineScroll, SIGNAL(nextPage()), SLOT(scrollNextPage()));
00121 
00122   connect(m_lineScroll, SIGNAL(prevLine()), SLOT(scrollPrevLine()));
00123   connect(m_lineScroll, SIGNAL(nextLine()), SLOT(scrollNextLine()));
00124 
00125   connect(m_lineScroll, SIGNAL(sliderMoved(int)), SLOT(scrollLines(int)));
00126   connect(m_lineScroll, SIGNAL(sliderMMBMoved(int)), SLOT(scrollLines(int)));
00127 
00128   // catch wheel events, completing the hijack
00129   m_lineScroll->installEventFilter(this);
00130 
00131   //
00132   // scrollbar for columns
00133   //
00134   m_columnScroll = new QScrollBar(QScrollBar::Horizontal,m_view);
00135 
00136   // hide the column scrollbar in the dynamic word wrap mode
00137   if (m_view->dynWordWrap())
00138     m_columnScroll->hide();
00139   else
00140     m_columnScroll->show();
00141 
00142   m_columnScroll->setTracking(true);
00143   m_startX = 0;
00144 
00145   connect( m_columnScroll, SIGNAL( valueChanged (int) ),
00146            this, SLOT( scrollColumns (int) ) );
00147 
00148   //
00149   // iconborder ;)
00150   //
00151   leftBorder = new KateIconBorder( this, m_view );
00152   leftBorder->show ();
00153 
00154   connect( leftBorder, SIGNAL(toggleRegionVisibility(unsigned int)),
00155            m_doc->foldingTree(), SLOT(toggleRegionVisibility(unsigned int)));
00156 
00157   connect( doc->foldingTree(), SIGNAL(regionVisibilityChangedAt(unsigned int)),
00158            this, SLOT(slotRegionVisibilityChangedAt(unsigned int)));
00159   connect( doc, SIGNAL(codeFoldingUpdated()),
00160            this, SLOT(slotCodeFoldingChanged()) );
00161 
00162   displayCursor.setPos(0, 0);
00163   cursor.setPos(0, 0);
00164   cXPos = 0;
00165 
00166   setAcceptDrops( true );
00167   setBackgroundMode( NoBackground );
00168 
00169   // event filter
00170   installEventFilter(this);
00171 
00172   // im
00173   setInputMethodEnabled(true);
00174 
00175   // set initial cursor
00176   setCursor( KCursor::ibeamCursor() );
00177   m_mouseCursor = IbeamCursor;
00178 
00179   // call mouseMoveEvent also if no mouse button is pressed
00180   setMouseTracking(true);
00181 
00182   dragInfo.state = diNone;
00183 
00184   // timers
00185   connect( &m_dragScrollTimer, SIGNAL( timeout() ),
00186              this, SLOT( doDragScroll() ) );
00187 
00188   connect( &m_scrollTimer, SIGNAL( timeout() ),
00189              this, SLOT( scrollTimeout() ) );
00190 
00191   connect( &m_cursorTimer, SIGNAL( timeout() ),
00192              this, SLOT( cursorTimeout() ) );
00193 
00194   connect( &m_textHintTimer, SIGNAL( timeout() ),
00195              this, SLOT( textHintTimeout() ) );
00196 
00197   // selection changed to set anchor
00198   connect( m_view, SIGNAL( selectionChanged() ),
00199              this, SLOT( viewSelectionChanged() ) );
00200 
00201 
00202 // this is a work arround for RTL desktops
00203 // should be changed in kde 3.3
00204 // BTW: this comment has been "ported" from 3.1.X tree
00205 //      any hacker with BIDI knowlege is welcomed to fix kate problems :)
00206   if (QApplication::reverseLayout()){
00207       m_view->m_grid->addMultiCellWidget(leftBorder,     0, 1, 2, 2);
00208       m_view->m_grid->addMultiCellWidget(m_columnScroll, 1, 1, 0, 1);
00209       m_view->m_grid->addMultiCellLayout(m_lineLayout, 0, 0, 0, 0);
00210   }
00211   else{
00212       m_view->m_grid->addMultiCellLayout(m_lineLayout, 0, 1, 2, 2);
00213       m_view->m_grid->addMultiCellWidget(m_columnScroll, 1, 1, 0, 1);
00214       m_view->m_grid->addWidget(leftBorder, 0, 0);
00215   }
00216 
00217   updateView ();
00218 }
00219 
00220 KateViewInternal::~KateViewInternal ()
00221 {
00222 }
00223 
00224 void KateViewInternal::prepareForDynWrapChange()
00225 {
00226   // Which is the current view line?
00227   m_wrapChangeViewLine = displayViewLine(displayCursor, true);
00228 }
00229 
00230 void KateViewInternal::dynWrapChanged()
00231 {
00232   if (m_view->dynWordWrap())
00233   {
00234     m_columnScroll->hide();
00235     m_dummy->hide ();
00236   }
00237   else
00238   {
00239     m_columnScroll->show();
00240     m_dummy->show ();
00241   }
00242 
00243   tagAll();
00244   updateView();
00245 
00246   if (m_view->dynWordWrap())
00247     scrollColumns(0);
00248 
00249   // Determine where the cursor should be to get the cursor on the same view line
00250   if (m_wrapChangeViewLine != -1) {
00251     KateTextCursor newStart = viewLineOffset(displayCursor, -m_wrapChangeViewLine);
00252     makeVisible(newStart, newStart.col(), true);
00253   } else {
00254     update();
00255   }
00256 }
00257 
00258 KateTextCursor KateViewInternal::endPos() const
00259 {
00260   int viewLines = linesDisplayed() - 1;
00261 
00262   if (viewLines < 0) {
00263     kdDebug(13030) << "WARNING: viewLines wrong!" << endl;
00264     viewLines = 0;
00265   }
00266 
00267   // Check to make sure that lineRanges isn't invalid
00268   if (!lineRanges.count() || lineRanges[0].line == -1 || viewLines >= (int)lineRanges.count()) {
00269     // Switch off use of the cache
00270     return KateTextCursor(m_doc->numVisLines() - 1, m_doc->lineLength(m_doc->getRealLine(m_doc->numVisLines() - 1)));
00271   }
00272 
00273   for (int i = viewLines; i >= 0; i--) {
00274     KateLineRange& thisRange = lineRanges[i];
00275 
00276     if (thisRange.line == -1) continue;
00277 
00278     if (thisRange.virtualLine >= (int)m_doc->numVisLines()) {
00279       // Cache is too out of date
00280       return KateTextCursor(m_doc->numVisLines() - 1, m_doc->lineLength(m_doc->getRealLine(m_doc->numVisLines() - 1)));
00281     }
00282 
00283     return KateTextCursor(thisRange.virtualLine, thisRange.wrap ? thisRange.endCol - 1 : thisRange.endCol);
00284   }
00285 
00286   Q_ASSERT(false);
00287   kdDebug(13030) << "WARNING: could not find a lineRange at all" << endl;
00288   return KateTextCursor(-1, -1);
00289 }
00290 
00291 uint KateViewInternal::endLine() const
00292 {
00293   return endPos().line();
00294 }
00295 
00296 KateLineRange KateViewInternal::yToKateLineRange(uint y) const
00297 {
00298   uint range = y / m_view->renderer()->fontHeight();
00299 
00300   // lineRanges is always bigger than 0, after the initial updateView call
00301   if (range >= lineRanges.size())
00302     return lineRanges[lineRanges.size()-1];
00303 
00304   return lineRanges[range];
00305 }
00306 
00307 int KateViewInternal::lineToY(uint viewLine) const
00308 {
00309   return (viewLine-startLine()) * m_view->renderer()->fontHeight();
00310 }
00311 
00312 void KateViewInternal::slotIncFontSizes()
00313 {
00314   m_view->renderer()->increaseFontSizes();
00315 }
00316 
00317 void KateViewInternal::slotDecFontSizes()
00318 {
00319   m_view->renderer()->decreaseFontSizes();
00320 }
00321 
00325 void KateViewInternal::scrollLines ( int line )
00326 {
00327   KateTextCursor newPos(line, 0);
00328   scrollPos(newPos);
00329 }
00330 
00331 // This can scroll less than one true line
00332 void KateViewInternal::scrollViewLines(int offset)
00333 {
00334   KateTextCursor c = viewLineOffset(startPos(), offset);
00335   scrollPos(c);
00336 
00337   m_lineScroll->blockSignals(true);
00338   m_lineScroll->setValue(startLine());
00339   m_lineScroll->blockSignals(false);
00340 }
00341 
00342 void KateViewInternal::scrollNextPage()
00343 {
00344   scrollViewLines(kMax( (int)linesDisplayed() - 1, 0 ));
00345 }
00346 
00347 void KateViewInternal::scrollPrevPage()
00348 {
00349   scrollViewLines(-kMax( (int)linesDisplayed() - 1, 0 ));
00350 }
00351 
00352 void KateViewInternal::scrollPrevLine()
00353 {
00354   scrollViewLines(-1);
00355 }
00356 
00357 void KateViewInternal::scrollNextLine()
00358 {
00359   scrollViewLines(1);
00360 }
00361 
00362 KateTextCursor KateViewInternal::maxStartPos(bool changed)
00363 {
00364   m_usePlainLines = true;
00365 
00366   if (m_cachedMaxStartPos.line() == -1 || changed)
00367   {
00368     KateTextCursor end(m_doc->numVisLines() - 1, m_doc->lineLength(m_doc->getRealLine(m_doc->numVisLines() - 1)));
00369 
00370     m_cachedMaxStartPos = viewLineOffset(end, -((int)linesDisplayed() - 1));
00371   }
00372 
00373   m_usePlainLines = false;
00374 
00375   return m_cachedMaxStartPos;
00376 }
00377 
00378 // c is a virtual cursor
00379 void KateViewInternal::scrollPos(KateTextCursor& c, bool force, bool calledExternally)
00380 {
00381   if (!force && ((!m_view->dynWordWrap() && c.line() == (int)startLine()) || c == startPos()))
00382     return;
00383 
00384   if (c.line() < 0)
00385     c.setLine(0);
00386 
00387   KateTextCursor limit = maxStartPos();
00388   if (c > limit) {
00389     c = limit;
00390 
00391     // Re-check we're not just scrolling to the same place
00392     if (!force && ((!m_view->dynWordWrap() && c.line() == (int)startLine()) || c == startPos()))
00393       return;
00394   }
00395 
00396   int viewLinesScrolled = 0;
00397 
00398   // only calculate if this is really used and usefull, could be wrong here, please recheck
00399   // for larger scrolls this makes 2-4 seconds difference on my xeon with dyn. word wrap on
00400   // try to get it really working ;)
00401   bool viewLinesScrolledUsable = !force
00402                                  && (c.line() >= (int)startLine()-(int)linesDisplayed()-1)
00403                                  && (c.line() <= (int)endLine()+(int)linesDisplayed()+1);
00404 
00405   if (viewLinesScrolledUsable)
00406     viewLinesScrolled = displayViewLine(c);
00407 
00408   m_startPos.setPos(c);
00409 
00410   // set false here but reversed if we return to makeVisible
00411   m_madeVisible = false;
00412 
00413   if (viewLinesScrolledUsable)
00414   {
00415     int lines = linesDisplayed();
00416     if ((int)m_doc->numVisLines() < lines) {
00417       KateTextCursor end(m_doc->numVisLines() - 1, m_doc->lineLength(m_doc->getRealLine(m_doc->numVisLines() - 1)));
00418       lines = kMin((int)linesDisplayed(), displayViewLine(end) + 1);
00419     }
00420 
00421     Q_ASSERT(lines >= 0);
00422 
00423     if (!calledExternally && QABS(viewLinesScrolled) < lines)
00424     {
00425       updateView(false, viewLinesScrolled);
00426 
00427       int scrollHeight = -(viewLinesScrolled * (int)m_view->renderer()->fontHeight());
00428       int scrollbarWidth = style().scrollBarExtent().width();
00429 
00430       //
00431       // updates are for working around the scrollbar leaving blocks in the view
00432       //
00433       scroll(0, scrollHeight);
00434       update(0, height()+scrollHeight-scrollbarWidth, width(), 2*scrollbarWidth);
00435 
00436       leftBorder->scroll(0, scrollHeight);
00437       leftBorder->update(0, leftBorder->height()+scrollHeight-scrollbarWidth, leftBorder->width(), 2*scrollbarWidth);
00438 
00439       return;
00440     }
00441   }
00442 
00443   updateView();
00444   update();
00445   leftBorder->update();
00446 }
00447 
00448 void KateViewInternal::scrollColumns ( int x )
00449 {
00450   if (x == m_startX)
00451     return;
00452 
00453   if (x < 0)
00454     x = 0;
00455 
00456   int dx = m_startX - x;
00457   m_startX = x;
00458 
00459   if (QABS(dx) < width())
00460     scroll(dx, 0);
00461   else
00462     update();
00463 
00464   m_columnScroll->blockSignals(true);
00465   m_columnScroll->setValue(m_startX);
00466   m_columnScroll->blockSignals(false);
00467 }
00468 
00469 // If changed is true, the lines that have been set dirty have been updated.
00470 void KateViewInternal::updateView(bool changed, int viewLinesScrolled)
00471 {
00472   m_updatingView = true;
00473 
00474   uint contentLines = m_doc->visibleLines();
00475 
00476   m_lineScroll->blockSignals(true);
00477 
00478   KateTextCursor maxStart = maxStartPos(changed);
00479   int maxLineScrollRange = maxStart.line();
00480   if (m_view->dynWordWrap() && maxStart.col() != 0)
00481     maxLineScrollRange++;
00482   m_lineScroll->setRange(0, maxLineScrollRange);
00483 
00484   m_lineScroll->setValue(startPos().line());
00485   m_lineScroll->setSteps(1, height() / m_view->renderer()->fontHeight());
00486   m_lineScroll->blockSignals(false);
00487 
00488   uint oldSize = lineRanges.size ();
00489   uint newSize = (height() / m_view->renderer()->fontHeight()) + 1;
00490   if (oldSize != newSize) {
00491     lineRanges.resize((height() / m_view->renderer()->fontHeight()) + 1);
00492     if (newSize > oldSize) {
00493       static KateLineRange blank;
00494       for (uint i = oldSize; i < newSize; i++) {
00495         lineRanges[i] = blank;
00496       }
00497     }
00498   }
00499 
00500   if (oldSize < lineRanges.size ())
00501   {
00502     for (uint i=oldSize; i < lineRanges.size(); i++)
00503       lineRanges[i].dirty = true;
00504   }
00505 
00506   // Move the lineRanges data if we've just scrolled...
00507   if (viewLinesScrolled != 0) {
00508     // loop backwards if we've just scrolled up...
00509     bool forwards = viewLinesScrolled >= 0 ? true : false;
00510     for (uint z = forwards ? 0 : lineRanges.count() - 1; z < lineRanges.count(); forwards ? z++ : z--) {
00511       uint oldZ = z + viewLinesScrolled;
00512       if (oldZ < lineRanges.count()) {
00513         lineRanges[z] = lineRanges[oldZ];
00514       } else {
00515         lineRanges[z].dirty = true;
00516       }
00517     }
00518   }
00519 
00520   if (m_view->dynWordWrap())
00521   {
00522     KateTextCursor realStart = startPos();
00523     realStart.setLine(m_doc->getRealLine(realStart.line()));
00524 
00525     KateLineRange startRange = range(realStart);
00526     uint line = startRange.virtualLine;
00527     int realLine = startRange.line;
00528     uint oldLine = line;
00529     int startCol = startRange.startCol;
00530     int startX = startRange.startX;
00531     int endX = startRange.startX;
00532     int shiftX = startRange.startCol ? startRange.shiftX : 0;
00533     bool wrap = false;
00534     int newViewLine = startRange.viewLine;
00535     // z is the current display view line
00536     KateTextLine::Ptr text = textLine(realLine);
00537 
00538     bool alreadyDirty = false;
00539 
00540     for (uint z = 0; z < lineRanges.size(); z++)
00541     {
00542       if (oldLine != line) {
00543         realLine = (int)m_doc->getRealLine(line);
00544 
00545         if (z)
00546           lineRanges[z-1].startsInvisibleBlock = (realLine != lineRanges[z-1].line + 1);
00547 
00548         text = textLine(realLine);
00549         startCol = 0;
00550         startX = 0;
00551         endX = 0;
00552         shiftX = 0;
00553         newViewLine = 0;
00554         oldLine = line;
00555       }
00556 
00557       if (line >= contentLines || !text)
00558       {
00559         if (lineRanges[z].line != -1)
00560           lineRanges[z].dirty = true;
00561 
00562         lineRanges[z].clear();
00563 
00564         line++;
00565       }
00566       else
00567       {
00568         if (lineRanges[z].line != realLine || lineRanges[z].startCol != startCol)
00569           alreadyDirty = lineRanges[z].dirty = true;
00570 
00571         if (lineRanges[z].dirty || changed || alreadyDirty) {
00572           alreadyDirty = true;
00573 
00574           lineRanges[z].virtualLine = line;
00575           lineRanges[z].line = realLine;
00576           lineRanges[z].startsInvisibleBlock = false;
00577 
00578           int tempEndX = 0;
00579 
00580           int endCol = m_view->renderer()->textWidth(text, startCol, width() - shiftX, &wrap, &tempEndX);
00581 
00582           endX += tempEndX;
00583 
00584           if (wrap)
00585           {
00586             if (m_view->config()->dynWordWrapAlignIndent() > 0)
00587             {
00588               if (startX == 0)
00589               {
00590                 int pos = text->nextNonSpaceChar(0);
00591 
00592                 if (pos > 0)
00593                   shiftX = m_view->renderer()->textWidth(text, pos);
00594 
00595                 if (shiftX > ((double)width() / 100 * m_view->config()->dynWordWrapAlignIndent()))
00596                   shiftX = 0;
00597               }
00598             }
00599 
00600             if ((lineRanges[z].startX != startX) || (lineRanges[z].endX != endX) ||
00601                 (lineRanges[z].startCol != startCol) || (lineRanges[z].endCol != endCol) ||
00602                 (lineRanges[z].shiftX != shiftX))
00603               lineRanges[z].dirty = true;
00604 
00605             lineRanges[z].startCol = startCol;
00606             lineRanges[z].endCol = endCol;
00607             lineRanges[z].startX = startX;
00608             lineRanges[z].endX = endX;
00609             lineRanges[z].viewLine = newViewLine;
00610             lineRanges[z].wrap = true;
00611 
00612             startCol = endCol;
00613             startX = endX;
00614           }
00615           else
00616           {
00617             if ((lineRanges[z].startX != startX) || (lineRanges[z].endX != endX) ||
00618                 (lineRanges[z].startCol != startCol) || (lineRanges[z].endCol != endCol))
00619               lineRanges[z].dirty = true;
00620 
00621             lineRanges[z].startCol = startCol;
00622             lineRanges[z].endCol = endCol;
00623             lineRanges[z].startX = startX;
00624             lineRanges[z].endX = endX;
00625             lineRanges[z].viewLine = newViewLine;
00626             lineRanges[z].wrap = false;
00627 
00628             line++;
00629           }
00630 
00631           lineRanges[z].shiftX = shiftX;
00632 
00633         } else {
00634           // The cached data is still intact
00635           if (lineRanges[z].wrap) {
00636             startCol = lineRanges[z].endCol;
00637             startX = lineRanges[z].endX;
00638             endX = lineRanges[z].endX;
00639           } else {
00640             line++;
00641           }
00642           shiftX = lineRanges[z].shiftX;
00643         }
00644       }
00645       newViewLine++;
00646     }
00647   }
00648   else
00649   {
00650     uint z = 0;
00651 
00652     for(; (z + startLine() < contentLines) && (z < lineRanges.size()); z++)
00653     {
00654       if (lineRanges[z].dirty || lineRanges[z].line != (int)m_doc->getRealLine(z + startLine())) {
00655         lineRanges[z].dirty = true;
00656 
00657         lineRanges[z].line = m_doc->getRealLine( z + startLine() );
00658         if (z)
00659           lineRanges[z-1].startsInvisibleBlock = (lineRanges[z].line != lineRanges[z-1].line + 1);
00660 
00661         lineRanges[z].virtualLine = z + startLine();
00662         lineRanges[z].startCol = 0;
00663         lineRanges[z].endCol = m_doc->lineLength(lineRanges[z].line);
00664         lineRanges[z].startX = 0;
00665         lineRanges[z].endX = m_view->renderer()->textWidth( textLine( lineRanges[z].line ), -1 );
00666         lineRanges[z].shiftX = 0;
00667         lineRanges[z].viewLine = 0;
00668         lineRanges[z].wrap = false;
00669       }
00670       else if (z && lineRanges[z-1].dirty)
00671       {
00672         lineRanges[z-1].startsInvisibleBlock = (lineRanges[z].line != lineRanges[z-1].line + 1);
00673       }
00674     }
00675 
00676     for (; z < lineRanges.size(); z++)
00677     {
00678       if (lineRanges[z].line != -1)
00679         lineRanges[z].dirty = true;
00680 
00681       lineRanges[z].clear();
00682     }
00683 
00684     int max = maxLen(startLine()) - width();
00685     if (max < 0)
00686       max = 0;
00687 
00688     // if we lose the ability to scroll horizontally, move view to the far-left
00689     if (max == 0)
00690     {
00691       scrollColumns(0);
00692     }
00693 
00694     m_columnScroll->blockSignals(true);
00695 
00696     // disable scrollbar
00697     m_columnScroll->setDisabled (max == 0);
00698 
00699     m_columnScroll->setRange(0, max);
00700 
00701     m_columnScroll->setValue(m_startX);
00702 
00703     // Approximate linescroll
00704     m_columnScroll->setSteps(m_view->renderer()->config()->fontMetrics()->width('a'), width());
00705 
00706     m_columnScroll->blockSignals(false);
00707   }
00708 
00709   m_updatingView = false;
00710 
00711   if (changed)
00712     paintText(0, 0, width(), height(), true);
00713 }
00714 
00715 void KateViewInternal::paintText (int x, int y, int width, int height, bool paintOnlyDirty)
00716 {
00717   //kdDebug() << k_funcinfo << x << " " << y << " " << width << " " << height << " " << paintOnlyDirty << endl;
00718   int xStart = startX() + x;
00719   int xEnd = xStart + width;
00720   uint h = m_view->renderer()->fontHeight();
00721   uint startz = (y / h);
00722   uint endz = startz + 1 + (height / h);
00723   uint lineRangesSize = lineRanges.size();
00724 
00725   static QPixmap drawBuffer;
00726 
00727   if (drawBuffer.width() < KateViewInternal::width() || drawBuffer.height() < (int)h)
00728     drawBuffer.resize(KateViewInternal::width(), (int)h);
00729 
00730   if (drawBuffer.isNull())
00731     return;
00732 
00733   QPainter paint(this);
00734   QPainter paintDrawBuffer(&drawBuffer);
00735 
00736   // TODO put in the proper places
00737   m_view->renderer()->setCaretStyle(m_view->isOverwriteMode() ? KateRenderer::Replace : KateRenderer::Insert);
00738   m_view->renderer()->setShowTabs(m_doc->configFlags() & KateDocument::cfShowTabs);
00739 
00740   for (uint z=startz; z <= endz; z++)
00741   {
00742     if ( (z >= lineRangesSize) || ((lineRanges[z].line == -1) && (!paintOnlyDirty || lineRanges[z].dirty)) )
00743     {
00744       if (!(z >= lineRangesSize))
00745         lineRanges[z].dirty = false;
00746 
00747       paint.fillRect( x, z * h, width, h, m_view->renderer()->config()->backgroundColor() );
00748     }
00749     else if (!paintOnlyDirty || lineRanges[z].dirty)
00750     {
00751       lineRanges[z].dirty = false;
00752 
00753       m_view->renderer()->paintTextLine(paintDrawBuffer, &lineRanges[z], xStart, xEnd, &cursor, &bm);
00754 
00755       paint.drawPixmap (x, z * h, drawBuffer, 0, 0, width, h);
00756     }
00757   }
00758 }
00759 
00764 void KateViewInternal::makeVisible (const KateTextCursor& c, uint endCol, bool force, bool center, bool calledExternally)
00765 {
00766   //kdDebug() << "MakeVisible start [" << startPos().line << "," << startPos().col << "] end [" << endPos().line << "," << endPos().col << "] -> request: [" << c.line << "," << c.col << "]" <<endl;// , new start [" << scroll.line << "," << scroll.col << "] lines " << (linesDisplayed() - 1) << " height " << height() << endl;
00767     // if the line is in a folded region, unfold all the way up
00768     //if ( m_doc->foldingTree()->findNodeForLine( c.line )->visible )
00769     //  kdDebug()<<"line ("<<c.line<<") should be visible"<<endl;
00770 
00771   if ( force )
00772   {
00773     KateTextCursor scroll = c;
00774     scrollPos(scroll, force, calledExternally);
00775   }
00776   else if (center && (c < startPos() || c > endPos()))
00777   {
00778     KateTextCursor scroll = viewLineOffset(c, -int(linesDisplayed()) / 2);
00779     scrollPos(scroll, false, calledExternally);
00780   }
00781   else if ( c > viewLineOffset(endPos(), -m_minLinesVisible) )
00782   {
00783     KateTextCursor scroll = viewLineOffset(c, -((int)linesDisplayed() - m_minLinesVisible - 1));
00784     scrollPos(scroll, false, calledExternally);
00785   }
00786   else if ( c < viewLineOffset(startPos(), m_minLinesVisible) )
00787   {
00788     KateTextCursor scroll = viewLineOffset(c, -m_minLinesVisible);
00789     scrollPos(scroll, false, calledExternally);
00790   }
00791   else
00792   {
00793     // Check to see that we're not showing blank lines
00794     KateTextCursor max = maxStartPos();
00795     if (startPos() > max) {
00796       scrollPos(max, max.col(), calledExternally);
00797     }
00798   }
00799 
00800   if (!m_view->dynWordWrap() && endCol != (uint)-1)
00801   {
00802     int sX = (int)m_view->renderer()->textWidth (textLine( m_doc->getRealLine( c.line() ) ), c.col() );
00803 
00804     int sXborder = sX-8;
00805     if (sXborder < 0)
00806       sXborder = 0;
00807 
00808     if (sX < m_startX)
00809       scrollColumns (sXborder);
00810     else if  (sX > m_startX + width())
00811       scrollColumns (sX - width() + 8);
00812   }
00813 
00814   m_madeVisible = !force;
00815 }
00816 
00817 void KateViewInternal::slotRegionVisibilityChangedAt(unsigned int)
00818 {
00819   kdDebug(13030) << "slotRegionVisibilityChangedAt()" << endl;
00820   m_cachedMaxStartPos.setLine(-1);
00821   KateTextCursor max = maxStartPos();
00822   if (startPos() > max)
00823     scrollPos(max);
00824 
00825   updateView();
00826   update();
00827   leftBorder->update();
00828 }
00829 
00830 void KateViewInternal::slotCodeFoldingChanged()
00831 {
00832   leftBorder->update();
00833 }
00834 
00835 void KateViewInternal::slotRegionBeginEndAddedRemoved(unsigned int)
00836 {
00837   kdDebug(13030) << "slotRegionBeginEndAddedRemoved()" << endl;
00838   // FIXME: performance problem
00839   leftBorder->update();
00840 }
00841 
00842 void KateViewInternal::showEvent ( QShowEvent *e )
00843 {
00844   updateView ();
00845 
00846   QWidget::showEvent (e);
00847 }
00848 
00849 uint KateViewInternal::linesDisplayed() const
00850 {
00851   int h = height();
00852   int fh = m_view->renderer()->fontHeight();
00853 
00854   return (h - (h % fh)) / fh;
00855 }
00856 
00857 QPoint KateViewInternal::cursorCoordinates()
00858 {
00859   int viewLine = displayViewLine(displayCursor, true);
00860 
00861   if (viewLine == -1)
00862     return QPoint(-1, -1);
00863 
00864   uint y = viewLine * m_view->renderer()->fontHeight();
00865   uint x = cXPos - m_startX - lineRanges[viewLine].startX + leftBorder->width() + lineRanges[viewLine].xOffset();
00866 
00867   return QPoint(x, y);
00868 }
00869 
00870 void KateViewInternal::updateMicroFocusHint()
00871 {
00872     int line = displayViewLine(displayCursor, true);
00873     /* Check for hasFocus() to avoid crashes in QXIMInputContext as in bug #131266.
00874     This is only a workaround until somebody can find the real reason of the crash
00875     (probably it's in Qt). */
00876     if (line == -1 || !hasFocus()) 
00877         return;
00878 
00879     KateRenderer *renderer = m_view->renderer();
00880 
00881     // Cursor placement code is changed for Asian input method that
00882     // shows candidate window. This behavior is same as Qt/E 2.3.7
00883     // which supports Asian input methods. Asian input methods need
00884     // start point of IM selection text to place candidate window as
00885     // adjacent to the selection text.
00886     uint preeditStrLen = renderer->textWidth(textLine(m_imPreeditStartLine), cursor.col()) - renderer->textWidth(textLine(m_imPreeditStartLine), m_imPreeditSelStart);
00887     uint x = cXPos - m_startX - lineRanges[line].startX + lineRanges[line].xOffset() - preeditStrLen;
00888     uint y = line * renderer->fontHeight();
00889 
00890     setMicroFocusHint(x, y, 0, renderer->fontHeight());
00891 }
00892 
00893 void KateViewInternal::doReturn()
00894 {
00895   KateTextCursor c = cursor;
00896   m_doc->newLine( c, this );
00897   updateCursor( c );
00898   updateView();
00899 }
00900 
00901 void KateViewInternal::doDelete()
00902 {
00903   m_doc->del( m_view, cursor );
00904   if (m_view->m_codeCompletion->codeCompletionVisible()) {
00905     m_view->m_codeCompletion->updateBox();
00906   }
00907 }
00908 
00909 void KateViewInternal::doBackspace()
00910 {
00911   m_doc->backspace( m_view, cursor );
00912   if (m_view->m_codeCompletion->codeCompletionVisible()) {
00913     m_view->m_codeCompletion->updateBox();
00914   }
00915 }
00916 
00917 void KateViewInternal::doTranspose()
00918 {
00919   m_doc->transpose( cursor );
00920 }
00921 
00922 void KateViewInternal::doDeleteWordLeft()
00923 {
00924   wordLeft( true );
00925   m_view->removeSelectedText();
00926   update();
00927 }
00928 
00929 void KateViewInternal::doDeleteWordRight()
00930 {
00931   wordRight( true );
00932   m_view->removeSelectedText();
00933   update();
00934 }
00935 
00936 class CalculatingCursor : public KateTextCursor {
00937 public:
00938   CalculatingCursor(KateViewInternal* vi)
00939     : KateTextCursor()
00940     , m_vi(vi)
00941   {
00942     Q_ASSERT(valid());
00943   }
00944 
00945   CalculatingCursor(KateViewInternal* vi, const KateTextCursor& c)
00946     : KateTextCursor(c)
00947     , m_vi(vi)
00948   {
00949     Q_ASSERT(valid());
00950   }
00951 
00952   // This one constrains its arguments to valid positions
00953   CalculatingCursor(KateViewInternal* vi, uint line, uint col)
00954     : KateTextCursor(line, col)
00955     , m_vi(vi)
00956   {
00957     makeValid();
00958   }
00959 
00960 
00961   virtual CalculatingCursor& operator+=( int n ) = 0;
00962 
00963   virtual CalculatingCursor& operator-=( int n ) = 0;
00964 
00965   CalculatingCursor& operator++() { return operator+=( 1 ); }
00966 
00967   CalculatingCursor& operator--() { return operator-=( 1 ); }
00968 
00969   void makeValid() {
00970     m_line = kMax( 0, kMin( int( m_vi->m_doc->numLines() - 1 ), line() ) );
00971     if (m_vi->m_view->wrapCursor())
00972       m_col = kMax( 0, kMin( m_vi->m_doc->lineLength( line() ), col() ) );
00973     else
00974       m_col = kMax( 0, col() );
00975     Q_ASSERT( valid() );
00976   }
00977 
00978   void toEdge( Bias bias ) {
00979     if( bias == left ) m_col = 0;
00980     else if( bias == right ) m_col = m_vi->m_doc->lineLength( line() );
00981   }
00982 
00983   bool atEdge() const { return atEdge( left ) || atEdge( right ); }
00984 
00985   bool atEdge( Bias bias ) const {
00986     switch( bias ) {
00987     case left:  return col() == 0;
00988     case none:  return atEdge();
00989     case right: return col() == m_vi->m_doc->lineLength( line() );
00990     default: Q_ASSERT(false); return false;
00991     }
00992   }
00993 
00994 protected:
00995   bool valid() const {
00996     return line() >= 0 &&
00997             uint( line() ) < m_vi->m_doc->numLines() &&
00998             col() >= 0 &&
00999             (!m_vi->m_view->wrapCursor() || col() <= m_vi->m_doc->lineLength( line() ));
01000   }
01001   KateViewInternal* m_vi;
01002 };
01003 
01004 class BoundedCursor : public CalculatingCursor {
01005 public:
01006   BoundedCursor(KateViewInternal* vi)
01007     : CalculatingCursor( vi ) {};
01008   BoundedCursor(KateViewInternal* vi, const KateTextCursor& c )
01009     : CalculatingCursor( vi, c ) {};
01010   BoundedCursor(KateViewInternal* vi, uint line, uint col )
01011     : CalculatingCursor( vi, line, col ) {};
01012   virtual CalculatingCursor& operator+=( int n ) {
01013     m_col += n;
01014 
01015     if (n > 0 && m_vi->m_view->dynWordWrap()) {
01016       // Need to constrain to current visible text line for dynamic wrapping mode
01017       if (m_col > m_vi->m_doc->lineLength(m_line)) {
01018         KateLineRange currentRange = m_vi->range(*this);
01019 
01020         int endX;
01021         bool crap;
01022         m_vi->m_view->renderer()->textWidth(m_vi->textLine(m_line), currentRange.startCol, m_vi->width() - currentRange.xOffset(), &crap, &endX);
01023         endX += (m_col - currentRange.endCol + 1) * m_vi->m_view->renderer()->spaceWidth();
01024 
01025         // Constraining if applicable NOTE: some code duplication in KateViewInternal::resize()
01026         if (endX >= m_vi->width() - currentRange.xOffset()) {
01027           m_col -= n;
01028           if ( uint( line() ) < m_vi->m_doc->numLines() - 1 ) {
01029             m_line++;
01030             m_col = 0;
01031           }
01032         }
01033       }
01034 
01035     } else if (n < 0 && col() < 0 && line() > 0 ) {
01036       m_line--;
01037       m_col = m_vi->m_doc->lineLength( line() );
01038     }
01039 
01040     m_col = kMax( 0, col() );
01041 
01042     Q_ASSERT( valid() );
01043     return *this;
01044   }
01045   virtual CalculatingCursor& operator-=( int n ) {
01046     return operator+=( -n );
01047   }
01048 };
01049 
01050 class WrappingCursor : public CalculatingCursor {
01051 public:
01052   WrappingCursor(KateViewInternal* vi)
01053     : CalculatingCursor( vi) {};
01054   WrappingCursor(KateViewInternal* vi, const KateTextCursor& c )
01055     : CalculatingCursor( vi, c ) {};
01056   WrappingCursor(KateViewInternal* vi, uint line, uint col )
01057     : CalculatingCursor( vi, line, col ) {};
01058 
01059   virtual CalculatingCursor& operator+=( int n ) {
01060     if( n < 0 ) return operator-=( -n );
01061     int len = m_vi->m_doc->lineLength( line() );
01062     if( col() + n <= len ) {
01063       m_col += n;
01064     } else if( uint( line() ) < m_vi->m_doc->numLines() - 1 ) {
01065       n -= len - col() + 1;
01066       m_col = 0;
01067       m_line++;
01068       operator+=( n );
01069     } else {
01070       m_col = len;
01071     }
01072     Q_ASSERT( valid() );
01073     return *this;
01074   }
01075   virtual CalculatingCursor& operator-=( int n ) {
01076     if( n < 0 ) return operator+=( -n );
01077     if( col() - n >= 0 ) {
01078       m_col -= n;
01079     } else if( line() > 0 ) {
01080       n -= col() + 1;
01081       m_line--;
01082       m_col = m_vi->m_doc->lineLength( line() );
01083       operator-=( n );
01084     } else {
01085       m_col = 0;
01086     }
01087     Q_ASSERT( valid() );
01088     return *this;
01089   }
01090 };
01091 
01092 void KateViewInternal::moveChar( Bias bias, bool sel )
01093 {
01094   KateTextCursor c;
01095   if ( m_view->wrapCursor() ) {
01096     c = WrappingCursor( this, cursor ) += bias;
01097   } else {
01098     c = BoundedCursor( this, cursor ) += bias;
01099   }
01100 
01101   updateSelection( c, sel );
01102   updateCursor( c );
01103 }
01104 
01105 void KateViewInternal::cursorLeft(  bool sel )
01106 {
01107   if ( ! m_view->wrapCursor() && cursor.col() == 0 )
01108     return;
01109 
01110   moveChar( left, sel );
01111   if (m_view->m_codeCompletion->codeCompletionVisible()) {
01112     m_view->m_codeCompletion->updateBox();
01113   }
01114 }
01115 
01116 void KateViewInternal::cursorRight( bool sel )
01117 {
01118   moveChar( right, sel );
01119   if (m_view->m_codeCompletion->codeCompletionVisible()) {
01120     m_view->m_codeCompletion->updateBox();
01121   }
01122 }
01123 
01124 void KateViewInternal::wordLeft ( bool sel )
01125 {
01126   WrappingCursor c( this, cursor );
01127 
01128   // First we skip backwards all space.
01129   // Then we look up into which category the current position falls:
01130   // 1. a "word" character
01131   // 2. a "non-word" character (except space)
01132   // 3. the beginning of the line
01133   // and skip all preceding characters that fall into this class.
01134   // The code assumes that space is never part of the word character class.
01135 
01136   KateHighlighting* h = m_doc->highlight();
01137   if( !c.atEdge( left ) ) {
01138 
01139     while( !c.atEdge( left ) && m_doc->textLine( c.line() )[ c.col() - 1 ].isSpace() )
01140       --c;
01141   }
01142   if( c.atEdge( left ) )
01143   {
01144     --c;
01145   }
01146   else if( h->isInWord( m_doc->textLine( c.line() )[ c.col() - 1 ] ) )
01147   {
01148     while( !c.atEdge( left ) && h->isInWord( m_doc->textLine( c.line() )[ c.col() - 1 ] ) )
01149       --c;
01150   }
01151   else
01152   {
01153     while( !c.atEdge( left )
01154            && !h->isInWord( m_doc->textLine( c.line() )[ c.col() - 1 ] )
01155            // in order to stay symmetric to wordLeft()
01156            // we must not skip space preceding a non-word sequence
01157            && !m_doc->textLine( c.line() )[ c.col() - 1 ].isSpace() )
01158     {
01159       --c;
01160     }
01161   }
01162 
01163   updateSelection( c, sel );
01164   updateCursor( c );
01165 }
01166 
01167 void KateViewInternal::wordRight( bool sel )
01168 {
01169   WrappingCursor c( this, cursor );
01170 
01171   // We look up into which category the current position falls:
01172   // 1. a "word" character
01173   // 2. a "non-word" character (except space)
01174   // 3. the end of the line
01175   // and skip all following characters that fall into this class.
01176   // If the skipped characters are followed by space, we skip that too.
01177   // The code assumes that space is never part of the word character class.
01178 
01179   KateHighlighting* h = m_doc->highlight();
01180   if( c.atEdge( right ) )
01181   {
01182     ++c;
01183   }
01184   else if( h->isInWord( m_doc->textLine( c.line() )[ c.col() ] ) )
01185   {
01186     while( !c.atEdge( right ) && h->isInWord( m_doc->textLine( c.line() )[ c.col() ] ) )
01187       ++c;
01188   }
01189   else
01190   {
01191     while( !c.atEdge( right )
01192            && !h->isInWord( m_doc->textLine( c.line() )[ c.col() ] )
01193            // we must not skip space, because if that space is followed
01194            // by more non-word characters, we would skip them, too
01195            && !m_doc->textLine( c.line() )[ c.col() ].isSpace() )
01196     {
01197       ++c;
01198     }
01199   }
01200 
01201   while( !c.atEdge( right ) && m_doc->textLine( c.line() )[ c.col() ].isSpace() )
01202     ++c;
01203 
01204   updateSelection( c, sel );
01205   updateCursor( c );
01206 }
01207 
01208 void KateViewInternal::moveEdge( Bias bias, bool sel )
01209 {
01210   BoundedCursor c( this, cursor );
01211   c.toEdge( bias );
01212   updateSelection( c, sel );
01213   updateCursor( c );
01214 }
01215 
01216 void KateViewInternal::home( bool sel )
01217 {
01218   if (m_view->m_codeCompletion->codeCompletionVisible()) {
01219     QKeyEvent e(QEvent::KeyPress, Qt::Key_Home, 0, 0);
01220     m_view->m_codeCompletion->handleKey(&e);
01221     return;
01222   }
01223 
01224   if (m_view->dynWordWrap() && currentRange().startCol) {
01225     // Allow us to go to the real start if we're already at the start of the view line
01226     if (cursor.col() != currentRange().startCol) {
01227       KateTextCursor c(cursor.line(), currentRange().startCol);
01228       updateSelection( c, sel );
01229       updateCursor( c );
01230       return;
01231     }
01232   }
01233 
01234   if( !(m_doc->configFlags() & KateDocument::cfSmartHome) ) {
01235     moveEdge( left, sel );
01236     return;
01237   }
01238 
01239   KateTextLine::Ptr l = textLine( cursor.line() );
01240 
01241   if (!l)
01242     return;
01243 
01244   KateTextCursor c = cursor;
01245   int lc = l->firstChar();
01246 
01247   if( lc < 0 || c.col() == lc ) {
01248     c.setCol(0);
01249   } else {
01250     c.setCol(lc);
01251   }
01252 
01253   updateSelection( c, sel );
01254   updateCursor( c, true );
01255 }
01256 
01257 void KateViewInternal::end( bool sel )
01258 {
01259   if (m_view->m_codeCompletion->codeCompletionVisible()) {
01260     QKeyEvent e(QEvent::KeyPress, Qt::Key_End, 0, 0);
01261     m_view->m_codeCompletion->handleKey(&e);
01262     return;
01263   }
01264   
01265   // FIXME: Both "smart end" and "smart home" use the current range's last/first character
01266   //        when jumping to the "absolute" extreme. For 4.0 and 3.5.5 (kling)
01267   bool alreadyAtEndOfLine = false;
01268 
01269   if (m_view->dynWordWrap() && currentRange().wrap) {
01270     // Allow us to go to the real end if we're already at the end of the view line
01271     if (cursor.col() < currentRange().endCol - 1) {
01272       KateTextCursor c(cursor.line(), currentRange().endCol - 1);
01273       updateSelection( c, sel );
01274       updateCursor( c );
01275       return;
01276     }
01277     alreadyAtEndOfLine = true;
01278   }
01279 
01280   if( !(m_doc->configFlags() & KateDocument::cfSmartHome) ) {
01281     moveEdge( right, sel );
01282     return;
01283   }
01284 
01285   KateTextLine::Ptr l = textLine( cursor.line() );
01286 
01287   if (!l)
01288     return;
01289 
01290   // "Smart End", as requested in bugs #78258 and #106970
01291   KateTextCursor c = cursor;
01292   int lc = l->lastChar();
01293 
01294   // Apparently, currentRange().endCol differs by 1 depending on m_view->dynWordWrap()...
01295   int endOfLine = currentRange().endCol - (m_view->dynWordWrap() ? 1 : 0);
01296 
01297   if (lc < 0 || c.col() == (lc + 1)) {
01298     if (alreadyAtEndOfLine) {
01299       moveEdge(right, sel);
01300       return;
01301     }
01302     c.setCol(endOfLine);
01303   } else {
01304     c.setCol(lc + 1);
01305   }
01306 
01307   updateSelection( c, sel );
01308   updateCursor( c, true );
01309 }
01310 
01311 KateLineRange KateViewInternal::range(int realLine, const KateLineRange* previous)
01312 {
01313   // look at the cache first
01314   if (!m_updatingView && realLine >= lineRanges[0].line && realLine <= lineRanges[lineRanges.count() - 1].line)
01315     for (uint i = 0; i < lineRanges.count(); i++)
01316       if (realLine == lineRanges[i].line)
01317         if (!m_view->dynWordWrap() || (!previous && lineRanges[i].startCol == 0) || (previous && lineRanges[i].startCol == previous->endCol))
01318           return lineRanges[i];
01319 
01320   // Not in the cache, we have to create it
01321   KateLineRange ret;
01322 
01323   KateTextLine::Ptr text = textLine(realLine);
01324   if (!text) {
01325     return KateLineRange();
01326   }
01327 
01328   if (!m_view->dynWordWrap()) {
01329     Q_ASSERT(!previous);
01330     ret.line = realLine;
01331     ret.virtualLine = m_doc->getVirtualLine(realLine);
01332     ret.startCol = 0;
01333     ret.endCol = m_doc->lineLength(realLine);
01334     ret.startX = 0;
01335     ret.endX = m_view->renderer()->textWidth(text, -1);
01336     ret.viewLine = 0;
01337     ret.wrap = false;
01338     return ret;
01339   }
01340 
01341   ret.endCol = (int)m_view->renderer()->textWidth(text, previous ? previous->endCol : 0, width() - (previous ? previous->shiftX : 0), &ret.wrap, &ret.endX);
01342 
01343   Q_ASSERT(ret.endCol > ret.startCol);
01344 
01345   ret.line = realLine;
01346 
01347   if (previous) {
01348     ret.virtualLine = previous->virtualLine;
01349     ret.startCol = previous->endCol;
01350     ret.startX = previous->endX;
01351     ret.endX += previous->endX;
01352     ret.shiftX = previous->shiftX;
01353     ret.viewLine = previous->viewLine + 1;
01354 
01355   } else {
01356     // TODO worthwhile optimising this to get the data out of the initial textWidth call?
01357     if (m_view->config()->dynWordWrapAlignIndent() > 0) {
01358       int pos = text->nextNonSpaceChar(0);
01359 
01360       if (pos > 0)
01361         ret.shiftX = m_view->renderer()->textWidth(text, pos);
01362 
01363       if (ret.shiftX > ((double)width() / 100 * m_view->config()->dynWordWrapAlignIndent()))
01364         ret.shiftX = 0;
01365     }
01366 
01367     ret.virtualLine = m_doc->getVirtualLine(realLine);
01368     ret.startCol = 0;
01369     ret.startX = 0;
01370     ret.viewLine = 0;
01371   }
01372 
01373   return ret;
01374 }
01375 
01376 KateLineRange KateViewInternal::currentRange()
01377 {
01378 //  Q_ASSERT(m_view->dynWordWrap());
01379 
01380   return range(cursor);
01381 }
01382 
01383 KateLineRange KateViewInternal::previousRange()
01384 {
01385   uint currentViewLine = viewLine(cursor);
01386 
01387   if (currentViewLine)
01388     return range(cursor.line(), currentViewLine - 1);
01389   else
01390     return range(m_doc->getRealLine(displayCursor.line() - 1), -1);
01391 }
01392 
01393 KateLineRange KateViewInternal::nextRange()
01394 {
01395   uint currentViewLine = viewLine(cursor) + 1;
01396 
01397   if (currentViewLine >= viewLineCount(cursor.line())) {
01398     currentViewLine = 0;
01399     return range(cursor.line() + 1, currentViewLine);
01400   } else {
01401     return range(cursor.line(), currentViewLine);
01402   }
01403 }
01404 
01405 KateLineRange KateViewInternal::range(const KateTextCursor& realCursor)
01406 {
01407 //  Q_ASSERT(m_view->dynWordWrap());
01408 
01409   KateLineRange thisRange;
01410   bool first = true;
01411 
01412   do {
01413     thisRange = range(realCursor.line(), first ? 0L : &thisRange);
01414     first = false;
01415   } while (thisRange.wrap && !(realCursor.col() >= thisRange.startCol && realCursor.col() < thisRange.endCol) && thisRange.startCol != thisRange.endCol);
01416 
01417   return thisRange;
01418 }
01419 
01420 KateLineRange KateViewInternal::range(uint realLine, int viewLine)
01421 {
01422 //  Q_ASSERT(m_view->dynWordWrap());
01423 
01424   KateLineRange thisRange;
01425   bool first = true;
01426 
01427   do {
01428     thisRange = range(realLine, first ? 0L : &thisRange);
01429     first = false;
01430   } while (thisRange.wrap && viewLine != thisRange.viewLine && thisRange.startCol != thisRange.endCol);
01431 
01432   if (viewLine != -1 && viewLine != thisRange.viewLine)
01433     kdDebug(13030) << "WARNING: viewLine " << viewLine << " of line " << realLine << " does not exist." << endl;
01434 
01435   return thisRange;
01436 }
01437 
01443 uint KateViewInternal::viewLine(const KateTextCursor& realCursor)
01444 {
01445   if (!m_view->dynWordWrap()) return 0;
01446 
01447   if (realCursor.col() == 0) return 0;
01448 
01449   KateLineRange thisRange;
01450   bool first = true;
01451 
01452   do {
01453     thisRange = range(realCursor.line(), first ? 0L : &thisRange);
01454     first = false;
01455   } while (thisRange.wrap && !(realCursor.col() >= thisRange.startCol && realCursor.col() < thisRange.endCol) && thisRange.startCol != thisRange.endCol);
01456 
01457   return thisRange.viewLine;
01458 }
01459 
01460 int KateViewInternal::displayViewLine(const KateTextCursor& virtualCursor, bool limitToVisible)
01461 {
01462   KateTextCursor work = startPos();
01463 
01464   int limit = linesDisplayed();
01465 
01466   // Efficient non-word-wrapped path
01467   if (!m_view->dynWordWrap()) {
01468     int ret = virtualCursor.line() - startLine();
01469     if (limitToVisible && (ret < 0 || ret > limit))
01470       return -1;
01471     else
01472       return ret;
01473   }
01474 
01475   if (work == virtualCursor) {
01476     return 0;
01477   }
01478 
01479   int ret = -(int)viewLine(work);
01480   bool forwards = (work < virtualCursor) ? true : false;
01481 
01482   // FIXME switch to using ranges? faster?
01483   if (forwards) {
01484     while (work.line() != virtualCursor.line()) {
01485       ret += viewLineCount(m_doc->getRealLine(work.line()));
01486       work.setLine(work.line() + 1);
01487       if (limitToVisible && ret > limit)
01488         return -1;
01489     }
01490   } else {
01491     while (work.line() != virtualCursor.line()) {
01492       work.setLine(work.line() - 1);
01493       ret -= viewLineCount(m_doc->getRealLine(work.line()));
01494       if (limitToVisible && ret < 0)
01495         return -1;
01496     }
01497   }
01498 
01499   // final difference
01500   KateTextCursor realCursor = virtualCursor;
01501   realCursor.setLine(m_doc->getRealLine(realCursor.line()));
01502   if (realCursor.col() == -1) realCursor.setCol(m_doc->lineLength(realCursor.line()));
01503   ret += viewLine(realCursor);
01504 
01505   if (limitToVisible && (ret < 0 || ret > limit))
01506     return -1;
01507 
01508   return ret;
01509 }
01510 
01511 uint KateViewInternal::lastViewLine(uint realLine)
01512 {
01513   if (!m_view->dynWordWrap()) return 0;
01514 
01515   KateLineRange thisRange;
01516   bool first = true;
01517 
01518   do {
01519     thisRange = range(realLine, first ? 0L : &thisRange);
01520     first = false;
01521   } while (thisRange.wrap && thisRange.startCol != thisRange.endCol);
01522 
01523   return thisRange.viewLine;
01524 }
01525 
01526 uint KateViewInternal::viewLineCount(uint realLine)
01527 {
01528   return lastViewLine(realLine) + 1;
01529 }
01530 
01531 /*
01532  * This returns the cursor which is offset by (offset) view lines.
01533  * This is the main function which is called by code not specifically dealing with word-wrap.
01534  * The opposite conversion (cursor to offset) can be done with displayViewLine.
01535  *
01536  * The cursors involved are virtual cursors (ie. equivalent to displayCursor)
01537  */
01538 KateTextCursor KateViewInternal::viewLineOffset(const KateTextCursor& virtualCursor, int offset, bool keepX)
01539 {
01540   if (!m_view->dynWordWrap()) {
01541     KateTextCursor ret(kMin((int)m_doc->visibleLines() - 1, virtualCursor.line() + offset), 0);
01542 
01543     if (ret.line() < 0)
01544       ret.setLine(0);
01545 
01546     if (keepX) {
01547       int realLine = m_doc->getRealLine(ret.line());
01548       ret.setCol(m_doc->lineLength(realLine) - 1);
01549 
01550       if (m_currentMaxX > cXPos)
01551         cXPos = m_currentMaxX;
01552 
01553       if (m_view->wrapCursor())
01554         cXPos = kMin(cXPos, (int)m_view->renderer()->textWidth(textLine(realLine), m_doc->lineLength(realLine)));
01555 
01556       m_view->renderer()->textWidth(ret, cXPos);
01557     }
01558 
01559     return ret;
01560   }
01561 
01562   KateTextCursor realCursor = virtualCursor;
01563   realCursor.setLine(m_doc->getRealLine(virtualCursor.line()));
01564 
01565   uint cursorViewLine = viewLine(realCursor);
01566 
01567   int currentOffset = 0;
01568   int virtualLine = 0;
01569 
01570   bool forwards = (offset > 0) ? true : false;
01571 
01572   if (forwards) {
01573     currentOffset = lastViewLine(realCursor.line()) - cursorViewLine;
01574     if (offset <= currentOffset) {
01575       // the answer is on the same line
01576       KateLineRange thisRange = range(realCursor.line(), cursorViewLine + offset);
01577       Q_ASSERT(thisRange.virtualLine == virtualCursor.line());
01578       return KateTextCursor(virtualCursor.line(), thisRange.startCol);
01579     }
01580 
01581     virtualLine = virtualCursor.line() + 1;
01582 
01583   } else {
01584     offset = -offset;
01585     currentOffset = cursorViewLine;
01586     if (offset <= currentOffset) {
01587       // the answer is on the same line
01588       KateLineRange thisRange = range(realCursor.line(), cursorViewLine - offset);
01589       Q_ASSERT(thisRange.virtualLine == virtualCursor.line());
01590       return KateTextCursor(virtualCursor.line(), thisRange.startCol);
01591     }
01592 
01593     virtualLine = virtualCursor.line() - 1;
01594   }
01595 
01596   currentOffset++;
01597 
01598   while (virtualLine >= 0 && virtualLine < (int)m_doc->visibleLines())
01599   {
01600     KateLineRange thisRange;
01601     bool first = true;
01602     int realLine = m_doc->getRealLine(virtualLine);
01603 
01604     do {
01605       thisRange = range(realLine, first ? 0L : &thisRange);
01606       first = false;
01607 
01608       if (offset == currentOffset) {
01609         if (!forwards) {
01610           // We actually want it the other way around
01611           int requiredViewLine = lastViewLine(realLine) - thisRange.viewLine;
01612           if (requiredViewLine != thisRange.viewLine) {
01613             thisRange = range(realLine, requiredViewLine);
01614           }
01615         }
01616 
01617         KateTextCursor ret(virtualLine, thisRange.startCol);
01618 
01619         // keep column position
01620         if (keepX) {
01621           ret.setCol(thisRange.endCol - 1);
01622           KateTextCursor realCursorTemp(m_doc->getRealLine(virtualCursor.line()), virtualCursor.col());
01623           int visibleX = m_view->renderer()->textWidth(realCursorTemp) - range(realCursorTemp).startX;
01624           int xOffset = thisRange.startX;
01625 
01626           if (m_currentMaxX > visibleX)
01627             visibleX = m_currentMaxX;
01628 
01629           cXPos = xOffset + visibleX;
01630 
01631           cXPos = kMin(cXPos, lineMaxCursorX(thisRange));
01632 
01633           m_view->renderer()->textWidth(ret, cXPos);
01634         }
01635 
01636         return ret;
01637       }
01638 
01639       currentOffset++;
01640 
01641     } while (thisRange.wrap);
01642 
01643     if (forwards)
01644       virtualLine++;
01645     else
01646       virtualLine--;
01647   }
01648 
01649   // Looks like we were asked for something a bit exotic.
01650   // Return the max/min valid position.
01651   if (forwards)
01652     return KateTextCursor(m_doc->visibleLines() - 1, m_doc->lineLength(m_doc->visibleLines() - 1));
01653   else
01654     return KateTextCursor(0, 0);
01655 }
01656 
01657 int KateViewInternal::lineMaxCursorX(const KateLineRange& range)
01658 {
01659   if (!m_view->wrapCursor() && !range.wrap)
01660     return INT_MAX;
01661 
01662   int maxX = range.endX;
01663 
01664   if (maxX && range.wrap) {
01665     QChar lastCharInLine = textLine(range.line)->getChar(range.endCol - 1);
01666     maxX -= m_view->renderer()->config()->fontMetrics()->width(lastCharInLine);
01667   }
01668 
01669   return maxX;
01670 }
01671 
01672 int KateViewInternal::lineMaxCol(const KateLineRange& range)
01673 {
01674   int maxCol = range.endCol;
01675 
01676   if (maxCol && range.wrap)
01677     maxCol--;
01678 
01679   return maxCol;
01680 }
01681 
01682 void KateViewInternal::cursorUp(bool sel)
01683 {
01684   if (m_view->m_codeCompletion->codeCompletionVisible()) {
01685     QKeyEvent e(QEvent::KeyPress, Qt::Key_Up, 0, 0);
01686     m_view->m_codeCompletion->handleKey(&e);
01687     return;
01688   }
01689 
01690   if (displayCursor.line() == 0 && (!m_view->dynWordWrap() || viewLine(cursor) == 0))
01691     return;
01692 
01693   int newLine = cursor.line(), newCol = 0, xOffset = 0, startCol = 0;
01694   m_preserveMaxX = true;
01695 
01696   if (m_view->dynWordWrap()) {
01697     // Dynamic word wrapping - navigate on visual lines rather than real lines
01698     KateLineRange thisRange = currentRange();
01699     // This is not the first line because that is already simplified out above
01700     KateLineRange pRange = previousRange();
01701 
01702     // Ensure we're in the right spot
01703     Q_ASSERT((cursor.line() == thisRange.line) &&
01704              (cursor.col() >= thisRange.startCol) &&
01705              (!thisRange.wrap || cursor.col() < thisRange.endCol));
01706 
01707     // VisibleX is the distance from the start of the text to the cursor on the current line.
01708     int visibleX = m_view->renderer()->textWidth(cursor) - thisRange.startX;
01709     int currentLineVisibleX = visibleX;
01710 
01711     // Translate to new line
01712     visibleX += thisRange.xOffset();
01713     visibleX -= pRange.xOffset();
01714 
01715     // Limit to >= 0
01716     visibleX = kMax(0, visibleX);
01717 
01718     startCol = pRange.startCol;
01719     xOffset = pRange.startX;
01720     newLine = pRange.line;
01721 
01722     // Take into account current max X (ie. if the current line was smaller
01723     // than the last definitely specified width)
01724     if (thisRange.xOffset() && !pRange.xOffset() && currentLineVisibleX == 0) // Special case for where xOffset may be > m_currentMaxX
01725       visibleX = m_currentMaxX;
01726     else if (visibleX < m_currentMaxX - pRange.xOffset())
01727       visibleX = m_currentMaxX - pRange.xOffset();
01728 
01729     cXPos = xOffset + visibleX;
01730 
01731     cXPos = kMin(cXPos, lineMaxCursorX(pRange));
01732 
01733     newCol = kMin((int)m_view->renderer()->textPos(newLine, visibleX, startCol), lineMaxCol(pRange));
01734 
01735   } else {
01736     newLine = m_doc->getRealLine(displayCursor.line() - 1);
01737 
01738     if ((m_view->wrapCursor()) && m_currentMaxX > cXPos)
01739       cXPos = m_currentMaxX;
01740   }
01741 
01742   KateTextCursor c(newLine, newCol);
01743   m_view->renderer()->textWidth(c, cXPos);
01744 
01745   updateSelection( c, sel );
01746   updateCursor( c );
01747 }
01748 
01749 void KateViewInternal::cursorDown(bool sel)
01750 {
01751   if (m_view->m_codeCompletion->codeCompletionVisible()) {
01752     QKeyEvent e(QEvent::KeyPress, Qt::Key_Down, 0, 0);
01753     m_view->m_codeCompletion->handleKey(&e);
01754     return;
01755   }
01756 
01757   if ((displayCursor.line() >= (int)m_doc->numVisLines() - 1) && (!m_view->dynWordWrap() || viewLine(cursor) == lastViewLine(cursor.line())))
01758     return;
01759 
01760   int newLine = cursor.line(), newCol = 0, xOffset = 0, startCol = 0;
01761   m_preserveMaxX = true;
01762 
01763   if (m_view->dynWordWrap()) {
01764     // Dynamic word wrapping - navigate on visual lines rather than real lines
01765     KateLineRange thisRange = currentRange();
01766     // This is not the last line because that is already simplified out above
01767     KateLineRange nRange = nextRange();
01768 
01769     // Ensure we're in the right spot
01770     Q_ASSERT((cursor.line() == thisRange.line) &&
01771              (cursor.col() >= thisRange.startCol) &&
01772              (!thisRange.wrap || cursor.col() < thisRange.endCol));
01773 
01774     // VisibleX is the distance from the start of the text to the cursor on the current line.
01775     int visibleX = m_view->renderer()->textWidth(cursor) - thisRange.startX;
01776     int currentLineVisibleX = visibleX;
01777 
01778     // Translate to new line
01779     visibleX += thisRange.xOffset();
01780     visibleX -= nRange.xOffset();
01781 
01782     // Limit to >= 0
01783     visibleX = kMax(0, visibleX);
01784 
01785     if (!thisRange.wrap) {
01786       newLine = m_doc->getRealLine(displayCursor.line() + 1);
01787     } else {
01788       startCol = thisRange.endCol;
01789       xOffset = thisRange.endX;
01790     }
01791 
01792     // Take into account current max X (ie. if the current line was smaller
01793     // than the last definitely specified width)
01794     if (thisRange.xOffset() && !nRange.xOffset() && currentLineVisibleX == 0) // Special case for where xOffset may be > m_currentMaxX
01795       visibleX = m_currentMaxX;
01796     else if (visibleX < m_currentMaxX - nRange.xOffset())
01797       visibleX = m_currentMaxX - nRange.xOffset();
01798 
01799     cXPos = xOffset + visibleX;
01800 
01801     cXPos = kMin(cXPos, lineMaxCursorX(nRange));
01802 
01803     newCol = kMin((int)m_view->renderer()->textPos(newLine, visibleX, startCol), lineMaxCol(nRange));
01804 
01805   } else {
01806     newLine = m_doc->getRealLine(displayCursor.line() + 1);
01807 
01808     if ((m_view->wrapCursor()) && m_currentMaxX > cXPos)
01809       cXPos = m_currentMaxX;
01810   }
01811 
01812   KateTextCursor c(newLine, newCol);
01813   m_view->renderer()->textWidth(c, cXPos);
01814 
01815   updateSelection(c, sel);
01816   updateCursor(c);
01817 }
01818 
01819 void KateViewInternal::cursorToMatchingBracket( bool sel )
01820 {
01821   KateTextCursor start( cursor ), end;
01822 
01823   if( !m_doc->findMatchingBracket( start, end ) )
01824     return;
01825 
01826   // The cursor is now placed just to the left of the matching bracket.
01827   // If it's an ending bracket, put it to the right (so we can easily
01828   // get back to the original bracket).
01829   if( end > start )
01830     end.setCol(end.col() + 1);
01831 
01832   updateSelection( end, sel );
01833   updateCursor( end );
01834 }
01835 
01836 void KateViewInternal::topOfView( bool sel )
01837 {
01838   KateTextCursor c = viewLineOffset(startPos(), m_minLinesVisible);
01839   updateSelection( c, sel );
01840   updateCursor( c );
01841 }
01842 
01843 void KateViewInternal::bottomOfView( bool sel )
01844 {
01845   // FIXME account for wordwrap
01846   KateTextCursor c = viewLineOffset(endPos(), -m_minLinesVisible);
01847   updateSelection( c, sel );
01848   updateCursor( c );
01849 }
01850 
01851 // lines is the offset to scroll by
01852 void KateViewInternal::scrollLines( int lines, bool sel )
01853 {
01854   KateTextCursor c = viewLineOffset(displayCursor, lines, true);
01855 
01856   // Fix the virtual cursor -> real cursor
01857   c.setLine(m_doc->getRealLine(c.line()));
01858 
01859   updateSelection( c, sel );
01860   updateCursor( c );
01861 }
01862 
01863 // This is a bit misleading... it's asking for the view to be scrolled, not the cursor
01864 void KateViewInternal::scrollUp()
01865 {
01866   KateTextCursor newPos = viewLineOffset(m_startPos, -1);
01867   scrollPos(newPos);
01868 }
01869 
01870 void KateViewInternal::scrollDown()
01871 {
01872   KateTextCursor newPos = viewLineOffset(m_startPos, 1);
01873   scrollPos(newPos);
01874 }
01875 
01876 void KateViewInternal::setAutoCenterLines(int viewLines, bool updateView)
01877 {
01878   m_autoCenterLines = viewLines;
01879   m_minLinesVisible = kMin(int((linesDisplayed() - 1)/2), m_autoCenterLines);
01880   if (updateView)
01881     KateViewInternal::updateView();
01882 }
01883 
01884 void KateViewInternal::pageUp( bool sel )
01885 {
01886   if (m_view->m_codeCompletion->codeCompletionVisible()) {
01887     QKeyEvent e(QEvent::KeyPress, Qt::Key_PageUp, 0, 0);
01888     m_view->m_codeCompletion->handleKey(&e);
01889     return;
01890   }
01891 
01892   // remember the view line and x pos
01893   int viewLine = displayViewLine(displayCursor);
01894   bool atTop = (startPos().line() == 0 && startPos().col() == 0);
01895 
01896   // Adjust for an auto-centering cursor
01897   int lineadj = 2 * m_minLinesVisible;
01898   int cursorStart = (linesDisplayed() - 1) - viewLine;
01899   if (cursorStart < m_minLinesVisible)
01900     lineadj -= m_minLinesVisible - cursorStart;
01901 
01902   int linesToScroll = -kMax( ((int)linesDisplayed() - 1) - lineadj, 0 );
01903   m_preserveMaxX = true;
01904 
01905   if (!m_doc->pageUpDownMovesCursor () && !atTop) {
01906     int xPos = m_view->renderer()->textWidth(cursor) - currentRange().startX;
01907 
01908     KateTextCursor newStartPos = viewLineOffset(startPos(), linesToScroll - 1);
01909     scrollPos(newStartPos);
01910 
01911     // put the cursor back approximately where it was
01912     KateTextCursor newPos = viewLineOffset(newStartPos, viewLine, true);
01913     newPos.setLine(m_doc->getRealLine(newPos.line()));
01914 
01915     KateLineRange newLine = range(newPos);
01916 
01917     if (m_currentMaxX - newLine.xOffset() > xPos)
01918       xPos = m_currentMaxX - newLine.xOffset();
01919 
01920     cXPos = kMin(newLine.startX + xPos, lineMaxCursorX(newLine));
01921 
01922     m_view->renderer()->textWidth( newPos, cXPos );
01923 
01924     m_preserveMaxX = true;
01925     updateSelection( newPos, sel );
01926     updateCursor(newPos);
01927 
01928   } else {
01929     scrollLines( linesToScroll, sel );
01930   }
01931 }
01932 
01933 void KateViewInternal::pageDown( bool sel )
01934 {
01935   if (m_view->m_codeCompletion->codeCompletionVisible()) {
01936     QKeyEvent e(QEvent::KeyPress, Qt::Key_PageDown, 0, 0);
01937     m_view->m_codeCompletion->handleKey(&e);
01938     return;
01939   }
01940 
01941   // remember the view line
01942   int viewLine = displayViewLine(displayCursor);
01943   bool atEnd = startPos() >= m_cachedMaxStartPos;
01944 
01945   // Adjust for an auto-centering cursor
01946   int lineadj = 2 * m_minLinesVisible;
01947   int cursorStart = m_minLinesVisible - viewLine;
01948   if (cursorStart > 0)
01949     lineadj -= cursorStart;
01950 
01951   int linesToScroll = kMax( ((int)linesDisplayed() - 1) - lineadj, 0 );
01952   m_preserveMaxX = true;
01953 
01954   if (!m_doc->pageUpDownMovesCursor () && !atEnd) {
01955     int xPos = m_view->renderer()->textWidth(cursor) - currentRange().startX;
01956 
01957     KateTextCursor newStartPos = viewLineOffset(startPos(), linesToScroll + 1);
01958     scrollPos(newStartPos);
01959 
01960     // put the cursor back approximately where it was
01961     KateTextCursor newPos = viewLineOffset(newStartPos, viewLine, true);
01962     newPos.setLine(m_doc->getRealLine(newPos.line()));
01963 
01964     KateLineRange newLine = range(newPos);
01965 
01966     if (m_currentMaxX - newLine.xOffset() > xPos)
01967       xPos = m_currentMaxX - newLine.xOffset();
01968 
01969     cXPos = kMin(newLine.startX + xPos, lineMaxCursorX(newLine));
01970 
01971     m_view->renderer()->textWidth( newPos, cXPos );
01972 
01973     m_preserveMaxX = true;
01974     updateSelection( newPos, sel );
01975     updateCursor(newPos);
01976 
01977   } else {
01978     scrollLines( linesToScroll, sel );
01979   }
01980 }
01981 
01982 int KateViewInternal::maxLen(uint startLine)
01983 {
01984 //  Q_ASSERT(!m_view->dynWordWrap());
01985 
01986   int displayLines = (m_view->height() / m_view->renderer()->fontHeight()) + 1;
01987 
01988   int maxLen = 0;
01989 
01990   for (int z = 0; z < displayLines; z++) {
01991     int virtualLine = startLine + z;
01992 
01993     if (virtualLine < 0 || virtualLine >= (int)m_doc->visibleLines())
01994       break;
01995 
01996     KateLineRange thisRange = range((int)m_doc->getRealLine(virtualLine));
01997 
01998     maxLen = kMax(maxLen, thisRange.endX);
01999   }
02000 
02001   return maxLen;
02002 }
02003 
02004 void KateViewInternal::top( bool sel )
02005 {
02006   KateTextCursor c( 0, cursor.col() );
02007   m_view->renderer()->textWidth( c, cXPos );
02008   updateSelection( c, sel );
02009   updateCursor( c );
02010 }
02011 
02012 void KateViewInternal::bottom( bool sel )
02013 {
02014   KateTextCursor c( m_doc->lastLine(), cursor.col() );
02015   m_view->renderer()->textWidth( c, cXPos );
02016   updateSelection( c, sel );
02017   updateCursor( c );
02018 }
02019 
02020 void KateViewInternal::top_home( bool sel )
02021 {
02022   if (m_view->m_codeCompletion->codeCompletionVisible()) {
02023     QKeyEvent e(QEvent::KeyPress, Qt::Key_Home, 0, 0);
02024     m_view->m_codeCompletion->handleKey(&e);
02025     return;
02026   }
02027   KateTextCursor c( 0, 0 );
02028   updateSelection( c, sel );
02029   updateCursor( c );
02030 }
02031 
02032 void KateViewInternal::bottom_end( bool sel )
02033 {
02034   if (m_view->m_codeCompletion->codeCompletionVisible()) {
02035     QKeyEvent e(QEvent::KeyPress, Qt::Key_End, 0, 0);
02036     m_view->m_codeCompletion->handleKey(&e);
02037     return;
02038   }
02039   KateTextCursor c( m_doc->lastLine(), m_doc->lineLength( m_doc->lastLine() ) );
02040   updateSelection( c, sel );
02041   updateCursor( c );
02042 }
02043 
02044 void KateViewInternal::updateSelection( const KateTextCursor& _newCursor, bool keepSel )
02045 {
02046   KateTextCursor newCursor = _newCursor;
02047   if( keepSel )
02048   {
02049     if ( !m_view->hasSelection() || (selectAnchor.line() == -1)
02050          || (m_view->config()->persistentSelection()
02051              && ((cursor < m_view->selectStart) || (cursor > m_view->selectEnd))) )
02052     {
02053       selectAnchor = cursor;
02054       m_view->setSelection( cursor, newCursor );
02055     }
02056     else
02057     {
02058       bool doSelect = true;
02059       switch (m_selectionMode)
02060       {
02061         case Word:
02062         {
02063           bool same = ( newCursor.line() == selStartCached.line() );
02064           uint c;
02065           if ( newCursor.line() > selStartCached.line() ||
02066                ( same && newCursor.col() > selEndCached.col() ) )
02067           {
02068             selectAnchor = selStartCached;
02069 
02070             KateTextLine::Ptr l = m_doc->kateTextLine( newCursor.line() );
02071 
02072             for ( c = newCursor.col(); c < l->length(); c++ )
02073               if ( !m_doc->highlight()->isInWord( l->getChar( c ) ) )
02074                 break;
02075 
02076             newCursor.setCol( c );
02077           }
02078           else if ( newCursor.line() < selStartCached.line() ||
02079                ( same && newCursor.col() < selStartCached.col() ) )
02080           {
02081             selectAnchor = selEndCached;
02082 
02083             KateTextLine::Ptr l = m_doc->kateTextLine( newCursor.line() );
02084 
02085             for ( c = newCursor.col(); c > 0; c-- )
02086               if ( !m_doc->highlight()->isInWord( l->getChar( c ) ) )
02087                 break;
02088 
02089             newCursor.setCol( c+1 );
02090           }
02091           else
02092             doSelect = false;
02093 
02094         }
02095         break;
02096         case Line:
02097           if ( newCursor.line() > selStartCached.line() )
02098           {
02099             selectAnchor = selStartCached;
02100             newCursor.setCol( m_doc->textLine( newCursor.line() ).length() );
02101           }
02102           else if ( newCursor.line() < selStartCached.line() )
02103           {
02104             selectAnchor = selEndCached;
02105             newCursor.setCol( 0 );
02106           }
02107           else // same line, ignore
02108             doSelect = false;
02109         break;
02110         default: // *allways* keep original selection for mouse
02111         {
02112           if ( selStartCached.line() < 0 ) // invalid
02113             break;
02114 
02115           if ( newCursor.line() > selEndCached.line() ||
02116                ( newCursor.line() == selEndCached.line() &&
02117                  newCursor.col() > selEndCached.col() ) )
02118             selectAnchor = selStartCached;
02119 
02120           else if ( newCursor.line() < selStartCached.line() ||
02121                ( newCursor.line() == selStartCached.line() &&
02122                  newCursor.col() < selStartCached.col() ) )
02123             selectAnchor = selEndCached;
02124 
02125           else
02126             doSelect = false;
02127         }
02128 //         break;
02129       }
02130 
02131       if ( doSelect )
02132         m_view->setSelection( selectAnchor, newCursor);
02133       else if ( selStartCached.line() > 0 ) // we have a cached selection, so we restore that
02134         m_view->setSelection( selStartCached, selEndCached );
02135     }
02136 
02137     m_selChangedByUser = true;
02138   }
02139   else if ( !m_view->config()->persistentSelection() )
02140   {
02141     m_view->clearSelection();
02142     selStartCached.setLine( -1 );
02143     selectAnchor.setLine( -1 );
02144   }
02145 }
02146 
02147 void KateViewInternal::updateCursor( const KateTextCursor& newCursor, bool force, bool center, bool calledExternally )
02148 {
02149   if ( !force && (cursor == newCursor) )
02150   {
02151     if ( !m_madeVisible )
02152     {
02153       // unfold if required
02154       m_doc->foldingTree()->ensureVisible( newCursor.line() );
02155 
02156       makeVisible ( displayCursor, displayCursor.col(), false, center, calledExternally );
02157     }
02158 
02159     return;
02160   }
02161 
02162   // unfold if required
02163   m_doc->foldingTree()->ensureVisible( newCursor.line() );
02164 
02165   KateTextCursor oldDisplayCursor = displayCursor;
02166 
02167   cursor.setPos (newCursor);
02168   displayCursor.setPos (m_doc->getVirtualLine(cursor.line()), cursor.col());
02169 
02170   cXPos = m_view->renderer()->textWidth( cursor );
02171   makeVisible ( displayCursor, displayCursor.col(), false, center, calledExternally );
02172 
02173   updateBracketMarks();
02174 
02175   // It's efficient enough to just tag them both without checking to see if they're on the same view line
02176   tagLine(oldDisplayCursor);
02177   tagLine(displayCursor);
02178 
02179   updateMicroFocusHint();
02180 
02181   if (m_cursorTimer.isActive ())
02182   {
02183     if ( KApplication::cursorFlashTime() > 0 )
02184       m_cursorTimer.start( KApplication::cursorFlashTime() / 2 );
02185     m_view->renderer()->setDrawCaret(true);
02186   }
02187 
02188   // Remember the maximum X position if requested
02189   if (m_preserveMaxX)
02190     m_preserveMaxX = false;
02191   else
02192     if (m_view->dynWordWrap())
02193       m_currentMaxX = m_view->renderer()->textWidth(displayCursor) - currentRange().startX + currentRange().xOffset();
02194     else
02195       m_currentMaxX = cXPos;
02196 
02197   //kdDebug() << "m_currentMaxX: " << m_currentMaxX << " (was "<< oldmaxx << "), cXPos: " << cXPos << endl;
02198   //kdDebug(13030) << "Cursor now located at real " << cursor.line << "," << cursor.col << ", virtual " << displayCursor.line << ", " << displayCursor.col << "; Top is " << startLine() << ", " << startPos().col <<  endl;
02199 
02200   paintText(0, 0, width(), height(), true);
02201 
02202   emit m_view->cursorPositionChanged();
02203 }
02204 
02205 void KateViewInternal::updateBracketMarks()
02206 {
02207   if ( bm.isValid() ) {
02208     KateTextCursor bmStart(m_doc->getVirtualLine(bm.start().line()), bm.start().col());
02209     KateTextCursor bmEnd(m_doc->getVirtualLine(bm.end().line()), bm.end().col());
02210 
02211     if( bm.getMinIndent() != 0 )
02212     {
02213       // @@ Do this only when cursor near start/end.
02214       if( bmStart > bmEnd )
02215       {
02216         tagLines(bmEnd, bmStart, true);
02217       }
02218       else
02219       {
02220         tagLines(bmStart, bmEnd, true);
02221       }
02222     }
02223     else
02224     {
02225       tagLine(bmStart);
02226       tagLine(bmEnd);
02227     }
02228   }
02229 
02230   // add some limit to this, this is really endless on big files without limit
02231   int maxLines = linesDisplayed () * 3;
02232   m_doc->newBracketMark( cursor, bm, maxLines );
02233 
02234   if ( bm.isValid() ) {
02235     KateTextCursor bmStart(m_doc->getVirtualLine(bm.start().line()), bm.start().col());
02236     KateTextCursor bmEnd(m_doc->getVirtualLine(bm.end().line()), bm.end().col());
02237 
02238     if( bm.getMinIndent() != 0 )
02239     {
02240       // @@ Do this only when cursor near start/end.
02241       if( bmStart > bmEnd )
02242       {
02243         tagLines(bmEnd, bmStart, true);
02244       }
02245       else
02246       {
02247         tagLines(bmStart, bmEnd, true);
02248       }
02249     }
02250     else
02251     {
02252       tagLine(bmStart);
02253       tagLine(bmEnd);
02254     }
02255   }
02256 }
02257 
02258 bool KateViewInternal::tagLine(const KateTextCursor& virtualCursor)
02259 {
02260   int viewLine = displayViewLine(virtualCursor, true);
02261   if (viewLine >= 0 && viewLine < (int)lineRanges.count()) {
02262     lineRanges[viewLine].dirty = true;
02263     leftBorder->update (0, lineToY(viewLine), leftBorder->width(), m_view->renderer()->fontHeight());
02264     return true;
02265   }
02266   return false;
02267 }
02268 
02269 bool KateViewInternal::tagLines( int start, int end, bool realLines )
02270 {
02271   return tagLines(KateTextCursor(start, 0), KateTextCursor(end, -1), realLines);
02272 }
02273 
02274 bool KateViewInternal::tagLines(KateTextCursor start, KateTextCursor end, bool realCursors)
02275 {
02276   if (realCursors)
02277   {
02278     //kdDebug()<<"realLines is true"<<endl;
02279     start.setLine(m_doc->getVirtualLine( start.line() ));
02280     end.setLine(m_doc->getVirtualLine( end.line() ));
02281   }
02282 
02283   if (end.line() < (int)startLine())
02284   {
02285     //kdDebug()<<"end<startLine"<<endl;
02286     return false;
02287   }
02288   if (start.line() > (int)endLine())
02289   {
02290     //kdDebug()<<"start> endLine"<<start<<" "<<((int)endLine())<<endl;
02291     return false;
02292   }
02293 
02294   //kdDebug(13030) << "tagLines( [" << start.line << "," << start.col << "], [" << end.line << "," << end.col << "] )\n";
02295 
02296   bool ret = false;
02297 
02298   for (uint z = 0; z < lineRanges.size(); z++)
02299   {
02300     if ((lineRanges[z].virtualLine > start.line() || (lineRanges[z].virtualLine == start.line() && lineRanges[z].endCol >= start.col() && start.col() != -1)) && (lineRanges[z].virtualLine < end.line() || (lineRanges[z].virtualLine == end.line() && (lineRanges[z].startCol <= end.col() || end.col() == -1)))) {
02301       ret = lineRanges[z].dirty = true;
02302       //kdDebug() << "Tagged line " << lineRanges[z].line << endl;
02303     }
02304   }
02305 
02306   if (!m_view->dynWordWrap())
02307   {
02308     int y = lineToY( start.line() );
02309     // FIXME is this enough for when multiple lines are deleted
02310     int h = (end.line() - start.line() + 2) * m_view->renderer()->fontHeight();
02311     if (end.line() == (int)m_doc->numVisLines() - 1)
02312       h = height();
02313 
02314     leftBorder->update (0, y, leftBorder->width(), h);
02315   }
02316   else
02317   {
02318     // FIXME Do we get enough good info in editRemoveText to optimise this more?
02319     //bool justTagged = false;
02320     for (uint z = 0; z < lineRanges.size(); z++)
02321     {
02322       if ((lineRanges[z].virtualLine > start.line() || (lineRanges[z].virtualLine == start.line() && lineRanges[z].endCol >= start.col() && start.col() != -1)) && (lineRanges[z].virtualLine < end.line() || (lineRanges[z].virtualLine == end.line() && (lineRanges[z].startCol <= end.col() || end.col() == -1))))
02323       {
02324         //justTagged = true;
02325         leftBorder->update (0, z * m_view->renderer()->fontHeight(), leftBorder->width(), leftBorder->height());
02326         break;
02327       }
02328       /*else if (justTagged)
02329       {
02330         justTagged = false;
02331         leftBorder->update (0, z * m_doc->viewFont.fontHeight, leftBorder->width(), m_doc->viewFont.fontHeight);
02332         break;
02333       }*/
02334     }
02335   }
02336 
02337   return ret;
02338 }
02339 
02340 void KateViewInternal::tagAll()
02341 {
02342   //kdDebug(13030) << "tagAll()" << endl;
02343   for (uint z = 0; z < lineRanges.size(); z++)
02344   {
02345       lineRanges[z].dirty = true;
02346   }
02347 
02348   leftBorder->updateFont();
02349   leftBorder->update ();
02350 }
02351 
02352 void KateViewInternal::paintCursor()
02353 {
02354   if (tagLine(displayCursor))
02355     paintText (0,0,width(), height(), true);
02356 }
02357 
02358 // Point in content coordinates
02359 void KateViewInternal::placeCursor( const QPoint& p, bool keepSelection, bool updateSelection )
02360 {
02361   KateLineRange thisRange = yToKateLineRange(p.y());
02362 
02363   if (thisRange.line == -1) {
02364     for (int i = (p.y() / m_view->renderer()->fontHeight()); i >= 0; i--) {
02365       thisRange = lineRanges[i];
02366       if (thisRange.line != -1)
02367         break;
02368     }
02369     Q_ASSERT(thisRange.line != -1);
02370   }
02371 
02372   int realLine = thisRange.line;
02373   int visibleLine = thisRange.virtualLine;
02374   uint startCol = thisRange.startCol;
02375 
02376   visibleLine = kMax( 0, kMin( visibleLine, int(m_doc->numVisLines()) - 1 ) );
02377 
02378   KateTextCursor c(realLine, 0);
02379 
02380   int x = kMin(kMax(-m_startX, p.x() - thisRange.xOffset()), lineMaxCursorX(thisRange) - thisRange.startX);
02381 
02382   m_view->renderer()->textWidth( c, startX() + x, startCol);
02383 
02384   if (updateSelection)
02385     KateViewInternal::updateSelection( c, keepSelection );
02386 
02387   updateCursor( c );
02388 }
02389 
02390 // Point in content coordinates
02391 bool KateViewInternal::isTargetSelected( const QPoint& p )
02392 {
02393   KateLineRange thisRange = yToKateLineRange(p.y());
02394 
02395   KateTextLine::Ptr l = textLine( thisRange.line );
02396   if( !l )
02397     return false;
02398 
02399   int col = m_view->renderer()->textPos( l, p.x() - thisRange.xOffset(), thisRange.startCol, false );
02400 
02401   return m_view->lineColSelected( thisRange.line, col );
02402 }
02403 
02404 //BEGIN EVENT HANDLING STUFF
02405 
02406 bool KateViewInternal::eventFilter( QObject *obj, QEvent *e )
02407 {
02408   if (obj == m_lineScroll)
02409   {
02410     // the second condition is to make sure a scroll on the vertical bar doesn't cause a horizontal scroll ;)
02411     if (e->type() == QEvent::Wheel && m_lineScroll->minValue() != m_lineScroll->maxValue())
02412     {
02413       wheelEvent((QWheelEvent*)e);
02414       return true;
02415     }
02416 
02417     // continue processing
02418     return QWidget::eventFilter( obj, e );
02419   }
02420 
02421   switch( e->type() )
02422   {
02423     case QEvent::KeyPress:
02424     {
02425       QKeyEvent *k = (QKeyEvent *)e;
02426 
02427       if (m_view->m_codeCompletion->codeCompletionVisible ())
02428       {
02429         kdDebug (13030) << "hint around" << endl;
02430 
02431         if( k->key() == Key_Escape )
02432           m_view->m_codeCompletion->abortCompletion();
02433       }
02434 
02435       if ((k->key() == Qt::Key_Escape) && !m_view->config()->persistentSelection() )
02436       {
02437         m_view->clearSelection();
02438         return true;
02439       }
02440       else if ( !((k->state() & ControlButton) || (k->state() & AltButton)) )
02441       {
02442         keyPressEvent( k );
02443         return k->isAccepted();
02444       }
02445 
02446     } break;
02447 
02448     case QEvent::DragMove:
02449     {
02450       QPoint currentPoint = ((QDragMoveEvent*) e)->pos();
02451 
02452       QRect doNotScrollRegion( scrollMargin, scrollMargin,
02453                           width() - scrollMargin * 2,
02454                           height() - scrollMargin * 2 );
02455 
02456       if ( !doNotScrollRegion.contains( currentPoint ) )
02457       {
02458           startDragScroll();
02459           // Keep sending move events
02460           ( (QDragMoveEvent*)e )->accept( QRect(0,0,0,0) );
02461       }
02462 
02463       dragMoveEvent((QDragMoveEvent*)e);
02464     } break;
02465 
02466     case QEvent::DragLeave:
02467       // happens only when pressing ESC while dragging
02468       stopDragScroll();
02469       break;
02470 
02471     case QEvent::WindowBlocked:
02472       // next focus originates from an internal dialog:
02473       // don't show the modonhd prompt
02474       m_doc->m_isasking = -1;
02475       break;
02476 
02477     default:
02478       break;
02479   }
02480 
02481   return QWidget::eventFilter( obj, e );
02482 }
02483 
02484 void KateViewInternal::keyPressEvent( QKeyEvent* e )
02485 {
02486   KKey key(e);
02487 
02488   bool codeComp = m_view->m_codeCompletion->codeCompletionVisible ();
02489 
02490   if (codeComp)
02491   {
02492     kdDebug (13030) << "hint around" << endl;
02493 
02494     if( e->key() == Key_Enter || e->key() == Key_Return  ||
02495     (key == SHIFT + Qt::Key_Return) || (key == SHIFT + Qt::Key_Enter)) {
02496       m_view->m_codeCompletion->doComplete();
02497       e->accept();
02498       return;
02499     }
02500   }
02501 
02502   if( !m_doc->isReadWrite() )
02503   {
02504     e->ignore();
02505     return;
02506   }
02507 
02508   if ((key == Qt::Key_Return) || (key == Qt::Key_Enter))
02509   {
02510     m_view->keyReturn();
02511     e->accept();
02512     return;
02513   }
02514 
02515   if ((key == SHIFT + Qt::Key_Return) || (key == SHIFT + Qt::Key_Enter))
02516   {
02517     uint ln = cursor.line();
02518     int col = cursor.col();
02519     KateTextLine::Ptr line = m_doc->kateTextLine( ln );
02520     int pos = line->firstChar();
02521     if (pos > cursor.col()) pos = cursor.col();
02522     if (pos != -1) {
02523       while ((int)line->length() > pos &&
02524              !line->getChar(pos).isLetterOrNumber() &&
02525              pos < cursor.col()) ++pos;
02526     } else {
02527       pos = line->length(); // stay indented
02528     }
02529     m_doc->editStart();
02530     m_doc->insertText( cursor.line(), line->length(), "\n" +  line->string(0, pos)
02531       + line->string().right( line->length() - cursor.col() ) );
02532     cursor.setPos(ln + 1, pos);
02533     if (col < int(line->length()))
02534       m_doc->editRemoveText(ln, col, line->length() - col);
02535     m_doc->editEnd();
02536     updateCursor(cursor, true);
02537     updateView();
02538     e->accept();
02539 
02540     return;
02541   }
02542 
02543   if (key == Qt::Key_Backspace || key == SHIFT + Qt::Key_Backspace)
02544   {
02545     m_view->backspace();
02546     e->accept();
02547 
02548     if (codeComp)
02549       m_view->m_codeCompletion->updateBox ();
02550 
02551     return;
02552   }
02553 
02554   if  (key == Qt::Key_Tab || key == SHIFT+Qt::Key_Backtab || key == Qt::Key_Backtab)
02555   {
02556     if (m_doc->invokeTabInterceptor(key)) {
02557       e->accept();
02558       return;
02559     } else
02560     if (m_doc->configFlags() & KateDocumentConfig::cfTabIndents)
02561     {
02562       if( key == Qt::Key_Tab )
02563       {
02564         if (m_view->hasSelection() || (m_doc->configFlags() & KateDocumentConfig::cfTabIndentsMode))
02565           m_doc->indent( m_view, cursor.line(), 1 );
02566         else if (m_doc->configFlags() & KateDocumentConfig::cfTabInsertsTab)
02567           m_doc->typeChars ( m_view, QString ("\t") );
02568         else
02569           m_doc->insertIndentChars ( m_view );
02570 
02571         e->accept();
02572 
02573         if (codeComp)
02574           m_view->m_codeCompletion->updateBox ();
02575 
02576         return;
02577       }
02578 
02579       if (key == SHIFT+Qt::Key_Backtab || key == Qt::Key_Backtab)
02580       {
02581         m_doc->indent( m_view, cursor.line(), -1 );
02582         e->accept();
02583 
02584         if (codeComp)
02585           m_view->m_codeCompletion->updateBox ();
02586 
02587         return;
02588       }
02589     }
02590 }
02591   if ( !(e->state() & ControlButton) && !(e->state() & AltButton)
02592        && m_doc->typeChars ( m_view, e->text() ) )
02593   {
02594     e->accept();
02595 
02596     if (codeComp)
02597       m_view->m_codeCompletion->updateBox ();
02598 
02599     return;
02600   }
02601 
02602   e->ignore();
02603 }
02604 
02605 void KateViewInternal::keyReleaseEvent( QKeyEvent* e )
02606 {
02607   KKey key(e);
02608 
02609   if (key == SHIFT)
02610     m_shiftKeyPressed = true;
02611   else
02612   {
02613     if (m_shiftKeyPressed)
02614     {
02615       m_shiftKeyPressed = false;
02616 
02617       if (m_selChangedByUser)
02618       {
02619         QApplication::clipboard()->setSelectionMode( true );
02620         m_view->copy();
02621         QApplication::clipboard()->setSelectionMode( false );
02622 
02623         m_selChangedByUser = false;
02624       }
02625     }
02626   }
02627 
02628   e->ignore();
02629   return;
02630 }
02631 
02632 void KateViewInternal::contextMenuEvent ( QContextMenuEvent * e )
02633 {
02634   // try to show popup menu
02635 
02636   QPoint p = e->pos();
02637 
02638   if ( m_view->m_doc->browserView() )
02639   {
02640     m_view->contextMenuEvent( e );
02641     return;
02642   }
02643 
02644   if ( e->reason() == QContextMenuEvent::Keyboard )
02645   {
02646     makeVisible( cursor, 0 );
02647     p = cursorCoordinates();
02648   }
02649   else if ( ! m_view->hasSelection() || m_view->config()->persistentSelection() )
02650     placeCursor( e->pos() );
02651 
02652   // popup is a qguardedptr now
02653   if (m_view->popup()) {
02654     m_view->popup()->popup( mapToGlobal( p ) );
02655     e->accept ();
02656   }
02657 }
02658 
02659 void KateViewInternal::mousePressEvent( QMouseEvent* e )
02660 {
02661   switch (e->button())
02662   {
02663     case LeftButton:
02664         m_selChangedByUser = false;
02665 
02666         if (possibleTripleClick)
02667         {
02668           possibleTripleClick = false;
02669 
02670           m_selectionMode = Line;
02671 
02672           if ( e->state() & Qt::ShiftButton )
02673           {
02674             updateSelection( cursor, true );
02675           }
02676           else
02677           {
02678             m_view->selectLine( cursor );
02679           }
02680 
02681           QApplication::clipboard()->setSelectionMode( true );
02682           m_view->copy();
02683           QApplication::clipboard()->setSelectionMode( false );
02684 
02685           selStartCached = m_view->selectStart;
02686           selEndCached = m_view->selectEnd;
02687 
02688           cursor.setCol(0);
02689           updateCursor( cursor, true );
02690           e->accept ();
02691           return;
02692         }
02693 
02694         if ( e->state() & Qt::ShiftButton )
02695         {
02696           selStartCached = m_view->selectStart;
02697           selEndCached = m_view->selectEnd;
02698         }
02699         else
02700           selStartCached.setLine( -1 ); // invalidate
02701 
02702         if( isTargetSelected( e->pos() ) )
02703         {
02704           dragInfo.state = diPending;
02705           dragInfo.start = e->pos();
02706         }
02707         else
02708         {
02709           dragInfo.state = diNone;
02710 
02711           placeCursor( e->pos(), e->state() & ShiftButton );
02712 
02713           scrollX = 0;
02714           scrollY = 0;
02715 
02716           m_scrollTimer.start (50);
02717         }
02718 
02719         e->accept ();
02720         break;
02721 
02722     default:
02723       e->ignore ();
02724       break;
02725   }
02726 }
02727 
02728 void KateViewInternal::mouseDoubleClickEvent(QMouseEvent *e)
02729 {
02730   switch (e->button())
02731   {
02732     case LeftButton:
02733       m_selectionMode = Word;
02734 
02735       if ( e->state() & Qt::ShiftButton )
02736       {
02737         selStartCached = m_view->selectStart;
02738         selEndCached = m_view->selectEnd;
02739         updateSelection( cursor, true );
02740       }
02741       else
02742       {
02743         // first clear the selection, otherweise we run into bug #106402
02744         // Parameters: 1st false: don't redraw
02745         //             2nd false: don't emit selectionChanged signals, as
02746         //             selectWord() emits this already
02747         m_view->clearSelection( false, false );
02748         m_view->selectWord( cursor );
02749         selectAnchor = KateTextCursor (m_view->selEndLine(), m_view->selEndCol());
02750         selStartCached = m_view->selectStart;
02751         selEndCached = m_view->selectEnd;
02752       }
02753 
02754       // Move cursor to end of selected word
02755       if (m_view->hasSelection())
02756       {
02757         QApplication::clipboard()->setSelectionMode( true );
02758         m_view->copy();
02759         QApplication::clipboard()->setSelectionMode( false );
02760 
02761         cursor.setPos(m_view->selectEnd);
02762         updateCursor( cursor, true );
02763 
02764         selStartCached = m_view->selectStart;
02765         selEndCached = m_view->selectEnd;
02766       }
02767 
02768       possibleTripleClick = true;
02769       QTimer::singleShot ( QApplication::doubleClickInterval(), this, SLOT(tripleClickTimeout()) );
02770 
02771       e->accept ();
02772       break;
02773 
02774     default:
02775       e->ignore ();
02776       break;
02777   }
02778 }
02779 
02780 void KateViewInternal::tripleClickTimeout()
02781 {
02782   possibleTripleClick = false;
02783 }
02784 
02785 void KateViewInternal::mouseReleaseEvent( QMouseEvent* e )
02786 {
02787   switch (e->button())
02788   {
02789     case LeftButton:
02790       m_selectionMode = Default;
02791 //       selStartCached.setLine( -1 );
02792 
02793       if (m_selChangedByUser)
02794       {
02795         QApplication::clipboard()->setSelectionMode( true );
02796         m_view->copy();
02797         QApplication::clipboard()->setSelectionMode( false );
02798 
02799         m_selChangedByUser = false;
02800       }
02801 
02802       if (dragInfo.state == diPending)
02803         placeCursor( e->pos(), e->state() & ShiftButton );
02804       else if (dragInfo.state == diNone)
02805         m_scrollTimer.stop ();
02806 
02807       dragInfo.state = diNone;
02808 
02809       e->accept ();
02810       break;
02811 
02812     case MidButton:
02813       placeCursor( e->pos() );
02814 
02815       if( m_doc->isReadWrite() )
02816       {
02817         QApplication::clipboard()->setSelectionMode( true );
02818         m_view->paste ();
02819         QApplication::clipboard()->setSelectionMode( false );
02820       }
02821 
02822       e->accept ();
02823       break;
02824 
02825     default:
02826       e->ignore ();
02827       break;
02828   }
02829 }
02830 
02831 void KateViewInternal::mouseMoveEvent( QMouseEvent* e )
02832 {
02833   if( e->state() & LeftButton )
02834   {
02835     if (dragInfo.state == diPending)
02836     {
02837       // we had a mouse down, but haven't confirmed a drag yet
02838       // if the mouse has moved sufficiently, we will confirm
02839       QPoint p( e->pos() - dragInfo.start );
02840 
02841       // we've left the drag square, we can start a real drag operation now
02842       if( p.manhattanLength() > KGlobalSettings::dndEventDelay() )
02843         doDrag();
02844 
02845       return;
02846     }
02847 
02848     mouseX = e->x();
02849     mouseY = e->y();
02850 
02851     scrollX = 0;
02852     scrollY = 0;
02853     int d = m_view->renderer()->fontHeight();
02854 
02855     if (mouseX < 0)
02856       scrollX = -d;
02857 
02858     if (mouseX > width())
02859       scrollX = d;
02860 
02861     if (mouseY < 0)
02862     {
02863       mouseY = 0;
02864       scrollY = -d;
02865     }
02866 
02867     if (mouseY > height())
02868     {
02869       mouseY = height();
02870       scrollY = d;
02871     }
02872 
02873     placeCursor( QPoint( mouseX, mouseY ), true );
02874 
02875   }
02876   else
02877   {
02878     if (isTargetSelected( e->pos() ) ) {
02879       // mouse is over selected text. indicate that the text is draggable by setting
02880       // the arrow cursor as other Qt text editing widgets do
02881       if (m_mouseCursor != ArrowCursor) {
02882         setCursor( KCursor::arrowCursor() );
02883         m_mouseCursor = ArrowCursor;
02884       }
02885     } else {
02886       // normal text cursor
02887       if (m_mouseCursor != IbeamCursor) {
02888         setCursor( KCursor::ibeamCursor() );
02889         m_mouseCursor = IbeamCursor;
02890       }
02891     }
02892 
02893     if (m_textHintEnabled)
02894     {
02895        m_textHintTimer.start(m_textHintTimeout);
02896        m_textHintMouseX=e->x();
02897        m_textHintMouseY=e->y();
02898     }
02899   }
02900 }
02901 
02902 void KateViewInternal::paintEvent(QPaintEvent *e)
02903 {
02904   paintText(e->rect().x(), e->rect().y(), e->rect().width(), e->rect().height());
02905 }
02906 
02907 void KateViewInternal::resizeEvent(QResizeEvent* e)
02908 {
02909   bool expandedHorizontally = width() > e->oldSize().width();
02910   bool expandedVertically = height() > e->oldSize().height();
02911   bool heightChanged = height() != e->oldSize().height();
02912 
02913   m_madeVisible = false;
02914 
02915   if (heightChanged) {
02916     setAutoCenterLines(m_autoCenterLines, false);
02917     m_cachedMaxStartPos.setPos(-1, -1);
02918   }
02919 
02920   if (m_view->dynWordWrap()) {
02921     bool dirtied = false;
02922 
02923     for (uint i = 0; i < lineRanges.count(); i++) {
02924       // find the first dirty line
02925       // the word wrap updateView algorithm is forced to check all lines after a dirty one
02926       if (lineRanges[i].wrap ||
02927          (!expandedHorizontally && (lineRanges[i].endX - lineRanges[i].startX) > width())) {
02928         dirtied = lineRanges[i].dirty = true;
02929         break;
02930       }
02931     }
02932 
02933     if (dirtied || heightChanged) {
02934       updateView(true);
02935       leftBorder->update();
02936     }
02937 
02938     if (width() < e->oldSize().width()) {
02939       if (!m_view->wrapCursor()) {
02940         // May have to restrain cursor to new smaller width...
02941         if (cursor.col() > m_doc->lineLength(cursor.line())) {
02942           KateLineRange thisRange = currentRange();
02943 
02944           KateTextCursor newCursor(cursor.line(), thisRange.endCol + ((width() - thisRange.xOffset() - (thisRange.endX - thisRange.startX)) / m_view->renderer()->spaceWidth()) - 1);
02945           updateCursor(newCursor);
02946         }
02947       }
02948     }
02949 
02950   } else {
02951     updateView();
02952 
02953     if (expandedHorizontally && startX() > 0)
02954       scrollColumns(startX() - (width() - e->oldSize().width()));
02955   }
02956 
02957   if (expandedVertically) {
02958     KateTextCursor max = maxStartPos();
02959     if (startPos() > max)
02960       scrollPos(max);
02961   }
02962 }
02963 
02964 void KateViewInternal::scrollTimeout ()
02965 {
02966   if (scrollX || scrollY)
02967   {
02968     scrollLines (startPos().line() + (scrollY / (int)m_view->renderer()->fontHeight()));
02969     placeCursor( QPoint( mouseX, mouseY ), true );
02970   }
02971 }
02972 
02973 void KateViewInternal::cursorTimeout ()
02974 {
02975   m_view->renderer()->setDrawCaret(!m_view->renderer()->drawCaret());
02976   paintCursor();
02977 }
02978 
02979 void KateViewInternal::textHintTimeout ()
02980 {
02981   m_textHintTimer.stop ();
02982 
02983   KateLineRange thisRange = yToKateLineRange(m_textHintMouseY);
02984 
02985   if (thisRange.line == -1) return;
02986 
02987   if (m_textHintMouseX> (lineMaxCursorX(thisRange) - thisRange.startX)) return;
02988 
02989   int realLine = thisRange.line;
02990   int startCol = thisRange.startCol;
02991 
02992   KateTextCursor c(realLine, 0);
02993   m_view->renderer()->textWidth( c, startX() + m_textHintMouseX, startCol);
02994 
02995   QString tmp;
02996 
02997   emit m_view->needTextHint(c.line(), c.col(), tmp);
02998 
02999   if (!tmp.isEmpty()) kdDebug(13030)<<"Hint text: "<<tmp<<endl;
03000 }
03001 
03002 void KateViewInternal::focusInEvent (QFocusEvent *)
03003 {
03004   if (KApplication::cursorFlashTime() > 0)
03005     m_cursorTimer.start ( KApplication::cursorFlashTime() / 2 );
03006 
03007   if (m_textHintEnabled)
03008     m_textHintTimer.start( m_textHintTimeout );
03009 
03010   paintCursor();
03011 
03012   m_doc->setActiveView( m_view );
03013 
03014   emit m_view->gotFocus( m_view );
03015 }
03016 
03017 void KateViewInternal::focusOutEvent (QFocusEvent *)
03018 {
03019   if( ! m_view->m_codeCompletion->codeCompletionVisible() )
03020   {
03021     m_cursorTimer.stop();
03022 
03023     m_view->renderer()->setDrawCaret(true);
03024     paintCursor();
03025     emit m_view->lostFocus( m_view );
03026   }
03027 
03028   m_textHintTimer.stop();
03029 }
03030 
03031 void KateViewInternal::doDrag()
03032 {
03033   dragInfo.state = diDragging;
03034   dragInfo.dragObject = new QTextDrag(m_view->selection(), this);
03035   dragInfo.dragObject->drag();
03036 }
03037 
03038 void KateViewInternal::dragEnterEvent( QDragEnterEvent* event )
03039 {
03040   event->accept( (QTextDrag::canDecode(event) && m_doc->isReadWrite()) ||
03041                   KURLDrag::canDecode(event) );
03042 }
03043 
03044 void KateViewInternal::dragMoveEvent( QDragMoveEvent* event )
03045 {
03046   // track the cursor to the current drop location
03047   placeCursor( event->pos(), true, false );
03048 
03049   // important: accept action to switch between copy and move mode
03050   // without this, the text will always be copied.
03051   event->acceptAction();
03052 }
03053 
03054 void KateViewInternal::dropEvent( QDropEvent* event )
03055 {
03056   if ( KURLDrag::canDecode(event) ) {
03057 
03058       emit dropEventPass(event);
03059 
03060   } else if ( QTextDrag::canDecode(event) && m_doc->isReadWrite() ) {
03061 
03062     QString text;
03063 
03064     if (!QTextDrag::decode(event, text))
03065       return;
03066 
03067     // is the source our own document?
03068     bool priv = false;
03069     if (event->source() && event->source()->inherits("KateViewInternal"))
03070       priv = m_doc->ownedView( ((KateViewInternal*)(event->source()))->m_view );
03071 
03072     // dropped on a text selection area?
03073     bool selected = isTargetSelected( event->pos() );
03074 
03075     if( priv && selected ) {
03076       // this is a drag that we started and dropped on our selection
03077       // ignore this case
03078       return;
03079     }
03080 
03081     // use one transaction
03082     m_doc->editStart ();
03083 
03084     // on move: remove selected text; on copy: duplicate text
03085     if ( event->action() != QDropEvent::Copy )
03086       m_view->removeSelectedText();
03087 
03088     m_doc->insertText( cursor.line(), cursor.col(), text );
03089 
03090     m_doc->editEnd ();
03091 
03092     placeCursor( event->pos() );
03093 
03094     event->acceptAction();
03095     updateView();
03096   }
03097 
03098   // finally finish drag and drop mode
03099   dragInfo.state = diNone;
03100   // important, because the eventFilter`s DragLeave does not occure
03101   stopDragScroll();
03102 }
03103 //END EVENT HANDLING STUFF
03104 
03105 void KateViewInternal::clear()
03106 {
03107   cursor.setPos(0, 0);
03108   displayCursor.setPos(0, 0);
03109 }
03110 
03111 void KateViewInternal::wheelEvent(QWheelEvent* e)
03112 {
03113   if (m_lineScroll->minValue() != m_lineScroll->maxValue() && e->orientation() != Qt::Horizontal) {
03114     // React to this as a vertical event
03115     if ( ( e->state() & ControlButton ) || ( e->state() & ShiftButton ) ) {
03116       if (e->delta() > 0)
03117         scrollPrevPage();
03118       else
03119         scrollNextPage();
03120     } else {
03121       scrollViewLines(-((e->delta() / 120) * QApplication::wheelScrollLines()));
03122       // maybe a menu was opened or a bubbled window title is on us -> we shall erase it
03123       update();
03124       leftBorder->update();
03125     }
03126 
03127   } else if (columnScrollingPossible()) {
03128     QWheelEvent copy = *e;
03129     QApplication::sendEvent(m_columnScroll, &copy);
03130 
03131   } else {
03132     e->ignore();
03133   }
03134 }
03135 
03136 void KateViewInternal::startDragScroll()
03137 {
03138   if ( !m_dragScrollTimer.isActive() ) {
03139     m_dragScrollTimer.start( scrollTime );
03140   }
03141 }
03142 
03143 void KateViewInternal::stopDragScroll()
03144 {
03145   m_dragScrollTimer.stop();
03146   updateView();
03147 }
03148 
03149 void KateViewInternal::doDragScroll()
03150 {
03151   QPoint p = this->mapFromGlobal( QCursor::pos() );
03152 
03153   int dx = 0, dy = 0;
03154   if ( p.y() < scrollMargin ) {
03155     dy = p.y() - scrollMargin;
03156   } else if ( p.y() > height() - scrollMargin ) {
03157     dy = scrollMargin - (height() - p.y());
03158   }
03159 
03160   if ( p.x() < scrollMargin ) {
03161     dx = p.x() - scrollMargin;
03162   } else if ( p.x() > width() - scrollMargin ) {
03163     dx = scrollMargin - (width() - p.x());
03164   }
03165 
03166   dy /= 4;
03167 
03168   if (dy)
03169     scrollLines(startPos().line() + dy);
03170 
03171   if (columnScrollingPossible () && dx)
03172     scrollColumns(kMin (m_startX + dx, m_columnScroll->maxValue()));
03173 
03174   if (!dy && !dx)
03175     stopDragScroll();
03176 }
03177 
03178 void KateViewInternal::enableTextHints(int timeout)
03179 {
03180   m_textHintTimeout=timeout;
03181   m_textHintEnabled=true;
03182   m_textHintTimer.start(timeout);
03183 }
03184 
03185 void KateViewInternal::disableTextHints()
03186 {
03187   m_textHintEnabled=false;
03188   m_textHintTimer.stop ();
03189 }
03190 
03191 bool KateViewInternal::columnScrollingPossible ()
03192 {
03193   return !m_view->dynWordWrap() && m_columnScroll->isEnabled() && (m_columnScroll->maxValue() > 0);
03194 }
03195 
03196 //BEGIN EDIT STUFF
03197 void KateViewInternal::editStart()
03198 {
03199   editSessionNumber++;
03200 
03201   if (editSessionNumber > 1)
03202     return;
03203 
03204   editIsRunning = true;
03205   editOldCursor = cursor;
03206 }
03207 
03208 void KateViewInternal::editEnd(int editTagLineStart, int editTagLineEnd, bool tagFrom)
03209 {
03210    if (editSessionNumber == 0)
03211     return;
03212 
03213   editSessionNumber--;
03214 
03215   if (editSessionNumber > 0)
03216     return;
03217 
03218   if (tagFrom && (editTagLineStart <= int(m_doc->getRealLine(startLine()))))
03219     tagAll();
03220   else
03221     tagLines (editTagLineStart, tagFrom ? m_doc->lastLine() : editTagLineEnd, true);
03222 
03223   if (editOldCursor == cursor)
03224     updateBracketMarks();
03225 
03226   if (m_imPreeditLength <= 0)
03227     updateView(true);
03228 
03229   if ((editOldCursor != cursor) && (m_imPreeditLength <= 0))
03230   {
03231     m_madeVisible = false;
03232     updateCursor ( cursor, true );
03233   }
03234   else if ( m_view->isActive() )
03235   {
03236     makeVisible(displayCursor, displayCursor.col());
03237   }
03238 
03239   editIsRunning = false;
03240 }
03241 
03242 void KateViewInternal::editSetCursor (const KateTextCursor &cursor)
03243 {
03244   if (this->cursor != cursor)
03245   {
03246     this->cursor.setPos (cursor);
03247   }
03248 }
03249 //END
03250 
03251 void KateViewInternal::viewSelectionChanged ()
03252 {
03253   if (!m_view->hasSelection())
03254     selectAnchor.setPos (-1, -1);
03255 }
03256 
03257 //BEGIN IM INPUT STUFF
03258 void KateViewInternal::imStartEvent( QIMEvent *e )
03259 {
03260   if ( m_doc->m_bReadOnly ) {
03261     e->ignore();
03262     return;
03263   }
03264 
03265   if ( m_view->hasSelection() )
03266     m_view->removeSelectedText();
03267 
03268   m_imPreeditStartLine = cursor.line();
03269   m_imPreeditStart = cursor.col();
03270   m_imPreeditLength = 0;
03271   m_imPreeditSelStart = m_imPreeditStart;
03272 
03273   m_view->setIMSelectionValue( m_imPreeditStartLine, m_imPreeditStart, 0, 0, 0, true );
03274 }
03275 
03276 void KateViewInternal::imComposeEvent( QIMEvent *e )
03277 {
03278   if ( m_doc->m_bReadOnly ) {
03279     e->ignore();
03280     return;
03281   }
03282 
03283   // remove old preedit
03284   if ( m_imPreeditLength > 0 ) {
03285     cursor.setPos( m_imPreeditStartLine, m_imPreeditStart );
03286     m_doc->removeText( m_imPreeditStartLine, m_imPreeditStart,
03287                        m_imPreeditStartLine, m_imPreeditStart + m_imPreeditLength );
03288   }
03289 
03290   m_imPreeditLength = e->text().length();
03291   m_imPreeditSelStart = m_imPreeditStart + e->cursorPos();
03292 
03293   // update selection
03294   m_view->setIMSelectionValue( m_imPreeditStartLine, m_imPreeditStart, m_imPreeditStart + m_imPreeditLength,
03295                               m_imPreeditSelStart, m_imPreeditSelStart + e->selectionLength(),
03296                               true );
03297 
03298   // insert new preedit
03299   m_doc->insertText( m_imPreeditStartLine, m_imPreeditStart, e->text() );
03300 
03301 
03302   // update cursor
03303   cursor.setPos( m_imPreeditStartLine, m_imPreeditSelStart );
03304   updateCursor( cursor, true );
03305 
03306   updateView( true );
03307 }
03308 
03309 void KateViewInternal::imEndEvent( QIMEvent *e )
03310 {
03311   if ( m_doc->m_bReadOnly ) {
03312     e->ignore();
03313     return;
03314   }
03315 
03316   if ( m_imPreeditLength > 0 ) {
03317     cursor.setPos( m_imPreeditStartLine, m_imPreeditStart );
03318     m_doc->removeText( m_imPreeditStartLine, m_imPreeditStart,
03319                        m_imPreeditStartLine, m_imPreeditStart + m_imPreeditLength );
03320   }
03321 
03322   m_view->setIMSelectionValue( m_imPreeditStartLine, m_imPreeditStart, 0, 0, 0, false );
03323 
03324   if ( e->text().length() > 0 ) {
03325     m_doc->insertText( cursor.line(), cursor.col(), e->text() );
03326 
03327     if ( !m_cursorTimer.isActive() && KApplication::cursorFlashTime() > 0 )
03328       m_cursorTimer.start ( KApplication::cursorFlashTime() / 2 );
03329 
03330     updateView( true );
03331     updateCursor( cursor, true );
03332   }
03333 
03334   m_imPreeditStart = 0;
03335   m_imPreeditLength = 0;
03336   m_imPreeditSelStart = 0;
03337 }
03338 //END IM INPUT STUFF
03339 
03340 // kate: space-indent on; indent-width 2; replace-tabs on;
KDE Home | KDE Accessibility Home | Description of Access Keys