Exemple #1
0
void KHTMLReader::completed()
{
    kDebug(30503) << "KHTMLReader::completed";
    qApp->exit_loop();
    DOM::Document doc = _html->document(); // FIXME parse <HEAD> too
    DOM::NodeList list = doc.getElementsByTagName("body");
    DOM::Node docbody = list.item(0);

    if (docbody.isNull()) {
        kWarning(30503) << "no <BODY>, giving up";
        _it_worked = false;
        return;
    }


    parseNode(docbody);

    list = doc.getElementsByTagName("head");
    DOM::Node dochead = list.item(0);
    if (!dochead.isNull())
        parse_head(dochead);
    else
        kWarning(30503) << "WARNING: no html <HEAD> section";

    _writer->cleanUpParagraph(state()->paragraph);
    _it_worked = _writer->writeDoc();
}
Exemple #2
0
static void clear_node(DOM::Node n) {
  if(!n.isNull())
  while(1) {
    DOM::Node f = n.firstChild();
    if(f.isNull())
      break;
    n.removeChild(f);
  }
}
void DOMTreeView::showRecursive(const DOM::Node &pNode, const DOM::Node &node, uint depth)
{
  DOMListViewItem *cur_item;
  DOMListViewItem *parent_item = m_itemdict.value(pNode.handle(), 0);

  if (depth > m_maxDepth) {
    m_maxDepth = depth;
  }

  if (depth == 0) {
    cur_item = new DOMListViewItem(node, m_listView);
    m_document = pNode.ownerDocument();
  } else {
    cur_item = new DOMListViewItem(node, parent_item);
  }

  //kDebug(90180) << node.nodeName().string() << " [" << depth << "]";
  cur_item = addElement (node, cur_item, false);
  m_listView->setItemExpanded(cur_item, depth < m_expansionDepth);

  if(node.handle()) {
    m_itemdict.insert(node.handle(), cur_item);
  }

  DOM::Node child = node.firstChild();
  if (child.isNull()) {
    DOM::HTMLFrameElement frame = node;
    if (!frame.isNull()) {
      child = frame.contentDocument().documentElement();
    } else {
      DOM::HTMLIFrameElement iframe = node;
      if (!iframe.isNull())
        child = iframe.contentDocument().documentElement();
    }
  }
  while(!child.isNull()) {
    showRecursive(node, child, depth + 1);
    child = child.nextSibling();
  }

  const DOM::Element element = node;
  if (!m_bPure) {
    if (!element.isNull() && !element.firstChild().isNull()) {
      if(depth == 0) {
	cur_item = new DOMListViewItem(node, m_listView, cur_item);
	m_document = pNode.ownerDocument();
      } else {
	cur_item = new DOMListViewItem(node, parent_item, cur_item);
      }
      //kDebug(90180) << "</" << node.nodeName().string() << ">";
      cur_item = addElement(element, cur_item, true);
//       m_listView->setItemExpanded(cur_item, depth < m_expansionDepth);
    }
  }
}
Exemple #4
0
void DOMTreeView::moveToParent()
{
  // This is a hypersmart algorithm.
  // If infoNode is defined, go to the parent of infoNode, otherwise, go
  // to the parent of the tree view's current item.
  // Hope this isn't too smart.

  DOM::Node cur = infoNode;
  if (cur.isNull()) cur = static_cast<DOMListViewItem *>(m_listView->currentItem())->node();

  if (cur.isNull()) return;

  cur = cur.parentNode();
  activateNode(cur);
}
Exemple #5
0
void KonqMFIcon::extractCard(DOM::Node node) {
	QString name, value;
	DOM::NodeList nodes = node.childNodes();
	unsigned int n = nodes.length();
	value += "BEGIN:VCARD\nVERSION:3.0\n";
	for (unsigned int i = 0; i < n; ++i) {
		DOM::Node node = nodes.item(i);
		DOM::NamedNodeMap map = node.attributes();
		for (unsigned int j = 0; j < map.length(); ++j) {
			if (map.item(j).nodeName().string() != "class") {
				continue;
			}
			QStringList l = QStringList::split(' ', map.item(j).nodeValue().string());
			for (QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
				if (*it == "photo") {
				} else if (*it == "adr") {
					value += "ADR:" + extractAddress(node) + "\n";
				} else if (*it == "tel") {
					value += "TEL;TYPE=VOICE:" + textForNode(node) + "\n";
				} else if (*it == "fn") {
					name = textForNode(node);
					value += "FN:" + name + "\n";
				} else if (*it == "url") {
					DOM::Node at = node.attributes().getNamedItem("href");
					if (!at.isNull()) {
						value += "URL:" + at.nodeValue().string().stripWhiteSpace() + "\n";
					}
				} else if (*it == "email") {
					DOM::Node at = node.attributes().getNamedItem("href");
					if (!at.isNull()) {
						QString v = at.nodeValue().string();
						if (v.startsWith("mailto:")) {
							v = v.mid(7);
						}
						value += "EMAIL:" + v.stripWhiteSpace() + "\n";
					}
				} else if (*it == "org") {
					value += "ORG:" + textForNode(node) + "\n";
				}
			}
		}
	}

	if (!name.isEmpty()) {
		value += "END:VCARD\n";
		_cards.append(qMakePair(name, value));
	}
}
QVariant KJSProxyImpl::evaluate(QString filename, int baseLine,
                                const QString&str, const DOM::Node &n, Completion *completion) {
  // evaluate code. Returns the JS return value or an invalid QVariant
  // if there was none, an error occured or the type couldn't be converted.

  initScript();
  // inlineCode is true for <a href="javascript:doSomething()">
  // and false for <script>doSomething()</script>. Check if it has the
  // expected value in all cases.
  // See smart window.open policy for where this is used.
  bool inlineCode = filename.isNull();
  //kdDebug(6070) << "KJSProxyImpl::evaluate inlineCode=" << inlineCode << endl;

#ifdef KJS_DEBUGGER
  if (inlineCode)
    filename = "(unknown file)";
  if (KJSDebugWin::instance()) {
    KJSDebugWin::instance()->attach(m_script);
    KJSDebugWin::instance()->setNextSourceInfo(filename,baseLine);
  //    KJSDebugWin::instance()->setMode(KJSDebugWin::Step);
  }
#else
  Q_UNUSED(baseLine);
#endif

  m_script->setInlineCode(inlineCode);
  Window* window = Window::retrieveWindow( m_part );
  KJS::Value thisNode = n.isNull() ? Window::retrieve( m_part ) : getDOMNode(m_script->globalExec(),n);

  UString code( str );

  KJSCPUGuard guard;
  guard.start();
  Completion comp = m_script->evaluate(code, thisNode);
  guard.stop();

  bool success = ( comp.complType() == Normal ) || ( comp.complType() == ReturnValue );

  if (completion)
    *completion = comp;

#ifdef KJS_DEBUGGER
    //    KJSDebugWin::instance()->setCode(QString::null);
#endif

  window->afterScriptExecution();

  // let's try to convert the return value
  if (success && !comp.value().isNull())
    return ValueToVariant( m_script->globalExec(), comp.value());
  else
  {
    if ( comp.complType() == Throw )
    {
        UString msg = comp.value().toString(m_script->globalExec());
        kdWarning(6070) << "Script threw exception: " << msg.qstring() << endl;
    }
    return QVariant();
  }
}
Exemple #7
0
bool KHTMLReader::parse_ul(DOM::Element e)
{
    _list_depth++;
    bool popstateneeded = false;
    for (DOM::Node items = e.firstChild();!items.isNull();items = items.nextSibling()) {
        if (items.nodeName().string().toLower() == "li") {
            if (popstateneeded) {
                popState();
                //popstateneeded = false;
            }
            pushNewState();
            startNewLayout();
            popstateneeded = true;
            _writer->layoutAttribute(state()->paragraph, "COUNTER", "numberingtype", "1");
            _writer->layoutAttribute(state()->paragraph, "COUNTER", "righttext", ".");
            if (e.tagName().string().toLower() == "ol") {
                _writer->layoutAttribute(state()->paragraph, "COUNTER", "type", "1");
                _writer->layoutAttribute(state()->paragraph, "COUNTER", "numberingtype", "1");
                _writer->layoutAttribute(state()->paragraph, "COUNTER", "righttext", ".");
            } else {
                _writer->layoutAttribute(state()->paragraph, "COUNTER", "type", "10");
                _writer->layoutAttribute(state()->paragraph, "COUNTER", "numberingtype", "");
                _writer->layoutAttribute(state()->paragraph, "COUNTER", "righttext", "");
            }
            _writer->layoutAttribute(state()->paragraph, "COUNTER", "depth", QString("%1").arg(_list_depth - 1));
        }
        parseNode(items);
    }
    if (popstateneeded)
        popState();
    _list_depth--;
    return false;
}
Exemple #8
0
void DOMTreeView::slotMovedItems(QPtrList<QListViewItem> &items, QPtrList<QListViewItem> &/*afterFirst*/, QPtrList<QListViewItem> &afterNow)
{
  MultiCommand *cmd = new MultiCommand(i18n("Move Nodes"));
  _refreshed = false;

  QPtrList<QListViewItem>::Iterator it = items.begin();
  QPtrList<QListViewItem>::Iterator anit = afterNow.begin();
  for (; it != items.end(); ++it, ++anit) {
    DOMListViewItem *item = static_cast<DOMListViewItem *>(*it);
    DOMListViewItem *anitem = static_cast<DOMListViewItem *>(*anit);
    DOM::Node parent = static_cast<DOMListViewItem *>(item->parent())->node();
    Q_ASSERT(!parent.isNull());

// kdDebug(90180) << " afternow " << anitem << " node " << (anitem ? anitem->node().nodeName().string() : QString()) << "=" << (anitem ? anitem->node().nodeValue().string() : QString()) << endl;

    cmd->addCommand(new MoveNodeCommand(item->node(), parent,
      anitem ? anitem->node().nextSibling() : parent.firstChild())
    );
  }

  mainWindow()->executeAndAddCommand(cmd);

  // refresh *anyways*, otherwise consistency is disturbed
  if (!_refreshed) refresh();

  slotShowNode(current_node);
}
Exemple #9
0
void KHTMLReader::parseNode(DOM::Node node)
{

    // check if this is a text node.
    DOM::Text t = node;
    if (!t.isNull()) {
        _writer->addText(state()->paragraph, t.data().string(), 1, state()->in_pre_mode);
        return; // no children anymore...
    }

    // is this really needed ? it can't do harm anyway.
    state()->format = _writer->currentFormat(state()->paragraph, true);
    state()->layout = _writer->currentLayout(state()->paragraph);
    pushNewState();

    DOM::Element e = node;

    bool go_recursive = true;

    if (!e.isNull()) {
        // get the CSS information
        parseStyle(e);
        // get the tag information
        go_recursive = parseTag(e);
    }
    if (go_recursive) {
        for (DOM::Node q = node.firstChild(); !q.isNull(); q = q.nextSibling()) {
            parseNode(q);
        }
    }
    popState();


}
Exemple #10
0
void DOMTreeView::initializeOptionsFromNode(const DOM::Node &node)
{
  infoNode = node;

  nodeName->clear();
  nodeType->clear();
  nodeNamespace->clear();
  nodeValue->clear();

  if (node.isNull()) {
    nodeInfoStack->raiseWidget(EmptyPanel);
    return;
  }

  nodeName->setText(node.nodeName().string());
  nodeType->setText(QString::number(node.nodeType()));
  nodeNamespace->setText(node.namespaceURI().string());
//   nodeValue->setText(node.value().string());

  DOM::Element element = node;
  if (!element.isNull()) {
    initializeOptionsFromElement(element);
    return;
  }

  DOM::CharacterData cdata = node;
  if (!cdata.isNull()) {
    initializeOptionsFromCData(cdata);
    return;
  }

  // Fallback
  nodeInfoStack->raiseWidget(EmptyPanel);
}
Exemple #11
0
void DOMTreeView::showTree(const DOM::Node &pNode)
{
    if(pNode.isNull() || document != pNode.ownerDocument())
    {
	clear();
	m_itemdict.clear();
	m_nodedict.clear();
	if(pNode.isNull())
	    return;
	else if(pNode.ownerDocument().isNull())
	    recursive(0, pNode);
	else
	    recursive(0, pNode.ownerDocument());
    }
    setCurrentItem(m_itemdict[pNode.handle()]);
    ensureItemVisible(m_itemdict[pNode.handle()]);
}
Exemple #12
0
void DOMTreeView::slotItemClicked(QListViewItem *cur_item)
{
  DOMListViewItem *cur = static_cast<DOMListViewItem *>(cur_item);
  if (!cur) return;

  DOM::Node handle = cur->node();
  if (!handle.isNull()) {
    part->setActiveNode(handle);
  }
}
Exemple #13
0
void KonqMFIcon::extractEvent(DOM::Node node) {
	QString name, value = "BEGIN:VCALENDAR\nPRODID:-//Konqueror//EN\nVERSION:2.0\nBEGIN:VEVENT\n";
	DOM::NodeList nodes = node.childNodes();
	unsigned int n = nodes.length();
	for (unsigned int i = 0; i < n; ++i) {
		DOM::Node node = nodes.item(i);
		DOM::NamedNodeMap map = node.attributes();
		for (unsigned int j = 0; j < map.length(); ++j) {
			if (map.item(j).nodeName().string() != "class") {
				continue;
			}
			QStringList l = QStringList::split(' ', map.item(j).nodeValue().string());
			for (QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
				if (*it == "url") {
					DOM::Node at = node.attributes().getNamedItem("href");
					if (!at.isNull()) {
						value += "URL:" + at.nodeValue().string().stripWhiteSpace() + "\n";
					}
				} else if (*it == "dtstart") {
					DOM::Node at = node.attributes().getNamedItem("title");
					if (!at.isNull()) {
						value += "DTSTART:" + at.nodeValue().string().stripWhiteSpace() + "\n";
					}
				} else if (*it == "dtend") {
					DOM::Node at = node.attributes().getNamedItem("title");
					if (!at.isNull()) {
						value += "DTEND:" + at.nodeValue().string().stripWhiteSpace() + "\n";
					}
				} else if (*it == "summary") {
					name = textForNode(node);
					value += "SUMMARY:" + name + "\n";
				} else if (*it == "location") {
					value += "LOCATION:" + textForNode(node) + "\n";
				}
			}
		}
	}

	if (!name.isEmpty()) {
		value += "END:VEVENT\nEND:VCALENDAR\n";
		_events.append(qMakePair(name, value));
	}
}
Exemple #14
0
static void clear_from(DOM::Node n) {
  DOM::Node p = n.parentNode();
  while(1) {
    DOM::Node next = n.nextSibling();
    p.removeChild(n);
    if(next.isNull())
      break;
    n = next;
  }
}
void KGet_plug_in::slotShowLinks()
{
    if ( !parent() || !parent()->inherits( "KHTMLPart" ) )
        return;

    KHTMLPart *htmlPart = static_cast<KHTMLPart*>( parent() );
    KParts::Part *activePart = 0L;
    if ( htmlPart->partManager() )
    {
        activePart = htmlPart->partManager()->activePart();
        if ( activePart && activePart->inherits( "KHTMLPart" ) )
            htmlPart = static_cast<KHTMLPart*>( activePart );
    }

    DOM::HTMLDocument doc = htmlPart->htmlDocument();
    if ( doc.isNull() )
        return;

    DOM::HTMLCollection links = doc.links();

    QPtrList<LinkItem> linkList;
    std::set<QString> dupeCheck;
    for ( uint i = 0; i < links.length(); i++ )
    {
        DOM::Node link = links.item( i );
        if ( link.isNull() || link.nodeType() != DOM::Node::ELEMENT_NODE )
            continue;

        LinkItem *item = new LinkItem( (DOM::Element) link );
        if ( item->isValid() &&
             dupeCheck.find( item->url.url() ) == dupeCheck.end() )
        {
            linkList.append( item );
            dupeCheck.insert( item->url.url() );
        }
        else
            delete item;
    }

    if ( linkList.isEmpty() )
    {
        KMessageBox::sorry( htmlPart->widget(),
            i18n("There are no links in the active frame of the current HTML page."),
            i18n("No Links") );
        return;
    }

    KGetLinkView *view = new KGetLinkView();
    QString url = doc.URL().string();
    view->setPageURL( url );

    view->setLinks( linkList );
    view->show();
}
void ManipulateNodeCommand::remove()
{
  DOM::DocumentFragment frag = _node;

  if (frag.isNull()) {	// do a normal remove
    _node = _parent.removeChild(_node);

  } else {		// remove fragment nodes and recreate fragment
    DOM::DocumentFragment newfrag = _parent.ownerDocument().createDocumentFragment();

    for (DOM::Node i = frag.firstChild(); !i.isNull(); i = i.nextSibling()) {
      newfrag.appendChild(_parent.removeChild(i));
    }

    _node = newfrag;
  }
}
  // evaluate code. Returns the JS return value or an invalid QVariant
  // if there was none, an error occured or the type couldn't be converted.
  QVariant kjs_eval(KJScript *script, const QChar *c, unsigned int len,
		    const DOM::Node &n, KHTMLPart *khtmlpart)
  {
    script->init(); // set a valid current interpreter

#ifdef KJS_DEBUGGER
    kjs_html_debugger->attach(script);
    kjs_html_debugger->setCode(QString(c, len));
    kjs_html_debugger->setMode(KJS::Debugger::Step);
#endif

    KJS::KJSO thisNode = n.isNull() ?
			 KJS::Global::current().prototype() : getDOMNode(n);

    KJS::Global::current().put("[[ScriptURL]]",String(khtmlpart->url().url()),DontEnum | DontDelete);
    bool ret = script->evaluate(thisNode, c, len);
    KJS::Global::current().put("[[ScriptURL]]",Undefined(),DontEnum | DontDelete);

#ifdef KJS_DEBUGGER
    kjs_html_debugger->setCode(QString::null);
#endif

    // let's try to convert the return value
    QVariant res;
    if (ret && script->returnValue()) {
      KJS::KJSO retVal(script->returnValue());
      switch (retVal.type()) {
      case BooleanType:
	  res = QVariant(retVal.toBoolean().value(), 0);
	  break;
      case NumberType:
	  res = QVariant(retVal.toNumber().value());
	  break;
      case StringType:
	  res = QVariant(retVal.toString().value().qstring());
	  break;
      default:
	// everything else will be 'invalid'
	  break;
      }
    }
    return res;
  }
Exemple #18
0
bool KHTMLReader::parse_pre(DOM::Element e)
{
#if 0 // see Bug #74601 (normal): kword doesn't recognize PRE-tags in HTML
    //pushNewState();
    /// \todo set fixed width font
    DOM::HTMLElement htmlelement(e);
    if (! htmlelement.isNull())
        _writer->addText(state()->paragraph, htmlelement.innerHTML().string(), 1);
    startNewParagraph();
    //popState();
    return false; // children are already handled.
#else
    pushNewState();
    state()->in_pre_mode = true;
    for (DOM::Node q = e.firstChild(); !q.isNull(); q = q.nextSibling()) {
        parseNode(q); // parse everything...
    }
    popState();
    return false; // children are already handled.
#endif
}
Exemple #19
0
void DOMTreeView::slotShowTree(const DOM::Node &pNode)
{
  DOM::Node child;

  m_listView->clear();
  m_itemdict.clear();

  try
  {
    child = pNode.firstChild();
  }
  catch (DOM::DOMException &)
  {
    return;
  }

  while(!child.isNull()) {
    showRecursive(0, child, 0);
    child = child.nextSibling();
  }

  m_maxDepth--;
  //kdDebug(90180) << " Max Depth: " << m_maxDepth << endl;
}
void HTMLEnhancer::postUnenhanceNode(DOM::Node domNode)
{
	DOM::Node child, next;
	kNodeAttrs *attrs;

	if(domNode.isNull())
		return;

	//Try to remove the EmptyTextAsChildOfAChildlessElement Node first if present
	if(domNode.hasChildNodes())
	{
		child = domNode.firstChild();
		while(!child.isNull())
		{
			attrs = m_wkafkapart->getAttrs(child);
			next = child.nextSibling();
			if(attrs && attrs->specialBehavior() == kNodeAttrs::emptyTextAsChildOfAChildlessElement)
				kafkaCommon::removeDomNode(child);
			child = next;
		}
	}

	//Then try to remove the emptyTextSurroundingBlockElement* Nodes if present.
	if(!domNode.previousSibling().isNull())
	{
		attrs = m_wkafkapart->getAttrs(domNode.previousSibling());
		if(attrs && attrs->specialBehavior() == kNodeAttrs::emptyTextSurroundingBlockElementAtTheLeft)
			kafkaCommon::removeDomNode(domNode.previousSibling());
	}
	if(!domNode.nextSibling().isNull())
	{
		attrs = m_wkafkapart->getAttrs(domNode.nextSibling());
		if(attrs && attrs->specialBehavior() == kNodeAttrs::emptyTextSurroundingBlockElementAtTheRight)
			kafkaCommon::removeDomNode(domNode.nextSibling());
	}
}
ArtSVP *LibartCanvas::clipSingleSVP(ArtSVP *svp, SVGShapeImpl *shape)
{
	ArtSVP *clippedSvp = copy_svp(svp);
	SVGStylableImpl *style = dynamic_cast<SVGStylableImpl *>(shape);

	if(style)
	{
		QString clipPathRef = style->getClipPath();

		if(!clipPathRef.isEmpty())
		{
			CanvasClipPath *clipPath = m_clipPaths[clipPathRef];

			if(clipPath)
			{
				LibartClipPath *lclip = dynamic_cast<LibartClipPath *>(clipPath);
				reinterpret_cast<SVGClipPathElementImpl *>(clipPath->element())->setBBoxTarget(shape);

				lclip->init();

				if(lclip->clipSVP())
				{
					ArtSVP *s = art_svp_intersect(lclip->clipSVP(), clippedSvp);
					art_svp_free(clippedSvp);
					clippedSvp = s;
				}
			}
		}
	}

	SVGSVGElementImpl *svg = dynamic_cast<SVGSVGElementImpl *>(shape);

	// Clip outer svg, unless width and height not set
	if(svg && (!svg->isRootElement() || !svg->getAttribute("width").isEmpty() || !svg->getAttribute("height").isEmpty()) && !svg->getOverflow())
	{
		ArtSVP *svgClip = clippingRect(svg->clip(), svg->screenCTM());
		ArtSVP *s = art_svp_intersect(svgClip, clippedSvp);
		art_svp_free(clippedSvp);
		art_svp_free(svgClip);
		clippedSvp = s;
	}

	if(dynamic_cast<SVGPatternElementImpl *>(shape) != 0)
	{
		// TODO: inherit clipping paths into tile space
	}
	else if(dynamic_cast<SVGMarkerElementImpl *>(shape) != 0)
	{
		SVGMarkerElementImpl *marker = static_cast<SVGMarkerElementImpl *>(shape);

		if(!marker->clipShape().isEmpty())
		{
			ArtSVP *clipShape = svpFromPolygon(marker->clipShape());
			ArtSVP *s = art_svp_intersect(clipShape, clippedSvp);
			art_svp_free(clipShape);
			art_svp_free(clippedSvp);
			clippedSvp = s;
		}

		// TODO: inherit clipping paths into marker space
	}
	else
	{
		SVGElementImpl *element = dynamic_cast<SVGElementImpl *>(shape);
		DOM::Node parentNode = element->parentNode();

		if(!parentNode.isNull())
		{
			SVGElementImpl *parent = element->ownerDoc()->getElementFromHandle(parentNode.handle());

			if(parent)
			{
				SVGShapeImpl *parentShape = dynamic_cast<SVGShapeImpl *>(parent);

				if(parentShape)
				{
					// Clip against ancestor clipping paths
					ArtSVP *parentClippedSvp = clipSingleSVP(clippedSvp, parentShape);
					art_svp_free(clippedSvp);
					clippedSvp = parentClippedSvp;
				}
			}
		}
	}

	return clippedSvp;
}
Exemple #22
0
bool KHTMLReader::parse_table(DOM::Element e)
{
    if (_writer->isInTable()) {
        // We are already inside of a table. Tables in tables are not supported
        // yet. So, just add that table-content as text.
        for (DOM::Node rows = e.firstChild().firstChild();!rows.isNull();rows = rows.nextSibling())
            if (!rows.isNull() && rows.nodeName().string().toLower() == "tr")
                for (DOM::Node cols = rows.firstChild();!cols.isNull();cols = cols.nextSibling())
                    if (!cols.isNull())
                        parseNode(cols);
        return false;
    }

    DOM::Element table_body = e.firstChild();
    if (table_body.isNull()) {
        // If the table_body is empty, we don't continue cause else
        // KHTML will throw a DOM::DOMException if we try to access
        // the null element.
        return true;
    }

    int tableno = _writer->createTable();
    int nrow = 0;
    int ncol = 0;
    bool has_borders = false;
    QColor bgcolor = parsecolor("#FFFFFF");

    if (!table_body.getAttribute("bgcolor").string().isEmpty())
        bgcolor = parsecolor(table_body.getAttribute("bgcolor").string());
    if ((e.getAttribute("border").string().toInt() > 0))
        has_borders = true;

    // fixme rewrite this proper
    //(maybe using computed sizes from khtml if thats once exported)
    for (DOM::Node rowsnode = table_body.firstChild();!rowsnode.isNull();rowsnode = rowsnode.nextSibling()) {
        DOM::Element rows = rowsnode;
        if (!rows.isNull() && rows.tagName().string().toLower() == "tr") {
            QColor obgcolor = bgcolor;
            if (!rows.getAttribute("bgcolor").string().isEmpty())
                bgcolor = parsecolor(rows.getAttribute("bgcolor").string());

            ncol = 0;
            for (DOM::Node colsnode = rows.firstChild();!colsnode.isNull();colsnode = colsnode.nextSibling()) {
                DOM::Element cols = colsnode;
                const QString nodename = cols.isNull() ? QString() : cols.nodeName().string().toLower();
                if (nodename == "td" || nodename == "th") {
                    QColor bbgcolor = bgcolor;
                    if (!cols.getAttribute("bgcolor").string().isEmpty())
                        bgcolor = parsecolor(cols.getAttribute("bgcolor").string());

                    pushNewState();
                    QRect colrect = cols.getRect();
                    state()->frameset = _writer->createTableCell(tableno, nrow, ncol, 1, colrect);
                    state()->frameset.firstChild().toElement().setAttribute("bkRed", bgcolor.red());
                    state()->frameset.firstChild().toElement().setAttribute("bkGreen", bgcolor.green());
                    state()->frameset.firstChild().toElement().setAttribute("bkBlue", bgcolor.blue());
                    if (has_borders) {
                        state()->frameset.firstChild().toElement().setAttribute("lWidth", 1);
                        state()->frameset.firstChild().toElement().setAttribute("rWidth", 1);
                        state()->frameset.firstChild().toElement().setAttribute("bWidth", 1);
                        state()->frameset.firstChild().toElement().setAttribute("tWidth", 1);
                    }

                    // fixme don't guess. get it right.
                    state()->paragraph = _writer->addParagraph(state()->frameset);
                    parseNode(cols);
                    _writer->cleanUpParagraph(state()->paragraph);
                    popState();
                    ncol++;
                    bgcolor = bbgcolor;
                }
            }
            nrow++;
            bgcolor = obgcolor;
        }
    }
    _writer->finishTable(tableno/*,0,0,r.right()-r.left(),r.bottom()-r.top()*/); // FIXME find something better.
    startNewParagraph(false, false);
    _writer->createInline(state()->paragraph, _writer->fetchTableCell(tableno, 0, 0));
    startNewParagraph(false, false);
    return false; // we do our own recursion
}
Exemple #23
0
void DOMTreeView::saveRecursive(const DOM::Node &pNode, int indent)
{
  const QString nodeName(pNode.nodeName().string());
  QString text;
  QString strIndent;
  strIndent.fill(' ', indent);
  const DOM::Element element = static_cast<const DOM::Element>(pNode);

  text = strIndent;

  if ( !element.isNull() ) {
    if (nodeName.at(0)=='-') {
      /* Don't save khtml internal tags '-konq..'
       * Approximating it with <DIV>
       */
      text += "<DIV> <!-- -KONG_BLOCK -->";
    } else {
      text += "<" + nodeName;

      QString attributes;
      DOM::Attr attr;
      const DOM::NamedNodeMap attrs = element.attributes();
      unsigned long lmap = attrs.length();
      for( uint j=0; j<lmap; j++ ) {
	attr = static_cast<DOM::Attr>(attrs.item(j));
	attributes += " " + attr.name().string() + "=\"" + attr.value().string() + "\"";
      }
      if (!(attributes.isEmpty())){
	text += " ";
      }

      text += attributes.simplifyWhiteSpace();

      if(element.firstChild().isNull()) {
	text += "/>";
      } else {
	text += ">";
      }
    }
  } else {
    text = strIndent + pNode.nodeValue().string();
  }

  kdDebug(90180) << text << endl;
  if (!(text.isEmpty())) {
    (*m_textStream) << text << endl;
  }

  DOM::Node child = pNode.firstChild();
  while(!child.isNull()) {
    saveRecursive(child, indent+2);
    child = child.nextSibling();
  }

  if (!(element.isNull()) && (!(element.firstChild().isNull()))) {
    if (nodeName.at(0)=='-') {
      text = strIndent + "</DIV> <!-- -KONG_BLOCK -->";
    } else {
      text = strIndent + "</" + pNode.nodeName().string() + ">";
    }
    kdDebug(90180) << text << endl;
    (*m_textStream) << text << endl;
  }
}
void HTMLEnhancer::postEnhanceNode(DOM::Node domNode)
{
	DOM::Node textNode;
	kNodeAttrs *props;
	QTag *qTag;
	bool isInline;

	if(domNode.isNull())
		return;

	//If domNode is a Block and there is no text around, and if domNode's parent can handle
	//text or a P tag, add an empty text DOM::Node
	// so that the user can access this area.
	qTag = QuantaCommon::tagFromDTD(m_wkafkapart->getCurrentDoc()->defaultDTD(),
		domNode.nodeName().string());
	isInline = kafkaCommon::isInline(domNode.nodeName().string());
	if(domNode.nodeType() == DOM::Node::ELEMENT_NODE &&
		(!isInline || (isInline && qTag && qTag->isSingle())))
	{
		qTag = QuantaCommon::tagFromDTD(m_wkafkapart->getNode(domNode.parentNode()));

		if((domNode.nextSibling().isNull() ||
			(!domNode.nextSibling().isNull() &&
			domNode.nextSibling().nodeType() == DOM::Node::ELEMENT_NODE &&
			!kafkaCommon::isInline(domNode.nextSibling().nodeName().string())))
			&& qTag && (qTag->isChild("#text", false) || qTag->isChild("p", false)) &&
			domNode.nodeName().string().lower() != "p")
		{
			textNode = kafkaCommon::createTextDomNode("",
				m_wkafkapart->getKafkaWidget()->document());
			props = m_wkafkapart->connectDomNodeToQuantaNode(textNode, 0L);
			props->setIsLinkedToNode(false);
			props->setSpecialBehavior(kNodeAttrs::emptyTextSurroundingBlockElementAtTheRight);
			kafkaCommon::insertDomNode(textNode, domNode.parentNode(),
				domNode.nextSibling());
		}

		if((domNode.previousSibling().isNull() || (!domNode.previousSibling().isNull() &&
			domNode.previousSibling().nodeType() == DOM::Node::ELEMENT_NODE &&
			!kafkaCommon::isInline(domNode.previousSibling().nodeName().string())))
			&& qTag && (qTag->isChild("#text", false) || qTag->isChild("p", false)) &&
			domNode.nodeName().string().lower() != "p")
		{
			textNode = kafkaCommon::createTextDomNode("",
				m_wkafkapart->getKafkaWidget()->document());
			props = m_wkafkapart->connectDomNodeToQuantaNode(textNode, 0L);
			props->setIsLinkedToNode(false);
			props->setSpecialBehavior(kNodeAttrs::emptyTextSurroundingBlockElementAtTheLeft);
			kafkaCommon::insertDomNode(textNode, domNode.parentNode(),
				domNode);
		}
	}

	//If domNode is an childless element, and if it can handle Text or a P tag,
	//add an empty text DOM::Node so that the
	//user can access this area.
	qTag = QuantaCommon::tagFromDTD(m_wkafkapart->getNode(domNode));
	if(domNode.nodeType() == DOM::Node::ELEMENT_NODE &&
		!domNode.hasChildNodes() && qTag && (qTag->isChild("#text", false) ||
		qTag->isChild("p", false)))
	{
		textNode = kafkaCommon::createTextDomNode("",
			m_wkafkapart->getKafkaWidget()->document());
		props = m_wkafkapart->connectDomNodeToQuantaNode(textNode, 0L);
		props->setIsLinkedToNode(false);
		props->setSpecialBehavior(kNodeAttrs::emptyTextAsChildOfAChildlessElement);
		kafkaCommon::insertDomNode(textNode, domNode);
	}
}