render_text.cpp 29.9 KB
Newer Older
kocienda's avatar
kocienda committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/**
 * This file is part of the DOM implementation for KDE.
 *
 * (C) 1999 Lars Knoll (knoll@kde.org)
 * (C) 2000 Dirk Mueller (mueller@kde.org)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 */
//#define DEBUG_LAYOUT
//#define BIDI_DEBUG

26 27 28
#include "rendering/render_text.h"
#include "rendering/break_lines.h"
#include "xml/dom_nodeimpl.h"
kocienda's avatar
kocienda committed
29 30 31 32 33

#include "misc/loader.h"

#include <qpainter.h>
#include <kdebug.h>
34
#include <assert.h>
kocienda's avatar
kocienda committed
35 36 37 38

using namespace khtml;
using namespace DOM;

darin's avatar
darin committed
39
void TextSlave::printSelection(const Font *f, RenderText *text, QPainter *p, RenderStyle* style, int tx, int ty, int startPos, int endPos)
kocienda's avatar
kocienda committed
40 41 42 43 44 45 46 47 48 49 50
{
    if(startPos > m_len) return;
    if(startPos < 0) startPos = 0;

    p->save();
    QColor c = style->color();
    p->setPen(QColor(0xff-c.red(),0xff-c.green(),0xff-c.blue()));

    ty += m_baseline;

    //kdDebug( 6040 ) << "textSlave::printing(" << s.string() << ") at(" << x+_tx << "/" << y+_ty << ")" << endl;
darin's avatar
darin committed
51 52
    f->drawText(p, m_x + tx, m_y + ty, text->str->s, text->str->l, m_start, m_len,
		m_toAdd, m_reversed ? QPainter::RTL : QPainter::LTR, startPos, endPos, c);
kocienda's avatar
kocienda committed
53 54 55 56 57 58 59 60
    p->restore();
}

void TextSlave::printDecoration( QPainter *pt, RenderText* p, int _tx, int _ty, int deco, bool begin, bool end)
{
    _tx += m_x;
    _ty += m_y;

61
    int width = m_width - 1;
kocienda's avatar
kocienda committed
62 63

    if( begin )
64
 	width -= p->paddingLeft() + p->borderLeft();
kocienda's avatar
kocienda committed
65 66 67 68

    if ( end )
        width -= p->paddingRight() + p->borderRight();

69
#ifdef APPLE_CHANGES
darin's avatar
darin committed
70 71 72 73
    if(deco & UNDERLINE) {
        QConstString s(p->str->s + m_start, m_len);
        pt->drawUnderlineForText(_tx, _ty + m_baseline, s.string());
    }
74
#else
kocienda's avatar
kocienda committed
75 76
    int underlineOffset = ( pt->fontMetrics().height() + m_baseline ) / 2;
    if(underlineOffset <= m_baseline) underlineOffset = m_baseline+1;
kocienda's avatar
kocienda committed
77

darin's avatar
darin committed
78
    if(deco & UNDERLINE){
79
        pt->drawLine(_tx, _ty + underlineOffset, _tx + width, _ty + underlineOffset );
darin's avatar
darin committed
80
    }
81
#endif
kocienda's avatar
kocienda committed
82 83 84 85 86 87 88 89 90 91 92 93
    if(deco & OVERLINE)
        pt->drawLine(_tx, _ty, _tx + width, _ty );
    if(deco & LINE_THROUGH)
        pt->drawLine(_tx, _ty + 2*m_baseline/3, _tx + width, _ty + 2*m_baseline/3 );
    // NO! Do NOT add BLINK! It is the most annouing feature of Netscape, and IE has a reason not to
    // support it. Lars
}

void TextSlave::printBoxDecorations(QPainter *pt, RenderStyle* style, RenderText *p, int _tx, int _ty, bool begin, bool end)
{
    int topExtra = p->borderTop() + p->paddingTop();
    int bottomExtra = p->borderBottom() + p->paddingBottom();
94 95
    // ### firstline
    int halfleading = (p->m_lineHeight - style->font().pixelSize() ) / 2;
kocienda's avatar
kocienda committed
96 97

    _tx += m_x;
98
    _ty += m_y + halfleading - topExtra;
kocienda's avatar
kocienda committed
99 100 101

    int width = m_width;

102 103
    // the height of the decorations is:  topBorder + topPadding + CSS font-size + bottomPadding + bottomBorder
    int height = style->font().pixelSize() + topExtra + bottomExtra;
kocienda's avatar
kocienda committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

    if( begin )
	_tx -= p->paddingLeft() + p->borderLeft();

    QColor c = style->backgroundColor();
    CachedImage *i = style->backgroundImage();
    if(c.isValid() && (!i || i->tiled_pixmap(c).mask()))
         pt->fillRect(_tx, _ty, width, height, c);

    if(i) {
        // ### might need to add some correct offsets
        // ### use paddingX/Y
        pt->drawTiledPixmap(_tx, _ty, width, height, i->tiled_pixmap(c));
    }

119 120
#ifdef DEBUG_VALIGN
    pt->fillRect(_tx, _ty, width, height, Qt::cyan );
kocienda's avatar
kocienda committed
121 122
#endif

123 124
    if(style->hasBorder())
        p->printBorder(pt, _tx, _ty, width, height, style, begin, end);
kocienda's avatar
kocienda committed
125 126
}

darin's avatar
darin committed
127
FindSelectionResult TextSlave::checkSelectionPoint(int _x, int _y, int _tx, int _ty, const Font *f, RenderText *text, int & offset, short lineHeight)
kocienda's avatar
kocienda committed
128
{
darin's avatar
darin committed
129 130
//     kdDebug(6040) << "TextSlave::checkSelectionPoint " << this << " _x=" << _x << " _y=" << _y
//                   << " _tx+m_x=" << _tx+m_x << " _ty+m_y=" << _ty+m_y << endl;
kocienda's avatar
kocienda committed
131 132 133 134 135
    offset = 0;

    if ( _y < _ty + m_y )
        return SelectionPointBefore; // above -> before

darin's avatar
darin committed
136 137
    if ( _y > _ty + m_y + lineHeight ) {
        // below -> after
kocienda's avatar
kocienda committed
138 139 140 141
        // Set the offset to the max
        offset = m_len;
        return SelectionPointAfter;
    }
darin's avatar
darin committed
142 143 144 145
    if ( _x > _tx + m_x + m_width ) {
	// to the right
	return m_reversed ? SelectionPointBeforeInLine : SelectionPointAfterInLine;
    }
kocienda's avatar
kocienda committed
146 147

    // The Y matches, check if we're on the left
darin's avatar
darin committed
148 149 150
    if ( _x < _tx + m_x ) {
        return m_reversed ? SelectionPointAfterInLine : SelectionPointBeforeInLine;
    }
kocienda's avatar
kocienda committed
151 152 153 154

    int delta = _x - (_tx + m_x);
    //kdDebug(6040) << "TextSlave::checkSelectionPoint delta=" << delta << endl;
    int pos = 0;
darin's avatar
darin committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    if ( m_reversed ) {
	delta -= m_width;
	while(pos < m_len) {
	    int w = f->width( text->str->s, text->str->l, m_start + pos);
	    int w2 = w/2;
	    w -= w2;
	    delta += w2;
	    if(delta >= 0) break;
	    pos++;
	    delta += w;
	}
    } else {
	while(pos < m_len) {
	    int w = f->width( text->str->s, text->str->l, m_start + pos);
	    int w2 = w/2;
	    w -= w2;
	    delta -= w2;
	    if(delta <= 0) break;
	    pos++;
	    delta -= w;
	}
kocienda's avatar
kocienda committed
176
    }
darin's avatar
darin committed
177
//     kdDebug( 6040 ) << " Text  --> inside at position " << pos << endl;
kocienda's avatar
kocienda committed
178 179 180 181 182 183 184 185 186 187 188 189 190
    offset = pos;
    return SelectionPointInside;
}

// -----------------------------------------------------------------------------

TextSlaveArray::TextSlaveArray()
{
    setAutoDelete(true);
}

int TextSlaveArray::compareItems( Item d1, Item d2 )
{
191 192
    assert(d1);
    assert(d2);
kocienda's avatar
kocienda committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

    return static_cast<TextSlave*>(d1)->m_y - static_cast<TextSlave*>(d2)->m_y;
}

// remove this once QVector::bsearch is fixed
int TextSlaveArray::findFirstMatching(Item d) const
{
    int len = count();

    if ( !len )
	return -1;
    if ( !d )
	return -1;
    int n1 = 0;
    int n2 = len - 1;
    int mid = 0;
    bool found = FALSE;
    while ( n1 <= n2 ) {
	int  res;
	mid = (n1 + n2)/2;
	if ( (*this)[mid] == 0 )			// null item greater
	    res = -1;
	else
216
	    res = ((QGVector*)this)->compareItems( d, (*this)[mid] );
kocienda's avatar
kocienda committed
217 218 219 220 221 222 223 224 225 226 227 228
	if ( res < 0 )
	    n2 = mid - 1;
	else if ( res > 0 )
	    n1 = mid + 1;
	else {					// found it
	    found = TRUE;
	    break;
	}
    }
    /* if ( !found )
	return -1; */
    // search to first one equal or bigger
229
    while ( found && (mid > 0) && !((QGVector*)this)->compareItems(d, (*this)[mid-1]) )
kocienda's avatar
kocienda committed
230 231 232 233 234 235
	mid--;
    return mid;
}

// -------------------------------------------------------------------------------------

236 237
RenderText::RenderText(DOM::NodeImpl* node, DOMStringImpl *_str)
    : RenderObject(node)
kocienda's avatar
kocienda committed
238 239 240 241 242 243 244 245
{
    // init RenderObject attributes
    setRenderText();   // our object inherits from RenderText

    m_minWidth = -1;
    m_maxWidth = -1;
    str = _str;
    if(str) str->ref();
246
    KHTMLAssert(!str || !str->l || str->s);
kocienda's avatar
kocienda committed
247 248 249 250 251 252

    m_selectionState = SelectionNone;
    m_hasReturn = true;

#ifdef DEBUG_LAYOUT
    QConstString cstr(str->s, str->l);
253
    kdDebug( 6040 ) << "RenderText ctr( "<< cstr.string().length() << " )  '" << cstr.string() << "'" << endl;
kocienda's avatar
kocienda committed
254 255 256 257 258
#endif
}

void RenderText::setStyle(RenderStyle *_style)
{
259
    if ( style() != _style ) {
darin's avatar
darin committed
260 261 262 263 264 265 266 267
        // ### fontvariant being implemented as text-transform: upper. sucks!
        bool changedText = (!style() && (_style->fontVariant() != FVNORMAL || _style->textTransform() != TTNONE)) ||
            ((style() && style()->textTransform() != _style->textTransform()) ||
             (style() && style()->fontVariant() != _style->fontVariant()));

        RenderObject::setStyle( _style );
        m_lineHeight = RenderObject::lineHeight(false);

darin's avatar
darin committed
268
        if (changedText && element() && element()->string())
darin's avatar
darin committed
269
            setText(element()->string(), changedText);
kocienda's avatar
kocienda committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    }
}

RenderText::~RenderText()
{
    deleteSlaves();
    if(str) str->deref();
}

void RenderText::deleteSlaves()
{
    // this is a slight variant of QArray::clear().
    // We don't delete the array itself here because its
    // likely to be used in the same size later again, saves
    // us resize() calls
    unsigned int len = m_lines.size();
    for(unsigned int i=0; i < len; i++)
        m_lines.remove(i);

289
    KHTMLAssert(m_lines.count() == 0);
kocienda's avatar
kocienda committed
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
}

TextSlave * RenderText::findTextSlave( int offset, int &pos )
{
    // The text slaves point to parts of the rendertext's str string
    // (they don't include '\n')
    // Find the text slave that includes the character at @p offset
    // and return pos, which is the position of the char in the slave.

    if ( m_lines.isEmpty() )
        return 0L;

    TextSlave* s = m_lines[0];
    uint si = 0;
    int off = s->m_len;
    while(offset > off && si < m_lines.count())
    {
        s = m_lines[++si];
darin's avatar
darin committed
308
        off = s->m_start + s->m_len;
kocienda's avatar
kocienda committed
309 310 311 312 313 314
    }
    // we are now in the correct text slave
    pos = (offset > off ? s->m_len : s->m_len - (off - offset) );
    return s;
}

darin's avatar
darin committed
315
bool RenderText::nodeAtPoint(NodeInfo& /*info*/, int _x, int _y, int _tx, int _ty)
kocienda's avatar
kocienda committed
316
{
317 318 319 320 321 322 323 324 325
    assert(parent());

    _tx -= paddingLeft() + borderLeft();
    _ty -= borderTop() + paddingTop();

    int height = m_lineHeight + borderTop() + paddingTop() +
                 borderBottom() + paddingBottom();

    bool inside = false;
kocienda's avatar
kocienda committed
326 327
    TextSlave *s = m_lines.count() ? m_lines[0] : 0;
    int si = 0;
328 329 330 331 332 333 334
    while(s) {
        if((_y >=_ty + s->m_y) && (_y < _ty + s->m_y + height) &&
           (_x >= _tx + s->m_x) && (_x <_tx + s->m_x + s->m_width) ) {
            inside = true;
            break;
        }

darin's avatar
darin committed
335
        s = si < (int) m_lines.count()-1 ? m_lines[++si] : 0;
kocienda's avatar
kocienda committed
336
    }
337 338 339 340

    setMouseInside(inside);

    return inside;
kocienda's avatar
kocienda committed
341 342
}

343
FindSelectionResult RenderText::checkSelectionPoint(int _x, int _y, int _tx, int _ty, DOM::NodeImpl*& node, int &offset)
kocienda's avatar
kocienda committed
344
{
345 346
//     kdDebug(6040) << "RenderText::checkSelectionPoint " << this << " _x=" << _x << " _y=" << _y
//                   << " _tx=" << _tx << " _ty=" << _ty << endl;
darin's avatar
darin committed
347 348
    TextSlave *lastPointAfterInline=0;

kocienda's avatar
kocienda committed
349 350 351 352
    for(unsigned int si = 0; si < m_lines.count(); si++)
    {
        TextSlave* s = m_lines[si];
        int result;
darin's avatar
darin committed
353 354
        const Font *f = htmlFont( si==0 );
        result = s->checkSelectionPoint(_x, _y, _tx, _ty, f, this, offset, m_lineHeight);
355

darin's avatar
darin committed
356
//         kdDebug(6040) << "RenderText::checkSelectionPoint " << this << " line " << si << " result=" << result << " offset=" << offset << endl;
kocienda's avatar
kocienda committed
357 358
        if ( result == SelectionPointInside ) // x,y is inside the textslave
        {
darin's avatar
darin committed
359
            offset += s->m_start; // add the offset from the previous lines
kocienda's avatar
kocienda committed
360
            //kdDebug(6040) << "RenderText::checkSelectionPoint inside -> " << offset << endl;
361
            node = element();
kocienda's avatar
kocienda committed
362
            return SelectionPointInside;
darin's avatar
darin committed
363
        } else if ( result == SelectionPointBefore ) {
kocienda's avatar
kocienda committed
364
            // x,y is before the textslave -> stop here
darin's avatar
darin committed
365 366
            if ( si > 0 && lastPointAfterInline ) {
                offset = lastPointAfterInline->m_start + lastPointAfterInline->m_len;
kocienda's avatar
kocienda committed
367
                //kdDebug(6040) << "RenderText::checkSelectionPoint before -> " << offset << endl;
368
                node = element();
kocienda's avatar
kocienda committed
369
                return SelectionPointInside;
darin's avatar
darin committed
370
            } else {
kocienda's avatar
kocienda committed
371
                offset = 0;
372 373
                //kdDebug(6040) << "RenderText::checkSelectionPoint " << this << "before us -> returning Before" << endl;
                node = element();
kocienda's avatar
kocienda committed
374 375
                return SelectionPointBefore;
            }
darin's avatar
darin committed
376 377 378 379
        } else if ( result == SelectionPointAfterInLine ) {
	    lastPointAfterInline = s;
	}

kocienda's avatar
kocienda committed
380 381 382 383
    }

    // set offset to max
    offset = str->l;
384 385
    //qDebug("setting node to %p", element());
    node = element();
kocienda's avatar
kocienda committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    return SelectionPointAfter;
}

void RenderText::cursorPos(int offset, int &_x, int &_y, int &height)
{
  if (!m_lines.count()) {
    _x = _y = height = -1;
    return;
  }

  int pos;
  TextSlave * s = findTextSlave( offset, pos );
  _y = s->m_y;
  height = m_lineHeight; // ### firstLine!!! s->m_height;

401
  const QFontMetrics &fm = metrics( false ); // #### wrong for first-line!
darin's avatar
darin committed
402
  QString tekst(str->s + s->m_start, s->m_len);
kocienda's avatar
kocienda committed
403 404
  _x = s->m_x + (fm.boundingRect(tekst, pos)).right();
  if(pos)
darin's avatar
darin committed
405
      _x += fm.rightBearing( *(str->s + s->m_start + pos - 1 ) );
kocienda's avatar
kocienda committed
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423

  int absx, absy;

  RenderObject *cb = containingBlock();

  if (cb && cb != this && cb->absolutePosition(absx,absy))
  {
    _x += absx;
    _y += absy;
  } else {
    // we don't know our absolute position, and there is not point returning
    // just a relative one
    _x = _y = -1;
  }
}

bool RenderText::absolutePosition(int &xPos, int &yPos, bool)
{
424 425
    return RenderObject::absolutePosition(xPos, yPos, false);

kocienda's avatar
kocienda committed
426
    if(parent() && parent()->absolutePosition(xPos, yPos, false)) {
427 428
        xPos -= paddingLeft() + borderLeft();
        yPos -= borderTop() + paddingTop();
kocienda's avatar
kocienda committed
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
        return true;
    }
    xPos = yPos = 0;
    return false;
}

void RenderText::posOfChar(int chr, int &x, int &y)
{
    if (!parent())
    {
       x = -1;
       y = -1;
       return;
    }
    parent()->absolutePosition( x, y, false );

    //if( chr > (int) str->l )
    //chr = str->l;

    int pos;
    TextSlave * s = findTextSlave( chr, pos );

    if ( s )
    {
        // s is the line containing the character
        x += s->m_x; // this is the x of the beginning of the line, but it's good enough for now
        y += s->m_y;
    }
}

459 460 461 462 463 464 465 466
int RenderText::rightmostPosition() const
{
    if (style()->whiteSpace() != NORMAL)
        return maxWidth();

    return 0;
}

kocienda's avatar
kocienda committed
467 468 469
void RenderText::printObject( QPainter *p, int /*x*/, int y, int /*w*/, int h,
                      int tx, int ty)
{
470
    int ow = style()->outlineWidth();
kocienda's avatar
kocienda committed
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    RenderStyle* pseudoStyle = style()->getPseudoStyle(RenderStyle::FIRST_LINE);
    int d = style()->textDecoration();
    TextSlave f(0, y-ty);
    int si = m_lines.findFirstMatching(&f);
    // something matching found, find the first one to print
    if(si >= 0)
    {
        // Move up until out of area to be printed
        while(si > 0 && m_lines[si-1]->checkVerticalPoint(y, ty, h, m_lineHeight))
            si--;

        //QConstString cstr(str->s, str->l);
        //kdDebug(6040) << this << " RenderText text '" << (const char *)cstr.string().utf8() << "'" << endl;
        //kdDebug(6040) << this << " RenderText::printObject y=" << y << " ty=" << ty << " h=" << h << " first line is " << si << endl;

        // Now calculate startPos and endPos, for printing selection.
        // We print selection while endPos > 0
        int endPos, startPos;
darin's avatar
darin committed
489 490
        if (selectionState() != SelectionNone) {
            if (selectionState() == SelectionInside) {
kocienda's avatar
kocienda committed
491 492 493
                //kdDebug(6040) << this << " SelectionInside -> 0 to end" << endl;
                startPos = 0;
                endPos = str->l;
darin's avatar
darin committed
494
            } else {
kocienda's avatar
kocienda committed
495 496 497 498 499 500 501 502 503 504 505 506 507
                selectionStartEnd(startPos, endPos);
                if(selectionState() == SelectionStart)
                    endPos = str->l;
                else if(selectionState() == SelectionEnd)
                    startPos = 0;
            }
            //kdDebug(6040) << this << " Selection from " << startPos << " to " << endPos << endl;
        }

        TextSlave* s;
        int minx =  1000000;
        int maxx = -1000000;
        int outlinebox_y = m_lines[si]->m_y;
508 509 510
	QPtrList <QRect> linerects;
        linerects.setAutoDelete(true);
        linerects.append(new QRect());
kocienda's avatar
kocienda committed
511

512
	bool renderOutline = style()->outlineWidth()!=0;
kocienda's avatar
kocienda committed
513

darin's avatar
darin committed
514 515
	const Font *font = &style()->htmlFont();

kocienda's avatar
kocienda committed
516 517 518 519 520 521
        // run until we find one that is outside the range, then we
        // know we can stop
        do {
            s = m_lines[si];
            RenderStyle* _style = pseudoStyle && s->m_firstLine ? pseudoStyle : style();

darin's avatar
darin committed
522
            if(_style->font() != p->font()) {
kocienda's avatar
kocienda committed
523
                p->setFont(_style->font());
darin's avatar
darin committed
524 525
		font = &_style->htmlFont();
	    }
kocienda's avatar
kocienda committed
526 527 528 529 530
            if((hasSpecialObjects()  &&
                (parent()->isInline() || pseudoStyle)) &&
               (!pseudoStyle || s->m_firstLine))
                s->printBoxDecorations(p, _style, this, tx, ty, si == 0, si == (int)m_lines.count()-1);

531

kocienda's avatar
kocienda committed
532 533 534
            if(_style->color() != p->pen().color())
                p->setPen(_style->color());

darin's avatar
darin committed
535 536 537
	    if (s->m_len > 0)
		font->drawText(p, s->m_x + tx, s->m_y + ty + s->m_baseline, str->s, str->l, s->m_start, s->m_len,
			       s->m_toAdd, s->m_reversed ? QPainter::RTL : QPainter::LTR);
kocienda's avatar
kocienda committed
538 539 540 541 542 543 544

            if(d != TDNONE)
            {
                p->setPen(_style->textDecorationColor());
                s->printDecoration(p, this, tx, ty, d, si == 0, si == ( int ) m_lines.count()-1);
            }

darin's avatar
darin committed
545 546 547 548 549 550 551 552
            if (selectionState() != SelectionNone ) {
		int offset = s->m_start;
		int sPos = QMAX( startPos - offset, 0 );
		int ePos = QMIN( endPos - offset, s->m_len );
                //kdDebug(6040) << this << " printSelection with startPos=" << sPos << " endPos=" << ePos << endl;
		if ( sPos < ePos )
		    s->printSelection(font, this, p, _style, tx, ty, sPos, ePos);

kocienda's avatar
kocienda committed
553
            }
554
            if(renderOutline) {
kocienda's avatar
kocienda committed
555 556
                if(outlinebox_y == s->m_y) {
                    if(minx > s->m_x)  minx = s->m_x;
557 558 559 560
                    int newmaxx = s->m_x+s->m_width;
                    //if (parent()->isInline() && si==0) newmaxx-=paddingLeft();
                    if (parent()->isInline() && si==int(m_lines.count())-1) newmaxx-=paddingRight();
                    if(maxx < newmaxx) maxx = newmaxx;
kocienda's avatar
kocienda committed
561 562
                }
                else {
563 564 565
                    QRect *curLine = new QRect(minx, outlinebox_y, maxx-minx, m_lineHeight);
                    linerects.append(curLine);

kocienda's avatar
kocienda committed
566 567 568
                    outlinebox_y = s->m_y;
                    minx = s->m_x;
                    maxx = s->m_x+s->m_width;
569 570
                    //if (parent()->isInline() && si==0) maxx-=paddingLeft();
                    if (parent()->isInline() && si==int(m_lines.count())-1) maxx-=paddingRight();
kocienda's avatar
kocienda committed
571 572
                }
            }
573 574 575 576 577 578 579 580 581 582 583 584
#ifdef BIDI_DEBUG
            {
                int h = lineHeight( false ) + paddingTop() + paddingBottom() + borderTop() + borderBottom();
                QColor c2 = QColor("#0000ff");
                drawBorder(p, tx, ty, tx+1, ty + h,
                              RenderObject::BSLeft, c2, c2, SOLID, 1, 1);
                drawBorder(p, tx + s->m_width, ty, tx + s->m_width + 1, ty + h,
                              RenderObject::BSRight, c2, c2, SOLID, 1, 1);
            }
#endif

        } while (++si < (int)m_lines.count() && m_lines[si]->checkVerticalPoint(y-ow, ty, h, m_lineHeight));
kocienda's avatar
kocienda committed
585

586 587 588 589 590 591 592
        if(renderOutline)
	  {
	    linerects.append(new QRect(minx, outlinebox_y, maxx-minx, m_lineHeight));
	    linerects.append(new QRect());
	    for (unsigned int i = 1; i < linerects.count() - 1; i++)
                printTextOutline(p, tx, ty, *linerects.at(i-1), *linerects.at(i), *linerects.at(i+1));
	  }
kocienda's avatar
kocienda committed
593 594 595 596 597 598
    }
}

void RenderText::print( QPainter *p, int x, int y, int w, int h,
                      int tx, int ty)
{
599
    if (style()->visibility() != VISIBLE) return;
kocienda's avatar
kocienda committed
600 601 602

    int s = m_lines.count() - 1;
    if ( s < 0 ) return;
603 604 605 606

    // ### incorporate padding/border here!
    if ( ty + m_lines[0]->m_y > y + h + 64 ) return;
    if ( ty + m_lines[s]->m_y + m_lines[s]->m_baseline + m_lineHeight + 64 < y ) return;
kocienda's avatar
kocienda committed
607 608 609 610 611 612

    printObject(p, x, y, w, h, tx, ty);
}

void RenderText::calcMinMaxWidth()
{
613
    KHTMLAssert( !minMaxKnown() );
kocienda's avatar
kocienda committed
614 615 616 617 618 619 620 621 622 623 624

    // ### calc Min and Max width...
    m_minWidth = 0;
    m_maxWidth = 0;

    int currMinWidth = 0;
    int currMaxWidth = 0;
    m_hasReturn = false;
    m_hasBreakableChar = false;

    // ### not 100% correct for first-line
darin's avatar
darin committed
625
    const Font *f = htmlFont( false );
kocienda's avatar
kocienda committed
626 627 628 629 630 631
    int len = str->l;
    if ( len == 1 && str->s->latin1() == '\n' )
	m_hasReturn = true;
    for(int i = 0; i < len; i++)
    {
        int wordlen = 0;
darin's avatar
darin committed
632
        while( i+wordlen < len && !(isBreakable( str->s, i+wordlen, str->l )) )
kocienda's avatar
kocienda committed
633 634 635
            wordlen++;
        if (wordlen)
        {
darin's avatar
darin committed
636
            int w = f->width(str->s, str->l, i, wordlen);
kocienda's avatar
kocienda committed
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
            currMinWidth += w;
            currMaxWidth += w;
        }
        if(i+wordlen < len)
        {
	    m_hasBreakableChar = true;
            if ( (*(str->s+i+wordlen)).latin1() == '\n' )
            {
		m_hasReturn = true;
                if(currMinWidth > m_minWidth) m_minWidth = currMinWidth;
                currMinWidth = 0;
                if(currMaxWidth > m_maxWidth) m_maxWidth = currMaxWidth;
                currMaxWidth = 0;
            }
            else
            {
                if(currMinWidth > m_minWidth) m_minWidth = currMinWidth;
                currMinWidth = 0;
darin's avatar
darin committed
655
                currMaxWidth += f->width( str->s, str->l, i + wordlen );
kocienda's avatar
kocienda committed
656 657 658 659 660 661 662 663 664 665 666 667 668
            }
            /* else if( c == '-')
            {
                currMinWidth += minus_width;
                if(currMinWidth > m_minWidth) m_minWidth = currMinWidth;
                currMinWidth = 0;
                currMaxWidth += minus_width;
            }*/
        }
        i += wordlen;
    }
    if(currMinWidth > m_minWidth) m_minWidth = currMinWidth;
    if(currMaxWidth > m_maxWidth) m_maxWidth = currMaxWidth;
669 670 671 672

    if (style()->whiteSpace() == NOWRAP)
        m_minWidth = m_maxWidth;

kocienda's avatar
kocienda committed
673
    setMinMaxKnown();
674
    //kdDebug( 6040 ) << "Text::calcMinMaxWidth(): min = " << m_minWidth << " max = " << m_maxWidth << endl;
kocienda's avatar
kocienda committed
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
}

int RenderText::minXPos() const
{
    if (!m_lines.count())
	return 0;
    int retval=6666666;
    for (unsigned i=0;i < m_lines.count(); i++)
    {
	retval = QMIN ( retval, m_lines[i]->m_x);
    }
    return retval;
}

int RenderText::xPos() const
{
    if (m_lines.count())
	return m_lines[0]->m_x;
    else
	return 0;
}

int RenderText::yPos() const
{
    if (m_lines.count())
        return m_lines[0]->m_y;
    else
        return 0;
}

const QFont &RenderText::font()
{
707
    return style()->font();
kocienda's avatar
kocienda committed
708 709
}

darin's avatar
darin committed
710
void RenderText::setText(DOMStringImpl *text, bool force)
kocienda's avatar
kocienda committed
711
{
712 713 714 715
#ifdef APPLE_CHANGES
    if (!text)
        return;
#endif
darin's avatar
darin committed
716
    if( !force && str == text ) return;
kocienda's avatar
kocienda committed
717 718
    if(str) str->deref();
    str = text;
darin's avatar
darin committed
719

darin's avatar
darin committed
720
    if ( str && style() ) {
darin's avatar
darin committed
721 722 723 724 725 726 727 728 729 730
        if ( style()->fontVariant() == SMALL_CAPS )
            str = str->upper();
        else
            switch(style()->textTransform()) {
            case CAPITALIZE:   str = str->capitalize();  break;
            case UPPERCASE:   str = str->upper();       break;
            case LOWERCASE:  str = str->lower();       break;
            case NONE:
            default:;
            }
darin's avatar
darin committed
731
        str->ref();
darin's avatar
darin committed
732
    }
kocienda's avatar
kocienda committed
733 734 735

    // ### what should happen if we change the text of a
    // RenderBR object ?
736 737
    KHTMLAssert(!isBR() || (str->l == 1 && (*str->s) == '\n'));
    KHTMLAssert(!str->l || str->s);
kocienda's avatar
kocienda committed
738 739

    setLayouted(false);
740
#ifdef BIDI_DEBUG
kocienda's avatar
kocienda committed
741
    QConstString cstr(str->s, str->l);
742
    kdDebug( 6040 ) << "RenderText::setText( " << cstr.string().length() << " ) '" << cstr.string() << "'" << endl;
kocienda's avatar
kocienda committed
743 744 745 746 747
#endif
}

int RenderText::height() const
{
748 749 750 751 752 753 754 755
    int retval;
    if ( m_lines.count() )
        retval = m_lines[m_lines.count()-1]->m_y + m_lineHeight - m_lines[0]->m_y;
    else
        retval = metrics( false ).height();

    retval += paddingTop() + paddingBottom() + borderTop() + borderBottom();

kocienda's avatar
kocienda committed
756 757 758
    return retval;
}

759
short RenderText::lineHeight( bool firstLine ) const
kocienda's avatar
kocienda committed
760
{
761 762 763
    if ( firstLine )
 	return RenderObject::lineHeight( firstLine );

kocienda's avatar
kocienda committed
764 765 766 767 768
    return m_lineHeight;
}

short RenderText::baselinePosition( bool firstLine ) const
{
769 770 771
    const QFontMetrics &fm = metrics( firstLine );
    return fm.ascent() +
        ( lineHeight( firstLine ) - fm.height() ) / 2;
kocienda's avatar
kocienda committed
772 773
}

darin's avatar
darin committed
774
void RenderText::position(int x, int y, int from, int len, int width, bool reverse, bool firstLine, int spaceAdd)
kocienda's avatar
kocienda committed
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
{
    // ### should not be needed!!!
    if(len == 0 || (len == 1 && *(str->s+from) == '\n') ) return;

    reverse = reverse && !style()->visuallyOrdered();

    // ### margins and RTL
    if(from == 0 && parent()->isInline() && parent()->firstChild()==this)
    {
        x += paddingLeft() + borderLeft() + marginLeft();
        width -= marginLeft();
    }

    if(from + len == int(str->l) && parent()->isInline() && parent()->lastChild()==this)
        width -= marginRight();

#ifdef DEBUG_LAYOUT
darin's avatar
darin committed
792
    QChar *ch = str->s+from;
kocienda's avatar
kocienda committed
793
    QConstString cstr(ch, len);
794
    qDebug("setting slave text to *%s*, len=%d, w)=%d" , cstr.string().latin1(), len, width );//" << y << ")" << " height=" << lineHeight(false) << " fontHeight=" << metrics(false).height() << " ascent =" << metrics(false).ascent() << endl;
kocienda's avatar
kocienda committed
795 796
#endif

darin's avatar
darin committed
797
    TextSlave *s = new TextSlave(x, y, from, len,
kocienda's avatar
kocienda committed
798
                                 baselinePosition( firstLine ),
darin's avatar
darin committed
799
                                 width, reverse, spaceAdd, firstLine);
kocienda's avatar
kocienda committed
800 801 802 803 804 805 806 807 808 809 810 811

    if(m_lines.count() == m_lines.size())
        m_lines.resize(m_lines.size()*2+1);

    m_lines.insert(m_lines.count(), s);
}

unsigned int RenderText::width(unsigned int from, unsigned int len, bool firstLine) const
{
    if(!str->s || from > str->l ) return 0;
    if ( from + len > str->l ) len = str->l - from;

darin's avatar
darin committed
812 813
    const Font *f = htmlFont( firstLine );
    return width( from, len, f );
kocienda's avatar
kocienda committed
814 815
}

darin's avatar
darin committed
816
unsigned int RenderText::width(unsigned int from, unsigned int len, const Font *f) const
kocienda's avatar
kocienda committed
817 818 819 820 821
{
    if(!str->s || from > str->l ) return 0;
    if ( from + len > str->l ) len = str->l - from;

    int w;
darin's avatar
darin committed
822
    if ( f == &style()->htmlFont() && from == 0 && len == str->l )
kocienda's avatar
kocienda committed
823 824
 	 w = m_maxWidth;
    else
darin's avatar
darin committed
825
	w = f->width(str->s, str->l, from, len );
kocienda's avatar
kocienda committed
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885

    // ### add margins and support for RTL

    if(parent()->isInline())
    {
        if(from == 0 && parent()->firstChild() == static_cast<const RenderObject*>(this))
            w += borderLeft() + paddingLeft() + marginLeft();
        if(from + len == str->l &&
           parent()->lastChild() == static_cast<const RenderObject*>(this))
            w += borderRight() + paddingRight() +marginRight();
    }

    //kdDebug( 6040 ) << "RenderText::width(" << from << ", " << len << ") = " << w << endl;
    return w;
}

short RenderText::width() const
{
    int w;
    int minx = 100000000;
    int maxx = 0;
    // slooow
    for(unsigned int si = 0; si < m_lines.count(); si++) {
        TextSlave* s = m_lines[si];
        if(s->m_x < minx)
            minx = s->m_x;
        if(s->m_x + s->m_width > maxx)
            maxx = s->m_x + s->m_width;
    }

    w = QMAX(0, maxx-minx);

    if(parent()->isInline())
    {
        if(parent()->firstChild() == static_cast<const RenderObject*>(this))
            w += borderLeft() + paddingLeft();
        if(parent()->lastChild() == static_cast<const RenderObject*>(this))
            w += borderRight() + paddingRight();
    }

    return w;
}

void RenderText::repaint()
{
    RenderObject *cb = containingBlock();
    if(cb != this)
        cb->repaint();
}

bool RenderText::isFixedWidthFont() const
{
    return QFontInfo(style()->font()).fixedPitch();
}

short RenderText::verticalPositionHint( bool firstLine ) const
{
    return parent()->verticalPositionHint( firstLine );
}

886
const QFontMetrics &RenderText::metrics(bool firstLine) const
kocienda's avatar
kocienda committed
887 888 889 890
{
    if( firstLine && hasFirstLine() ) {
	RenderStyle *pseudoStyle  = style()->getPseudoStyle(RenderStyle::FIRST_LINE);
	if ( pseudoStyle )
891
	    return pseudoStyle->fontMetrics();
kocienda's avatar
kocienda committed
892
    }
893 894 895
    return style()->fontMetrics();
}

darin's avatar
darin committed
896 897 898 899 900 901 902 903 904 905 906 907 908
const Font *RenderText::htmlFont(bool firstLine) const
{
    const Font *f = 0;
    if( firstLine && hasFirstLine() ) {
	RenderStyle *pseudoStyle  = style()->getPseudoStyle(RenderStyle::FIRST_LINE);
	if ( pseudoStyle )
	    f = &pseudoStyle->htmlFont();
    } else {
	f = &style()->htmlFont();
    }
    return f;
}

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
void RenderText::printTextOutline(QPainter *p, int tx, int ty, const QRect &lastline, const QRect &thisline, const QRect &nextline)
{
  int ow = style()->outlineWidth();
  EBorderStyle os = style()->outlineStyle();
  QColor oc = style()->outlineColor();

  int t = ty + thisline.top();
  int l = tx + thisline.left();
  int b = ty + thisline.bottom() + 1;
  int r = tx + thisline.right() + 1;

  // left edge
  drawBorder(p,
	     l - ow,
	     t - (lastline.isEmpty() || thisline.left() < lastline.left() || lastline.right() <= thisline.left() ? ow : 0),
	     l,
	     b + (nextline.isEmpty() || thisline.left() <= nextline.left() || nextline.right() <= thisline.left() ? ow : 0),
	     BSLeft,
	     oc, style()->color(), os,
	     (lastline.isEmpty() || thisline.left() < lastline.left() || lastline.right() <= thisline.left() ? ow : -ow),
	     (nextline.isEmpty() || thisline.left() <= nextline.left() || nextline.right() <= thisline.left() ? ow : -ow),
	     true);

  // right edge
  drawBorder(p,
	     r,
	     t - (lastline.isEmpty() || lastline.right() < thisline.right() || thisline.right() <= lastline.left() ? ow : 0),
	     r + ow,
	     b + (nextline.isEmpty() || nextline.right() <= thisline.right() || thisline.right() <= nextline.left() ? ow : 0),
	     BSRight,
	     oc, style()->color(), os,
	     (lastline.isEmpty() || lastline.right() < thisline.right() || thisline.right() <= lastline.left() ? ow : -ow),
	     (nextline.isEmpty() || nextline.right() <= thisline.right() || thisline.right() <= nextline.left() ? ow : -ow),
	     true);
  // upper edge
  if ( thisline.left() < lastline.left())
      drawBorder(p,
		 l - ow,
		 t - ow,
		 QMIN(r+ow, (lastline.isValid()? tx+lastline.left() : 1000000)),
		 t ,
		 BSTop, oc, style()->color(), os,
		 ow,
		 (lastline.isValid() && tx+lastline.left()+1<r+ow ? -ow : ow),
		 true);

  if (lastline.right() < thisline.right())
      drawBorder(p,
		 QMAX(lastline.isValid()?tx + lastline.right() + 1:-1000000, l - ow),
		 t - ow,
		 r + ow,
		 t ,
		 BSTop, oc, style()->color(), os,
		 (lastline.isValid() && l-ow < tx+lastline.right()+1 ? -ow : ow),
		 ow,
		 true);

  // lower edge
  if ( thisline.left() < nextline.left())
      drawBorder(p,
		 l - ow,
		 b,
		 QMIN(r+ow, nextline.isValid()? tx+nextline.left()+1 : 1000000),
		 b + ow,
		 BSBottom, oc, style()->color(), os,
		 ow,
		 (nextline.isValid() && tx+nextline.left()+1<r+ow? -ow : ow),
		 true);

  if (nextline.right() < thisline.right())
      drawBorder(p,
		 QMAX(nextline.isValid()?tx+nextline.right()+1:-1000000 , l-ow),
		 b,
		 r + ow,
		 b + ow,
		 BSBottom, oc, style()->color(), os,
		 (nextline.isValid() && l-ow < tx+nextline.right()+1? -ow : ow),
		 ow,
		 true);
kocienda's avatar
kocienda committed
988 989 990
}

#undef BIDI_DEBUG
991
#undef DEBUG_LAYOUT