html_imageimpl.cpp 16.9 KB
Newer Older
George Staikos's avatar
George Staikos 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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
/**
 * This file is part of the DOM implementation for KDE.
 *
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@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., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "html/html_imageimpl.h"
#include "html/html_formimpl.h"
#include "html/html_documentimpl.h"

#include "khtmlview.h"
#include "khtml_part.h"

#include <kstringhandler.h>
#include <kglobal.h>
#include <kdebug.h>

#include "rendering/render_image.h"
#include "rendering/render_flow.h"
#include "css/cssstyleselector.h"
#include "css/cssproperties.h"
#include "css/cssvalues.h"
#include "xml/dom2_eventsimpl.h"

Dirk Mueller's avatar
Dirk Mueller committed
41 42
#include <QtCore/QCharRef>
#include <QtCore/QPoint>
Tobias Koenig's avatar
Tobias Koenig committed
43
#include <QtCore/QStack>
Dirk Mueller's avatar
Dirk Mueller committed
44 45
#include <QtGui/QRegion>
#include <QtGui/QImage>
George Staikos's avatar
George Staikos committed
46 47 48 49 50 51

using namespace DOM;
using namespace khtml;

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

Germain Garand's avatar
Germain Garand committed
52
HTMLImageElementImpl::HTMLImageElementImpl(DocumentImpl *doc, HTMLFormElementImpl *f)
53
    : HTMLElementImpl(doc), ismap(false), loadEventSent(true), unsafe(false), m_image(0), m_form(f)
George Staikos's avatar
George Staikos committed
54 55 56 57 58 59 60
{
    if (m_form)
        m_form->registerImgElement(this);
}

HTMLImageElementImpl::~HTMLImageElementImpl()
{
61 62
    if (document())
        document()->removeImage(this);
George Staikos's avatar
George Staikos committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

    if (m_image)
        m_image->deref(this);

    if (m_form)
        m_form->removeImgElement(this);
}

NodeImpl::Id HTMLImageElementImpl::id() const
{
    return ID_IMG;
}

void HTMLImageElementImpl::parseAttribute(AttributeImpl *attr)
{
    switch (attr->id())
    {
    case ATTR_ALT:
        setChanged();
        break;
    case ATTR_SRC: {
        setChanged();

        //Start loading the image already, to generate events
87
        const DOMString imgSrcUrl = attr->value().trimSpaces();
88 89
        if (!imgSrcUrl.isEmpty()) { //### why do we not hide or something when setting this?
            CachedImage* newImage = document()->docLoader()->requestImage(imgSrcUrl);
George Staikos's avatar
George Staikos committed
90
            if (newImage && newImage != m_image) {
Maks Orlovich's avatar
Maks Orlovich committed
91
                CachedImage* oldImage = m_image;
George Staikos's avatar
George Staikos committed
92 93 94
                loadEventSent = false;
                m_image = newImage;
                m_image->ref(this);
Maks Orlovich's avatar
Maks Orlovich committed
95 96
                if (oldImage)
                    oldImage->deref(this);
George Staikos's avatar
George Staikos committed
97
            }
98

99 100 101 102 103 104
            if (m_image) {
                const KUrl fullURL = KUrl(m_image->url().string());
                if (document()->origin()->taintsCanvas(fullURL)) {
                    unsafe = true;
                }
            }
George Staikos's avatar
George Staikos committed
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        }
    }
    break;
    case ATTR_WIDTH:
        if (!attr->value().isEmpty())
            addCSSLength(CSS_PROP_WIDTH, attr->value());
        else
            removeCSSProperty(CSS_PROP_WIDTH);
        break;
    case ATTR_HEIGHT:
        if (!attr->value().isEmpty())
            addCSSLength(CSS_PROP_HEIGHT, attr->value());
        else
            removeCSSProperty(CSS_PROP_HEIGHT);
        break;
    case ATTR_BORDER:
        // border="noborder" -> border="0"
        if(attr->value().toInt()) {
            addCSSLength(CSS_PROP_BORDER_WIDTH, attr->value());
            addCSSProperty( CSS_PROP_BORDER_TOP_STYLE, CSS_VAL_SOLID );
            addCSSProperty( CSS_PROP_BORDER_RIGHT_STYLE, CSS_VAL_SOLID );
            addCSSProperty( CSS_PROP_BORDER_BOTTOM_STYLE, CSS_VAL_SOLID );
            addCSSProperty( CSS_PROP_BORDER_LEFT_STYLE, CSS_VAL_SOLID );
        } else {
             removeCSSProperty( CSS_PROP_BORDER_WIDTH );
             removeCSSProperty( CSS_PROP_BORDER_TOP_STYLE );
             removeCSSProperty( CSS_PROP_BORDER_RIGHT_STYLE );
             removeCSSProperty( CSS_PROP_BORDER_BOTTOM_STYLE );
             removeCSSProperty( CSS_PROP_BORDER_LEFT_STYLE );
        }
        break;
    case ATTR_VSPACE:
        addCSSLength(CSS_PROP_MARGIN_TOP, attr->value());
        addCSSLength(CSS_PROP_MARGIN_BOTTOM, attr->value());
        break;
    case ATTR_HSPACE:
        addCSSLength(CSS_PROP_MARGIN_LEFT, attr->value());
        addCSSLength(CSS_PROP_MARGIN_RIGHT, attr->value());
        break;
    case ATTR_ALIGN:
	addHTMLAlignment( attr->value() );
	break;
    case ATTR_VALIGN:
	addCSSProperty(CSS_PROP_VERTICAL_ALIGN, attr->value().lower());
        break;
    case ATTR_USEMAP:
        if ( attr->value()[0] == '#' )
Maks Orlovich's avatar
Maks Orlovich committed
152
            usemap = attr->value().lower();
George Staikos's avatar
George Staikos committed
153
        else {
154
            QString url = document()->completeURL(attr->value().trimSpaces().string());
George Staikos's avatar
George Staikos committed
155 156 157 158 159
            // ### we remove the part before the anchor and hope
            // the map is on the same html page....
            usemap = url;
        }
        m_hasAnchor = attr->val() != 0;
160
        break;
George Staikos's avatar
George Staikos committed
161 162 163 164 165
    case ATTR_ISMAP:
        ismap = true;
        break;
    case ATTR_ONABORT: // ### add support for this
        setHTMLEventListener(EventImpl::ABORT_EVENT,
166
	    document()->createHTMLEventListener(attr->value().string(), "onabort", this));
George Staikos's avatar
George Staikos committed
167 168 169
        break;
    case ATTR_ONERROR:
        setHTMLEventListener(EventImpl::ERROR_EVENT,
170
	    document()->createHTMLEventListener(attr->value().string(), "onerror", this));
George Staikos's avatar
George Staikos committed
171 172 173
        break;
    case ATTR_ONLOAD:
        setHTMLEventListener(EventImpl::LOAD_EVENT,
174
	    document()->createHTMLEventListener(attr->value().string(), "onload", this));
George Staikos's avatar
George Staikos committed
175 176 177 178 179
        break;
    case ATTR_NOSAVE:
	break;
    case ATTR_NAME:
        if (inDocument() && m_name != attr->value()) {
Maks Orlovich's avatar
Maks Orlovich committed
180 181
            document()->underDocNamedCache().remove(m_name,        this);
            document()->underDocNamedCache().add   (attr->value(), this);
George Staikos's avatar
George Staikos committed
182 183 184 185 186 187 188 189 190 191 192
        }
        m_name = attr->value();
        //fallthrough
    default:
        HTMLElementImpl::parseAttribute(attr);
    }
}

void HTMLImageElementImpl::notifyFinished(CachedObject *finishedObj)
{
    if (m_image == finishedObj) {
193
        document()->dispatchImageLoadEventSoon(this);
George Staikos's avatar
George Staikos committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    }
}

void HTMLImageElementImpl::dispatchLoadEvent()
{
    if (!loadEventSent) {
        loadEventSent = true;
        if (m_image->isErrorImage()) {
            dispatchHTMLEvent(EventImpl::ERROR_EVENT, false, false);
        } else {
            dispatchHTMLEvent(EventImpl::LOAD_EVENT, false, false);
        }
    }
}

DOMString HTMLImageElementImpl::altText() const
{
    // lets figure out the alt text.. magic stuff
    // http://www.w3.org/TR/1998/REC-html40-19980424/appendix/notes.html#altgen
    // also heavily discussed by Hixie on bugzilla
    DOMString alt( getAttribute( ATTR_ALT ) );
    // fall back to title attribute
    if ( alt.isNull() )
        alt = getAttribute( ATTR_TITLE );
#if 0
    if ( alt.isNull() ) {
220
        QString p = KUrl( document()->completeURL( getAttribute(ATTR_SRC).string() ) ).prettyUrl();
George Staikos's avatar
George Staikos committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        int pos;
        if ( ( pos = p.lastIndexOf( '.' ) ) > 0 )
            p.truncate( pos );
        alt = DOMString( KStringHandler::csqueeze( p ) );
    }
#endif

    return alt;
}

void HTMLImageElementImpl::attach()
{
    assert(!attached());
    assert(!m_render);
    assert(parentNode());

237
    RenderStyle* _style = document()->styleSelector()->styleForElement(this);
George Staikos's avatar
George Staikos committed
238 239 240 241
    _style->ref();
    if (parentNode()->renderer() && parentNode()->renderer()->childAllowed() &&
        _style->display() != NONE)
    {
242
        m_render = new (document()->renderArena()) RenderImage(this);
George Staikos's avatar
George Staikos committed
243 244 245 246 247 248 249 250 251 252 253 254
        m_render->setStyle(_style);
        parentNode()->renderer()->addChild(m_render, nextRenderer());
    }
    _style->deref();

    NodeBaseImpl::attach();
    if (m_render)
        m_render->updateFromElement();
}

void HTMLImageElementImpl::removedFromDocument()
{
Maks Orlovich's avatar
Maks Orlovich committed
255
    document()->underDocNamedCache().remove(m_name, this);
George Staikos's avatar
George Staikos committed
256 257 258 259 260
    HTMLElementImpl::removedFromDocument();
}

void HTMLImageElementImpl::insertedIntoDocument()
{
Maks Orlovich's avatar
Maks Orlovich committed
261
    document()->underDocNamedCache().add(m_name, this);
George Staikos's avatar
George Staikos committed
262 263 264
    HTMLElementImpl::insertedIntoDocument();
}

Maks Orlovich's avatar
Maks Orlovich committed
265
void HTMLImageElementImpl::removeId(const DOMString& id)
George Staikos's avatar
George Staikos committed
266
{
267
    document()->underDocNamedCache().remove(id, this);
George Staikos's avatar
George Staikos committed
268 269 270
    HTMLElementImpl::removeId(id);
}

Maks Orlovich's avatar
Maks Orlovich committed
271
void HTMLImageElementImpl::addId   (const DOMString& id)
George Staikos's avatar
George Staikos committed
272
{
273
    document()->underDocNamedCache().add(id, this);
George Staikos's avatar
George Staikos committed
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    HTMLElementImpl::addId(id);
}


long HTMLImageElementImpl::width() const
{
    if (!m_render) {
        DOMString widthAttr = getAttribute(ATTR_WIDTH);
        if (!widthAttr.isNull())
            return widthAttr.toInt();
        else if (m_image && m_image->pixmap_size().isValid())
            return m_image->pixmap_size().width();
        else
            return 0;
    }

Maks Orlovich's avatar
Maks Orlovich committed
290
    document()->updateLayout();
George Staikos's avatar
George Staikos committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307

    return m_render ? m_render->contentWidth() :
                      getAttribute(ATTR_WIDTH).toInt();
}

long HTMLImageElementImpl::height() const
{
    if (!m_render) {
        DOMString heightAttr = getAttribute(ATTR_HEIGHT);
        if (!heightAttr.isNull())
            return heightAttr.toInt();
        else if (m_image && m_image->pixmap_size().isValid())
            return m_image->pixmap_size().height();
        else
            return 0;
    }

Maks Orlovich's avatar
Maks Orlovich committed
308
    document()->updateLayout();
George Staikos's avatar
George Staikos committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325

    return m_render ? m_render->contentHeight() :
                      getAttribute(ATTR_HEIGHT).toInt();
}

void HTMLImageElementImpl::setWidth(long width)
{
    setAttribute(ATTR_WIDTH, QString::number(width));
}

void HTMLImageElementImpl::setHeight(long height)
{
    setAttribute(ATTR_HEIGHT, QString::number(height));
}

QImage HTMLImageElementImpl::currentImage() const
{
326 327
    if (!complete() || !m_image || !m_image->image())
        return QImage();
328

329 330 331 332 333
    QImage* im = m_image->image()->qimage();
    if (im)
        return *im;
    else
        return QImage();
George Staikos's avatar
George Staikos committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
}

long HTMLImageElementImpl::x() const
{
    if (renderer()) {
        int x = 0;
        int y = 0;
        renderer()->absolutePosition(x,y);
        return x;
    }
    return 0;
}

long HTMLImageElementImpl::y() const
{
    if (renderer()) {
        int x = 0;
        int y = 0;
        renderer()->absolutePosition(x,y);
        return y;
    }
    return 0;
}

QPixmap HTMLImageElementImpl::currentPixmap() const
{
    if (m_image) {
        return m_image->pixmap();
    }

    return QPixmap();
}

bool HTMLImageElementImpl::complete() const
{
    return m_image && m_image->isComplete();
}

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

Germain Garand's avatar
Germain Garand committed
374
HTMLMapElementImpl::HTMLMapElementImpl(DocumentImpl *doc)
George Staikos's avatar
George Staikos committed
375 376 377 378 379 380
    : HTMLElementImpl(doc)
{
}

HTMLMapElementImpl::~HTMLMapElementImpl()
{
381 382
    if(document() && document()->isHTMLDocument())
        static_cast<HTMLDocumentImpl*>(document())->mapMap.remove(name);
George Staikos's avatar
George Staikos committed
383 384 385 386 387 388 389 390 391 392 393 394 395
}

NodeImpl::Id HTMLMapElementImpl::id() const
{
    return ID_MAP;
}

bool
HTMLMapElementImpl::mapMouseEvent(int x_, int y_, int width_, int height_,
                                  RenderObject::NodeInfo& info)
{
    //cout << "map:mapMouseEvent " << endl;
    //cout << x_ << " " << y_ <<" "<< width_ <<" "<< height_ << endl;
Tobias Koenig's avatar
Tobias Koenig committed
396
    QStack<NodeImpl*> nodeStack;
George Staikos's avatar
George Staikos committed
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

    NodeImpl *current = firstChild();
    while(1)
    {
        if(!current)
        {
            if(nodeStack.isEmpty()) break;
            current = nodeStack.pop();
            current = current->nextSibling();
            continue;
        }
        if(current->id()==ID_AREA)
        {
            //cout << "area found " << endl;
            HTMLAreaElementImpl* area=static_cast<HTMLAreaElementImpl*>(current);
            if (area->mapMouseEvent(x_,y_,width_,height_, info))
                return true;
        }
        NodeImpl *child = current->firstChild();
        if(child)
        {
            nodeStack.push(current);
            current = child;
        }
        else
        {
            current = current->nextSibling();
        }
    }

    return false;
}

void HTMLMapElementImpl::parseAttribute(AttributeImpl *attr)
{
    switch (attr->id())
    {
    case ATTR_ID:
435
        if (document()->htmlMode() != DocumentImpl::XHtml) {
George Staikos's avatar
George Staikos committed
436 437
            HTMLElementImpl::parseAttribute(attr);
            break;
438
        }
439 440
        else {
            // add name with full url:
441
            const QString url = document()->completeURL(attr->value().trimSpaces().string());
442 443
            if(document()->isHTMLDocument())
                static_cast<HTMLDocumentImpl*>(document())->mapMap[url] = this;
George Staikos's avatar
George Staikos committed
444 445 446 447 448 449
        }
        // fall through
    case ATTR_NAME:
    {
        DOMString s = attr->value();
        if(*s.unicode() == '#')
Tobias Koenig's avatar
Tobias Koenig committed
450
            name = QString(s.unicode()+1, s.length()-1).toLower();
George Staikos's avatar
George Staikos committed
451
        else
Tobias Koenig's avatar
Tobias Koenig committed
452
            name = s.string().toLower();
George Staikos's avatar
George Staikos committed
453
	// ### make this work for XML documents, e.g. in case of <html:map...>
454 455
        if(document()->isHTMLDocument())
            static_cast<HTMLDocumentImpl*>(document())->mapMap[name] = this;
George Staikos's avatar
George Staikos committed
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470

        //fallthrough
    }
    default:
        HTMLElementImpl::parseAttribute(attr);
    }
}

HTMLCollectionImpl* HTMLMapElementImpl::areas()
{
    return new HTMLCollectionImpl(this, HTMLCollectionImpl::MAP_AREAS);
}

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

Germain Garand's avatar
Germain Garand committed
471
HTMLAreaElementImpl::HTMLAreaElementImpl(DocumentImpl *doc)
George Staikos's avatar
George Staikos committed
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    : HTMLAnchorElementImpl(doc)
{
    m_coords=0;
    m_coordsLen = 0;
    nohref = false;
    shape = Unknown;
    lasth = lastw = -1;
}

HTMLAreaElementImpl::~HTMLAreaElementImpl()
{
    delete [] m_coords;
}

NodeImpl::Id HTMLAreaElementImpl::id() const
{
    return ID_AREA;
}

void HTMLAreaElementImpl::parseAttribute(AttributeImpl *attr)
{
    switch (attr->id())
    {
    case ATTR_SHAPE:
        if ( strcasecmp( attr->value(), "default" ) == 0 )
            shape = Default;
        else if ( strcasecmp( attr->value(), "circle" ) == 0 )
            shape = Circle;
        else if ( strcasecmp( attr->value(), "poly" ) == 0 || strcasecmp( attr->value(),  "polygon" ) == 0 )
            shape = Poly;
        else if ( strcasecmp( attr->value(), "rect" ) == 0 )
            shape = Rect;
        break;
    case ATTR_COORDS:
        delete [] m_coords;
        m_coords = attr->val()->toCoordsArray(m_coordsLen);
        break;
    case ATTR_NOHREF:
        nohref = attr->val() != 0;
        break;
    case ATTR_TARGET:
        m_hasTarget = attr->val() != 0;
        break;
    case ATTR_ALT:
        break;
    case ATTR_ACCESSKEY:
        break;
    default:
        HTMLAnchorElementImpl::parseAttribute(attr);
    }
}

bool HTMLAreaElementImpl::mapMouseEvent(int x_, int y_, int width_, int height_,
                                   RenderObject::NodeInfo& info)
{
    bool inside = false;
    if (width_ != lastw || height_ != lasth)
    {
        region=getRegion(width_, height_);
        lastw=width_; lasth=height_;
    }
    if (region.contains(QPoint(x_,y_)))
    {
        inside = true;
        info.setInnerNode(this);
        info.setURLElement(this);
    }

    return inside;
}

QRect HTMLAreaElementImpl::getRect() const
{
    if (parentNode()->renderer()==0)
        return QRect();
    int dx, dy;
    if (!parentNode()->renderer()->absolutePosition(dx, dy))
        return QRect();
    QRegion region = getRegion(lastw,lasth);
    region.translate(dx, dy);
    return region.boundingRect();
}

QRegion HTMLAreaElementImpl::getRegion(int width_, int height_) const
{
    QRegion region;
    if (!m_coords)
        return region;

    // added broken HTML support (Dirk): some pages omit the SHAPE
    // attribute, so we try to guess by looking at the coords count
    // what the HTML author tried to tell us.

    // a Poly needs at least 3 points (6 coords), so this is correct
    if ((shape==Poly || shape==Unknown) && m_coordsLen > 5) {
Frederik Schwarzer's avatar
Frederik Schwarzer committed
567
        // make sure it is even
George Staikos's avatar
George Staikos committed
568 569 570 571 572 573 574
        int len = m_coordsLen >> 1;
        QPolygon points(len);
        for (int i = 0; i < len; ++i)
            points.setPoint(i, m_coords[(i<<1)].minWidth(width_),
                            m_coords[(i<<1)+1].minWidth(height_));
        region = QRegion(points);
    }
Tom Albers's avatar
Tom Albers committed
575
    else if ((shape==Circle && m_coordsLen>=3) || (shape==Unknown && m_coordsLen == 3)) {
George Staikos's avatar
George Staikos committed
576 577 578 579
        int r = qMin(m_coords[2].minWidth(width_), m_coords[2].minWidth(height_));
        region = QRegion(m_coords[0].minWidth(width_)-r,
                         m_coords[1].minWidth(height_)-r, 2*r, 2*r,QRegion::Ellipse);
    }
Tom Albers's avatar
Tom Albers committed
580
    else if ((shape==Rect && m_coordsLen>=4) || (shape==Unknown && m_coordsLen == 4)) {
George Staikos's avatar
George Staikos committed
581 582 583 584
        int x0 = m_coords[0].minWidth(width_);
        int y0 = m_coords[1].minWidth(height_);
        int x1 = m_coords[2].minWidth(width_);
        int y1 = m_coords[3].minWidth(height_);
585 586 587
        // use qMin () and qAbs () to make sure that this works for any pair
        // of opposite corners (x0,y0) and (x1,y1)
        region = QRegion(qMin(x0,x1),qMin(y0,y1),qAbs(x1-x0),qAbs(y1-y0));
George Staikos's avatar
George Staikos committed
588 589 590 591 592 593 594 595
    }
    else if (shape==Default)
        region = QRegion(0,0,width_,height_);
    // else
       // return null region

    return region;
}