Exemplo n.º 1
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();


}
Exemplo n.º 2
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);
}
Exemplo n.º 3
0
bool KHTMLReader::parse_font(DOM::Element e)
{
    // fixme don't hardcode 12 font size ...
    QString face = e.getAttribute("face").string();
    QColor color = parsecolor("#000000");
    if (!e.getAttribute("color").string().isEmpty())
        color = parsecolor(e.getAttribute("color").string());
    QString size = e.getAttribute("size").string();
    int isize = -1;
    if (size.startsWith('+'))
        isize = 12 + size.right(size.length() - 1).toInt();
    else if (size.startsWith('-'))
        isize = 12 - size.right(size.length() - 1).toInt();
    else
        isize = 12 + size.toInt();

    _writer->formatAttribute(state()->paragraph, "FONT", "name", face);
    if ((isize >= 0) && (isize != 12))
        _writer->formatAttribute(state()->paragraph, "SIZE", "value", QString("%1").arg(isize));

    _writer->formatAttribute(state()->paragraph, "COLOR", "red", QString("%1").arg(color.red()));
    _writer->formatAttribute(state()->paragraph, "COLOR", "green", QString("%1").arg(color.green()));
    _writer->formatAttribute(state()->paragraph, "COLOR", "blue", QString("%1").arg(color.blue()));
    return true;
}
Exemplo n.º 4
0
void DOMTreeView::slotItemRenamed(QListViewItem *lvi, const QString &str, int col)
{
  AttributeListItem *item = static_cast<AttributeListItem *>(lvi);

  DOM::Element element = infoNode;
  if (element.isNull()) return; // Should never happen

  switch (col) {
    case 0: {
      ManipulationCommand *cmd;
//       kdDebug(90180) << k_funcinfo << "col 0: " << element.nodeName() << " isNew: " << item->isNew() << endl;
      if (item->isNew()) {
        cmd = new AddAttributeCommand(element, str, item->text(1));
	item->setNew(false);
      } else
        cmd = new RenameAttributeCommand(element, item->text(0), str);

      mainWindow()->executeAndAddCommand(cmd);
      break;
    }
    case 1: {
      if (item->isNew()) { lvi->setText(1, QString()); break; }

      ChangeAttributeValueCommand *cmd = new ChangeAttributeValueCommand(
      			  element, item->text(0), str);
      mainWindow()->executeAndAddCommand(cmd);
      break;
    }
  }
}
Exemplo n.º 5
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;
}
Exemplo n.º 6
0
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);
    }
  }
}
Exemplo n.º 7
0
  void do_start_element(const std::string& qName,
                        const std::string& namespaceURI,
                        const SAX::Attributes<std::string>& atts)
  {
    indent();
    DOM::Element<std::string> elem = document().createElementNS(namespaceURI, qName);
    current().appendChild(elem);

    // attributes here
    for(int i = 0; i < atts.getLength(); ++i)
      elem.setAttributeNS(atts.getURI(i), atts.getQName(i), atts.getValue(i));

    current_ = elem;
  } // do_start_element
Exemplo n.º 8
0
void Textual::remove(const Index& index) {
  DOM::HTMLDocument document = htmlDocument();
  if(index.atVariationStart()) {
    DOM::Element vc = document.getElementById("vc_"+index);
    if(!vc.isNull()) {
      /* remove a number? */
      DOM::Element comm(vc.previousSibling());
      DOM::Element mvnum(vc.nextSibling());
      if(!mvnum.isNull() && mvnum.getAttribute("id").string().startsWith("nm_") &&
            !comm.isNull() && comm.getAttribute("id").string().startsWith("cm_"))
      {
        DOM::Element move(mvnum.nextSibling());
        int mv_num = move.getAttribute("mvnum").string().toInt();
        int sub_mv_num = move.getAttribute("submvnum").string().toInt();
        if(!(mv_num>0 && (sub_mv_num==0 && (mv_num%2 || m_layout_style))))
          mvnum.parentNode().removeChild(mvnum);
      }
      vc.parentNode().removeChild(vc);
    }
  }
  else {
    DOM::Element rm = document.getElementById("nm_"+index);
    if(rm.isNull())
      rm = document.getElementById("mv_"+index);
    if(!rm.isNull())
      clear_from(rm);
  }
  if(m_curr_selected >= index)
    m_curr_selected = Index(-1);
}
Exemplo n.º 9
0
bool KHTMLReader::parse_a(DOM::Element e)
{
    QString url = e.getAttribute("href").string();
    if (!url.isEmpty()) {
        QString linkName;
        DOM::Text t = e.firstChild();
        if (t.isNull()) {
            /* Link without text -> just drop it*/
            return false; /* stop parsing recursively */
        }
        linkName = t.data().string().simplified();
        t.setData(DOM::DOMString("#")); // replace with '#'
        _writer->createLink(state()->paragraph, linkName, url);
    }
    return true; /* stop parsing recursively */
}
Exemplo n.º 10
0
bool KHTMLReader::parse_CommonAttributes(DOM::Element e)
{
    kDebug(30503) << "entering KHTMLReader::parse_CommonAttributes";
    kDebug(30503) << "tagName is" << e.tagName().string();
    QString s = e.getAttribute("align").string();
    if (!s.isEmpty()) {
        _writer->formatAttribute(state()->paragraph, "FLOW", "align", s);
    }
    QRegExp rx("h[0-9]+");
    if (0 == rx.search(e.getAttribute("class").string()))
        // example: <p class="h1" style="text-align:left; ">
    {
        _writer->layoutAttribute(state()->paragraph, "NAME", "value", e.getAttribute("class").string());
    }
    return true;
}
Exemplo n.º 11
0
void KHTMLReader::parseStyle(DOM::Element e)
{
    // styles are broken broken broken broken broken broken.
    // FIXME: use getComputedStyle - note: it only returns 0, but works nevertheless
    kDebug(30503) << "entering parseStyle";
    DOM::CSSStyleDeclaration s1 = e.style();
    DOM::Document doc = _html->document();
    DOM::CSSStyleDeclaration s2 = doc.defaultView().getComputedStyle(e, "");

    kDebug(30503) << "font-weight=" << s1.getPropertyValue("font-weight").string();
    if (s1.getPropertyValue("font-weight").string() == "bolder") {
        _writer->formatAttribute(state()->paragraph, "WEIGHT", "value", "75");
    }
    if (s1.getPropertyValue("font-weight").string() == "bold") {
        _writer->formatAttribute(state()->paragraph, "WEIGHT", "value", "75");
    }

    // process e.g. <style="color: #ffffff">
    if (! s1.getPropertyValue("color").string().isEmpty()) {
        QColor c = parsecolor(s1.getPropertyValue("color").string());
        _writer->formatAttribute(state()->paragraph, "COLOR", "red", QString::number(c.red()));
        _writer->formatAttribute(state()->paragraph, "COLOR", "green", QString::number(c.green()));
        _writer->formatAttribute(state()->paragraph, "COLOR", "blue", QString::number(c.blue()));
    } // done
    // process e.g. <style="font-size: 42">
    if (! s1.getPropertyValue("font-size").string().isEmpty()) {
        QString size = s1.getPropertyValue("font-size").string();
        if (size.endsWith("pt")) {
            size = size.left(size.length() - 2);
        }
        _writer->formatAttribute(state()->paragraph, "SIZE", "value", size);
    }
    // done
    // process e.g. <style="text-align: center">this is in the center</style>
    if (! s1.getPropertyValue("text-align").string().isEmpty()) {
        state()->layout = _writer->setLayout(state()->paragraph, state()->layout);
        _writer->layoutAttribute(state()->paragraph, "FLOW", "align", s1.getPropertyValue("text-align").string());
    }
    // done

    /*if (DOM::PROPV("font-weight") == "bolder")
    _writer->formatAttribute(state()->paragraph,"WEIGHT","value","75");
    */
    /*
         // debugging code.
         kDebug(30503) <<"e.style()";
         for (unsigned int i=0;i<s1.length();i++) {
            kDebug(30503) << QString("%1: %2").arg(s1.item(i).string()).arg(s1.getPropertyValue(s1.item(i)).string());
         }
         kDebug(30503) <<"override style";
         for (unsigned int i=0;i<s2.length();i++) {
            kDebug(30503) << QString("%1: %2").arg(s2.item(i).string()).arg(s2.getPropertyValue(s2.item(i)).string());
         }
    */
}
Exemplo n.º 12
0
LinkItem::LinkItem( DOM::Element link )
    : m_valid( false )
{
    DOM::NamedNodeMap attrs = link.attributes();
    DOM::Node href = attrs.getNamedItem( "href" );

    // Load source address of images too
    DOM::Node src = attrs.getNamedItem( "src" );
    if ( href.nodeValue().string().isEmpty() && !src.nodeValue().string().isEmpty() )
      href = src;

    // qDebug("*** href: %s", href.nodeValue().string().latin1() );

    QString urlString = link.ownerDocument().completeURL( href.nodeValue() ).string();
    if ( urlString.isEmpty() )
        return;

    url = KUrl( urlString );
    if ( !KProtocolManager::supportsReading( url ) )
        return;

    // somehow getElementsByTagName("#text") doesn't work :(
    DOM::NodeList children = link.childNodes();
    for ( uint i = 0; i < children.length(); i++ )
    {
        DOM::Node node = children.item( i );
        if ( node.nodeType() == DOM::Node::TEXT_NODE )
            text.append( node.nodeValue().string() );
    }

    // force "local file" mimetype determination
    KMimeType::Ptr mt = KMimeType::findByUrl( url, 0, true, true);
    icon = mt->iconName();
    mimeType = mt->comment();

    m_valid = true;
}
Exemplo n.º 13
0
bool KHTMLReader::parseTag(DOM::Element e)
{
    _PP(a);
    _PP(p);
    _PP(br);
    _PP(table);
    _PP(pre);
    _PP(ul);
    _PP(ol);
    _PP(font);
    _PP(hr);

    // FIXME we can get rid of these, make things tons more simple
    // when khtml finally implements getComputedStyle
    _PF(b, WEIGHT, value, 75);
    _PF(strong, WEIGHT, value, 75);
    _PF(u, UNDERLINE, value, 1);
    _PF(i, ITALIC, value, 1);

    _PL(center, FLOW, align, center);
    _PL(right, FLOW, align, right);
    _PL(left, FLOW, align, left);

    _PL(h1, NAME, value, h1);
    _PL(h2, NAME, value, h2);
    _PL(h3, NAME, value, h3);
    _PL(h4, NAME, value, h4);
    _PL(h5, NAME, value, h5);
    _PL(h6, NAME, value, h6);

    // Don't handle the content of comment- or script-nodes.
    if (e.nodeType() == DOM::Node::COMMENT_NODE || e.tagName().lower() == "script") {
        return false;
    }

    return true;
}
Exemplo n.º 14
0
void KHTMLReader::parse_head(DOM::Element e)
{
    for (DOM::Element items = e.firstChild();!items.isNull();items = items.nextSibling()) {
        if (items.tagName().string().lower() == "title") {
            DOM::Text t = items.firstChild();
            if (!t.isNull()) {
                _writer->createDocInfo("HTML import filter", t.data().string());
            }
        }
    }
}
Exemplo n.º 15
0
void Textual::select(const Index& index) {
  if(index == m_curr_selected)
    return;
  DOM::HTMLDocument document = htmlDocument();
  DOM::Element currs = document.getElementById("mv_"+m_curr_selected);
  DOM::Element news = document.getElementById("mv_"+index);
  if(!currs.isNull())
    currs.style().removeProperty("background-color");
  if(!news.isNull())
    news.style().setProperty("background-color", "#C0E0FF", "important");
  m_curr_selected = index;
}
Exemplo n.º 16
0
void DOMTreeView::initializeOptionsFromElement(const DOM::Element &element)
{
  QListViewItem *last = 0;
  nodeAttributes->clear();

  DOM::NamedNodeMap attrs = element.attributes();
  unsigned long lmap = attrs.length();
  for (unsigned int j = 0; j < lmap; j++) {
    DOM::Attr attr = attrs.item(j);
//     kdDebug(90180) << attr.name().string() << "=" << attr.value().string() << endl;
    QListViewItem *item = new AttributeListItem(attr.name().string(),
    			attr.value().string(), nodeAttributes, last);
    last = item;
  }

  // append new item
  last = new AttributeListItem(nodeAttributes, last);

  nodeInfoStack->raiseWidget(ElementPanel);
}
Exemplo n.º 17
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
}
Exemplo n.º 18
0
void DOMTreeView::initializeDOMInfoFromElement(const DOM::Element &element)
{
  QTreeWidgetItem *last = 0;
  nodeAttributes->clear();

  DOM::NamedNodeMap attrs = element.attributes();
  unsigned long lmap = attrs.length();
  for (unsigned int j = 0; j < lmap; j++) {
    DOM::Attr attr = attrs.item(j);
//     kDebug(90180) << attr.name().string() << "=" << attr.value().string();
    QTreeWidgetItem *item = new AttributeListItem(attr.name().string(),
                                                  attr.value().string(),
                                                  nodeAttributes, last);
    last = item;
  }

  // append new item
  last = new AttributeListItem(nodeAttributes, last);

  nodeAttributes->sortByColumn(0, Qt::AscendingOrder);

  nodeInfoStack->setCurrentIndex(ElementPanel);
}
Exemplo n.º 19
0
void DOMTreeView::initializeCSSInfoFromElement(const DOM::Element &element)
{
  DOM::Document doc = element.ownerDocument();
  DOM::AbstractView view = doc.defaultView();
  DOM::CSSStyleDeclaration styleDecl = view.getComputedStyle(element,
                                                             DOM::DOMString());

  unsigned long l = styleDecl.length();
  cssProperties->clear();
  cssProperties->setEnabled(true);
  QList<QTreeWidgetItem *> items;
  for (unsigned long i = 0; i < l; ++i) {
    DOM::DOMString name = styleDecl.item(i);
    DOM::DOMString value = styleDecl.getPropertyValue(name);

    QStringList values;
    values.append(name.string());
    values.append(value.string());
    items.append(new QTreeWidgetItem(static_cast<QTreeWidget*>(0), values));
  }

  cssProperties->insertTopLevelItems(0, items);
  cssProperties->resizeColumnToContents(0);
}
Exemplo n.º 20
0
void ofxDOMFlexBoxLayout::align(FlexDirection direction){

	bool horizontal = direction == FlexDirection::ROW;

	float paddingHorizontal = DOMLH::getPaddingHorizontal(_parent);
	float paddingVertical = DOMLH::getPaddingVertical(_parent);

	float wParent = ofGetWidth();
	float hParent = ofGetHeight();
	if(_parent->parent()){
		wParent = _parent->getSizeByParent().x;
		hParent = _parent->getSizeByParent().y;
	}

	float totalWidth = DOMLH::getDesiredWidthStretched(_parent, wParent) - paddingHorizontal;
	float totalHeight = DOMLH::getDesiredHeightStretched(_parent, hParent) - paddingVertical;

//	if(ofxGuiElement* el = dynamic_cast<ofxGuiElement*>(_parent)){
//		cout << el->getName() << " total size: " << totalWidth << " " << totalHeight << endl;
//	}

	vector<vector<DOM::Element*>> lines;
	vector<vector<DOM::Element*>> noFlexItems;
	vector<vector<DOM::Element*>> flexItems;
	vector<vector<float>> flexItemsBasis;
	vector<float> totalSpaceMainAxis;

	float mainAxisSize =  horizontal ? totalWidth : totalHeight;
	float crossAxisSize = horizontal ? totalHeight : totalWidth;

	int linecount = 0;

	if(children().size() > 0){
		//newline
		lines.push_back(vector<DOM::Element*>());
		noFlexItems.push_back(vector<DOM::Element*>());
		flexItems.push_back(vector<DOM::Element*>());
		flexItemsBasis.push_back(vector<float>());
		totalSpaceMainAxis.push_back(mainAxisSize);
	}

	//sort children according to flex attribute and main size of children

	for(unsigned int i = 0; i < children().size(); i++){

		DOM::Element* element = children().at(i);
		float w, h;
		if(horizontal){
			w = DOMLH::getDesiredWidth(element, totalWidth);
			h = DOMLH::getDesiredHeight(element, totalHeight);
		}else{
			w = DOMLH::getDesiredWidth(element, totalWidth);
			h = DOMLH::getDesiredHeight(element, totalHeight);
		}

		float elementMainSize = horizontal ? w : h;
		float elementCrossSize = horizontal ? h : w;

		if(element){
			if(elementFlexing(element)){

//				element->setSizeByParent(totalWidth, totalHeight);

				// set to minimal size on main axis
				if(horizontal){
					element->setSizeByParent(elementMainSize + DOMLH::getMarginHorizontal(element), elementCrossSize + DOMLH::getMarginVertical(element));
					element->setLayoutSize(elementMainSize, elementCrossSize, true);
					elementMainSize = element->getWidth() + DOMLH::getMarginHorizontal(element);
				}else {
					element->setSizeByParent(elementCrossSize + DOMLH::getMarginHorizontal(element), elementMainSize + DOMLH::getMarginVertical(element));
					element->setLayoutSize(elementCrossSize, elementMainSize, true);
					elementMainSize = element->getHeight() + DOMLH::getMarginVertical(element);
				}

				//if element is flexible, add it to the current line and save the items flex basis
				if(element->hasAttribute("_flex")){
					std::string flexval = element->getAttribute<std::string>("_flex");
					if(flexval == "auto"){
						lines.at(linecount).push_back(element);
						flexItems.at(linecount).push_back(element);
						flexItemsBasis.at(linecount).push_back(1);
						continue;
					}
					if(isFloat(ofTrim(flexval))){
						float intflexval = ofToFloat(flexval);
						if(intflexval > 0){
							lines.at(linecount).push_back(element);
							flexItems.at(linecount).push_back(element);
							flexItemsBasis.at(linecount).push_back(intflexval);
							continue;
						}
					}
				}

				// not flexible or no valid flex attribute, not flexing on main axis

				// add to new line if it does not fit and flex-wrap is on
				if((int)totalSpaceMainAxis.at(linecount) - (int)elementMainSize < 0){
					FlexWrap _wrap = getFlexWrap(_parent);
					if(_wrap == FlexWrap::NOWRAP || i == 0){
						//no new line
					}else{
						//new line
						linecount++;
						lines.push_back(vector<DOM::Element*>());
						flexItems.push_back(vector<DOM::Element*>());
						flexItemsBasis.push_back(vector<float>());
						totalSpaceMainAxis.push_back(mainAxisSize);
					}
				}

				lines.at(linecount).push_back(element);
				totalSpaceMainAxis.at(linecount) -= elementMainSize;
			}else {
				//set an absolute positioned element to its desired independent size
				if(DOMLH::elementAbsolutePositioned(element)){

					element->setLayoutSize(w, h);

				}
			}
		}
	}

	//set main size of flex items if they are flexible

	for(unsigned int i = 0; i < flexItems.size(); i++){
		int partscount = 0;
		for(int parts : flexItemsBasis.at(i)){
			partscount += parts;
		}

		if(partscount > 0){

			float partsize = totalSpaceMainAxis.at(i)/partscount;

			totalSpaceMainAxis.at(i) = 0;

			for(unsigned int j = 0; j < flexItems.at(i).size(); j++){
				DOM::Element* element = flexItems.at(i).at(j);
				if(horizontal){
					element->setSizeByParent(flexItemsBasis.at(i).at(j)*partsize, element->getSizeByParent().y);
					setLayoutWidthMinusMargin(element, flexItemsBasis.at(i).at(j)*partsize);
				}else{
					element->setSizeByParent(element->getSizeByParent().x, flexItemsBasis.at(i).at(j)*partsize);
					setLayoutHeightMinusMargin(element, flexItemsBasis.at(i).at(j)*partsize);
				}
			}
		}

	}

	//set cross size of items if they stretch

	AlignItems alignItems = getAlignItems(_parent);

	vector<float> lineSizes;
	float totalSpaceCrossAxis = crossAxisSize;

	for(unsigned int i = 0; i < lines.size(); i++){

		float lineSize = 0;
		for(auto e : lines.at(i)){
			float elementCrossSize = horizontal ?
						e->getHeight()+DOMLH::getMarginVertical(e) :
						e->getWidth()+DOMLH::getMarginHorizontal(e);
			AlignSelf alignSelf = getAlignSelf(e);
			if(((alignSelf != AlignSelf::AUTO) && (alignSelf != AlignSelf::STRETCH)) ||
			  ((alignSelf == AlignSelf::AUTO) && (alignItems != AlignItems::STRETCH))){
				if(elementCrossSize > lineSize){
					lineSize = elementCrossSize;
				}
			}
		}
		totalSpaceCrossAxis -= lineSize;
		lineSizes.push_back(lineSize);
	}

	// count how many lines do not have a fixed size
	int zerolines = 0;
	for(int lineSize : lineSizes){
		if(lineSize == 0){
			zerolines++;
		}
	}

	// if there are lines without fixed height, take the remaining height of the parent
	// and share it between the lines without fixed height
	if(zerolines > 0){
		for(unsigned int i = 0; i < lineSizes.size(); i++){
			if(lineSizes[i] == 0){
				lineSizes[i] = totalSpaceCrossAxis / zerolines;
			}
		}
		totalSpaceCrossAxis = 0;
	}

	// check if lines are not big enough to fit in all elements minimal size
	for(unsigned int i = 0; i < lines.size(); i++){

		float lineSize = lineSizes.at(i);
		for(auto e : lines.at(i)){
			float elementCrossSize = horizontal ?
						e->getHeight()+DOMLH::getMarginVertical(e) :
						e->getWidth()+DOMLH::getMarginHorizontal(e);

			if(elementCrossSize > lineSize){
				lineSize = elementCrossSize;
			}
		}
		lineSizes.at(i) = lineSize;
	}

	float newCrossAxisSize = 0;
	for(int size : lineSizes){
		newCrossAxisSize += size;
	}
	if(newCrossAxisSize > crossAxisSize){
		totalSpaceCrossAxis = 0;
//		if(horizontal){
//			setHeightInLayoutAddPadding_parent, newCrossAxisSize);
//		}else {
//			setWidthInLayoutAddPadding(_parent, newCrossAxisSize);
//		}
	}

	//take care of empty space on cross axis
	int spacingCrossAxisStart = 0;
	int spacingCrossAxisBetween = 0;
	if(lines.size() > 1){
		if(totalSpaceCrossAxis > 0){
			switch(getAlignContent(_parent)){
				case AlignContent::CENTER:
					spacingCrossAxisStart = totalSpaceCrossAxis/2;
					break;
				case AlignContent::FLEX_END:
					spacingCrossAxisStart = totalSpaceCrossAxis;
					break;
				case AlignContent::SPACE_AROUND:
					spacingCrossAxisStart = totalSpaceCrossAxis/(lines.size()+1);
					spacingCrossAxisBetween = spacingCrossAxisStart;
					break;
				case AlignContent::SPACE_BETWEEN:
					spacingCrossAxisBetween = totalSpaceCrossAxis/(lines.size()-1);
					break;
				case AlignContent::STRETCH:
					spacingCrossAxisBetween = totalSpaceCrossAxis/lines.size();
					break;
				default:break;
			}
		}
	}else{
		if(lines.size()>0){
			lineSizes.at(0) = max(lineSizes.at(0),crossAxisSize);
		}
	}

	totalWidth += paddingHorizontal;
	totalHeight += paddingVertical;

	float parentPaddingLeft = DOMLH::getPaddingLeft(_parent);
	float parentPaddingTop = DOMLH::getPaddingTop(_parent);

	float currentMainPos = 0;
	float currentCrossPos = spacingCrossAxisStart;
	currentCrossPos += horizontal ? parentPaddingTop : parentPaddingLeft;

	for(unsigned int i = 0; i < lines.size(); i++){

		//take care of empty space on main axis
		int spacingMainAxisStart = horizontal ? parentPaddingLeft : parentPaddingTop;
		int spacingMainAxisBetween = 0;
		if(totalSpaceMainAxis.at(i) > 0){
			switch(getJustifyContent(_parent)){
				case JustifyContent::CENTER:
					spacingMainAxisStart += totalSpaceMainAxis.at(i)/2;
					break;
				case JustifyContent::FLEX_END:
					spacingMainAxisStart += totalSpaceMainAxis.at(i);
					break;
				case JustifyContent::SPACE_AROUND:
					spacingMainAxisStart += totalSpaceMainAxis.at(i)/(lines.at(i).size()+1);
					spacingMainAxisBetween = spacingMainAxisStart;
					break;
				case JustifyContent::SPACE_BETWEEN:
					spacingMainAxisBetween = totalSpaceMainAxis.at(i)/(lines.at(i).size()-1);
					break;
				default:break;
			}
		}

		currentMainPos = spacingMainAxisStart;

		for(unsigned int j = 0; j < lines.at(i).size(); j++){

			// set cross size of item

			DOM::Element* element = lines.at(i).at(j);
			AlignSelf alignSelf = getAlignSelf(element);
			if(alignSelf == AlignSelf::STRETCH ||
			  ((alignSelf == AlignSelf::AUTO) && (alignItems == AlignItems::STRETCH))){
				if(horizontal){
					element->setSizeByParent(element->getSizeByParent().x, lineSizes.at(i));
					setLayoutHeightMinusMargin(element, lineSizes.at(i));
				}else{
					element->setSizeByParent(lineSizes.at(i), element->getSizeByParent().y);
					setLayoutWidthMinusMargin(element, lineSizes.at(i));
				}
			}

			//align item

			float elementMainPos = currentMainPos;
			float elementCrossPos = currentCrossPos;
			float elementMainSize = horizontal ? getWidthPlusMargin(element) : getHeightPlusMargin(element);
			float elementCrossSize = horizontal ? getHeightPlusMargin(element) : getWidthPlusMargin(element);

			//align item on cross axis

			AlignItems alignItem = alignItems;
			if(alignSelf != AlignSelf::AUTO){
				switch(alignSelf){
					case AlignSelf::CENTER:
						alignItem = AlignItems::CENTER;
						break;
					case AlignSelf::STRETCH:
					case AlignSelf::FLEX_START:
						alignItem = AlignItems::FLEX_START;
						break;
					case AlignSelf::FLEX_END:
						alignItem = AlignItems::FLEX_END;
						break;
					default:
						break;
				}
			}

			switch(alignItem){
				case AlignItems::FLEX_END:
					elementCrossPos += lineSizes.at(i)-elementCrossSize;
					break;
				case AlignItems::CENTER:
					elementCrossPos += (lineSizes.at(i)-elementCrossSize)/2.;
					break;
				default:
					break;
			}

			//set final element position
			if(horizontal){
				DOMLH::setPosition(element, ofPoint(elementMainPos, elementCrossPos));
			}else{
				DOMLH::setPosition(element, ofPoint(elementCrossPos, elementMainPos));
			}

			totalWidth = max(totalWidth, element->getShape().getRight()+DOMLH::getMarginRight(element)+DOMLH::getPaddingRight(_parent));
			totalHeight = max(totalHeight, element->getShape().getBottom()+DOMLH::getMarginBottom(element)+DOMLH::getPaddingBottom(_parent));

			currentMainPos += elementMainSize + spacingMainAxisBetween;

		}

		currentCrossPos += lineSizes.at(i) + spacingCrossAxisBetween;

	}


	//make sure parent element contains all child elements on the main axis
//	maxX += DOMLH::getPaddingRight(_parent);
//	maxY += DOMLH::getPaddingBottom(_parent);
//	if(horizontal){
//		_parent->setLayoutSize(max(maxX,_parent->getWidth()), max(maxY,_parent->getHeight()));
//	}else{
//		_parent->setLayoutSize(max(maxX,_parent->getWidth()), max(maxY,_parent->getHeight()));
//	}

//	if(ofxGuiElement* el = dynamic_cast<ofxGuiElement*>(_parent)){
//		cout << el->getName() << " total size end: " << totalWidth << " " << totalHeight << endl;
//	}

	_parent->setLayoutSize(totalWidth, totalHeight, false);
	_parent->setNeedsRedraw();

}
Exemplo n.º 21
0
void Textual::setMove(const Index& index, int turn, const DecoratedMove& move,
                                                          const QString& comment) {
  //kDebug() << "i= " << index;
  DOM::HTMLDocument document = htmlDocument();
  QString istr = (QString)index;

  DOM::Element this_mv = document.getElementById("mv_"+istr);
  DOM::Element this_cm = document.getElementById("cm_"+istr);
  if(!this_mv.isNull() && !this_cm.isNull()) {
    clear_node(this_mv);
    for(int i=0;i<move.size();i++) {
      DOM::Text t = document.createTextNode(move[i].m_string);
      this_mv.appendChild(t);
    }

    clear_node(this_cm);
    if(!comment.isEmpty()) {
      this_cm.appendChild(document.createTextNode(comment));
      this_cm.appendChild(document.createTextNode(QString(" ")));
    }
    return;
  }

  DOM::Element parent;
  DOM::Element prev_mv;
  DOM::Element prev_cm;

  if(index != Index(0)) {
    prev_cm = document.getElementById("cm_"+index.prev());
    prev_mv = document.getElementById("mv_"+index.prev());
    if(prev_cm.isNull() || prev_mv.isNull()) {
      kDebug() << " --> Error in Textual::setMove, no previous move!";
      return;
    }
  }

  int mv_num = 0;
  int sub_mv_num = 0;
  if(!prev_mv.isNull()) {
    int prev_turn = prev_mv.getAttribute("turn").string().toInt();
    int prev_mv_num = prev_mv.getAttribute("mvnum").string().toInt();
    int prev_sub_mv_num = prev_mv.getAttribute("submvnum").string().toInt();
    if(prev_turn != turn)
      mv_num = prev_mv_num+1;
    else {
      mv_num = prev_mv_num;
      sub_mv_num = prev_sub_mv_num+1;
    }
  }

  if(!index.nested.size()) {
    parent = document.body();
    if(parent.isNull()) {
      kDebug() << "QUEEEEEEEEE!!!!!!!";
      return;
    }
  }
  else if(index.atVariationStart()) {
    QString var_id = "vc_" + istr;
    DOM::Element add_before = prev_cm.nextSibling();

    while(!add_before.isNull()) {

      QString id = add_before.getAttribute("id").string();
      if(id.startsWith("vc_") && id < var_id)
        add_before = add_before.nextSibling();
      else
        break;
    }

    DOM::Element var_el = document.createElement("span");
    var_el.setAttribute("id", var_id);
    var_el.setAttribute("class", "variation");
    var_el.appendChild(document.createTextNode("[ "));


    parent = document.createElement("span");
    parent.setAttribute("id", "vr_" + istr);
    DOM::Element vk_el = document.createElement("span");
    vk_el.setAttribute("id", "vk_" + istr);
    vk_el.setAttribute("class", "comment");
    //vk_el.setContentEditable(true);
    parent.appendChild(vk_el);
    var_el.appendChild(parent);

    var_el.appendChild(document.createTextNode("] "));
    prev_cm.parentNode().insertBefore(var_el, add_before);

    if(!add_before.isNull() && add_before.getAttribute("id").string().startsWith("mv_")) {
      int mv_num = add_before.getAttribute("mvnum").string().toInt();
      int sub_mv_num = add_before.getAttribute("submvnum").string().toInt();
      QString num_str;
      if(m_layout_style == 0) {
        if(mv_num%2)
          num_str = QString("%1. ").arg((mv_num+1)/2);
        else
          num_str = QString("%1. ... ").arg((mv_num+2)/2);
      }
      else {
        if(sub_mv_num==0)
          num_str = QString("%1. ").arg(mv_num);
        else
          num_str = QString("%1+%2. ").arg(mv_num).arg(sub_mv_num);
      }
      DOM::Element num_el = document.createElement("a");
      num_el.setAttribute("class", "mvnum");
      num_el.setAttribute("id", "nm_"+istr);
      num_el.appendChild(document.createTextNode(num_str));
      prev_cm.parentNode().insertBefore(num_el, add_before);
    }
  }
  else {
    Index pi = index.prev(index.nested.back().num_moves);
    parent = document.getElementById("vr_"+pi);
    if(parent.isNull()) {
      kDebug() << " --> Error in Textual::setMove, no variation?!?!?";
      return;
    }
  }

  if(mv_num>0 && ((sub_mv_num==0 && (mv_num%2 || m_layout_style)) || parent.lastChild() != prev_cm) ) {
    QString num_str;
    if(m_layout_style == 0) {
      if(mv_num%2)
        num_str = QString("%1. ").arg((mv_num+1)/2);
      else
        num_str = QString("%1. ... ").arg((mv_num+2)/2);
    }
    else {
      if(sub_mv_num==0)
        num_str = QString("%1. ").arg(mv_num);
      else
        num_str = QString("%1+%2. ").arg(mv_num).arg(sub_mv_num);
    }
    DOM::Element num_el = document.createElement("a");
    num_el.setAttribute("class", "mvnum");
    num_el.setAttribute("id", "nm_"+istr);
    num_el.appendChild(document.createTextNode(num_str));
    parent.appendChild(num_el);
  }

  DOM::Element mv_el = document.createElement("a");
  mv_el.setAttribute("id", "mv_"+istr);
  mv_el.setAttribute("href", "index://"+istr);
  mv_el.setAttribute("class", "move");
  mv_el.setAttribute("turn", QString::number(turn));
  mv_el.setAttribute("mvnum", QString::number(mv_num));
  mv_el.setAttribute("submvnum", QString::number(sub_mv_num));
  for(int i=0;i<move.size();i++) {
    if(move[i].m_type == MovePart::Figurine) {
      ::Loader::Glyph g = m_loader.getValue< ::Loader::Glyph>(move[i].m_string);
      DOM::Element el = document.createElement("span");
#if 1
      kDebug() << "size = " << QString("%1%").arg(g.m_font.pointSize()*100/12);
      el.style().setProperty("font-size", QString("%1%").arg(g.m_font.pointSize()*100/12), "important");
      el.style().setProperty("line-height", QString("%1%").arg(g.m_font.pointSize()*100/12), "important");
#endif
      kDebug() << "familiy = " << g.m_font.family();
      el.style().setProperty("font-weight", "normal", "important");
      el.style().setProperty("font-family", g.m_font.family(), "important");
      DOM::Text t = document.createTextNode(QString(g.m_char));
      el.appendChild(t);
      mv_el.appendChild(el);
    }
    else {
      DOM::Text t = document.createTextNode(move[i].m_string);
      mv_el.appendChild(t);
    }
  }
  parent.appendChild(mv_el);

  parent.appendChild(document.createTextNode(QString(" ")));

  DOM::Element cm_el = document.createElement("span");
  cm_el.setAttribute("id", "cm_"+istr);
  cm_el.setAttribute("class", "comment");
  if(!comment.isEmpty()) {
    cm_el.appendChild(document.createTextNode(comment));
    cm_el.appendChild(document.createTextNode(QString(" ")));
  }
  //cm_el.setContentEditable(true);
  parent.appendChild(cm_el);
}
Exemplo n.º 22
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;
  }
}
Exemplo n.º 23
0
void DOMTreeView::addElement ( const DOM::Node &node,  DOMListViewItem *cur_item, bool isLast)
{
  cur_item->setClosing(isLast);

  const QString nodeName(node.nodeName().string());
  QString text;
  const DOM::Element element = node;
  if (!element.isNull()) {
    if (!m_bPure) {
      if (isLast) {
	text ="</";
      } else {
	text = "<";
      }
      text += nodeName;
    } else {
      text = nodeName;
    }

    if (m_bShowAttributes && !isLast) {
      QString attributes;
      DOM::Attr attr;
      DOM::NamedNodeMap attrs = element.attributes();
      unsigned long lmap = attrs.length();
      for( unsigned int 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 (!m_bPure) {
      if(element.firstChild().isNull()) {
	text += "/>";
      } else {
	text += ">";
      }
    }
    cur_item->setText(0, text);
  } else {
    text = "`" + node.nodeValue().string() + "'";

    // Hacks to deal with PRE
    QTextStream ts( text, IO_ReadOnly );
    while (!ts.eof()) {
      const QString txt(ts.readLine());
      const QFont font(KGlobalSettings::fixedFont());
      cur_item->setFont( font );
      cur_item->setText(0, txt);

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

      DOMListViewItem *parent;
      if (cur_item->parent()) {
	parent = static_cast<DOMListViewItem *>(cur_item->parent());
      } else {
	parent = cur_item;
      }
      cur_item = new DOMListViewItem(node, parent, cur_item);
    }
    // This is one is too much
    DOMListViewItem *notLastItem = static_cast<DOMListViewItem *>(cur_item->itemAbove());
    delete cur_item;
    cur_item = notLastItem;
  }

  if (m_bHighlightHTML && node.ownerDocument().isHTMLDocument()) {
    highlightHTML(cur_item, nodeName);
  }
}
Exemplo n.º 24
0
/*
   we just simplify the process. if we use KParts::BrowserExtension, we have to do
   lots extra work, adding so much classes. so just hack like following.

   grab useful code from TDEHTMLPopupGUIClient(tdehtml_ext.cpp),
   and change a little bit to fit our needs

*/
void EvaChatView::slotPopupMenu( const TQString & _url, const TQPoint & point )
{
    menu->clear();

    bool isImage = false;
    bool hasSelection = TDEHTMLPart::hasSelection();
    KURL url = KURL(_url);

    if(d) delete d;
    d = new MenuPrivateData;
    d->m_url = url;


    DOM::Element e = nodeUnderMouse();
    if ( !e.isNull() && (e.elementId() == ID_IMG) ) {
        DOM::HTMLImageElement ie = static_cast<DOM::HTMLImageElement>(e);
        TQString src = ie.src().string();
        d->m_imageURL = KURL(src);
        d->m_suggestedFilename = src.right(src.length() - src.findRev("/") -1);
        isImage=true;
    }


    TDEAction *action = 0L;

    if(hasSelection) {
        //action =  new TDEAction( i18n( "&Copy Text" ), TDEShortcut("Ctrl+C"), this, SLOT( copy() ),
        //			actionCollection(), "copy" );
        //action = KStdAction::copy( browserExtension(), SLOT(copy()), actionCollection(), "copy");
        //action->setText(i18n("&Copy Text"));
        //action->setEnabled(true);
        copyAction->plug(menu);

        // search text
        TQString selectedText = TDEHTMLPart::selectedText();
        if ( selectedText.length()>18 ) {
            selectedText.truncate(15);
            selectedText+="...";
        }
#ifdef HAS_KONTQUEROR
        // Fill search provider entries
        TDEConfig config("kuriikwsfilterrc");
        config.setGroup("General");
        const TQString defaultEngine = config.readEntry("DefaultSearchEngine", "google");
        const char keywordDelimiter = config.readNumEntry("KeywordDelimiter", ':');


        // default search provider
        KService::Ptr service = KService::serviceByDesktopPath(TQString("searchproviders/%1.desktop").arg(defaultEngine));

        // search provider icon
        TQPixmap icon;
        KURIFilterData data;
        TQStringList list;
        const TQString defaultSearchProviderPrefix = *(service->property("Keys").toStringList().begin()) + keywordDelimiter;
        data.setData( defaultSearchProviderPrefix + TQString("some keyword") );
        list << "kurisearchfilter" << "kuriikwsfilter";

        TQString name;
        if ( KURIFilter::self()->filterURI(data, list) ) {
            TQString iconPath = locate("cache", KMimeType::favIconForURL(data.uri()) + ".png");
            if ( iconPath.isEmpty() )
                icon = SmallIcon("edit-find");
            else
                icon = TQPixmap( iconPath );

            name = service->name();
        } else {
            icon = SmallIcon("google");
            name = "Google";
        }

        action = new TDEAction( i18n( "Search '%1' at %2" ).arg( selectedText ).arg( name ), icon, 0, this,
                                SLOT( searchProvider() ), actionCollection(), "searchProvider" );
        action->plug(menu);

        // favorite search providers
        TQStringList favoriteEngines;
        favoriteEngines = config.readListEntry("FavoriteSearchEngines"); // for KDE 3.2 API compatibility
        if(favoriteEngines.isEmpty())
            favoriteEngines << "google" << "google_groups" << "google_news" << "webster" << "dmoz" << "wikipedia";

        if ( !favoriteEngines.isEmpty()) {
            TDEActionMenu* providerList = new TDEActionMenu( i18n( "Search '%1' At" ).arg( selectedText ), actionCollection(), "searchProviderList" );
            bool hasSubMenus = false;
            TQStringList::ConstIterator it = favoriteEngines.begin();
            for ( ; it != favoriteEngines.end(); ++it ) {
                if (*it==defaultEngine)
                    continue;
                service = KService::serviceByDesktopPath(TQString("searchproviders/%1.desktop").arg(*it));
                if (!service)
                    continue;
                const TQString searchProviderPrefix = *(service->property("Keys").toStringList().begin()) + keywordDelimiter;
                data.setData( searchProviderPrefix + "some keyword" );

                if ( KURIFilter::self()->filterURI(data, list) ) {
                    TQString iconPath = locate("cache", KMimeType::favIconForURL(data.uri()) + ".png");
                    if ( iconPath.isEmpty() )
                        icon = SmallIcon("edit-find");
                    else
                        icon = TQPixmap( iconPath );
                    name = service->name();

                    providerList->insert( new TDEAction( name, icon, 0, this,
                                                         SLOT( searchProvider() ), actionCollection(), TQString( "searchProvider" + searchProviderPrefix ).latin1() ) );
                    hasSubMenus = true;
                }
            }
            if(hasSubMenus) providerList->plug(menu);
        }
#endif // HAS_KONTQUEROR
        if ( selectedText.contains("://") && KURL(selectedText).isValid() ) {
            action = new TDEAction( i18n( "Open '%1'" ).arg( selectedText ), "window_new", 0,
                                    this, SLOT( openSelection() ), actionCollection(), "openSelection" );
            action->plug(menu);
        }
    }
    if ( !url.isEmpty() ) {
        if (url.protocol() == "mailto")	{
            action = new TDEAction( i18n( "Copy Email Address" ), 0, this, SLOT( slotCopyLinkLocation() ),
                                    actionCollection(), "copylinklocation" );
            action->plug(menu);
        } else {
            action = new TDEAction( i18n( "Copy &Link Address" ), 0, this, SLOT( slotCopyLinkLocation() ),
                                    actionCollection(), "copylinklocation" );
            action->plug(menu);
        }
    }

    if (isImage)	{
#ifndef QT_NO_MIMECLIPBOARD
        action = (new TDEAction( i18n( "Copy Image" ), 0, this, SLOT( slotCopyImage() ),
                                 actionCollection(), "copyimage" ));
        action->plug(menu);
#endif
        action = new TDEAction( i18n( "Save Image As..." ), 0, this, SLOT( slotSaveImageAs() ),
                                actionCollection(), "saveimageas" );
        action->plug(menu);

        action = new TDEAction( i18n( "Save As Custom Smiley"), 0, this, SLOT( slotSaveAsCustomSmiley() ),
                                actionCollection(), "saveascustomsmiley" );
        action->plug(menu);
    }

    if(menu->count()) menu->popup(point);
}
Exemplo n.º 25
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
}