lib

KoTextParag.cpp

00001 /* This file is part of the KDE project
00002    Copyright (C) 2001-2006 David Faure <faure@kde.org>
00003    Copyright (C) 2005 Martin Ellis <martin.ellis@kdemail.net>
00004 
00005    This library is free software; you can redistribute it and/or
00006    modify it under the terms of the GNU Library General Public
00007    License as published by the Free Software Foundation; either
00008    version 2 of the License, or (at your option) any later version.
00009 
00010    This library is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013    Library General Public License for more details.
00014 
00015    You should have received a copy of the GNU Library General Public License
00016    along with this library; see the file COPYING.LIB.  If not, write to
00017    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00018  * Boston, MA 02110-1301, USA.
00019 */
00020 
00021 #include "KoTextParag.h"
00022 #include "KoTextDocument.h"
00023 #include "KoParagCounter.h"
00024 #include "KoTextZoomHandler.h"
00025 #include "KoStyleCollection.h"
00026 #include "KoVariable.h"
00027 #include <KoOasisContext.h>
00028 #include <KoXmlWriter.h>
00029 #include <KoGenStyles.h>
00030 #include <KoDom.h>
00031 #include <KoXmlNS.h>
00032 #include <kglobal.h>
00033 #include <klocale.h>
00034 #include <kdebug.h>
00035 #include <kglobalsettings.h>
00036 #include <assert.h>
00037 
00038 //#define DEBUG_PAINT
00039 
00040 KoTextParag::KoTextParag( KoTextDocument *d, KoTextParag *pr, KoTextParag *nx, bool updateIds )
00041     : p( pr ), n( nx ), doc( d ),
00042       m_invalid( true ),
00043       changed( FALSE ),
00044       fullWidth( TRUE ),
00045       newLinesAllowed( TRUE ), // default in kotext
00046       visible( TRUE ), //breakable( TRUE ),
00047       movedDown( FALSE ),
00048       m_toc( false ),
00049       align( 0 ),
00050       m_lineChanged( -1 ),
00051       m_wused( 0 ),
00052       mSelections( 0 ),
00053       mFloatingItems( 0 ),
00054       tArray( 0 )
00055 {
00056     defFormat = formatCollection()->defaultFormat();
00057     /*if ( !doc ) {
00058     tabStopWidth = defFormat->width( 'x' ) * 8;
00059     commandHistory = new KoTextDocCommandHistory( 100 );
00060     }*/
00061 
00062     if ( p ) {
00063     p->n = this;
00064     }
00065     if ( n ) {
00066     n->p = this;
00067     }
00068 
00069     if ( !p && doc )
00070     doc->setFirstParag( this );
00071     if ( !n && doc )
00072     doc->setLastParag( this );
00073 
00074     //firstFormat = TRUE; //// unused
00075     //firstPProcess = TRUE;
00076     //state = -1;
00077     //needPreProcess = FALSE;
00078 
00079     if ( p )
00080     id = p->id + 1;
00081     else
00082     id = 0;
00083     if ( n && updateIds ) {
00084     KoTextParag *s = n;
00085     while ( s ) {
00086         s->id = s->p->id + 1;
00087         //s->lm = s->rm = s->tm = s->bm = -1, s->flm = -1;
00088         s = s->n;
00089     }
00090     }
00091 
00092     str = new KoTextString();
00093     str->insert( 0, " ", formatCollection()->defaultFormat() );
00094     setJoinBorder( true );
00095 }
00096 
00097 KoTextParag::~KoTextParag()
00098 {
00099     //kdDebug(32500) << "KoTextParag::~KoTextParag " << this << " id=" << paragId() << endl;
00100 
00101     // #107961: unregister custom items; KoTextString::clear() will delete them
00102     const int len = str->length();
00103     for ( int i = 0; i < len; ++i ) {
00104     KoTextStringChar *c = at( i );
00105     if ( doc && c->isCustom() ) {
00106         doc->unregisterCustomItem( c->customItem(), this );
00107         //removeCustomItem();
00108     }
00109     }
00110 
00111     delete str;
00112     str = 0;
00113 //    if ( doc && p == doc->minwParag ) {
00114 //  doc->minwParag = 0;
00115 //  doc->minw = 0;
00116 //    }
00117     if ( !doc ) {
00118     //delete pFormatter;
00119     //delete commandHistory;
00120     }
00121     delete [] tArray;
00122     //delete eData;
00123     QMap<int, KoTextParagLineStart*>::Iterator it = lineStarts.begin();
00124     for ( ; it != lineStarts.end(); ++it )
00125     delete *it;
00126     if ( mSelections ) delete mSelections;
00127     if ( mFloatingItems ) delete mFloatingItems;
00128 
00129     if (p)
00130        p->setNext(n);
00131     if (n)
00132        n->setPrev(p);
00133 
00135     if ( doc && !doc->isDestroying() )
00136     {
00137         doc->informParagraphDeleted( this );
00138     }
00139     //kdDebug(32500) << "KoTextParag::~KoTextParag " << this << " done" << endl;
00141 }
00142 
00143 void KoTextParag::setNext( KoTextParag *s )
00144 {
00145     n = s;
00146     if ( !n && doc )
00147     doc->setLastParag( this );
00148 }
00149 
00150 void KoTextParag::setPrev( KoTextParag *s )
00151 {
00152     p = s;
00153     if ( !p && doc )
00154     doc->setFirstParag( this );
00155 }
00156 
00157 void KoTextParag::invalidate( int /*chr, ignored*/ )
00158 {
00159     m_invalid = true;
00160 #if 0
00161     if ( invalid < 0 )
00162     invalid = chr;
00163     else
00164     invalid = QMIN( invalid, chr );
00165 #endif
00166 }
00167 
00168 void KoTextParag::setChanged( bool b, bool /*recursive*/ )
00169 {
00170     changed = b;
00171     m_lineChanged = -1; // all
00172 }
00173 
00174 void KoTextParag::setLineChanged( short int line )
00175 {
00176     if ( m_lineChanged == -1 ) {
00177         if ( !changed ) // only if the whole parag wasn't "changed" already
00178             m_lineChanged = line;
00179     }
00180     else
00181         m_lineChanged = QMIN( m_lineChanged, line ); // also works if line=-1
00182     changed = true;
00183     //kdDebug(32500) << "KoTextParag::setLineChanged line=" << line << " -> m_lineChanged=" << m_lineChanged << endl;
00184 }
00185 
00186 void KoTextParag::insert( int index, const QString &s )
00187 {
00188     str->insert( index, s, formatCollection()->defaultFormat() );
00189     invalidate( index );
00190     //needPreProcess = TRUE;
00191 }
00192 
00193 void KoTextParag::truncate( int index )
00194 {
00195     str->truncate( index );
00196     insert( length(), " " );
00197     //needPreProcess = TRUE;
00198 }
00199 
00200 void KoTextParag::remove( int index, int len )
00201 {
00202     if ( index + len - str->length() > 0 )
00203     return;
00204     for ( int i = index; i < index + len; ++i ) {
00205     KoTextStringChar *c = at( i );
00206     if ( doc && c->isCustom() ) {
00207         doc->unregisterCustomItem( c->customItem(), this );
00208         //removeCustomItem();
00209     }
00210     }
00211     str->remove( index, len );
00212     invalidate( 0 );
00213     //needPreProcess = TRUE;
00214 }
00215 
00216 void KoTextParag::join( KoTextParag *s )
00217 {
00218     //kdDebug(32500) << "KoTextParag::join this=" << paragId() << " (length " << length() << ") with " << s->paragId() << " (length " << s->length() << ")" << endl;
00219     int oh = r.height() + s->r.height();
00220     n = s->n;
00221     if ( n )
00222     n->p = this;
00223     else if ( doc )
00224     doc->setLastParag( this );
00225 
00226     int start = str->length();
00227     if ( length() > 0 && at( length() - 1 )->c == ' ' ) {
00228     remove( length() - 1, 1 );
00229     --start;
00230     }
00231     append( s->str->toString(), TRUE );
00232 
00233     for ( int i = 0; i < s->length(); ++i ) {
00234     if ( !doc || doc->useFormatCollection() ) {
00235         s->str->at( i ).format()->addRef();
00236         str->setFormat( i + start, s->str->at( i ).format(), TRUE );
00237     }
00238     if ( s->str->at( i ).isCustom() ) {
00239         KoTextCustomItem * item = s->str->at( i ).customItem();
00240         str->at( i + start ).setCustomItem( item );
00241         s->str->at( i ).loseCustomItem();
00242         doc->unregisterCustomItem( item, s ); // ### missing in QRT
00243         doc->registerCustomItem( item, this );
00244     }
00245     }
00246     Q_ASSERT(str->at(str->length()-1).c == ' ');
00247 
00248     /*if ( !extraData() && s->extraData() ) {
00249     setExtraData( s->extraData() );
00250     s->setExtraData( 0 );
00251     } else if ( extraData() && s->extraData() ) {
00252     extraData()->join( s->extraData() );
00253         }*/
00254     delete s;
00255     invalidate( 0 );
00257     invalidateCounters();
00259     r.setHeight( oh );
00260     //needPreProcess = TRUE;
00261     if ( n ) {
00262     KoTextParag *s = n;
00263     while ( s ) {
00264         s->id = s->p->id + 1;
00265         //s->state = -1;
00266         //s->needPreProcess = TRUE;
00267         s->changed = TRUE;
00268         s = s->n;
00269     }
00270     }
00271     format();
00272     //state = -1;
00273 }
00274 
00275 void KoTextParag::move( int &dy )
00276 {
00277     //kdDebug(32500) << "KoTextParag::move paragId=" << paragId() << " dy=" << dy << endl;
00278     if ( dy == 0 )
00279     return;
00280     changed = TRUE;
00281     r.moveBy( 0, dy );
00282     if ( mFloatingItems ) {
00283     for ( KoTextCustomItem *i = mFloatingItems->first(); i; i = mFloatingItems->next() ) {
00284         i->finalize();
00285     }
00286     }
00287     //if ( p )
00288     //    p->lastInFrame = TRUE; // Qt does this, but the loop at the end of format() calls move a lot!
00289 
00290     movedDown = FALSE;
00291 
00292     // do page breaks if required
00293     if ( doc && doc->isPageBreakEnabled() ) {
00294     int shift;
00295     if ( ( shift = doc->formatter()->formatVertically(  doc, this ) ) ) {
00296         if ( p )
00297         p->setChanged( TRUE );
00298         dy += shift;
00299     }
00300     }
00301 }
00302 
00303 void KoTextParag::format( int start, bool doMove )
00304 {
00305     if ( !str || str->length() == 0 || !formatter() )
00306     return;
00307 
00308     if ( isValid() )
00309     return;
00310 
00311     //kdDebug(32500) << "KoTextParag::format " << this << " id:" << paragId() << endl;
00312 
00313     r.moveTopLeft( QPoint( documentX(), p ? p->r.y() + p->r.height() : documentY() ) );
00314     //if ( p )
00315     //    p->lastInFrame = FALSE;
00316 
00317     movedDown = FALSE;
00318     bool formattedAgain = FALSE;
00319 
00320  formatAgain:
00321     r.setWidth( documentWidth() );
00322 
00323     // Not really useful....
00324     if ( doc && mFloatingItems ) {
00325     for ( KoTextCustomItem *i = mFloatingItems->first(); i; i = mFloatingItems->next() ) {
00326         if ( i->placement() == KoTextCustomItem::PlaceRight )
00327         i->move( r.x() + r.width() - i->width, r.y() );
00328         else
00329         i->move( i->x(), r.y() );
00330     }
00331     }
00332     QMap<int, KoTextParagLineStart*> oldLineStarts = lineStarts;
00333     lineStarts.clear();
00334     int y;
00335     bool formatterWorked = formatter()->format( doc, this, start, oldLineStarts, y, m_wused );
00336 
00337     // It can't happen that width < minimumWidth -- hopefully.
00338     //r.setWidth( QMAX( r.width(), formatter()->minimumWidth() ) );
00339     //m_minw = formatter()->minimumWidth();
00340 
00341     QMap<int, KoTextParagLineStart*>::Iterator it = oldLineStarts.begin();
00342 
00343     for ( ; it != oldLineStarts.end(); ++it )
00344     delete *it;
00345 
00346 /*    if ( hasBorder() || str->isRightToLeft() )
00349     {
00350         setWidth( textDocument()->width() - 1 );
00351     }
00352     else*/
00353     {
00354         if ( lineStarts.count() == 1 ) { //&& ( !doc || doc->flow()->isEmpty() ) ) {
00355 // kotext: for proper parag borders, we want all parags to be as wide as linestart->w
00356 /*            if ( !str->isBidi() ) {
00357                 KoTextStringChar *c = &str->at( str->length() - 1 );
00358                 r.setWidth( c->x + c->width );
00359             } else*/ {
00360                 r.setWidth( lineStarts[0]->w );
00361             }
00362         }
00363         if ( newLinesAllowed ) {
00364             it = lineStarts.begin();
00365             int usedw = 0; int lineid = 0;
00366             for ( ; it != lineStarts.end(); ++it, ++lineid ) {
00367                 usedw = QMAX( usedw, (*it)->w );
00368             }
00369             if ( r.width() <= 0 ) {
00370                 // if the user specifies an invalid rect, this means that the
00371                 // bounding box should grow to the width that the text actually
00372                 // needs
00373                 r.setWidth( usedw );
00374             } else {
00375                 r.setWidth( QMIN( usedw, r.width() ) );
00376             }
00377         }
00378     }
00379 
00380     if ( y != r.height() )
00381     r.setHeight( y );
00382 
00383     if ( !visible )
00384     r.setHeight( 0 );
00385 
00386     // do page breaks if required
00387     if ( doc && doc->isPageBreakEnabled() ) {
00388         int shift = doc->formatter()->formatVertically( doc, this );
00389         //kdDebug(32500) << "formatVertically returned shift=" << shift << endl;
00390         if ( shift && !formattedAgain ) {
00391             formattedAgain = TRUE;
00392             goto formatAgain;
00393         }
00394     }
00395 
00396     if ( doc )
00397         doc->formatter()->postFormat( this );
00398 
00399     if ( n && doMove && n->isValid() && r.y() + r.height() != n->r.y() ) {
00400         //kdDebug(32500) << "r=" << r << " n->r=" << n->r << endl;
00401     int dy = ( r.y() + r.height() ) - n->r.y();
00402     KoTextParag *s = n;
00403     bool makeInvalid = false; //p && p->lastInFrame;
00404     //kdDebug(32500) << "might move of dy=" << dy << ". previous's lastInFrame (=makeInvalid): " << makeInvalid << endl;
00405     while ( s && dy ) {
00406             if ( s->movedDown ) { // (not in QRT) : moved down -> invalidate and stop moving down
00407                 s->invalidate( 0 ); // (there is no point in moving down a parag that has a frame break...)
00408                 break;
00409             }
00410         if ( !s->isFullWidth() )
00411         makeInvalid = TRUE;
00412         if ( makeInvalid )
00413         s->invalidate( 0 );
00414         s->move( dy );
00415         //if ( s->lastInFrame )
00416             //    makeInvalid = TRUE;
00417         s = s->n;
00418     }
00419     }
00420 
00421 //#define DEBUG_CI_PLACEMENT
00422     if ( mFloatingItems ) {
00423 #ifdef DEBUG_CI_PLACEMENT
00424         kdDebug(32500) << lineStarts.count() << " lines" << endl;
00425 #endif
00426         // Place custom items - after the formatting is finished
00427         int len = length();
00428         int line = -1;
00429         int lineY = 0; // the one called "cy" in other algos
00430         int baseLine = 0;
00431         QMap<int, KoTextParagLineStart*>::Iterator it = lineStarts.begin();
00432         for ( int i = 0 ; i < len; ++i ) {
00433             KoTextStringChar *chr = &str->at( i );
00434             if ( chr->lineStart ) {
00435                 ++line;
00436                 if ( line > 0 )
00437                     ++it;
00438                 lineY = (*it)->y;
00439                 baseLine = (*it)->baseLine;
00440 #ifdef DEBUG_CI_PLACEMENT
00441                 kdDebug(32500) << "New line (" << line << "): lineStart=" << (*it) << " lineY=" << lineY << " baseLine=" << baseLine << " height=" << (*it)->h << endl;
00442 #endif
00443             }
00444             if ( chr->isCustom() ) {
00445                 int x = chr->x;
00446                 KoTextCustomItem* item = chr->customItem();
00447                 Q_ASSERT( baseLine >= item->ascent() ); // something went wrong in KoTextFormatter if this isn't the case
00448                 int y = lineY + baseLine - item->ascent();
00449 #ifdef DEBUG_CI_PLACEMENT
00450                 kdDebug(32500) << "Custom item: i=" << i << " x=" << x << " lineY=" << lineY << " baseLine=" << baseLine << " ascent=" << item->ascent() << " -> y=" << y << endl;
00451 #endif
00452                 item->move( x, y );
00453                 item->finalize();
00454             }
00455         }
00456     }
00457 
00458     //firstFormat = FALSE; //// unused
00459     if ( formatterWorked > 0 ) // only if it worked, i.e. we had some width to format it
00460     {
00461         m_invalid = false;
00462     }
00463     changed = TRUE;
00464     //####   str->setTextChanged( FALSE );
00465 }
00466 
00467 int KoTextParag::lineHeightOfChar( int i, int *bl, int *y ) const
00468 {
00469     if ( !isValid() )
00470     ( (KoTextParag*)this )->format();
00471 
00472     QMap<int, KoTextParagLineStart*>::ConstIterator it = lineStarts.end();
00473     --it;
00474     for ( ;; ) {
00475     if ( i >= it.key() ) {
00476         if ( bl )
00477         *bl = ( *it )->baseLine;
00478         if ( y )
00479         *y = ( *it )->y;
00480         return ( *it )->h;
00481     }
00482     if ( it == lineStarts.begin() )
00483         break;
00484     --it;
00485     }
00486 
00487     kdWarning(32500) << "KoTextParag::lineHeightOfChar: couldn't find lh for " << i << endl;
00488     return 15;
00489 }
00490 
00491 KoTextStringChar *KoTextParag::lineStartOfChar( int i, int *index, int *line ) const
00492 {
00493     if ( !isValid() )
00494     ( (KoTextParag*)this )->format();
00495 
00496     int l = (int)lineStarts.count() - 1;
00497     QMap<int, KoTextParagLineStart*>::ConstIterator it = lineStarts.end();
00498     --it;
00499     for ( ;; ) {
00500     if ( i >= it.key() ) {
00501         if ( index )
00502         *index = it.key();
00503         if ( line )
00504         *line = l;
00505         return &str->at( it.key() );
00506     }
00507     if ( it == lineStarts.begin() )
00508         break;
00509     --it;
00510     --l;
00511     }
00512 
00513     kdWarning(32500) << "KoTextParag::lineStartOfChar: couldn't find " << i << endl;
00514     return 0;
00515 }
00516 
00517 int KoTextParag::lines() const
00518 {
00519     if ( !isValid() )
00520     ( (KoTextParag*)this )->format();
00521 
00522     return (int)lineStarts.count();
00523 }
00524 
00525 KoTextStringChar *KoTextParag::lineStartOfLine( int line, int *index ) const
00526 {
00527     if ( !isValid() )
00528     ( (KoTextParag*)this )->format();
00529 
00530     if ( line >= 0 && line < (int)lineStarts.count() ) {
00531     QMap<int, KoTextParagLineStart*>::ConstIterator it = lineStarts.begin();
00532     while ( line-- > 0 )
00533         ++it;
00534     int i = it.key();
00535     if ( index )
00536         *index = i;
00537     return &str->at( i );
00538     }
00539 
00540     kdWarning(32500) << "KoTextParag::lineStartOfLine: couldn't find " << line << endl;
00541     return 0;
00542 }
00543 
00544 int KoTextParag::leftGap() const
00545 {
00546     if ( !isValid() )
00547     ( (KoTextParag*)this )->format();
00548 
00549     int line = 0;
00550     int x = str->at(0).x;  /* set x to x of first char */
00551     if ( str->isBidi() ) {
00552     for ( int i = 1; i < str->length(); ++i )
00553         x = QMIN(x, str->at(i).x);
00554     return x;
00555     }
00556 
00557     QMap<int, KoTextParagLineStart*>::ConstIterator it = lineStarts.begin();
00558     while (line < (int)lineStarts.count()) {
00559     int i = it.key(); /* char index */
00560     x = QMIN(x, str->at(i).x);
00561     ++it;
00562     ++line;
00563     }
00564     return x;
00565 }
00566 
00567 void KoTextParag::setFormat( int index, int len, const KoTextFormat *_f, bool useCollection, int flags )
00568 {
00569     Q_ASSERT( useCollection ); // just for info
00570     if ( index < 0 )
00571     index = 0;
00572     if ( index > str->length() - 1 )
00573     index = str->length() - 1;
00574     if ( index + len >= str->length() )
00575     len = str->length() - index;
00576 
00577     KoTextFormatCollection *fc = 0;
00578     if ( useCollection )
00579     fc = formatCollection();
00580     KoTextFormat *of;
00581     for ( int i = 0; i < len; ++i ) {
00582     of = str->at( i + index ).format();
00583     if ( !changed && _f->key() != of->key() )
00584         changed = TRUE;
00585         // Check things that need the textformatter to run
00586         // (e.g. not color changes)
00587         // ######## Is this test exhaustive?
00588     if ( m_invalid == false &&
00589          ( _f->font().family() != of->font().family() ||
00590            _f->pointSize() != of->pointSize() ||
00591            _f->font().weight() != of->font().weight() ||
00592            _f->font().italic() != of->font().italic() ||
00593            _f->vAlign() != of->vAlign() ||
00594                _f->relativeTextSize() != of->relativeTextSize() ||
00595                _f->offsetFromBaseLine() != of->offsetFromBaseLine() ||
00596                _f->wordByWord() != of->wordByWord()  ||
00597                _f->attributeFont() != of->attributeFont() ||
00598                _f->language() != of->language() ||
00599                _f->hyphenation() != of->hyphenation() ||
00600                _f->shadowDistanceX() != of->shadowDistanceX() ||
00601                _f->shadowDistanceY() != of->shadowDistanceY()
00602                  ) ) {
00603         invalidate( 0 );
00604     }
00605     if ( flags == -1 || flags == KoTextFormat::Format || !fc ) {
00606 #ifdef DEBUG_COLLECTION
00607         kdDebug(32500) << " KoTextParag::setFormat, will use format(f) " << f << " " << _f->key() << endl;
00608 #endif
00609             KoTextFormat* f = fc ? fc->format( _f ) : const_cast<KoTextFormat *>( _f );
00610         str->setFormat( i + index, f, useCollection, true );
00611     } else {
00612 #ifdef DEBUG_COLLECTION
00613         kdDebug(32500) << " KoTextParag::setFormat, will use format(of,f,flags) of=" << of << " " << of->key() << ", f=" << _f << " " << _f->key() << endl;
00614 #endif
00615         KoTextFormat *fm = fc->format( of, _f, flags );
00616 #ifdef DEBUG_COLLECTION
00617         kdDebug(32500) << " KoTextParag::setFormat, format(of,f,flags) returned " << fm << " " << fm->key() << " " << endl;
00618 #endif
00619         str->setFormat( i + index, fm, useCollection );
00620     }
00621     }
00622 }
00623 
00624 void KoTextParag::drawCursorDefault( QPainter &painter, KoTextCursor *cursor, int curx, int cury, int curh, const QColorGroup &cg )
00625 {
00626     painter.fillRect( QRect( curx, cury, 1, curh ), cg.color( QColorGroup::Text ) );
00627     painter.save();
00628     if ( str->isBidi() ) {
00629         const int d = 4;
00630         if ( at( cursor->index() )->rightToLeft ) {
00631             painter.setPen( Qt::black );
00632             painter.drawLine( curx, cury, curx - d / 2, cury + d / 2 );
00633             painter.drawLine( curx, cury + d, curx - d / 2, cury + d / 2 );
00634         } else {
00635             painter.setPen( Qt::black );
00636             painter.drawLine( curx, cury, curx + d / 2, cury + d / 2 );
00637             painter.drawLine( curx, cury + d, curx + d / 2, cury + d / 2 );
00638         }
00639     }
00640     painter.restore();
00641 }
00642 
00643 int *KoTextParag::tabArray() const
00644 {
00645     int *ta = tArray;
00646     if ( !ta && doc )
00647     ta = doc->tabArray();
00648     return ta;
00649 }
00650 
00651 int KoTextParag::nextTabDefault( int, int x )
00652 {
00653     int *ta = tArray;
00654     //if ( doc ) {
00655     if ( !ta )
00656         ta = doc->tabArray();
00657     int tabStopWidth = doc->tabStopWidth();
00658     //}
00659     if ( tabStopWidth != 0 )
00660     return tabStopWidth*(x/tabStopWidth+1);
00661     else
00662         return x;
00663 }
00664 
00665 KoTextFormatCollection *KoTextParag::formatCollection() const
00666 {
00667     if ( doc )
00668     return doc->formatCollection();
00669     //if ( !qFormatCollection )
00670     //    qFormatCollection = new KoTextFormatCollection;
00671     //return qFormatCollection;
00672     return 0L;
00673 }
00674 
00675 void KoTextParag::show()
00676 {
00677     if ( visible || !doc )
00678     return;
00679     visible = TRUE;
00680 }
00681 
00682 void KoTextParag::hide()
00683 {
00684     if ( !visible || !doc )
00685     return;
00686     visible = FALSE;
00687 }
00688 
00689 void KoTextParag::setDirection( QChar::Direction d )
00690 {
00691     if ( str && str->direction() != d ) {
00692     str->setDirection( d );
00693     invalidate( 0 );
00695         m_layout.direction = d;
00696     invalidateCounters(); // #47178
00698     }
00699 }
00700 
00701 QChar::Direction KoTextParag::direction() const
00702 {
00703     return (str ? str->direction() : QChar::DirON );
00704 }
00705 
00706 void KoTextParag::setSelection( int id, int start, int end )
00707 {
00708     QMap<int, KoTextParagSelection>::ConstIterator it = selections().find( id );
00709     if ( it != mSelections->end() ) {
00710     if ( start == ( *it ).start && end == ( *it ).end )
00711         return;
00712     }
00713 
00714     KoTextParagSelection sel;
00715     sel.start = start;
00716     sel.end = end;
00717     (*mSelections)[ id ] = sel;
00718     setChanged( TRUE, TRUE );
00719 }
00720 
00721 void KoTextParag::removeSelection( int id )
00722 {
00723     if ( !hasSelection( id ) )
00724     return;
00725     if ( mSelections )
00726     mSelections->remove( id );
00727     setChanged( TRUE, TRUE );
00728 }
00729 
00730 int KoTextParag::selectionStart( int id ) const
00731 {
00732     if ( !mSelections )
00733     return -1;
00734     QMap<int, KoTextParagSelection>::ConstIterator it = mSelections->find( id );
00735     if ( it == mSelections->end() )
00736     return -1;
00737     return ( *it ).start;
00738 }
00739 
00740 int KoTextParag::selectionEnd( int id ) const
00741 {
00742     if ( !mSelections )
00743     return -1;
00744     QMap<int, KoTextParagSelection>::ConstIterator it = mSelections->find( id );
00745     if ( it == mSelections->end() )
00746     return -1;
00747     return ( *it ).end;
00748 }
00749 
00750 bool KoTextParag::hasSelection( int id ) const
00751 {
00752     if ( !mSelections )
00753     return FALSE;
00754     QMap<int, KoTextParagSelection>::ConstIterator it = mSelections->find( id );
00755     if ( it == mSelections->end() )
00756     return FALSE;
00757     return ( *it ).start != ( *it ).end || length() == 1;
00758 }
00759 
00760 bool KoTextParag::fullSelected( int id ) const
00761 {
00762     if ( !mSelections )
00763     return FALSE;
00764     QMap<int, KoTextParagSelection>::ConstIterator it = mSelections->find( id );
00765     if ( it == mSelections->end() )
00766     return FALSE;
00767     return ( *it ).start == 0 && ( *it ).end == str->length() - 1;
00768 }
00769 
00770 int KoTextParag::lineY( int l ) const
00771 {
00772     if ( l > (int)lineStarts.count() - 1 ) {
00773     kdWarning(32500) << "KoTextParag::lineY: line " << l << " out of range!" << endl;
00774     return 0;
00775     }
00776 
00777     if ( !isValid() )
00778     ( (KoTextParag*)this )->format();
00779 
00780     QMap<int, KoTextParagLineStart*>::ConstIterator it = lineStarts.begin();
00781     while ( l-- > 0 )
00782     ++it;
00783     return ( *it )->y;
00784 }
00785 
00786 int KoTextParag::lineBaseLine( int l ) const
00787 {
00788     if ( l > (int)lineStarts.count() - 1 ) {
00789     kdWarning(32500) << "KoTextParag::lineBaseLine: line " << l << " out of range!" << endl;
00790     return 10;
00791     }
00792 
00793     if ( !isValid() )
00794     ( (KoTextParag*)this )->format();
00795 
00796     QMap<int, KoTextParagLineStart*>::ConstIterator it = lineStarts.begin();
00797     while ( l-- > 0 )
00798     ++it;
00799     return ( *it )->baseLine;
00800 }
00801 
00802 int KoTextParag::lineHeight( int l ) const
00803 {
00804     if ( l > (int)lineStarts.count() - 1 ) {
00805     kdWarning(32500) << "KoTextParag::lineHeight: line " << l << " out of range!" << endl;
00806     return 15;
00807     }
00808 
00809     if ( !isValid() )
00810     ( (KoTextParag*)this )->format();
00811 
00812     QMap<int, KoTextParagLineStart*>::ConstIterator it = lineStarts.begin();
00813     while ( l-- > 0 )
00814     ++it;
00815     return ( *it )->h;
00816 }
00817 
00818 void KoTextParag::lineInfo( int l, int &y, int &h, int &bl ) const
00819 {
00820     if ( l > (int)lineStarts.count() - 1 ) {
00821     kdWarning(32500) << "KoTextParag::lineInfo: line " << l << " out of range!" << endl;
00822     kdDebug(32500) << (int)lineStarts.count() - 1 << " " << l << endl;
00823     y = 0;
00824     h = 15;
00825     bl = 10;
00826     return;
00827     }
00828 
00829     if ( !isValid() )
00830     ( (KoTextParag*)this )->format();
00831 
00832     QMap<int, KoTextParagLineStart*>::ConstIterator it = lineStarts.begin();
00833     while ( l-- > 0 )
00834     ++it;
00835     y = ( *it )->y;
00836     h = ( *it )->h;
00837     bl = ( *it )->baseLine;
00838 }
00839 
00840 uint KoTextParag::alignment() const
00841 {
00842     return align;
00843 }
00844 
00845 void KoTextParag::setFormat( KoTextFormat *fm )
00846 {
00847 #if 0
00848     bool doUpdate = FALSE;
00849     if (defFormat && (defFormat != formatCollection()->defaultFormat()))
00850        doUpdate = TRUE;
00851 #endif
00852     defFormat = formatCollection()->format( fm );
00853 #if 0
00854     if ( !doUpdate )
00855     return;
00856     for ( int i = 0; i < length(); ++i ) {
00857     if ( at( i )->format()->styleName() == defFormat->styleName() )
00858         at( i )->format()->updateStyle();
00859     }
00860 #endif
00861 }
00862 
00863 KoTextFormatterBase *KoTextParag::formatter() const
00864 {
00865     if ( doc )
00866     return doc->formatter();
00867     return 0;
00868 }
00869 
00870 /*int KoTextParag::minimumWidth() const
00871 {
00872     //return doc ? doc->minimumWidth() : 0;
00873     return m_minw;
00874 }*/
00875 
00876 int KoTextParag::widthUsed() const
00877 {
00878     return m_wused;
00879 }
00880 
00881 void KoTextParag::setTabArray( int *a )
00882 {
00883     delete [] tArray;
00884     tArray = a;
00885 }
00886 
00887 void KoTextParag::setTabStops( int tw )
00888 {
00889     if ( doc )
00890     doc->setTabStops( tw );
00891     //else
00892     //    tabStopWidth = tw;
00893 }
00894 
00895 QMap<int, KoTextParagSelection> &KoTextParag::selections() const
00896 {
00897     if ( !mSelections )
00898     ((KoTextParag *)this)->mSelections = new QMap<int, KoTextParagSelection>;
00899     return *mSelections;
00900 }
00901 
00902 QPtrList<KoTextCustomItem> &KoTextParag::floatingItems() const
00903 {
00904     if ( !mFloatingItems )
00905     ((KoTextParag *)this)->mFloatingItems = new QPtrList<KoTextCustomItem>;
00906     return *mFloatingItems;
00907 }
00908 
00909 void KoTextCursor::setIndex( int i, bool /*restore*/ )
00910 {
00911 // Note: QRT doesn't allow to position the cursor at string->length
00912 // However we need it, when applying a style to a paragraph, so that
00913 // the trailing space gets the style change applied as well.
00914 // Obviously "right of the trailing space" isn't a good place for a real
00915 // cursor, but this needs to be checked somewhere else.
00916     if ( i < 0 || i > string->length() ) {
00917 #if defined(QT_CHECK_RANGE)
00918     kdWarning(32500) << "KoTextCursor::setIndex: " << i << " out of range" << endl;
00919         //abort();
00920 #endif
00921     i = i < 0 ? 0 : string->length() - 1;
00922     }
00923 
00924     tmpIndex = -1;
00925     idx = i;
00926 }
00927 
00929 
00930 // Return the counter associated with this paragraph.
00931 KoParagCounter *KoTextParag::counter()
00932 {
00933     if ( !m_layout.counter )
00934         return 0L;
00935 
00936     // Garbage collect un-needed counters.
00937     if ( m_layout.counter->numbering() == KoParagCounter::NUM_NONE
00938         // [keep it for unnumbered outlines (the depth is useful)]
00939          && ( !m_layout.style || !m_layout.style->isOutline() ) )
00940         setNoCounter();
00941     return m_layout.counter;
00942 }
00943 
00944 void KoTextParag::setMargin( QStyleSheetItem::Margin m, double _i )
00945 {
00946     //kdDebug(32500) << "KoTextParag::setMargin " << m << " margin " << _i << endl;
00947     m_layout.margins[m] = _i;
00948     if ( m == QStyleSheetItem::MarginTop && prev() )
00949         prev()->invalidate(0);     // for top margin (post-1.1: remove this, not necessary anymore)
00950     invalidate(0);
00951 }
00952 
00953 void KoTextParag::setMargins( const double * margins )
00954 {
00955     for ( int i = 0 ; i < 5 ; ++i )
00956         m_layout.margins[i] = margins[i];
00957     invalidate(0);
00958 }
00959 
00960 void KoTextParag::setAlign( int align )
00961 {
00962     Q_ASSERT( align <= Qt::AlignJustify );
00963     align &= Qt::AlignHorizontal_Mask;
00964     setAlignment( align );
00965     m_layout.alignment = align;
00966 }
00967 
00968 int KoTextParag::resolveAlignment() const
00969 {
00970     if ( (int)m_layout.alignment == Qt::AlignAuto )
00971         return str->isRightToLeft() ? Qt::AlignRight : Qt::AlignLeft;
00972     return m_layout.alignment;
00973 }
00974 
00975 void KoTextParag::setLineSpacing( double _i )
00976 {
00977     m_layout.setLineSpacingValue(_i);
00978     invalidate(0);
00979 }
00980 
00981 void KoTextParag::setLineSpacingType( KoParagLayout::SpacingType _type )
00982 {
00983     m_layout.lineSpacingType = _type;
00984     invalidate(0);
00985 }
00986 
00987 void KoTextParag::setTopBorder( const KoBorder & _brd )
00988 {
00989     m_layout.topBorder = _brd;
00990     invalidate(0);
00991 }
00992 
00993 void KoTextParag::setBottomBorder( const KoBorder & _brd )
00994 {
00995     m_layout.bottomBorder = _brd;
00996     invalidate(0);
00997 }
00998 
00999 void KoTextParag::setJoinBorder( bool join )
01000 {
01001     m_layout.joinBorder = join;
01002     invalidate(0);
01003 }
01004 
01005 void KoTextParag::setBackgroundColor ( const QColor& color )
01006 {
01007     m_layout.backgroundColor = color;
01008     invalidate(0);
01009 }
01010 
01011 void KoTextParag::setNoCounter()
01012 {
01013     delete m_layout.counter;
01014     m_layout.counter = 0L;
01015     invalidateCounters();
01016 }
01017 
01018 void KoTextParag::setCounter( const KoParagCounter & counter )
01019 {
01020     // Garbage collect unnneeded counters.
01021     if ( counter.numbering() == KoParagCounter::NUM_NONE
01022          // [keep it for unnumbered outlines (the depth is useful)]
01023          && ( !m_layout.style || !m_layout.style->isOutline() ) )
01024     {
01025         setNoCounter();
01026     }
01027     else
01028     {
01029         delete m_layout.counter;
01030         m_layout.counter = new KoParagCounter( counter );
01031 
01032         // Invalidate the counters
01033         invalidateCounters();
01034     }
01035 }
01036 
01037 void KoTextParag::invalidateCounters()
01038 {
01039     // Invalidate this paragraph and all the following ones
01040     // (Numbering may have changed)
01041     invalidate( 0 );
01042     if ( m_layout.counter )
01043         m_layout.counter->invalidate();
01044     KoTextParag *s = next();
01045     // #### Possible optimization: since any invalidation propagates down,
01046     // it's enough to stop at the first paragraph with an already-invalidated counter, isn't it?
01047     // This is only true if nobody else calls counter->invalidate...
01048     while ( s ) {
01049         if ( s->m_layout.counter )
01050             s->m_layout.counter->invalidate();
01051         s->invalidate( 0 );
01052         s = s->next();
01053     }
01054 }
01055 
01056 int KoTextParag::counterWidth() const
01057 {
01058     if ( !m_layout.counter )
01059         return 0;
01060 
01061     return m_layout.counter->width( this );
01062 }
01063 
01064 // Draw the complete label (i.e. heading/list numbers/bullets) for this paragraph.
01065 // This is called by KoTextParag::paint.
01066 void KoTextParag::drawLabel( QPainter* p, int xLU, int yLU, int /*wLU*/, int /*hLU*/, int baseLU, const QColorGroup& /*cg*/ )
01067 {
01068     if ( !m_layout.counter ) // shouldn't happen
01069         return;
01070 
01071     if ( m_layout.counter->numbering() == KoParagCounter::NUM_NONE )
01072         return;
01073 
01074     int counterWidthLU = m_layout.counter->width( this );
01075 
01076     // We use the formatting of the first char as the formatting of the counter
01077     KoTextFormat counterFormat( *KoParagCounter::counterFormat( this ) );
01078     if ( !m_layout.style || !m_layout.style->isOutline() )
01079     {
01080       // But without bold/italic for normal lists, since some items could be bold and others not.
01081       // For headings we must keep the bold when the heading is bold.
01082       counterFormat.setBold( false );
01083       counterFormat.setItalic( false );
01084     }
01085     KoTextFormat* format = &counterFormat;
01086     p->save();
01087 
01088     QColor textColor( format->color() );
01089     if ( !textColor.isValid() ) // Resolve the color at this point
01090         textColor = KoTextFormat::defaultTextColor( p );
01091     p->setPen( QPen( textColor ) );
01092 
01093     KoTextZoomHandler * zh = textDocument()->paintingZoomHandler();
01094     assert( zh );
01095     //bool forPrint = ( p->device()->devType() == QInternal::Printer );
01096 
01097     bool rtl = str->isRightToLeft(); // when true, we put suffix+counter+prefix at the RIGHT of the paragraph.
01098     int xLeft = zh->layoutUnitToPixelX( xLU - (rtl ? 0 : counterWidthLU) );
01099     int y = zh->layoutUnitToPixelY( yLU );
01100     //int h = zh->layoutUnitToPixelY( yLU, hLU );
01101     int base = zh->layoutUnitToPixelY( yLU, baseLU );
01102     int counterWidth = zh->layoutUnitToPixelX( xLU, counterWidthLU );
01103     int height = zh->layoutUnitToPixelY( yLU, format->height() );
01104 
01105     QFont font( format->screenFont( zh ) );
01106     // Footnote numbers are in superscript (in WP and Word, not in OO)
01107     if ( m_layout.counter->numbering() == KoParagCounter::NUM_FOOTNOTE )
01108     {
01109         int pointSize = ( ( font.pointSize() * 2 ) / 3 );
01110         font.setPointSize( pointSize );
01111         y -= ( height - QFontMetrics(font).height() );
01112     }
01113     p->setFont( font );
01114 
01115     // Now draw any bullet that is required over the space left for it.
01116     if ( m_layout.counter->isBullet() )
01117     {
01118     int xBullet = xLeft + zh->layoutUnitToPixelX( m_layout.counter->bulletX() );
01119 
01120         //kdDebug(32500) << "KoTextParag::drawLabel xLU=" << xLU << " counterWidthLU=" << counterWidthLU << endl;
01121     // The width and height of the bullet is the width of one space
01122         int width = zh->layoutUnitToPixelX( xLeft, format->width( ' ' ) );
01123 
01124         //kdDebug(32500) << "Pix: xLeft=" << xLeft << " counterWidth=" << counterWidth
01125         //          << " xBullet=" << xBullet << " width=" << width << endl;
01126 
01127         QString prefix = m_layout.counter->prefix();
01128         if ( !prefix.isEmpty() )
01129         {
01130             if ( rtl )
01131                 prefix.prepend( ' ' /*the space before the bullet in RTL mode*/ );
01132             KoTextParag::drawFontEffects( p, format, zh, format->screenFont( zh ), textColor, xLeft, base, width, y, height, prefix[0] );
01133 
01134             int posY =y + base - format->offsetFromBaseLine();
01135             //we must move to bottom text because we create
01136             //shadow to 'top'.
01137             int sy = format->shadowY( zh );
01138             if ( sy < 0)
01139                 posY -= sy;
01140 
01141             p->drawText( xLeft, posY, prefix );
01142         }
01143 
01144         QRect er( xBullet + (rtl ? width : 0), y + height / 2 - width / 2, width, width );
01145         // Draw the bullet.
01146         int posY = 0;
01147         switch ( m_layout.counter->style() )
01148         {
01149             case KoParagCounter::STYLE_DISCBULLET:
01150                 p->setBrush( QBrush(textColor) );
01151                 p->drawEllipse( er );
01152                 p->setBrush( Qt::NoBrush );
01153                 break;
01154             case KoParagCounter::STYLE_SQUAREBULLET:
01155                 p->fillRect( er, QBrush(textColor) );
01156                 break;
01157             case KoParagCounter::STYLE_BOXBULLET:
01158                 p->drawRect( er );
01159                 break;
01160             case KoParagCounter::STYLE_CIRCLEBULLET:
01161                 p->drawEllipse( er );
01162                 break;
01163             case KoParagCounter::STYLE_CUSTOMBULLET:
01164             {
01165                 // The user has selected a symbol from a special font. Override the paragraph
01166                 // font with the given family. This conserves the right size etc.
01167                 if ( !m_layout.counter->customBulletFont().isEmpty() )
01168                 {
01169                     QFont bulletFont( p->font() );
01170                     bulletFont.setFamily( m_layout.counter->customBulletFont() );
01171                     p->setFont( bulletFont );
01172                 }
01173                 KoTextParag::drawFontEffects( p, format, zh, format->screenFont( zh ), textColor, xBullet, base, width, y, height, ' ' );
01174 
01175                 posY = y + base- format->offsetFromBaseLine();
01176                 //we must move to bottom text because we create
01177                 //shadow to 'top'.
01178                 int sy = format->shadowY( zh );
01179                 if ( sy < 0)
01180                     posY -= sy;
01181 
01182                 p->drawText( xBullet, posY, m_layout.counter->customBulletCharacter() );
01183                 break;
01184             }
01185             default:
01186                 break;
01187         }
01188 
01189         QString suffix = m_layout.counter->suffix();
01190         if ( !suffix.isEmpty() )
01191         {
01192             if ( !rtl )
01193                 suffix += ' ' /*the space after the bullet*/;
01194 
01195             KoTextParag::drawFontEffects( p, format, zh, format->screenFont( zh ), textColor, xBullet + width, base, counterWidth, y,height, suffix[0] );
01196 
01197             int posY =y + base- format->offsetFromBaseLine();
01198             //we must move to bottom text because we create
01199             //shadow to 'top'.
01200             int sy = format->shadowY( zh );
01201             if ( sy < 0)
01202                 posY -= sy;
01203 
01204             p->drawText( xBullet + width, posY, suffix, -1 );
01205         }
01206     }
01207     else
01208     {
01209         QString counterText = m_layout.counter->text( this );
01210         // There are no bullets...any parent bullets have already been suppressed.
01211         // Just draw the text! Note: one space is always appended.
01212         if ( !counterText.isEmpty() )
01213         {
01214             KoTextParag::drawFontEffects( p, format, zh, format->screenFont( zh ), textColor, xLeft, base, counterWidth, y, height, counterText[0] );
01215 
01216             counterText += ' ' /*the space after the bullet (before in RTL mode)*/;
01217 
01218             int posY =y + base - format->offsetFromBaseLine();
01219             //we must move to bottom text because we create
01220             //shadow to 'top'.
01221             int sy = format->shadowY( zh );
01222             if ( sy < 0)
01223                 posY -= sy;
01224 
01225             p->drawText( xLeft, posY , counterText, -1 );
01226         }
01227     }
01228     p->restore();
01229 }
01230 
01231 int KoTextParag::breakableTopMargin() const
01232 {
01233     KoTextZoomHandler * zh = textDocument()->formattingZoomHandler();
01234     return zh->ptToLayoutUnitPixY(
01235         m_layout.margins[ QStyleSheetItem::MarginTop ] );
01236 }
01237 
01238 int KoTextParag::topMargin() const
01239 {
01240     KoTextZoomHandler * zh = textDocument()->formattingZoomHandler();
01241     return zh->ptToLayoutUnitPixY(
01242         m_layout.margins[ QStyleSheetItem::MarginTop ]
01243         + ( ( prev() && prev()->joinBorder() && prev()->bottomBorder() == m_layout.bottomBorder &&
01244         prev()->topBorder() == m_layout.topBorder && prev()->leftBorder() == m_layout.leftBorder &&
01245         prev()->rightBorder() == m_layout.rightBorder) ? 0 : m_layout.topBorder.width() ) );
01246 }
01247 
01248 int KoTextParag::bottomMargin() const
01249 {
01250     KoTextZoomHandler * zh = textDocument()->formattingZoomHandler();
01251     return zh->ptToLayoutUnitPixY(
01252         m_layout.margins[ QStyleSheetItem::MarginBottom ]
01253         + ( ( joinBorder() && next() && next()->bottomBorder() == m_layout.bottomBorder &&
01254         next()->topBorder() == m_layout.topBorder && next()->leftBorder() == m_layout.leftBorder &&
01255         next()->rightBorder() == m_layout.rightBorder) ? 0 : m_layout.bottomBorder.width() ) );
01256 }
01257 
01258 int KoTextParag::leftMargin() const
01259 {
01260     KoTextZoomHandler * zh = textDocument()->formattingZoomHandler();
01261     return zh->ptToLayoutUnitPixX(
01262         m_layout.margins[ QStyleSheetItem::MarginLeft ]
01263         + m_layout.leftBorder.width() );
01264 }
01265 
01266 int KoTextParag::rightMargin() const
01267 {
01268     KoTextZoomHandler * zh = textDocument()->formattingZoomHandler();
01269     int cw=0;
01270     if( m_layout.counter && str->isRightToLeft() &&
01271         (( m_layout.counter->alignment() == Qt::AlignRight ) || ( m_layout.counter->alignment() == Qt::AlignAuto )))
01272         cw = counterWidth();
01273 
01274     return zh->ptToLayoutUnitPixX(
01275         m_layout.margins[ QStyleSheetItem::MarginRight ]
01276         + m_layout.rightBorder.width() )
01277         + cw; /* in layout units already */
01278 }
01279 
01280 int KoTextParag::firstLineMargin() const
01281 {
01282     KoTextZoomHandler * zh = textDocument()->formattingZoomHandler();
01283     return zh->ptToLayoutUnitPixY(
01284         m_layout.margins[ QStyleSheetItem::MarginFirstLine ] );
01285 }
01286 
01287 int KoTextParag::lineSpacing( int line ) const
01288 {
01289     Q_ASSERT( isValid() );
01290     if ( m_layout.lineSpacingType == KoParagLayout::LS_SINGLE )
01291         return 0; // or shadow, see calculateLineSpacing
01292     else {
01293         if( line >= (int)lineStarts.count() )
01294         {
01295             kdError() << "KoTextParag::lineSpacing assert(line<lines) failed: line=" << line << " lines=" << lineStarts.count() << endl;
01296             return 0;
01297         }
01298         QMap<int, KoTextParagLineStart*>::ConstIterator it = lineStarts.begin();
01299         while ( line-- > 0 )
01300             ++it;
01301         return (*it)->lineSpacing;
01302     }
01303 }
01304 
01305 // Called by KoTextFormatter
01306 int KoTextParag::calculateLineSpacing( int line, int startChar, int lastChar ) const
01307 {
01308     KoTextZoomHandler * zh = textDocument()->formattingZoomHandler();
01309     // TODO add shadow in KoTextFormatter!
01310     int shadow = 0; //QABS( zh->ptToLayoutUnitPixY( shadowDistanceY() ) );
01311     if ( m_layout.lineSpacingType == KoParagLayout::LS_SINGLE )
01312         return shadow;
01313     else if ( m_layout.lineSpacingType == KoParagLayout::LS_CUSTOM )
01314         return zh->ptToLayoutUnitPixY( m_layout.lineSpacingValue() ) + shadow;
01315     else {
01316         if( line >= (int)lineStarts.count() )
01317         {
01318             kdError() << "KoTextParag::lineSpacing assert(line<lines) failed: line=" << line << " lines=" << lineStarts.count() << endl;
01319             return 0+shadow;
01320         }
01321         QMap<int, KoTextParagLineStart*>::ConstIterator it = lineStarts.begin();
01322         while ( line-- > 0 )
01323             ++it;
01324 
01325         //kdDebug(32500) << " line spacing type: " << m_layout.lineSpacingType << " value:" << m_layout.lineSpacingValue() << " line_height=" << (*it)->h << " startChar=" << startChar << " lastChar=" << lastChar << endl;
01326         switch ( m_layout.lineSpacingType )
01327         {
01328         case KoParagLayout::LS_MULTIPLE:
01329         {
01330             double n = m_layout.lineSpacingValue() - 1.0; // yes, can be negative
01331             return shadow + qRound( n * heightForLineSpacing( startChar, lastChar ) );
01332         }
01333         case KoParagLayout::LS_ONEANDHALF:
01334         {
01335             // Special case of LS_MULTIPLE, with n=1.5
01336             return shadow + heightForLineSpacing( startChar, lastChar ) / 2;
01337         }
01338         case KoParagLayout::LS_DOUBLE:
01339         {
01340             // Special case of LS_MULTIPLE, with n=1
01341             return shadow + heightForLineSpacing( startChar, lastChar );
01342         }
01343         case KoParagLayout::LS_AT_LEAST:
01344         {
01345             int atLeast = zh->ptToLayoutUnitPixY( m_layout.lineSpacingValue() );
01346             const int lineHeight = ( *it )->h;
01347             int h = QMAX( lineHeight, atLeast );
01348             // height is now the required total height
01349             return shadow + h - lineHeight;
01350         }
01351         case KoParagLayout::LS_FIXED:
01352         {
01353             const int lineHeight = ( *it )->h;
01354             return shadow + zh->ptToLayoutUnitPixY( m_layout.lineSpacingValue() ) - lineHeight;
01355         }
01356         // Silence compiler warnings
01357         case KoParagLayout::LS_SINGLE:
01358         case KoParagLayout::LS_CUSTOM:
01359             break;
01360         }
01361     }
01362     kdWarning() << "Unhandled linespacing type : " << m_layout.lineSpacingType << endl;
01363     return 0+shadow;
01364 }
01365 
01366 QRect KoTextParag::pixelRect( KoTextZoomHandler *zh ) const
01367 {
01368     QRect rct( zh->layoutUnitToPixel( rect() ) );
01369     //kdDebug(32500) << "   pixelRect for parag " << paragId()
01370     //               << ": rect=" << rect() << " pixelRect=" << rct << endl;
01371 
01372     // After division we almost always end up with the top overwriting the bottom of the parag above
01373     if ( prev() )
01374     {
01375         QRect prevRect( zh->layoutUnitToPixel( prev()->rect() ) );
01376         if ( rct.top() < prevRect.bottom() + 1 )
01377         {
01378             //kdDebug(32500) << "   pixelRect: rct.top() adjusted to " << prevRect.bottom() + 1 << " (was " << rct.top() << ")" << endl;
01379             rct.setTop( prevRect.bottom() + 1 );
01380         }
01381     }
01382     return rct;
01383 }
01384 
01385 // Paint this paragraph. This is called by KoTextDocument::drawParagWYSIWYG
01386 // (KoTextDocument::drawWithoutDoubleBuffer when printing)
01387 void KoTextParag::paint( QPainter &painter, const QColorGroup &cg, KoTextCursor *cursor, bool drawSelections,
01388                          int clipx, int clipy, int clipw, int cliph )
01389 {
01390 #ifdef DEBUG_PAINT
01391     kdDebug(32500) << "KoTextParag::paint =====  id=" << paragId() << " clipx=" << clipx << " clipy=" << clipy << " clipw=" << clipw << " cliph=" << cliph << endl;
01392     kdDebug(32500) << " clipw in pix (approx) : " << textDocument()->paintingZoomHandler()->layoutUnitToPixelX( clipw ) << " cliph in pix (approx) : " << textDocument()->paintingZoomHandler()->layoutUnitToPixelX( cliph ) << endl;
01393 #endif
01394 
01395     KoTextZoomHandler * zh = textDocument()->paintingZoomHandler();
01396     assert(zh);
01397 
01398     // Draw the paragraph background color
01399     if ( backgroundColor().isValid() )
01400     {
01401         QRect paraRect = pixelRect( zh );
01402         // Find left margin size, first line offset and right margin in pixels
01403         int leftMarginPix = zh->layoutUnitToPixelX( leftMargin() );
01404         int firstLineOffset = zh->layoutUnitToPixelX( firstLineMargin() );
01405         int backgroundRight = paraRect.width() - zh->layoutUnitToPixelX( rightMargin() );
01406 
01407         // Render background from either left margin indent, or first line indent,
01408         // whichever is nearer the left.
01409         int backgroundLeft = QMIN ( leftMarginPix,  leftMarginPix + firstLineOffset );
01410         int backgroundWidth = backgroundRight - backgroundLeft;
01411         int backgroundHeight = pixelRect( zh ).height();
01412         painter.fillRect( backgroundLeft, 0,
01413                           backgroundWidth, backgroundHeight,
01414                           backgroundColor() );
01415     }
01416 
01417     // Let's call drawLabel ourselves, rather than having to deal with QStyleSheetItem to get paintLines to call it!
01418     if ( m_layout.counter && m_layout.counter->numbering() != KoParagCounter::NUM_NONE && m_lineChanged <= 0 )
01419     {
01420         int cy, h, baseLine;
01421         lineInfo( 0, cy, h, baseLine );
01422         int xLabel = at(0)->x;
01423         if ( str->isRightToLeft() )
01424             xLabel += at(0)->width;
01425         drawLabel( &painter, xLabel, cy, 0, 0, baseLine, cg );
01426     }
01427 
01428     paintLines( painter, cg, cursor, drawSelections, clipx, clipy, clipw, cliph );
01429 
01430     // Now draw paragraph border
01431     if ( m_layout.hasBorder() )
01432     {
01433         bool const drawTopBorder = !prev() || !prev()->joinBorder() || prev()->bottomBorder() != bottomBorder() || prev()->topBorder() != topBorder() || prev()->leftBorder() != leftBorder() || prev()->rightBorder() != rightBorder();
01434         bool const drawBottomBorder = !joinBorder() || !next() || next()->bottomBorder() != bottomBorder() || next()->topBorder() != topBorder() || next()->leftBorder() != leftBorder() || next()->rightBorder() != rightBorder();
01435         QRect r;
01436         // Old solution: stick to the text
01437         //r.setLeft( at( 0 )->x - counterWidth() - 1 );
01438         //r.setRight( rect().width() - rightMargin() - 1 );
01439 
01440         // New solution: occupy the full width
01441         // Note that this is what OpenOffice does too.
01442         // For something closer to the text, we need a border feature in KoTextFormat, I guess.
01443 
01444         // drawBorders paints outside the give rect, so we need to 'subtract' the border
01445         // width on all sides.
01446         r.setLeft( KoBorder::zoomWidthX( m_layout.leftBorder.width(), zh, 0 ) );
01447         // The +1 is because if border is 1 pixel, nothing to subtract. 2 pixels -> subtract 1.
01448         r.setRight( zh->layoutUnitToPixelX(rect().width()) - KoBorder::zoomWidthX( m_layout.rightBorder.width(), zh, 0 ) );
01449         r.setTop( zh->layoutUnitToPixelY(lineY( 0 )) );
01450 
01451         int lastLine = lines() - 1;
01452         // We need to start from the pixelRect, to make sure the bottom border is entirely painted.
01453         // This is a case where we DO want to subtract pixels to pixels...
01454         int paragBottom = pixelRect(zh).height()-1;
01455         // If we don't have a bottom border, we need go as low as possible ( to touch the next parag's border ).
01456         // If we have a bottom border, then we rather exclude the linespacing. Looks nicer. OO does that too.
01457         if ( m_layout.bottomBorder.width() > 0 && drawBottomBorder)
01458             paragBottom -= zh->layoutUnitToPixelY( lineSpacing( lastLine ) );
01459         paragBottom -= KoBorder::zoomWidthY( m_layout.bottomBorder.width(), zh, 0 );
01460         //kdDebug(32500) << "Parag border: paragBottom=" << paragBottom
01461         //               << " bottom border width = " << KoBorder::zoomWidthY( m_layout.bottomBorder.width(), zh, 0 ) << endl;
01462         r.setBottom( paragBottom );
01463 
01464         //kdDebug(32500) << "KoTextParag::paint documentWidth=" << documentWidth() << " LU (" << zh->layoutUnitToPixelX(documentWidth()) << " pixels) bordersRect=" << r << endl;
01465         KoBorder::drawBorders( painter, zh, r,
01466                                m_layout.leftBorder, m_layout.rightBorder, m_layout.topBorder, m_layout.bottomBorder,
01467                                0, QPen(), drawTopBorder, drawBottomBorder );
01468     }
01469 }
01470 
01471 
01472 void KoTextParag::paintLines( QPainter &painter, const QColorGroup &cg, KoTextCursor *cursor, bool drawSelections,
01473             int clipx, int clipy, int clipw, int cliph )
01474 {
01475     if ( !visible )
01476     return;
01477     //KoTextStringChar *chr = at( 0 );
01478     //if (!chr) { kdDebug(32500) << "paragraph " << (void*)this << " " << paragId() << ", can't paint, EMPTY !" << endl;
01479 
01480     // This is necessary with the current code, but in theory it shouldn't
01481     // be necessary, if Xft really gives us fully proportionnal chars....
01482 #define CHECK_PIXELXADJ
01483 
01484     int curx = -1, cury = 0, curh = 0, curline = 0;
01485     int xstart, xend = 0;
01486 
01487     QString qstr = str->toString();
01488     qstr.replace( QChar(0x00a0U), ' ' ); // Not all fonts have non-breakable-space glyph
01489 
01490     const int nSels = doc ? doc->numSelections() : 1;
01491     QMemArray<int> selectionStarts( nSels );
01492     QMemArray<int> selectionEnds( nSels );
01493     if ( drawSelections ) {
01494     bool hasASelection = FALSE;
01495     for ( int i = 0; i < nSels; ++i ) {
01496         if ( !hasSelection( i ) ) {
01497         selectionStarts[ i ] = -1;
01498         selectionEnds[ i ] = -1;
01499         } else {
01500         hasASelection = TRUE;
01501         selectionStarts[ i ] = selectionStart( i );
01502         int end = selectionEnd( i );
01503         if ( end == length() - 1 && n && n->hasSelection( i ) )
01504             end++;
01505         selectionEnds[ i ] = end;
01506         }
01507     }
01508     if ( !hasASelection )
01509         drawSelections = FALSE;
01510     }
01511 
01512     // Draw the lines!
01513     int line = m_lineChanged;
01514     if (line<0) line = 0;
01515 
01516     int numLines = lines();
01517 #ifdef DEBUG_PAINT
01518     kdDebug(32500) << " paintLines: from line " << line << " to " << numLines-1 << endl;
01519 #endif
01520     for( ; line<numLines ; line++ )
01521     {
01522     // get the start and length of the line
01523     int nextLine;
01524         int startOfLine;
01525         lineStartOfLine(line, &startOfLine);
01526     if (line == numLines-1 )
01527             nextLine = length();
01528     else
01529             lineStartOfLine(line+1, &nextLine);
01530 
01531     // init this line
01532         int cy, h, baseLine;
01533     lineInfo( line, cy, h, baseLine );
01534     if ( clipy != -1 && cy > clipy - r.y() + cliph ) // outside clip area, leave
01535         break;
01536 
01537         // Vars related to the current "run of text"
01538     int paintStart = startOfLine;
01539     KoTextStringChar* chr = at(startOfLine);
01540         KoTextStringChar* nextchr = chr;
01541 
01542     // okay, paint the line!
01543     for(int i=startOfLine;i<nextLine;i++)
01544     {
01545             chr = nextchr;
01546             if ( i < nextLine-1 )
01547                 nextchr = at( i+1 );
01548 
01549             // we flush at end of line
01550             bool flush = ( i == nextLine - 1 );
01551             // Optimization note: QRT uses "flush |=", which doesn't have shortcut optimization
01552 
01553             // we flush on format changes
01554         flush = flush || ( nextchr->format() != chr->format() );
01555         // we flush on link changes
01556         //flush = flush || ( nextchr->isLink() != chr->isLink() );
01557             // we flush on small caps changes
01558             if ( !flush && chr->format()->attributeFont() == KoTextFormat::ATT_SMALL_CAPS )
01559             {
01560                 bool isLowercase = chr->c.upper() != chr->c;
01561                 bool nextLowercase = nextchr->c.upper() != nextchr->c;
01562                 flush = isLowercase != nextLowercase;
01563             }
01564         // we flush on start of run
01565         flush = flush || nextchr->startOfRun;
01566         // we flush on bidi changes
01567         flush = flush || ( nextchr->rightToLeft != chr->rightToLeft );
01568 #ifdef CHECK_PIXELXADJ
01569             // we flush when the value of pixelxadj changes
01570             // [unless inside a ligature]
01571             flush = flush || ( nextchr->pixelxadj != chr->pixelxadj && nextchr->charStop );
01572 #endif
01573         // we flush before and after tabs
01574         flush = flush || ( chr->c == '\t' || nextchr->c == '\t' );
01575         // we flush on soft hypens
01576         flush = flush || ( chr->c.unicode() == 0xad );
01577         // we flush on custom items
01578         flush = flush || chr->isCustom();
01579         // we flush before custom items
01580         flush = flush || nextchr->isCustom();
01581         // when painting justified we flush on spaces
01582         if ((alignment() & Qt::AlignJustify) == Qt::AlignJustify )
01583         //flush = flush || QTextFormatter::isBreakable( str, i );
01584                 flush = flush || chr->whiteSpace;
01585         // when underlining or striking "word by word" we flush before/after spaces
01586         if (!flush && chr->format()->wordByWord() && chr->format()->isStrikedOrUnderlined())
01587                 flush = flush || chr->whiteSpace || nextchr->whiteSpace;
01588         // we flush when the string is getting too long
01589         flush = flush || ( i - paintStart >= 256 );
01590         // we flush when the selection state changes
01591         if ( drawSelections ) {
01592                 // check if selection state changed - TODO update from QRT
01593         bool selectionChange = FALSE;
01594         if ( drawSelections ) {
01595             for ( int j = 0; j < nSels; ++j ) {
01596             selectionChange = selectionStarts[ j ] == i+1 || selectionEnds[ j ] == i+1;
01597             if ( selectionChange )
01598                 break;
01599             }
01600         }
01601                 flush = flush || selectionChange;
01602             }
01603 
01604             // check for cursor mark
01605             if ( cursor && this == cursor->parag() && i == cursor->index() ) {
01606                 curx = cursor->x();
01607                 curline = line;
01608                 KoTextStringChar *c = chr;
01609                 if ( i > 0 )
01610                     --c;
01611                 curh = c->height();
01612                 cury = cy + baseLine - c->ascent();
01613             }
01614 
01615             if ( flush ) {  // something changed, draw what we have so far
01616 
01617                 KoTextStringChar* cStart = at( paintStart );
01618                 if ( chr->rightToLeft ) {
01619                     xstart = chr->x;
01620                     xend = cStart->x + cStart->width;
01621                 } else {
01622                     xstart = cStart->x;
01623                         if ( i < length() - 1 && !str->at( i + 1 ).lineStart &&
01624                          str->at( i + 1 ).rightToLeft == chr->rightToLeft )
01625                         xend = str->at( i + 1 ).x;
01626                     else
01627                         xend = chr->x + chr->width;
01628                 }
01629 
01630                 if ( (clipx == -1 || clipw == -1) || (xend >= clipx && xstart <= clipx + clipw) ) {
01631                     if ( !chr->isCustom() ) {
01632                         drawParagString( painter, qstr, paintStart, i - paintStart + 1, xstart, cy,
01633                                          baseLine, xend-xstart, h, drawSelections,
01634                                          chr->format(), selectionStarts, selectionEnds,
01635                                          cg, chr->rightToLeft, line );
01636                     }
01637                     else
01638                         if ( chr->customItem()->placement() == KoTextCustomItem::PlaceInline ) {
01639                             chr->customItem()->draw( &painter, chr->x, cy + baseLine - chr->customItem()->ascent(),
01640                                                      clipx - r.x(), clipy - r.y(), clipw, cliph, cg,
01641                                                      drawSelections && nSels && selectionStarts[ 0 ] <= i && selectionEnds[ 0 ] > i );
01642                     }
01643                 }
01644                 paintStart = i+1;
01645             }
01646         } // end of character loop
01647     } // end of line loop
01648 
01649     // if we should draw a cursor, draw it now
01650     if ( curx != -1 && cursor ) {
01651         drawCursor( painter, cursor, curx, cury, curh, cg );
01652     }
01653 }
01654 
01655 // Called by KoTextParag::paintLines
01656 // Draw a set of characters with the same formattings.
01657 // Reimplemented here to convert coordinates first, and call @ref drawFormattingChars.
01658 void KoTextParag::drawParagString( QPainter &painter, const QString &str, int start, int len, int startX,
01659                                    int lastY, int baseLine, int bw, int h, bool drawSelections,
01660                                    KoTextFormat *format, const QMemArray<int> &selectionStarts,
01661                                    const QMemArray<int> &selectionEnds, const QColorGroup &cg, bool rightToLeft, int line )
01662 {
01663     KoTextZoomHandler * zh = textDocument()->paintingZoomHandler();
01664     assert(zh);
01665 
01666 #ifdef DEBUG_PAINT
01667     kdDebug(32500) << "KoTextParag::drawParagString drawing from " << start << " to " << start+len << endl;
01668     kdDebug(32500) << " startX in LU: " << startX << " lastY in LU:" << lastY
01669                    << " baseLine in LU:" << baseLine << endl;
01670 #endif
01671 
01672     // Calculate offset (e.g. due to shadow on left or top)
01673     // Important: don't use the 2-args methods here, offsets are not heights
01674     // (0 should be 0, not 1) (#63256)
01675     int shadowOffsetX_pix = zh->layoutUnitToPixelX( format->offsetX() );
01676     int shadowOffsetY_pix = zh->layoutUnitToPixelY( format->offsetY() );
01677 
01678     // Calculate startX in pixels
01679     int startX_pix = zh->layoutUnitToPixelX( startX ) /* + at( rightToLeft ? start+len-1 : start )->pixelxadj */;
01680 #ifdef DEBUG_PAINT
01681     kdDebug(32500) << "KoTextParag::drawParagString startX in pixels : " << startX_pix /*<< " adjustment:" << at( rightToLeft ? start+len-1 : start )->pixelxadj*/ << " bw=" << bw << endl;
01682 #endif
01683 
01684     int bw_pix = zh->layoutUnitToPixelX( startX, bw );
01685     int lastY_pix = zh->layoutUnitToPixelY( lastY );
01686     int baseLine_pix = zh->layoutUnitToPixelY( lastY, baseLine ); // 2 args=>+1. Is that correct?
01687     int h_pix = zh->layoutUnitToPixelY( lastY, h );
01688 #ifdef DEBUG_PAINT
01689     kdDebug(32500) << "KoTextParag::drawParagString h(LU)=" << h << " lastY(LU)=" << lastY
01690                    << " h(PIX)=" << h_pix << " lastY(PIX)=" << lastY_pix
01691                    << " baseLine(PIX)=" << baseLine_pix << endl;
01692 #endif
01693 
01694     if ( format->textBackgroundColor().isValid() )
01695         painter.fillRect( startX_pix, lastY_pix, bw_pix, h_pix, format->textBackgroundColor() );
01696 
01697     // don't want to draw line breaks but want them when drawing formatting chars
01698     int draw_len = len;
01699     int draw_startX = startX;
01700     int draw_bw = bw_pix;
01701     if ( at( start + len - 1 )->c == '\n' )
01702     {
01703         draw_len--;
01704         draw_bw -= at( start + len - 1 )->pixelwidth;
01705         if ( rightToLeft && draw_len > 0 )
01706             draw_startX = at( start + draw_len - 1 )->x;
01707     }
01708 
01709     // Draw selection (moved here to do it before applying the offset from the shadow)
01710     // (and because it's not part of the shadow drawing)
01711     if ( drawSelections ) {
01712         bool inSelection = false;
01713     const int nSels = doc ? doc->numSelections() : 1;
01714     for ( int j = 0; j < nSels; ++j ) {
01715         if ( start >= selectionStarts[ j ] && start < selectionEnds[ j ] ) {
01716                 inSelection = true;
01717                 switch (j) {
01718                 case KoTextDocument::Standard:
01719                     painter.fillRect( startX_pix, lastY_pix, bw_pix, h_pix, cg.color( QColorGroup::Highlight ) );
01720                     break;
01721                 case KoTextDocument::InputMethodPreedit:
01722                     // no highlight
01723                     break;
01724                 default:
01725                     painter.fillRect( startX_pix, lastY_pix, bw_pix, h_pix, doc ? doc->selectionColor( j ) : cg.color( QColorGroup::Highlight ) );
01726                     break;
01727                 }
01728         }
01729     }
01730         if ( !inSelection )
01731             drawSelections = false; // save time in drawParagStringInternal
01732     }
01733 
01734     // Draw InputMethod Preedit Underline
01735     const int nSels = doc ? doc->numSelections() : 1;
01736     if ( KoTextDocument::InputMethodPreedit < nSels
01737          && doc->hasSelection( KoTextDocument::InputMethodPreedit )
01738          && start >= selectionStarts[ KoTextDocument::InputMethodPreedit ]
01739          && start < selectionEnds[ KoTextDocument::InputMethodPreedit ] )
01740     {
01741         QColor textColor( format->color() );
01742         painter.setPen( QPen( textColor ) );
01743 
01744         QPoint p1( startX_pix, lastY_pix + h_pix - 1 );
01745         QPoint p2( startX_pix + bw_pix, lastY_pix + h_pix - 1 );
01746         painter.drawLine( p1, p2 );
01747     }
01748 
01749     if ( draw_len > 0 )
01750     {
01751         int draw_startX_pix = zh->layoutUnitToPixelX( draw_startX ) /* + at( rightToLeft ? start+draw_len-1 : start )->pixelxadj*/;
01752         draw_startX_pix += shadowOffsetX_pix;
01753         lastY_pix += shadowOffsetY_pix;
01754 
01755         if ( format->shadowDistanceX() != 0 || format->shadowDistanceY() != 0 ) {
01756             int sx = format->shadowX( zh );
01757             int sy = format->shadowY( zh );
01758             if ( sx != 0 || sy != 0 )
01759             {
01760                 painter.save();
01761                 painter.translate( sx, sy );
01762                 drawParagStringInternal( painter, str, start, draw_len, draw_startX_pix,
01763                                          lastY_pix, baseLine_pix,
01764                                          draw_bw,
01765                                          h_pix, FALSE /*drawSelections*/,
01766                                          format, selectionStarts,
01767                                          selectionEnds, cg, rightToLeft, line, zh, true );
01768                 painter.restore();
01769             }
01770         }
01771 
01772         drawParagStringInternal( painter, str, start, draw_len, draw_startX_pix,
01773                                  lastY_pix, baseLine_pix,
01774                                  draw_bw,
01775                                  h_pix, drawSelections, format, selectionStarts,
01776                                  selectionEnds, cg, rightToLeft, line, zh, false );
01777     }
01778 
01779     bool forPrint = ( painter.device()->devType() == QInternal::Printer );
01780     if ( textDocument()->drawFormattingChars() && !forPrint )
01781     {
01782         drawFormattingChars( painter, start, len,
01783                              lastY_pix, baseLine_pix, h_pix,
01784                              drawSelections,
01785                              format, selectionStarts,
01786                              selectionEnds, cg, rightToLeft,
01787                              line, zh, AllFormattingChars );
01788     }
01789 }
01790 
01791 // Copied from the original KoTextParag
01792 // (we have to copy it here, so that color & font changes don't require changing
01793 // a local copy of the text format)
01794 // And we have to keep it separate from drawParagString to avoid s/startX/startX_pix/ etc.
01795 void KoTextParag::drawParagStringInternal( QPainter &painter, const QString &s, int start, int len, int startX,
01796                                    int lastY, int baseLine, int bw, int h, bool drawSelections,
01797                                    KoTextFormat *format, const QMemArray<int> &selectionStarts,
01798                                    const QMemArray<int> &selectionEnds, const QColorGroup &cg, bool rightToLeft, int line, KoTextZoomHandler* zh, bool drawingShadow )
01799 {
01800 #ifdef DEBUG_PAINT
01801     kdDebug(32500) << "KoTextParag::drawParagStringInternal start=" << start << " len=" << len << " : '" << s.mid(start,len) << "'" << endl;
01802     kdDebug(32500) << "In pixels:  startX=" << startX << " lastY=" << lastY << " baseLine=" << baseLine
01803                    << " bw=" << bw << " h=" << h << " rightToLeft=" << rightToLeft << endl;
01804 #endif
01805     if ( drawingShadow && format->shadowDistanceX() == 0 && format->shadowDistanceY() == 0 )
01806         return;
01807     // 1) Sort out the color
01808     QColor textColor( drawingShadow ? format->shadowColor() : format->color() );
01809     if ( !textColor.isValid() ) // Resolve the color at this point
01810         textColor = KoTextFormat::defaultTextColor( &painter );
01811 
01812     // 2) Sort out the font
01813     QFont font( format->screenFont( zh ) );
01814     if ( format->attributeFont() == KoTextFormat::ATT_SMALL_CAPS && s[start].upper() != s[start] )
01815         font = format->smallCapsFont( zh, true );
01816 
01817 #if 0
01818     QFontInfo fi( font );
01819     kdDebug(32500) << "KoTextParag::drawParagStringInternal requested font " << font.pointSizeFloat() << " using font " << fi.pointSize() << "pt (format font: " << format->font().pointSizeFloat() << "pt)" << endl;
01820     QFontMetrics fm( font );
01821     kdDebug(32500) << "Real font: " << fi.family() << ". Font height in pixels: " << fm.height() << endl;
01822 #endif
01823 
01824     // 3) Paint
01825     QString str( s );
01826     if ( str[ (int)str.length() - 1 ].unicode() == 0xad )
01827         str.remove( str.length() - 1, 1 );
01828     painter.setPen( QPen( textColor ) );
01829     painter.setFont( font );
01830 
01831     KoTextDocument* doc = document();
01832 
01833     if ( drawSelections ) {
01834     const int nSels = doc ? doc->numSelections() : 1;
01835     for ( int j = 0; j < nSels; ++j ) {
01836         if ( start >= selectionStarts[ j ] && start < selectionEnds[ j ] ) {
01837         if ( !doc || doc->invertSelectionText( j ) )
01838             textColor = cg.color( QColorGroup::HighlightedText );
01839             painter.setPen( QPen( textColor ) );
01840                     break;
01841             }
01842         }
01843     }
01844 
01845     QPainter::TextDirection dir = rightToLeft ? QPainter::RTL : QPainter::LTR;
01846 
01847     if ( dir != QPainter::RTL && start + len == length() ) // don't draw the last character (trailing space)
01848     {
01849        len--;
01850        if ( len <= 0 )
01851            return;
01852        bw-=at(length()-1)->pixelwidth;
01853     }
01854     KoTextParag::drawFontEffects( &painter, format, zh, font, textColor, startX, baseLine, bw, lastY, h, str[start] );
01855 
01856     if ( str[ start ] != '\t' && str[ start ].unicode() != 0xad ) {
01857         str = format->displayedString( str ); // #### This converts the whole string, instead of from start to start+len!
01858     if ( format->vAlign() == KoTextFormat::AlignNormal ) {
01859             int posY = lastY + baseLine;
01860             //we must move to bottom text because we create
01861             //shadow to 'top'.
01862             int sy = format->shadowY( zh );
01863             if ( sy < 0)
01864                 posY -= sy;
01865         painter.drawText( startX, posY, str, start, len, dir );
01866 #ifdef BIDI_DEBUG
01867         painter.save();
01868         painter.setPen ( Qt::red );
01869         painter.drawLine( startX, lastY, startX, lastY + baseLine );
01870         painter.drawLine( startX, lastY + baseLine/2, startX + 10, lastY + baseLine/2 );
01871         int w = 0;
01872         int i = 0;
01873         while( i < len )
01874         w += painter.fontMetrics().charWidth( str, start + i++ );
01875         painter.setPen ( Qt::blue );
01876         painter.drawLine( startX + w - 1, lastY, startX + w - 1, lastY + baseLine );
01877         painter.drawLine( startX + w - 1, lastY + baseLine/2, startX + w - 1 - 10, lastY + baseLine/2 );
01878         painter.restore();
01879 #endif
01880     } else if ( format->vAlign() == KoTextFormat::AlignSuperScript ) {
01881             int posY =lastY + baseLine - ( painter.fontMetrics().height() / 2 );
01882             //we must move to bottom text because we create
01883             //shadow to 'top'.
01884             int sy = format->shadowY( zh );
01885             if ( sy < 0)
01886                 posY -= sy;
01887         painter.drawText( startX, posY, str, start, len, dir );
01888     } else if ( format->vAlign() == KoTextFormat::AlignSubScript ) {
01889             int posY =lastY + baseLine + ( painter.fontMetrics().height() / 6 );
01890             //we must move to bottom text because we create
01891             //shadow to 'top'.
01892             int sy = format->shadowY( zh );
01893             if ( sy < 0)
01894                 posY -= sy;
01895         painter.drawText( startX, posY, str, start, len, dir );
01896     } else if ( format->vAlign() == KoTextFormat::AlignCustom ) {
01897             int posY = lastY + baseLine - format->offsetFromBaseLine();
01898             //we must move to bottom text because we create
01899             //shadow to 'top'.
01900             int sy = format->shadowY( zh );
01901             if ( sy < 0)
01902                 posY -= sy;
01903         painter.drawText( startX, posY, str, start, len, dir );
01904     }
01905     }
01906     if ( str[ start ] == '\t' && m_tabCache.contains( start ) ) {
01907     painter.save();
01908     KoTextZoomHandler * zh = textDocument()->paintingZoomHandler();
01909     const KoTabulator& tab = m_layout.tabList()[ m_tabCache[ start ] ];
01910     int lineWidth = zh->zoomItY( tab.ptWidth );
01911     switch ( tab.filling ) {
01912         case TF_DOTS:
01913         painter.setPen( QPen( textColor, lineWidth, Qt::DotLine ) );
01914         painter.drawLine( startX, lastY + baseLine, startX + bw, lastY + baseLine );
01915         break;
01916         case TF_LINE:
01917         painter.setPen( QPen( textColor, lineWidth, Qt::SolidLine ) );
01918         painter.drawLine( startX, lastY + baseLine, startX + bw, lastY + baseLine );
01919             case TF_DASH:
01920         painter.setPen( QPen( textColor, lineWidth, Qt::DashLine ) );
01921         painter.drawLine( startX, lastY + baseLine, startX + bw, lastY + baseLine );
01922         break;
01923             case TF_DASH_DOT:
01924         painter.setPen( QPen( textColor, lineWidth, Qt::DashDotLine ) );
01925         painter.drawLine( startX, lastY + baseLine, startX + bw, lastY + baseLine );
01926         break;
01927             case TF_DASH_DOT_DOT:
01928         painter.setPen( QPen( textColor, lineWidth, Qt::DashDotDotLine ) );
01929         painter.drawLine( startX, lastY + baseLine, startX + bw, lastY + baseLine );
01930         break;
01931 
01932             default:
01933                 break;
01934     }
01935     painter.restore();
01936     }
01937 
01938     if ( start+len < length() && at( start+len )->lineStart )
01939     {
01940 #ifdef DEBUG_PAINT
01941         //kdDebug(32500) << "we are drawing the end of line " << line << ". Auto-hyphenated: " << lineHyphenated( line ) << endl;
01942 #endif
01943         bool drawHyphen = at( start+len-1 )->c.unicode() == 0xad;
01944         drawHyphen = drawHyphen || lineHyphenated( line );
01945         if ( drawHyphen ) {
01946 #ifdef DEBUG_PAINT
01947             kdDebug(32500) << "drawing hyphen at x=" << startX+bw << endl;
01948 #endif
01949             painter.drawText( startX + bw, lastY + baseLine, "-" ); // \xad gives squares with some fonts (!?)
01950         }
01951     }
01952 
01953     // Paint a zigzag line for "wrong" background spellchecking checked words:
01954     if(
01955         painter.device()->devType() != QInternal::Printer &&
01956         format->isMisspelled() &&
01957         !drawingShadow &&
01958         textDocument()->drawingMissingSpellLine() )
01959     {
01960         painter.save();
01961         painter.setPen( QPen( Qt::red, 1 ) );
01962 
01963         // Draw 3 pixel lines with increasing offset and distance 4:
01964         for( int zigzag_line = 0; zigzag_line < 3; ++zigzag_line )
01965         {
01966             for( int zigzag_x = zigzag_line; zigzag_x < bw; zigzag_x += 4 )
01967             {
01968                 painter.drawPoint(
01969                     startX + zigzag_x,
01970                     lastY + baseLine + h/12 - 1 + zigzag_line );
01971             }
01972         }
01973 
01974         // "Double" the pixel number for the middle line:
01975         for( int zigzag_x = 3; zigzag_x < bw; zigzag_x += 4 )
01976         {
01977             painter.drawPoint(
01978                 startX + zigzag_x,
01979                 lastY + baseLine + h/12 );
01980         }
01981 
01982         painter.restore();
01983     }
01984 }
01985 
01986 bool KoTextParag::lineHyphenated( int l ) const
01987 {
01988     if ( l > (int)lineStarts.count() - 1 ) {
01989     kdWarning() << "KoTextParag::lineHyphenated: line " << l << " out of range!" << endl;
01990     return false;
01991     }
01992 
01993     if ( !isValid() )
01994     const_cast<KoTextParag*>(this)->format();
01995 
01996     QMap<int, KoTextParagLineStart*>::ConstIterator it = lineStarts.begin();
01997     while ( l-- > 0 )
01998     ++it;
01999     return ( *it )->hyphenated;
02000 }
02001 
02003 void KoTextParag::drawCursor( QPainter &painter, KoTextCursor *cursor, int curx, int cury, int curh, const QColorGroup &cg )
02004 {
02005     KoTextZoomHandler * zh = textDocument()->paintingZoomHandler();
02006     int x = zh->layoutUnitToPixelX( curx ) /*+ cursor->parag()->at( cursor->index() )->pixelxadj*/;
02007     //kdDebug(32500) << "  drawCursor: LU: [cur]x=" << curx << ", cury=" << cury << " -> PIX: x=" << x << ", y=" << zh->layoutUnitToPixelY( cury ) << endl;
02008     KoTextParag::drawCursorDefault( painter, cursor, x,
02009                             zh->layoutUnitToPixelY( cury ),
02010                             zh->layoutUnitToPixelY( cury, curh ), cg );
02011 }
02012 
02013 // Reimplemented from KoTextParag
02014 void KoTextParag::copyParagData( KoTextParag *parag )
02015 {
02016     // Style of the previous paragraph
02017     KoParagStyle * style = parag->style();
02018     // Obey "following style" setting
02019     bool styleApplied = false;
02020     if ( style )
02021     {
02022         KoParagStyle * newStyle = style->followingStyle();
02023         if ( newStyle && style != newStyle ) // if same style, keep paragraph-specific changes as usual
02024         {
02025             setParagLayout( newStyle->paragLayout() );
02026             KoTextFormat * format = &newStyle->format();
02027             setFormat( format );
02028             format->addRef();
02029             str->setFormat( 0, format, true ); // prepare format for text insertion
02030             styleApplied = true;
02031         }
02032     }
02033     // This should never happen in KWord, but it happens in KPresenter
02034     //else
02035     //    kdWarning() << "Paragraph has no style " << paragId() << endl;
02036 
02037     // No "following style" setting, or same style -> copy layout & format of previous paragraph
02038     if (!styleApplied)
02039     {
02040         setParagLayout( parag->paragLayout() );
02041         // Remove pagebreak flags from initial parag - they got copied to the new parag
02042         parag->m_layout.pageBreaking &= ~KoParagLayout::HardFrameBreakBefore;
02043         parag->m_layout.pageBreaking &= ~KoParagLayout::HardFrameBreakAfter;
02044         // Remove footnote counter text from second parag
02045         if ( m_layout.counter && m_layout.counter->numbering() == KoParagCounter::NUM_FOOTNOTE )
02046             setNoCounter();
02047         // Do not copy 'restart numbering at this paragraph' option (would be silly)
02048         if ( m_layout.counter )
02049             m_layout.counter->setRestartCounter(false);
02050 
02051         // set parag format to the format of the trailing space of the previous parag
02052         setFormat( parag->at( parag->length()-1 )->format() );
02053         // KoTextCursor::splitAndInsertEmptyParag takes care of setting the format
02054         // for the chars in the new parag
02055     }
02056 
02057     // Note: we don't call the original KoTextParag::copyParagData on purpose.
02058     // We don't want setListStyle to get called - it ruins our stylesheetitems
02059     // And we don't care about copying the stylesheetitems directly,
02060     // applying the parag layout will create them
02061 }
02062 
02063 void KoTextParag::setTabList( const KoTabulatorList &tabList )
02064 {
02065     KoTabulatorList lst( tabList );
02066     m_layout.setTabList( lst );
02067     if ( !tabList.isEmpty() )
02068     {
02069         KoTextZoomHandler* zh = textDocument()->formattingZoomHandler();
02070         int * tabs = new int[ tabList.count() + 1 ]; // will be deleted by ~KoTextParag
02071         KoTabulatorList::Iterator it = lst.begin();
02072         unsigned int i = 0;
02073         for ( ; it != lst.end() ; ++it, ++i )
02074             tabs[i] = zh->ptToLayoutUnitPixX( (*it).ptPos );
02075         tabs[i] = 0;
02076         assert( i == tabList.count() );
02077         setTabArray( tabs );
02078     } else
02079     {
02080         setTabArray( 0 );
02081     }
02082     invalidate( 0 );
02083 }
02084 
02086 int KoTextParag::nextTab( int chnum, int x, int availableWidth )
02087 {
02088     if ( !m_layout.tabList().isEmpty() )
02089     {
02090         // Fetch the zoomed and sorted tab positions from KoTextParag
02091         // We stored them there for faster access
02092         int * tArray = tabArray();
02093         int i = 0;
02094         if ( str->isRightToLeft() )
02095             i = m_layout.tabList().size() - 1;
02096         KoTextZoomHandler* zh = textDocument()->formattingZoomHandler();
02097 
02098         while ( i >= 0 && i < (int)m_layout.tabList().size() ) {
02099             //kdDebug(32500) << "KoTextParag::nextTab tArray[" << i << "]=" << tArray[i] << " type " << m_layout.tabList()[i].type << endl;
02100             int tab = tArray[ i ];
02101 
02102             // If a right-aligned tab is after the right edge then assume
02103             // that it -is- on the right edge, otherwise the last letters will fall off.
02104             // This is compatible with OOo's behavior.
02105             if ( tab > availableWidth ) {
02106                 //kdDebug(32500) << "Tab position adjusted to availableWidth=" << availableWidth << endl;
02107                 tab = availableWidth;
02108             }
02109 
02110             if ( str->isRightToLeft() )
02111                 tab = availableWidth - tab;
02112 
02113             if ( tab > x ) {
02114                 int type = m_layout.tabList()[i].type;
02115 
02116                 // fix the tab type for right to left text
02117                 if ( str->isRightToLeft() )
02118                     if ( type == T_RIGHT )
02119                         type = T_LEFT;
02120                     else if ( type == T_LEFT )
02121                         type = T_RIGHT;
02122 
02123                 switch ( type ) {
02124                 case T_RIGHT:
02125                 case T_CENTER:
02126                 {
02127                     // Look for the next tab (or EOL)
02128                     int c = chnum + 1;
02129                     int w = 0;
02130                     while ( c < str->length() - 1 && str->at( c ).c != '\t' && str->at( c ).c != '\n' )
02131                     {
02132                         KoTextStringChar & ch = str->at( c );
02133                         // Determine char width
02134                         // This must be done in the same way as in KoTextFormatter::format() or there can be different rounding errors.
02135                         if ( ch.isCustom() )
02136                             w += ch.customItem()->width;
02137                         else
02138                         {
02139                             KoTextFormat *charFormat = ch.format();
02140                             int ww = charFormat->charWidth( zh, false, &ch, this, c );
02141                             ww = KoTextZoomHandler::ptToLayoutUnitPt( ww );
02142                             w += ww;
02143                         }
02144                         ++c;
02145                     }
02146 
02147                     m_tabCache[chnum] = i;
02148 
02149                     if ( type == T_RIGHT )
02150                         return tab - w;
02151                     else // T_CENTER
02152                         return tab - w/2;
02153                 }
02154                 case T_DEC_PNT:
02155                 {
02156                     // Look for the next tab (or EOL), and for alignChar
02157                     // Default to right-aligned if no decimal point found (behavior from msword)
02158                     int c = chnum + 1;
02159                     int w = 0;
02160                     while ( c < str->length()-1 && str->at( c ).c != '\t' && str->at( c ).c != '\n' )
02161                     {
02162                         KoTextStringChar & ch = str->at( c );
02163                         if ( ch.c == m_layout.tabList()[i].alignChar )
02164                         {
02165                             // Can't use ch.width yet, since the formatter hasn't run over those chars
02166                             int ww = ch.format()->charWidth( zh, false, &ch, this, c );
02167                             ww = KoTextZoomHandler::ptToLayoutUnitPt( ww );
02168                             if ( str->isRightToLeft() )
02169                             {
02170                                 w = ww / 2; // center around the decimal point
02171                                 ++c;
02172                                 continue;
02173                             }
02174                             else
02175                             {
02176                                 w += ww / 2; // center around the decimal point
02177                                 break;
02178                             }
02179                         }
02180 
02181                         // Determine char width
02182                         if ( ch.isCustom() )
02183                             w += ch.customItem()->width;
02184                         else
02185                         {
02186                             int ww = ch.format()->charWidth( zh, false, &ch, this, c );
02187                             w += KoTextZoomHandler::ptToLayoutUnitPt( ww );
02188                         }
02189 
02190                         ++c;
02191                     }
02192                     m_tabCache[chnum] = i;
02193                     return tab - w;
02194                 }
02195                 default: // case T_LEFT:
02196                     m_tabCache[chnum] = i;
02197                     return tab;
02198                 }
02199             }
02200             if ( str->isRightToLeft() )
02201                 --i;
02202             else
02203                 ++i;
02204         }
02205     }
02206     // No tab list, use tab-stop-width. qrichtext.cpp has the code :)
02207     return KoTextParag::nextTabDefault( chnum, x );
02208 }
02209 
02210 void KoTextParag::applyStyle( KoParagStyle *style )
02211 {
02212     setParagLayout( style->paragLayout() );
02213     KoTextFormat *newFormat = &style->format();
02214     setFormat( 0, str->length(), newFormat );
02215     setFormat( newFormat );
02216 }
02217 
02218 void KoTextParag::setParagLayout( const KoParagLayout & layout, int flags, int marginIndex )
02219 {
02220     //kdDebug(32500) << "KoTextParag::setParagLayout flags=" << flags << endl;
02221     if ( flags & KoParagLayout::Alignment )
02222         setAlign( layout.alignment );
02223     if ( flags & KoParagLayout::Margins ) {
02224         if ( marginIndex == -1 )
02225             setMargins( layout.margins );
02226         else
02227             setMargin( (QStyleSheetItem::Margin)marginIndex, layout.margins[marginIndex] );
02228     }
02229     if ( flags & KoParagLayout::LineSpacing )
02230     {
02231         setLineSpacingType( layout.lineSpacingType );
02232         setLineSpacing( layout.lineSpacingValue() );
02233     }
02234     if ( flags & KoParagLayout::Borders )
02235     {
02236         setLeftBorder( layout.leftBorder );
02237         setRightBorder( layout.rightBorder );
02238         setTopBorder( layout.topBorder );
02239         setBottomBorder( layout.bottomBorder );
02240         setJoinBorder( layout.joinBorder );
02241     }
02242     if ( flags & KoParagLayout::BackgroundColor )
02243     {
02244         setBackgroundColor( layout.backgroundColor );
02245     }
02246     if ( flags & KoParagLayout::BulletNumber )
02247         setCounter( layout.counter );
02248     if ( flags & KoParagLayout::Tabulator )
02249         setTabList( layout.tabList() );
02250     if ( flags == KoParagLayout::All )
02251     {
02252         setDirection( static_cast<QChar::Direction>(layout.direction) );
02253         // Don't call applyStyle from here, it would overwrite any paragraph-specific settings
02254         setStyle( layout.style );
02255     }
02256 }
02257 
02258 void KoTextParag::setCustomItem( int index, KoTextCustomItem * custom, KoTextFormat * currentFormat )
02259 {
02260     //kdDebug(32500) << "KoTextParag::setCustomItem " << index << "  " << (void*)custom
02261     //               << "  currentFormat=" << (void*)currentFormat << endl;
02262     if ( currentFormat )
02263         setFormat( index, 1, currentFormat );
02264     at( index )->setCustomItem( custom );
02265     //addCustomItem();
02266     document()->registerCustomItem( custom, this );
02267     custom->recalc(); // calc value (e.g. for variables) and set initial size
02268     invalidate( 0 );
02269     setChanged( true );
02270 }
02271 
02272 void KoTextParag::removeCustomItem( int index )
02273 {
02274     Q_ASSERT( at( index )->isCustom() );
02275     KoTextCustomItem * item = at( index )->customItem();
02276     at( index )->loseCustomItem();
02277     //KoTextParag::removeCustomItem();
02278     document()->unregisterCustomItem( item, this );
02279 }
02280 
02281 
02282 int KoTextParag::findCustomItem( const KoTextCustomItem * custom ) const
02283 {
02284     int len = str->length();
02285     for ( int i = 0; i < len; ++i )
02286     {
02287         KoTextStringChar & ch = str->at(i);
02288         if ( ch.isCustom() && ch.customItem() == custom )
02289             return i;
02290     }
02291     kdWarning() << "KoTextParag::findCustomItem custom item " << (void*)custom
02292               << " not found in paragraph " << paragId() << endl;
02293     return 0;
02294 }
02295 
02296 #ifndef NDEBUG
02297 void KoTextParag::printRTDebug( int info )
02298 {
02299     QString specialFlags;
02300     if ( str->needsSpellCheck() )
02301         specialFlags += " needsSpellCheck=true";
02302     if ( wasMovedDown() )
02303         specialFlags += " wasMovedDown=true";
02304     if ( partOfTableOfContents() )
02305         specialFlags += " part-of-TOC=true";
02306     kdDebug(32500) << "Paragraph " << this << " (" << paragId() << ") [changed="
02307               << hasChanged() << ", valid=" << isValid()
02308               << specialFlags
02309               << "] ------------------ " << endl;
02310     if ( prev() && prev()->paragId() + 1 != paragId() )
02311         kdWarning() << "  Previous paragraph " << prev() << " has ID " << prev()->paragId() << endl;
02312     if ( next() && next()->paragId() != paragId() + 1 )
02313         kdWarning() << "  Next paragraph " << next() << " has ID " << next()->paragId() << endl;
02314     //if ( !next() )
02315     //    kdDebug(32500) << "  next is 0L" << endl;
02316     kdDebug(32500) << "  Style: " << style() << " " << ( style() ? style()->name().local8Bit().data() : "NO STYLE" ) << endl;
02317     kdDebug(32500) << "  Text: '" << str->toString() << "'" << endl;
02318     if ( info == 0 ) // paragraph info
02319     {
02320         if ( m_layout.counter )
02321         {
02322             m_layout.counter->printRTDebug( this );
02323         }
02324         static const char * const s_align[] = { "Auto", "Left", "Right", "ERROR", "HCenter", "ERR", "ERR", "ERR", "Justify", };
02325         static const char * const s_linespacing[] = { "Single", "1.5", "2", "custom", "atLeast", "Multiple", "Fixed" };
02326         static const char * const s_dir[] = { "DirL", "DirR", "DirEN", "DirES", "DirET", "DirAN", "DirCS", "DirB", "DirS", "DirWS", "DirON", "DirLRE", "DirLRO", "DirAL", "DirRLE", "DirRLO", "DirPDF", "DirNSM", "DirBN" };
02327         kdDebug(32500) << "  align: " << s_align[alignment()] << "  resolveAlignment: " << s_align[resolveAlignment()]
02328                   << "  isRTL:" << str->isRightToLeft()
02329                   << "  dir: " << s_dir[direction()] << endl;
02330         QRect pixr = pixelRect( textDocument()->paintingZoomHandler() );
02331         kdDebug(32500) << "  rect() : " << DEBUGRECT( rect() )
02332                   << "  pixelRect() : " << DEBUGRECT( pixr ) << endl;
02333         kdDebug(32500) << "  topMargin()=" << topMargin() << " bottomMargin()=" << bottomMargin()
02334                   << " leftMargin()=" << leftMargin() << " firstLineMargin()=" << firstLineMargin()
02335                   << " rightMargin()=" << rightMargin() << endl;
02336         if ( kwLineSpacingType() != KoParagLayout::LS_SINGLE )
02337             kdDebug(32500) << "  linespacing type=" << s_linespacing[ -kwLineSpacingType() ]
02338                            << " value=" << kwLineSpacing() << endl;
02339         const int pageBreaking = m_layout.pageBreaking;
02340         QStringList pageBreakingFlags;
02341         if ( pageBreaking & KoParagLayout::KeepLinesTogether )
02342             pageBreakingFlags.append( "KeepLinesTogether" );
02343         if ( pageBreaking & KoParagLayout::HardFrameBreakBefore )
02344             pageBreakingFlags.append( "HardFrameBreakBefore" );
02345         if ( pageBreaking & KoParagLayout::HardFrameBreakAfter )
02346             pageBreakingFlags.append( "HardFrameBreakAfter" );
02347         if ( pageBreaking & KoParagLayout::KeepWithPrevious )
02348             pageBreakingFlags.append( "KeepWithPrevious" );
02349         if ( pageBreaking & KoParagLayout::KeepWithNext )
02350             pageBreakingFlags.append( "KeepWithNext" );
02351         if ( !pageBreakingFlags.isEmpty() )
02352             kdDebug(32500) << " page Breaking: " << pageBreakingFlags.join(",") << endl;
02353 
02354         static const char * const tabtype[] = { "T_LEFT", "T_CENTER", "T_RIGHT", "T_DEC_PNT", "error!!!" };
02355         KoTabulatorList tabList = m_layout.tabList();
02356         if ( tabList.isEmpty() ) {
02357             if ( str->toString().find( '\t' ) != -1 )
02358                 kdDebug(32500) << "Tab width: " << textDocument()->tabStopWidth() << endl;
02359         } else {
02360             KoTabulatorList::Iterator it = tabList.begin();
02361             for ( ; it != tabList.end() ; it++ )
02362                 kdDebug(32500) << "Tab type:" << tabtype[(*it).type] << " at: " << (*it).ptPos << endl;
02363         }
02364     } else if ( info == 1 ) // formatting info
02365     {
02366         kdDebug(32500) << "  Paragraph format=" << paragFormat() << " " << paragFormat()->key()
02367                   << " fontsize:" << dynamic_cast<KoTextFormat *>(paragFormat())->pointSize() << endl;
02368 
02369         for ( int line = 0 ; line < lines(); ++ line ) {
02370             int y, h, baseLine;
02371             lineInfo( line, y, h, baseLine );
02372             int startOfLine;
02373             lineStartOfLine( line, &startOfLine );
02374             kdDebug(32500) << "  Line " << line << " y=" << y << " height=" << h << " baseLine=" << baseLine << " startOfLine(index)=" << startOfLine << endl;
02375         }
02376         kdDebug(32500) << endl;
02377         KoTextString * s = string();
02378         int lastX = 0; // pixels
02379         int lastW = 0; // pixels
02380         for ( int i = 0 ; i < s->length() ; ++i )
02381         {
02382             KoTextStringChar & ch = s->at(i);
02383             int pixelx =  textDocument()->formattingZoomHandler()->layoutUnitToPixelX( ch.x )
02384                           + ch.pixelxadj;
02385             if ( ch.lineStart )
02386                 kdDebug(32500) << "LINESTART" << endl;
02387             QString attrs = " ";
02388             if ( ch.whiteSpace )
02389                 attrs += "whitespace ";
02390             if ( !ch.charStop )
02391                 attrs += "notCharStop ";
02392             if ( ch.wordStop )
02393                 attrs += "wordStop ";
02394             attrs.truncate( attrs.length() - 1 );
02395 
02396             kdDebug(32500) << i << ": '" << QString(ch.c).rightJustify(2)
02397                            << "' (" << QString::number( ch.c.unicode() ).rightJustify(3) << ")"
02398                       << " x(LU)=" << ch.x
02399                       << " w(LU)=" << ch.width//s->width(i)
02400                       << " x(PIX)=" << pixelx
02401                       << " (xadj=" << + ch.pixelxadj << ")"
02402                       << " w(PIX)=" << ch.pixelwidth
02403                       << " height=" << ch.height()
02404                       << attrs
02405                 //      << " format=" << ch.format()
02406                 //      << " \"" << ch.format()->key() << "\" "
02407                 //<< " fontsize:" << dynamic_cast<KoTextFormat *>(ch.format())->pointSize()
02408                       << endl;
02409 
02410         // Check that the format is in the collection (i.e. its defaultFormat or in the dict)
02411         if ( ch.format() != textDocument()->formatCollection()->defaultFormat() )
02412                 Q_ASSERT( textDocument()->formatCollection()->dict()[ch.format()->key()] );
02413 
02414             if ( !str->isBidi() && !ch.lineStart )
02415                 Q_ASSERT( lastX + lastW == pixelx ); // looks like some rounding problem with justified spaces
02416             lastX = pixelx;
02417             lastW = ch.pixelwidth;
02418             if ( ch.isCustom() )
02419             {
02420                 KoTextCustomItem * item = ch.customItem();
02421                 kdDebug(32500) << " - custom item " << item
02422                           << " ownline=" << item->ownLine()
02423                           << " size=" << item->width << "x" << item->height
02424                           << " ascent=" << item->ascent()
02425                           << endl;
02426             }
02427         }
02428     }
02429 }
02430 #endif
02431 
02432 void KoTextParag::drawFontEffects( QPainter * p, KoTextFormat *format, KoTextZoomHandler *zh, QFont font, const QColor & color, int startX, int baseLine, int bw, int lastY, int /*h*/, QChar firstChar )
02433 {
02434     // This is about drawing underlines and strikeouts
02435     // So abort immediately if there's none to draw.
02436     if ( !format->isStrikedOrUnderlined() )
02437         return;
02438     //kdDebug(32500) << "drawFontEffects wordByWord=" << format->wordByWord() <<
02439     //    " firstChar='" << QString(firstChar) << "'" << endl;
02440     // paintLines ensures that we're called word by word if wordByWord is true.
02441     if ( format->wordByWord() && firstChar.isSpace() )
02442         return;
02443 
02444     double dimd;
02445     int y;
02446     int offset = 0;
02447     if (format->vAlign() == KoTextFormat::AlignSubScript )
02448         offset = p->fontMetrics().height() / 6;
02449     else if (format->vAlign() == KoTextFormat::AlignSuperScript )
02450         offset = -p->fontMetrics().height() / 2;
02451 
02452     dimd = KoBorder::zoomWidthY( format->underLineWidth(), zh, 1 );
02453     if((format->vAlign() == KoTextFormat::AlignSuperScript) ||
02454     (format->vAlign() == KoTextFormat::AlignSubScript ) || (format->vAlign() == KoTextFormat::AlignCustom ))
02455     dimd*=format->relativeTextSize();
02456     y = lastY + baseLine + offset - ( (format->vAlign() == KoTextFormat::AlignCustom)?format->offsetFromBaseLine():0 );
02457 
02458     if ( format->doubleUnderline())
02459     {
02460         QColor col = format->textUnderlineColor().isValid() ? format->textUnderlineColor(): color ;
02461     int dim=static_cast<int>(0.75*dimd);
02462     dim=dim?dim:1; //width of line should be at least 1
02463         p->save();
02464 
02465         switch( format->underlineStyle())
02466         {
02467         case KoTextFormat::U_SOLID:
02468             p->setPen( QPen( col, dim, Qt::SolidLine ) );
02469             break;
02470         case KoTextFormat::U_DASH:
02471             p->setPen( QPen( col, dim, Qt::DashLine ) );
02472             break;
02473         case KoTextFormat::U_DOT:
02474             p->setPen( QPen( col, dim, Qt::DotLine ) );
02475             break;
02476         case KoTextFormat::U_DASH_DOT:
02477             p->setPen( QPen( col, dim, Qt::DashDotLine ) );
02478             break;
02479         case KoTextFormat::U_DASH_DOT_DOT:
02480             p->setPen( QPen( col, dim, Qt::DashDotDotLine ) );
02481             break;
02482         default:
02483             p->setPen( QPen( color, dim, Qt::SolidLine ) );
02484         }
02485 
02486         y += static_cast<int>(1.125*dimd); // slightly under the baseline if possible
02487         p->drawLine( startX, y, startX + bw, y );
02488         y += static_cast<int>(1.5*dimd);
02489         p->drawLine( startX, y, startX + bw, y );
02490         p->restore();
02491         if ( font.underline() ) { // can this happen?
02492             font.setUnderline( FALSE );
02493             p->setFont( font );
02494         }
02495     }
02496     else if ( format->underline() ||
02497                 format->underlineType() == KoTextFormat::U_SIMPLE_BOLD)
02498     {
02499 
02500         QColor col = format->textUnderlineColor().isValid() ? format->textUnderlineColor(): color ;
02501         p->save();
02502     int dim=(format->underlineType() == KoTextFormat::U_SIMPLE_BOLD)?static_cast<int>(2*dimd):static_cast<int>(dimd);
02503     dim=dim?dim:1; //width of line should be at least 1
02504         y += static_cast<int>(1.875*dimd);
02505 
02506         switch( format->underlineStyle() )
02507         {
02508         case KoTextFormat::U_SOLID:
02509             p->setPen( QPen( col, dim, Qt::SolidLine ) );
02510             break;
02511         case KoTextFormat::U_DASH:
02512             p->setPen( QPen( col, dim, Qt::DashLine ) );
02513             break;
02514         case KoTextFormat::U_DOT:
02515             p->setPen( QPen( col, dim, Qt::DotLine ) );
02516             break;
02517         case KoTextFormat::U_DASH_DOT:
02518             p->setPen( QPen( col, dim, Qt::DashDotLine ) );
02519             break;
02520         case KoTextFormat::U_DASH_DOT_DOT:
02521             p->setPen( QPen( col, dim, Qt::DashDotDotLine ) );
02522             break;
02523         default:
02524             p->setPen( QPen( col, dim, Qt::SolidLine ) );
02525         }
02526 
02527         p->drawLine( startX, y, startX + bw, y );
02528         p->restore();
02529         font.setUnderline( FALSE );
02530         p->setFont( font );
02531     }
02532     else if ( format->waveUnderline() )
02533     {
02534     int dim=static_cast<int>(dimd);
02535     dim=dim?dim:1; //width of line should be at least 1
02536         y += dim;
02537         QColor col = format->textUnderlineColor().isValid() ? format->textUnderlineColor(): color ;
02538         p->save();
02539     int offset = 2 * dim;
02540     QPen pen(col, dim, Qt::SolidLine);
02541     pen.setCapStyle(Qt::RoundCap);
02542     p->setPen(pen);
02543     Q_ASSERT(offset);
02544     double anc=acos(1.0-2*(static_cast<double>(offset-(startX)%offset)/static_cast<double>(offset)))/3.1415*180;
02545     int pos=1;
02546     //set starting position
02547     if(2*((startX/offset)/2)==startX/offset)
02548         pos*=-1;
02549     //draw first part of wave
02550     p->drawArc( (startX/offset)*offset, y, offset, offset, 0, -qRound(pos*anc*16) );
02551         //now the main part
02552     int zigzag_x = (startX/offset+1)*offset;
02553     for ( ; zigzag_x + offset <= bw+startX; zigzag_x += offset)
02554         {
02555         p->drawArc( zigzag_x, y, offset, offset, 0, pos*180*16 );
02556         pos*=-1;
02557         }
02558     //and here we finish
02559     anc=acos(1.0-2*(static_cast<double>((startX+bw)%offset)/static_cast<double>(offset)))/3.1415*180;
02560     p->drawArc( zigzag_x, y, offset, offset, 180*16, -qRound(pos*anc*16) );
02561     p->restore();
02562         font.setUnderline( FALSE );
02563         p->setFont( font );
02564     }
02565 
02566     dimd = KoBorder::zoomWidthY( static_cast<double>(format->pointSize())/18.0, zh, 1 );
02567     if((format->vAlign() == KoTextFormat::AlignSuperScript) ||
02568     (format->vAlign() == KoTextFormat::AlignSubScript ) || (format->vAlign() == KoTextFormat::AlignCustom ))
02569     dimd*=format->relativeTextSize();
02570     y = lastY + baseLine + offset - ( (format->vAlign() == KoTextFormat::AlignCustom)?format->offsetFromBaseLine():0 );
02571 
02572     if ( format->strikeOutType() == KoTextFormat::S_SIMPLE
02573          || format->strikeOutType() == KoTextFormat::S_SIMPLE_BOLD)
02574     {
02575         unsigned int dim = (format->strikeOutType() == KoTextFormat::S_SIMPLE_BOLD)? static_cast<int>(2*dimd) : static_cast<int>(dimd);
02576         p->save();
02577 
02578         switch( format->strikeOutStyle() )
02579         {
02580         case KoTextFormat::S_SOLID:
02581             p->setPen( QPen( color, dim, Qt::SolidLine ) );
02582             break;
02583         case KoTextFormat::S_DASH:
02584             p->setPen( QPen( color, dim, Qt::DashLine ) );
02585             break;
02586         case KoTextFormat::S_DOT:
02587             p->setPen( QPen( color, dim, Qt::DotLine ) );
02588             break;
02589         case KoTextFormat::S_DASH_DOT:
02590             p->setPen( QPen( color, dim, Qt::DashDotLine ) );
02591             break;
02592         case KoTextFormat::S_DASH_DOT_DOT:
02593             p->setPen( QPen( color, dim, Qt::DashDotDotLine ) );
02594             break;
02595         default:
02596             p->setPen( QPen( color, dim, Qt::SolidLine ) );
02597         }
02598 
02599         y -= static_cast<int>(5*dimd);
02600         p->drawLine( startX, y, startX + bw, y );
02601         p->restore();
02602         font.setStrikeOut( FALSE );
02603         p->setFont( font );
02604     }
02605     else if ( format->strikeOutType() == KoTextFormat::S_DOUBLE )
02606     {
02607         unsigned int dim = static_cast<int>(dimd);
02608         p->save();
02609 
02610         switch( format->strikeOutStyle() )
02611         {
02612         case KoTextFormat::S_SOLID:
02613             p->setPen( QPen( color, dim, Qt::SolidLine ) );
02614             break;
02615         case KoTextFormat::S_DASH:
02616             p->setPen( QPen( color, dim, Qt::DashLine ) );
02617             break;
02618         case KoTextFormat::S_DOT:
02619             p->setPen( QPen( color, dim, Qt::DotLine ) );
02620             break;
02621         case KoTextFormat::S_DASH_DOT:
02622             p->setPen( QPen( color, dim, Qt::DashDotLine ) );
02623             break;
02624         case KoTextFormat::S_DASH_DOT_DOT:
02625             p->setPen( QPen( color, dim, Qt::DashDotDotLine ) );
02626             break;
02627         default:
02628             p->setPen( QPen( color, dim, Qt::SolidLine ) );
02629         }
02630 
02631     y -= static_cast<int>(4*dimd);
02632         p->drawLine( startX, y, startX + bw, y);
02633     y -= static_cast<int>(2*dimd);
02634         p->drawLine( startX, y, startX + bw, y);
02635         p->restore();
02636         font.setStrikeOut( FALSE );
02637         p->setFont( font );
02638     }
02639 
02640 }
02641 
02642 // ### is this method correct for RTL text?
02643 QString KoTextParag::toString( int from, int length ) const
02644 {
02645     QString str;
02646     if ( from == 0 && m_layout.counter && m_layout.counter->numbering() != KoParagCounter::NUM_FOOTNOTE )
02647         str += m_layout.counter->text( this ) + ' ';
02648     if ( length == -1 )
02649         length = this->length() - 1 /*trailing space*/ - from;
02650     for ( int i = from ; i < (length+from) ; ++i )
02651     {
02652         KoTextStringChar *ch = at( i );
02653         if ( ch->isCustom() )
02654         {
02655             KoVariable * var = dynamic_cast<KoVariable *>(ch->customItem());
02656             if ( var )
02657                 str += var->text(true);
02658             else //frame inline
02659                 str +=' ';
02660         }
02661         else
02662             str += ch->c;
02663     }
02664     return str;
02665 }
02666 
02667 void KoTextParag::loadOasisSpan( const QDomElement& parent, KoOasisContext& context, uint& pos )
02668 {
02669     // Parse every child node of the parent
02670     // Can't use forEachElement here since we also care about text nodes
02671     QDomNode node;
02672     for ( node = parent.firstChild(); !node.isNull(); node = node.nextSibling() )
02673     {
02674         QDomElement ts = node.toElement();
02675         QString textData;
02676         const QString localName( ts.localName() );
02677         const bool isTextNS = ts.namespaceURI() == KoXmlNS::text;
02678         KoTextCustomItem* customItem = 0;
02679 
02680         // allow loadSpanTag to modify the stylestack
02681         context.styleStack().save();
02682 
02683         // Try to keep the order of the tag names by probability of happening
02684         if ( node.isText() )
02685         {
02686             textData = node.toText().data();
02687         }
02688         else if ( isTextNS && localName == "span" ) // text:span
02689         {
02690             context.styleStack().save();
02691             context.fillStyleStack( ts, KoXmlNS::text, "style-name", "text" );
02692             loadOasisSpan( ts, context, pos ); // recurse
02693             context.styleStack().restore();
02694         }
02695         else if ( isTextNS && localName == "s" ) // text:s
02696         {
02697             int howmany = 1;
02698             if (ts.hasAttributeNS( KoXmlNS::text, "c"))
02699                 howmany = ts.attributeNS( KoXmlNS::text, "c", QString::null).toInt();
02700 
02701             textData.fill(32, howmany);
02702         }
02703         else if ( isTextNS && localName == "tab" ) // text:tab (it's tab-stop in OO-1.1 but tab in oasis)
02704         {
02705             textData = '\t';
02706         }
02707         else if ( isTextNS && localName == "line-break" ) // text:line-break
02708         {
02709             textData = '\n';
02710         }
02711         else if ( isTextNS && localName == "number" ) // text:number
02712         {
02713             // This is the number in front of a numbered paragraph,
02714             // written out to help export filters. We can ignore it.
02715         }
02716         else if ( node.isProcessingInstruction() )
02717         {
02718             QDomProcessingInstruction pi = node.toProcessingInstruction();
02719             if ( pi.target() == "opendocument" && pi.data().startsWith( "cursor-position" ) )
02720             {
02721                 context.setCursorPosition( this, pos );
02722             }
02723         }
02724         else
02725         {
02726             bool handled = false;
02727             // Check if it's a variable
02728             KoVariable* var = context.variableCollection().loadOasisField( textDocument(), ts, context );
02729             if ( var )
02730             {
02731                 textData = "#";     // field placeholder
02732                 customItem = var;
02733                 handled = true;
02734             }
02735             if ( !handled )
02736             {
02737                 handled = textDocument()->loadSpanTag( ts, context,
02738                                                        this, pos,
02739                                                        textData, customItem );
02740                 if ( !handled )
02741                 {
02742                     kdWarning(32500) << "Ignoring tag " << ts.tagName() << endl;
02743                     context.styleStack().restore();
02744                     continue;
02745                 }
02746             }
02747         }
02748 
02749         const uint length = textData.length();
02750         if ( length )
02751         {
02752             insert( pos, textData );
02753             if ( customItem )
02754                 setCustomItem( pos, customItem, 0 );
02755             KoTextFormat f;
02756             f.load( context );
02757             //kdDebug(32500) << "loadOasisSpan: applying formatting from " << pos << " to " << pos+length << "\n   format=" << f.key() << endl;
02758             setFormat( pos, length, document()->formatCollection()->format( &f ), TRUE );
02759             pos += length;
02760         }
02761         context.styleStack().restore();
02762     }
02763 }
02764 
02765 KoParagLayout KoTextParag::loadParagLayout( KoOasisContext& context, KoStyleCollection *styleCollection, bool findStyle )
02766 {
02767     KoParagLayout layout;
02768 
02769     // Only when loading paragraphs, not when loading styles
02770     if ( findStyle )
02771     {
02772         KoParagStyle *style;
02773         // Name of the style. If there is no style, then we do not supply
02774         // any default!
02775         QString styleName = context.styleStack().userStyleName( "paragraph" );
02776         if ( !styleName.isEmpty() )
02777         {
02778             style = styleCollection->findStyle( styleName );
02779             // When pasting the style names are random, the display names matter
02780             if (!style)
02781                 style = styleCollection->findStyleByDisplayName( context.styleStack().userStyleDisplayName( "paragraph" ) );
02782             if (!style)
02783             {
02784                 kdError(32500) << "Cannot find style \"" << styleName << "\" - using Standard" << endl;
02785                 style = styleCollection->findStyle( "Standard" );
02786             }
02787             //else kdDebug() << "KoParagLayout::KoParagLayout setting style to " << style << " " << style->name() << endl;
02788         }
02789         else
02790         {
02791             kdError(32500) << "No style name !? - using Standard" << endl;
02792             style = styleCollection->findStyle( "Standard" );
02793         }
02794         Q_ASSERT(style);
02795         layout.style = style;
02796     }
02797 
02798     KoParagLayout::loadOasisParagLayout( layout, context );
02799 
02800     return layout;
02801 }
02802 
02803 void KoTextParag::loadOasis( const QDomElement& parent, KoOasisContext& context, KoStyleCollection *styleCollection, uint& pos )
02804 {
02805     // First load layout from style
02806     KoParagLayout paragLayout = loadParagLayout( context, styleCollection, true );
02807     setParagLayout( paragLayout );
02808 
02809     // Load paragraph format
02810     KoTextFormat defaultFormat;
02811     defaultFormat.load( context );
02812     setFormat( document()->formatCollection()->format( &defaultFormat ) );
02813 
02814     // Load text
02815     loadOasisSpan( parent, context, pos );
02816 
02817     // Apply default format to trailing space
02818     const int len = str->length();
02819     Q_ASSERT( len >= 1 );
02820     setFormat( len - 1, 1, paragFormat(), TRUE );
02821 
02822     setChanged( true );
02823     invalidate( 0 );
02824 }
02825 
02826 void KoTextParag::saveOasis( KoXmlWriter& writer, KoSavingContext& context,
02827                              int from /* default 0 */, int to /* usually length()-2 */,
02828                              bool /*saveAnchorsFramesets*/ /* default false */ ) const
02829 {
02830     KoGenStyles& mainStyles = context.mainStyles();
02831 
02832     // Write paraglayout to styles (with parent == the parag's style)
02833     QString parentStyleName;
02834     if ( m_layout.style )
02835         parentStyleName = m_layout.style->name();
02836 
02837     KoGenStyle autoStyle( KoGenStyle::STYLE_AUTO, "paragraph", parentStyleName );
02838     paragFormat()->save( autoStyle, context );
02839     m_layout.saveOasis( autoStyle, context, false );
02840 
02841     // First paragraph is special, it includes page-layout info (for word-processing at least)
02842     if ( !prev() ) {
02843         if ( context.variableSettings() )
02844             autoStyle.addProperty( "style:page-number", context.variableSettings()->startingPageNumber() );
02845         // Well we support only one page layout, so the first parag always points to "Standard".
02846         autoStyle.addAttribute( "style:master-page-name", "Standard" );
02847     }
02848 
02849 
02850     QString autoParagStyleName = mainStyles.lookup( autoStyle, "P", KoGenStyles::ForceNumbering );
02851 
02852     KoParagCounter* paragCounter = m_layout.counter;
02853     // outline (text:h) assumes paragCounter != 0 (because depth is mandatory)
02854     bool outline = m_layout.style && m_layout.style->isOutline() && paragCounter;
02855     bool normalList = paragCounter && paragCounter->style() != KoParagCounter::STYLE_NONE && !outline;
02856     if ( normalList ) // non-heading list
02857     {
02858         writer.startElement( "text:numbered-paragraph" );
02859         writer.addAttribute( "text:level", (int)paragCounter->depth() + 1 );
02860         if ( paragCounter->restartCounter() )
02861             writer.addAttribute( "text:start-value", paragCounter->startNumber() );
02862 
02863         KoGenStyle listStyle( KoGenStyle::STYLE_AUTO_LIST /*, no family*/ );
02864         paragCounter->saveOasis( listStyle );
02865 
02866         QString autoListStyleName = mainStyles.lookup( listStyle, "L", KoGenStyles::ForceNumbering );
02867         writer.addAttribute( "text:style-name", autoListStyleName );
02868 
02869         QString textNumber = m_layout.counter->text( this );
02870         if ( !textNumber.isEmpty() )
02871         {
02872             // This is to help export filters
02873             writer.startElement( "text:number" );
02874             writer.addTextNode( textNumber );
02875             writer.endElement();
02876         }
02877     }
02878     else if ( outline ) // heading
02879     {
02880         writer.startElement( "text:h", false /*no indent inside this tag*/ );
02881         writer.addAttribute( "text:style-name", autoParagStyleName );
02882         writer.addAttribute( "text:outline-level", (int)paragCounter->depth() + 1 );
02883         if ( paragCounter->numbering() == KoParagCounter::NUM_NONE )
02884             writer.addAttribute( "text:is-list-header", "true" );
02885 
02886         QString textNumber = paragCounter->text( this );
02887         if ( !textNumber.isEmpty() )
02888         {
02889             // This is to help export filters
02890             writer.startElement( "text:number" );
02891             writer.addTextNode( textNumber );
02892             writer.endElement();
02893         }
02894     }
02895 
02896     if ( !outline ) // normal (non-numbered) paragraph, or normalList
02897     {
02898         writer.startElement( "text:p", false /*no indent inside this tag*/ );
02899         writer.addAttribute( "text:style-name", autoParagStyleName );
02900     }
02901 
02902     QString text = str->toString();
02903     Q_ASSERT( text.right(1)[0] == ' ' );
02904 
02905     const int cursorIndex = context.cursorTextParagraph() == this ? context.cursorTextIndex() : -1;
02906 
02907     //kdDebug() << k_funcinfo << "'" << text << "' from=" << from << " to=" << to << " cursorIndex=" << cursorIndex << endl;
02908 
02909     // A helper method would need no less than 7 params...
02910 #define WRITESPAN( next ) { \
02911         if ( curFormat == paragFormat() ) {                             \
02912             writer.addTextSpan( text.mid( startPos, next - startPos ), m_tabCache ); \
02913         } else {                                                        \
02914             KoGenStyle gs( KoGenStyle::STYLE_AUTO, "text" );            \
02915             curFormat->save( gs, context, paragFormat() );              \
02916             writer.startElement( "text:span" );                         \
02917             if ( !gs.isEmpty() ) {                                      \
02918                 const QString autoStyleName = mainStyles.lookup( gs, "T" ); \
02919                 writer.addAttribute( "text:style-name", autoStyleName );    \
02920             }                                                           \
02921             writer.addTextSpan( text.mid( startPos, next - startPos ), m_tabCache ); \
02922             writer.endElement();                                        \
02923         }                                                               \
02924     }
02925 #define ISSTARTBOOKMARK( i ) bkStartIter != bookmarkStarts.end() && (*bkStartIter).pos == i
02926 #define ISENDBOOKMARK( i ) bkEndIter != bookmarkEnds.end() && (*bkEndIter).pos == i
02927 #define CHECKPOS( i ) \
02928         if ( cursorIndex == i ) { \
02929             writer.addProcessingInstruction( "opendocument cursor-position" ); \
02930         } \
02931         if ( ISSTARTBOOKMARK( i ) ) { \
02932             if ( (*bkStartIter).startEqualsEnd ) \
02933                 writer.startElement( "text:bookmark" ); \
02934             else \
02935                 writer.startElement( "text:bookmark-start" ); \
02936             writer.addAttribute( "text:name", (*bkStartIter).name ); \
02937             writer.endElement(); \
02938             ++bkStartIter; \
02939         } \
02940         if ( ISENDBOOKMARK( i ) ) { \
02941             writer.startElement( "text:bookmark-end" ); \
02942             writer.addAttribute( "text:name", (*bkEndIter).name ); \
02943             writer.endElement(); \
02944             ++bkEndIter; \
02945         }
02946 
02947 
02948 
02949     // Make (shallow) copy of bookmark list, since saving an inline frame might overwrite it
02950     // from the context while we're saving this paragraph.
02951     typedef KoSavingContext::BookmarkPositions BookmarkPositions;
02952     BookmarkPositions bookmarkStarts = context.bookmarkStarts();
02953     BookmarkPositions::const_iterator bkStartIter = bookmarkStarts.begin();
02954     while ( bkStartIter != bookmarkStarts.end() && (*bkStartIter).pos < from )
02955         ++bkStartIter;
02956     //int nextBookmarkStart = bkStartIter == bookmarkStarts.end() ? -1 : (*bkStartIter).pos;
02957     BookmarkPositions bookmarkEnds = context.bookmarkEnds();
02958     BookmarkPositions::const_iterator bkEndIter = bookmarkEnds.begin();
02959     while ( bkEndIter != bookmarkEnds.end() && (*bkEndIter).pos < from )
02960         ++bkEndIter;
02961 
02962     KoTextFormat *curFormat = 0;
02963     KoTextFormat *lastFormatRaw = 0; // this is for speeding up "removing misspelled" from each char
02964     KoTextFormat *lastFormatFixed = 0; // raw = as stored in the chars; fixed = after removing misspelled
02965     int startPos = from;
02966     for ( int i = from; i <= to; ++i ) {
02967         KoTextStringChar & ch = str->at(i);
02968         KoTextFormat * newFormat = static_cast<KoTextFormat *>( ch.format() );
02969         if ( newFormat->isMisspelled() ) {
02970             if ( newFormat == lastFormatRaw )
02971                 newFormat = lastFormatFixed; // the fast way
02972             else
02973             {
02974                 lastFormatRaw = newFormat;
02975                 // Remove isMisspelled from format, to avoid useless derived styles
02976                 // (which would be indentical to their parent style)
02977                 KoTextFormat tmpFormat( *newFormat );
02978                 tmpFormat.setMisspelled( false );
02979                 newFormat = formatCollection()->format( &tmpFormat );
02980                 lastFormatFixed = newFormat;
02981             }
02982         }
02983         if ( !curFormat )
02984             curFormat = newFormat;
02985         if ( newFormat != curFormat  // Format changed, save previous one.
02986              || ch.isCustom() || cursorIndex == i || ISSTARTBOOKMARK( i ) || ISENDBOOKMARK( i ) )
02987         {
02988             WRITESPAN( i ) // write text up to i-1
02989             startPos = i;
02990             curFormat = newFormat;
02991         }
02992         CHECKPOS( i ) // do cursor position and bookmarks
02993         if ( ch.isCustom() ) {
02994             KoGenStyle gs( KoGenStyle::STYLE_AUTO, "text" );
02995             curFormat->save( gs, context, paragFormat() );
02996             writer.startElement( "text:span" );
02997             if ( !gs.isEmpty() ) {
02998                 const QString autoStyleName = mainStyles.lookup( gs, "T" );
02999                 writer.addAttribute( "text:style-name", autoStyleName );
03000             }
03001             KoTextCustomItem* customItem = ch.customItem();
03002             customItem->saveOasis( writer, context );
03003             writer.endElement();
03004             startPos = i + 1;
03005         }
03006     }
03007 
03008     //kdDebug() << k_funcinfo << "startPos=" << startPos << " to=" << to << " curFormat=" << curFormat << endl;
03009 
03010     if ( to >= startPos ) { // Save last format
03011         WRITESPAN( to + 1 )
03012     }
03013     CHECKPOS( to + 1 ) // do cursor position and bookmarks
03014 
03015     writer.endElement(); // text:p or text:h
03016     if ( normalList )
03017         writer.endElement(); // text:numbered-paragraph (englobing a text:p)
03018 }
03019 
03020 void KoTextParag::applyListStyle( KoOasisContext& context, int restartNumbering, bool orderedList, bool heading, int level )
03021 {
03022     //kdDebug(32500) << k_funcinfo << "applyListStyle to parag " << this << " heading=" << heading << endl;
03023     delete m_layout.counter;
03024     m_layout.counter = new KoParagCounter;
03025     m_layout.counter->loadOasis( context, restartNumbering, orderedList, heading, level );
03026     // We emulate space-before with a left paragraph indent (#109223)
03027     const QDomElement listStyleProperties = context.listStyleStack().currentListStyleProperties();
03028     if ( listStyleProperties.hasAttributeNS( KoXmlNS::text, "space-before" ) )
03029     {
03030         double spaceBefore = KoUnit::parseValue( listStyleProperties.attributeNS( KoXmlNS::text, "space-before", QString::null ) );
03031         m_layout.margins[ QStyleSheetItem::MarginLeft ] += spaceBefore; // added to left-margin, see 15.12 in spec.
03032     }
03033     // need to call invalidateCounters() ? Not during the initial loading at least.
03034 }
03035 
03036 int KoTextParag::documentWidth() const
03037 {
03038     return doc ? doc->width() : 0; //docRect.width();
03039 }
03040 
03041 //int KoTextParag::documentVisibleWidth() const
03042 //{
03043 //    return doc ? doc->visibleWidth() : 0; //docRect.width();
03044 //}
03045 
03046 int KoTextParag::documentX() const
03047 {
03048     return doc ? doc->x() : 0; //docRect.x();
03049 }
03050 
03051 int KoTextParag::documentY() const
03052 {
03053     return doc ? doc->y() : 0; //docRect.y();
03054 }
03055 
03056 void KoTextParag::fixParagWidth( bool viewFormattingChars )
03057 {
03058     // Fixing the parag rect for the formatting chars (only CR here, KWord handles framebreak).
03059     if ( viewFormattingChars && lineStartList().count() == 1 ) // don't use lines() here, parag not formatted yet
03060     {
03061         KoTextFormat * lastFormat = at( length() - 1 )->format();
03062         setWidth( QMIN( rect().width() + lastFormat->width('x'), doc->width() ) );
03063     }
03064     // Warning, if adding anything else here, adjust KWTextFrameSet::fixParagWidth
03065 }
03066 
03067 // Called by KoTextParag::drawParagString - all params are in pixel coordinates
03068 void KoTextParag::drawFormattingChars( QPainter &painter, int start, int len,
03069                                        int lastY_pix, int baseLine_pix, int h_pix, // in pixels
03070                                        bool /*drawSelections*/,
03071                                        KoTextFormat * /*lastFormat*/, const QMemArray<int> &/*selectionStarts*/,
03072                                        const QMemArray<int> &/*selectionEnds*/, const QColorGroup & /*cg*/,
03073                                        bool rightToLeft, int /*line*/, KoTextZoomHandler* zh,
03074                                        int whichFormattingChars )
03075 {
03076     if ( !whichFormattingChars )
03077         return;
03078     painter.save();
03079     //QPen pen( cg.color( QColorGroup::Highlight ) );
03080     QPen pen( KGlobalSettings::linkColor() ); // #101820
03081     painter.setPen( pen );
03082     //kdDebug() << "KWTextParag::drawFormattingChars start=" << start << " len=" << len << " length=" << length() << endl;
03083     if ( start + len == length() && ( whichFormattingChars & FormattingEndParag ) )
03084     {
03085         // drawing the end of the parag
03086         KoTextStringChar &ch = str->at( length() - 1 );
03087         KoTextFormat* format = static_cast<KoTextFormat *>( ch.format() );
03088         int w = format->charWidth( zh, true, &ch, this, 'X' );
03089         int size = QMIN( w, h_pix * 3 / 4 );
03090         // x,y is the bottom right corner of the
03091         //kdDebug() << "startX=" << startX << " bw=" << bw << " w=" << w << endl;
03092         int x;
03093         if ( rightToLeft )
03094             x = zh->layoutUnitToPixelX( ch.x ) /*+ ch.pixelxadj*/ + ch.pixelwidth - 1;
03095         else
03096             x = zh->layoutUnitToPixelX( ch.x ) /*+ ch.pixelxadj*/ + w;
03097         int y = lastY_pix + baseLine_pix;
03098         //kdDebug() << "KWTextParag::drawFormattingChars drawing CR at " << x << "," << y << endl;
03099         painter.drawLine( (int)(x - size * 0.2), y - size, (int)(x - size * 0.2), y );
03100         painter.drawLine( (int)(x - size * 0.5), y - size, (int)(x - size * 0.5), y );
03101         painter.drawLine( x, y, (int)(x - size * 0.7), y );
03102         painter.drawLine( x, y - size, (int)(x - size * 0.5), y - size);
03103         painter.drawArc( x - size, y - size, size, (int)(size / 2), -90*16, -180*16 );
03104 #ifdef DEBUG_FORMATTING
03105         painter.setPen( Qt::blue );
03106         painter.drawRect( zh->layoutUnitToPixelX( ch.x ) /*+ ch.pixelxadj*/ - 1, lastY_pix, ch.pixelwidth, baseLine_pix );
03107         QPen pen( cg.color( QColorGroup::Highlight ) );
03108         painter.setPen( pen );
03109 #endif
03110     }
03111 
03112     // Now draw spaces, tabs and newlines
03113     if ( (whichFormattingChars & FormattingSpace) ||
03114          (whichFormattingChars & FormattingTabs) ||
03115          (whichFormattingChars & FormattingBreak) )
03116     {
03117         int end = QMIN( start + len, length() - 1 ); // don't look at the trailing space
03118         for ( int i = start ; i < end ; ++i )
03119         {
03120             KoTextStringChar &ch = str->at(i);
03121 #ifdef DEBUG_FORMATTING
03122             painter.setPen( (i % 2)? Qt::red: Qt::green );
03123             painter.drawRect( zh->layoutUnitToPixelX( ch.x ) /*+ ch.pixelxadj*/ - 1, lastY_pix, ch.pixelwidth, baseLine_pix );
03124             QPen pen( cg.color( QColorGroup::Highlight ) );
03125             painter.setPen( pen );
03126 #endif
03127             if ( ch.isCustom() )
03128                 continue;
03129             if ( (ch.c == ' ' || ch.c.unicode() == 0x00a0U)
03130                  && (whichFormattingChars & FormattingSpace))
03131             {
03132                 // Don't use ch.pixelwidth here. We want a square with
03133                 // the same size for all spaces, even the justified ones
03134                 int w = zh->layoutUnitToPixelX( ch.format()->width( ' ' ) );
03135                 int height = zh->layoutUnitToPixelY( ch.ascent() );
03136                 int size = QMAX( 2, QMIN( w/2, height/3 ) ); // Enfore that it's a square, and that it's visible
03137                 int x = zh->layoutUnitToPixelX( ch.x ); // + ch.pixelxadj;
03138                 QRect spcRect( x + (ch.pixelwidth - size) / 2, lastY_pix + baseLine_pix - (height - size) / 2, size, size );
03139                 if ( ch.c == ' ' )
03140                     painter.drawRect( spcRect );
03141                 else // nbsp
03142                     painter.fillRect( spcRect, pen.color() );
03143             }
03144             else if ( ch.c == '\t' && (whichFormattingChars & FormattingTabs) )
03145             {
03146                 /*KoTextStringChar &nextch = str->at(i+1);
03147                   int nextx = (nextch.x > ch.x) ? nextch.x : rect().width();
03148                   //kdDebug() << "tab x=" << ch.x << " nextch.x=" << nextch.x
03149                   //          << " nextx=" << nextx << " startX=" << startX << " bw=" << bw << endl;
03150                   int availWidth = nextx - ch.x - 1;
03151                   availWidth=zh->layoutUnitToPixelX(availWidth);*/
03152 
03153                 int availWidth = ch.pixelwidth;
03154 
03155                 KoTextFormat* format = ch.format();
03156                 int x = zh->layoutUnitToPixelX( ch.x ) /*+ ch.pixelxadj*/ + availWidth / 2;
03157                 int charWidth = format->screenFontMetrics( zh ).width( 'W' );
03158                 int size = QMIN( availWidth, charWidth ) / 2 ; // actually the half size
03159                 int y = lastY_pix + baseLine_pix - zh->layoutUnitToPixelY( ch.ascent()/2 );
03160                 int arrowsize = zh->zoomItY( 2 );
03161                 painter.drawLine( x - size, y, x + size, y );
03162                 if ( rightToLeft )
03163                 {
03164                     painter.drawLine( x - size, y, x - size + arrowsize, y - arrowsize );
03165                     painter.drawLine( x - size, y, x - size + arrowsize, y + arrowsize );
03166                 }
03167                 else
03168                 {
03169                     painter.drawLine( x + size, y, x + size - arrowsize, y - arrowsize );
03170                     painter.drawLine( x + size, y, x + size - arrowsize, y + arrowsize );
03171                 }
03172             }
03173             else if ( ch.c == '\n' && (whichFormattingChars & FormattingBreak) )
03174             {
03175                 // draw line break
03176                 KoTextFormat* format = static_cast<KoTextFormat *>( ch.format() );
03177                 int w = format->charWidth( zh, true, &ch, this, 'X' );
03178                 int size = QMIN( w, h_pix * 3 / 4 );
03179                 int arrowsize = zh->zoomItY( 2 );
03180                 // x,y is the bottom right corner of the reversed L
03181                 //kdDebug() << "startX=" << startX << " bw=" << bw << " w=" << w << endl;
03182                 int y = lastY_pix + baseLine_pix - arrowsize;
03183                 //kdDebug() << "KWTextParag::drawFormattingChars drawing Line Break at " << x << "," << y << endl;
03184                 if ( rightToLeft )
03185                 {
03186                     int x = zh->layoutUnitToPixelX( ch.x ) /*+ ch.pixelxadj*/ + ch.pixelwidth - 1;
03187                     painter.drawLine( x - size, y - size, x - size, y );
03188                     painter.drawLine( x - size, y, (int)(x - size * 0.3), y );
03189                     // Now the arrow
03190                     painter.drawLine( (int)(x - size * 0.3), y, (int)(x - size * 0.3 - arrowsize), y - arrowsize );
03191                     painter.drawLine( (int)(x - size * 0.3), y, (int)(x - size * 0.3 - arrowsize), y + arrowsize );
03192                 }
03193                 else
03194                 {
03195                     int x = zh->layoutUnitToPixelX( ch.x ) /*+ ch.pixelxadj*/ + w - 1;
03196                     painter.drawLine( x, y - size, x, y );
03197                     painter.drawLine( x, y, (int)(x - size * 0.7), y );
03198                     // Now the arrow
03199                     painter.drawLine( (int)(x - size * 0.7), y, (int)(x - size * 0.7 + arrowsize), y - arrowsize );
03200                     painter.drawLine( (int)(x - size * 0.7), y, (int)(x - size * 0.7 + arrowsize), y + arrowsize );
03201                 }
03202             }
03203         }
03204         painter.restore();
03205     }
03206 }
03207 
03208 int KoTextParag::heightForLineSpacing( int startChar, int lastChar ) const
03209 {
03210     int h = 0;
03211     int end = QMIN( lastChar, length() - 1 ); // don't look at the trailing space
03212     for( int i = startChar; i <= end; ++i )
03213     {
03214         const KoTextStringChar &chr = str->at( i );
03215         if ( !chr.isCustom() )
03216             h = QMAX( h, chr.format()->height() );
03217     }
03218     return h;
03219 }
KDE Home | KDE Accessibility Home | Description of Access Keys