Position Position::equivalentRangeCompliantPosition() const
{
    if (isNull())
        return Position();

    // Make sure that 0 <= constrainedOffset <= num kids, otherwise using this Position
    // in DOM calls can result in exceptions.
    long maxOffset = node()->isTextNode() ? static_cast<TextImpl *>(node())->length(): node()->childNodeCount();
    long constrainedOffset = offset() <= 0 ? 0 : kMin(maxOffset, offset());

    if (!node()->parentNode())
        return Position(node(), constrainedOffset);

    RenderObject *renderer = node()->renderer();
    if (!renderer)
        return Position(node(), constrainedOffset);
        
    if (!renderer->isReplaced() && !renderer->isBR())
        return Position(node(), constrainedOffset);
    
    long o = offset();
    const NodeImpl *n = node();
    while ((n = n->previousSibling()))
        o++;
    
    // Make sure that 0 <= constrainedOffset <= num kids, as above.
    NodeImpl *parent = node()->parentNode();
    maxOffset = parent->isTextNode() ? static_cast<TextImpl *>(parent)->length(): parent->childNodeCount();
    constrainedOffset = o <= 0 ? 0 : kMin(maxOffset, o);
    return Position(parent, constrainedOffset);
}
QRect KstGfxMouseHandlerUtils::resizeRectFromCornerCentered(const QRect& originalRect, const QPoint& pos, const QRect& bounds, bool maintainAspect) {
  QRect newRect;
  QPoint anchorPoint = originalRect.center();

  int newHalfWidth, newHalfHeight;

  newHalfWidth = abs((pos - anchorPoint).x());
  newHalfHeight = abs((pos - anchorPoint).y());

  if (maintainAspect) {
    newHalfWidth = kMin(newHalfWidth,anchorPoint.x() - bounds.left());
    newHalfWidth = kMin(newHalfWidth,bounds.right() - anchorPoint.x());

    newHalfHeight = kMin(newHalfHeight,anchorPoint.y() - bounds.top());
    newHalfHeight = kMin(newHalfHeight,bounds.bottom() - anchorPoint.y());

    QSize newSize(originalRect.size());
    newSize.scale(2*newHalfWidth, 2*newHalfHeight, QSize::ScaleMin);

    newRect.setSize(newSize);
    newRect.moveCenter(anchorPoint);
  } else {
    newRect = QRect(0, 0, 2*newHalfWidth, 2*newHalfHeight);
    newRect.moveCenter(anchorPoint);
    newRect = newRect.intersect(bounds);
  }

  return newRect;
}
示例#3
0
void KDecorationPreview::positionPreviews()
    {
    int titleBarHeight, leftBorder, rightBorder, xoffset,
        dummy1, dummy2, dummy3;
    QRect geometry;
    QSize size;

    no_preview->resize( this->size() );

    if ( !deco[Active] || !deco[Inactive] )
        return;

    // don't have more than one reference to the same dummy variable in one borders() call.
    deco[Active]->borders( dummy1, dummy2, titleBarHeight, dummy3 );
    deco[Inactive]->borders( leftBorder, rightBorder, dummy1, dummy2 );

    titleBarHeight = kMin( int( titleBarHeight * .9 ), 30 );
    xoffset = kMin( kMax( 10, QApplication::reverseLayout()
			    ? leftBorder : rightBorder ), 30 );

    // Resize the active window
    size = QSize( width() - xoffset, height() - titleBarHeight )
                .expandedTo( deco[Active]->minimumSize() );
    geometry = QRect( QPoint( 0, titleBarHeight ), size );
    deco[Active]->widget()->setGeometry( QStyle::visualRect( geometry, this ) );

    // Resize the inactive window
    size = QSize( width() - xoffset, height() - titleBarHeight )
                .expandedTo( deco[Inactive]->minimumSize() );
    geometry = QRect( QPoint( xoffset, 0 ), size );
    deco[Inactive]->widget()->setGeometry( QStyle::visualRect( geometry, this ) );
    }
QPoint KstGfxMouseHandlerUtils::findNearestPtOnLine(const QPoint& fromPoint, const QPoint& toPoint, const QPoint& pos, const QRect &bounds) {
  QPoint npos = pos;

  if (fromPoint.y() == toPoint.y()) {
    npos.setY(fromPoint.y());
    npos.setX(kMax(npos.x(), bounds.left()));
    npos.setX(kMin(npos.x(), bounds.right()));
  } else if (fromPoint.x() == toPoint.x()) {
    npos.setX(fromPoint.x());
    npos.setY(kMax(npos.y(), bounds.top()));
    npos.setY(kMin(npos.y(), bounds.bottom()));
  } else {
    double newxpos, newypos;
    double slope = double(toPoint.y() - fromPoint.y()) / double(toPoint.x() - fromPoint.x());

    newxpos = (double(pos.y()) + slope*double(fromPoint.x()) + double(pos.x())/slope -double(fromPoint.y())) / (slope + 1.0/slope); //we want the tip of our new line to be as close as possible to the original line (while still maintaining aspect). 

    newxpos = kMin(newxpos, double(bounds.right())); //ensure that our x is inside the bounds.
    newxpos = kMax(newxpos, double(bounds.left())); // ""
    newypos = slope*(newxpos - double(fromPoint.x())) + double(fromPoint.y()); //consistency w/ x.

    newypos = kMin(newypos, double(bounds.bottom())); //ensure that our y is inside the bounds.
    newypos = kMax(newypos, double(bounds.top())); // ""*/
    newxpos = double(fromPoint.x()) + (newypos - double(fromPoint.y()))/slope; // x will still be inside the bounds because we have just moved newypos closer to fromPoint.y(), which will send newxpos closer to fromPoint.x(), ie. in the direction further 'into' the bounds.

    npos.setX(int(newxpos));
    npos.setY(int(newypos));
  }

  return npos;
}
示例#5
0
void DRect::unite(const DRect &r)
{
    if ( !r.isValid() ) return;
    if ( !isValid() ) {
        *this = r;
        return;
    }
    _left = kMin(_left, r._left);
    _right = kMax(_right, r._right);
    _top = kMin(_top, r._top);
    _bottom = kMax(_bottom, r._bottom);
}
示例#6
0
DRect DPath::boundingRect() const
{
    if ( size()==0 ) return DRect();
    DRect r(at(0).x, at(0).x, at(0).y, at(0).y);
    for (uint i=1; i<size(); i++) {
        r.setTop( kMin(r.top(), at(i).y) );
        r.setBottom( kMax(r.bottom(), at(i).y) );
        r.setLeft( kMin(r.left(), at(i).x) );
        r.setRight( kMax(r.right(), at(i).x) );
    }
    return r;
}
示例#7
0
QRect KstGfxMouseHandlerUtils::resizeRectFromEdge(const QRect& originalSize, const QPoint& anchorPoint, const QPoint& movePoint, const QPoint& pos, const QRect &bounds, bool maintainAspect) {
  QRect newSize(originalSize);

  if (movePoint.y() == anchorPoint.y()) {
      int newWidth = pos.x() - anchorPoint.x(); //defined differently than in QRect.

      if (maintainAspect) {
        double newHalfHeight = originalSize.height() * (abs(newWidth) + 1) / originalSize.width() / 2.0; //defined with the QRect convention (height = bot - top + 1)

        newHalfHeight = kMin(double(movePoint.y() - bounds.top()) + 1, newHalfHeight); // ensure we are still within the bounds.
        newHalfHeight = kMin(double(bounds.bottom() - movePoint.y()) + 1, newHalfHeight);

        if (newWidth == 0) { // anything better to be done?
          newWidth = 1;
        }

        newWidth = (int(originalSize.width() * (newHalfHeight * 2.0) / originalSize.height()) - 1)*newWidth/abs(newWidth); // consistency of width w/ the newly calculated height.

        newSize.setTop(anchorPoint.y() + int(newHalfHeight - 0.5));
        newSize.setBottom(anchorPoint.y() - int(newHalfHeight - 0.5));
      }

      newSize.setLeft(anchorPoint.x());
      newSize.setRight(anchorPoint.x() + newWidth); // +1 for the way widths are defined in QRect.

    } else if (movePoint.x() == anchorPoint.x()) {
      // mimic the case for (movePoint.y() == anchorPoint.y()). comments are there.
      int newHeight = pos.y() - anchorPoint.y();

      if (maintainAspect) {
        double newHalfWidth = originalSize.width() * (abs(newHeight) + 1) / originalSize.height() / 2.0;

        newHalfWidth = kMin(double(movePoint.x() - bounds.left() + 1), newHalfWidth);
        newHalfWidth = kMin(double(bounds.right() - movePoint.x() + 1), newHalfWidth);

        if (newHeight == 0) {
          newHeight = 1;
        }

        newHeight = (int(originalSize.height() * newHalfWidth * 2.0 / originalSize.width()) - 1)*newHeight/abs(newHeight);
        newSize.setLeft(anchorPoint.x() + int(newHalfWidth - .5));
        newSize.setRight(anchorPoint.x() - int(newHalfWidth - .5));
      }

      newSize.setTop(anchorPoint.y());
      newSize.setBottom(anchorPoint.y() + newHeight);
    }

    return newSize.normalize();
}
QRect KstGfxMouseHandlerUtils::resizeRectFromEdgeCentered(const QRect& originalRect, const QPoint& anchorPoint, const QPoint& movePoint, const QPoint& pos, const QRect& bounds, bool maintainAspect) {
  QRect newRect;
  bool vertical;
  int newHalfWidth = abs((pos - anchorPoint).x());
  int newHalfHeight = abs((pos - anchorPoint).y());

  if (movePoint.x() == anchorPoint.x()) {
    vertical = true;
  } else {
    vertical = false;
  }

  if (maintainAspect) {
    QSize newSize(originalRect.size());

    if (vertical) {
      newHalfHeight = kMin(newHalfHeight, anchorPoint.y() - bounds.top());
      newHalfHeight = kMin(newHalfHeight, bounds.bottom() - anchorPoint.y());
      if (newHalfHeight > originalRect.height()/2) {
        newSize.scale(originalRect.width(), 2*newHalfHeight, QSize::ScaleMax);
      } else {
        newSize.scale(originalRect.width(), 2*newHalfHeight, QSize::ScaleMin);
      }
    } else {
      newHalfWidth = kMin(newHalfWidth, anchorPoint.x() - bounds.left());
      newHalfWidth = kMin(newHalfWidth, bounds.right() - anchorPoint.x());
      if (newHalfWidth > originalRect.width()/2) {
        newSize.scale(2*newHalfWidth, originalRect.height(), QSize::ScaleMax);
      } else {
        newSize.scale(2*newHalfWidth, originalRect.height(), QSize::ScaleMin);
      }
    }

    newRect.setSize(newSize);
    newRect.moveCenter(anchorPoint);
    newRect = newRect.intersect(bounds);
  } else {
    if (vertical) {
      newRect = QRect(0, 0, originalRect.width(), 2*newHalfHeight);
    } else {
      newRect = QRect(0, 0, 2*newHalfWidth, originalRect.height());
    }
    newRect.moveCenter(anchorPoint);
    newRect = newRect.intersect(bounds);
  }

  return newRect;
}
示例#9
0
// __________________________________________________________________________________________________
void KikiScrollMenu::activeIndexChanged ()
{
	int min_index_offset = kMax(0, active_index - visible_items + 1);
	int max_index_offset = active_index;
	offset = kMin(max_index_offset, kMax(min_index_offset, offset));

	menu_items.clear();
    for (int index = offset;
         index < kMin ((int)all_menu_items.size(), offset + visible_items);
		 index++)
    {
         menu_items.push_back (all_menu_items[index]);
    }
	index_offset = offset;
    alignItems();
} 
示例#10
0
void KateSearch::wrapSearch()
{
  if( s.flags.selected )
  {
    KateTextCursor start (s.selBegin);
    KateTextCursor end (s.selEnd);

    // recalc for block sel, to have start with lowest col, end with highest
    if (m_view->blockSelectionMode())
    {
      start.setCol (kMin(s.selBegin.col(), s.selEnd.col()));
      end.setCol (kMax(s.selBegin.col(), s.selEnd.col()));
    }

    s.cursor = s.flags.backward ? end : start;
  }
  else
  {
    if( !s.flags.backward ) {
      s.cursor.setPos(0, 0);
    } else {
      s.cursor.setLine(doc()->numLines() - 1);
      s.cursor.setCol(doc()->lineLength( s.cursor.line() ) );
    }
  }

  // oh, we wrapped around one time allready now !
  // only check that on replace
  s.wrapped = s.flags.replace;

  replaces = 0;
  s.flags.finished = true;
}
示例#11
0
/**
 * Schedules an Audioscrobbler handshake or submit as required.
 * Returns true if an immediate submit was possible
 */
bool ScrobblerSubmitter::schedule( bool failure )
{
    m_timer.stop();
    if ( m_inProgress || !canSubmit() )
        return false;

    uint when, currentTime = QDateTime::currentDateTime( Qt::UTC ).toTime_t();
    if ( currentTime - m_prevSubmitTime > m_interval )
        when = 0;
    else
        when = m_interval - ( currentTime - m_prevSubmitTime );

    if ( failure )
    {
        m_backoff = kMin( kMax( m_backoff * 2, unsigned( MIN_BACKOFF ) ), unsigned( MAX_BACKOFF ) );
        when = kMax( m_backoff, m_interval );
    }
    else
        m_backoff = 0;

    if ( m_needHandshake || m_challenge.isEmpty() )
    {
        m_challenge = QString::null;
        m_needHandshake = false;

        if ( when == 0 )
        {
            debug() << "Performing immediate handshake" << endl;
            performHandshake();
        }
        else
        {
            debug() << "Performing handshake in " << when << " seconds" << endl;
            m_timer.start( when * 1000, true );
        }
    }
    else if ( !m_submitQueue.isEmpty() || !m_holdFakeQueue && !m_fakeQueue.isEmpty() )
    {
        // if we only have stuff in the fake queue, we need to only schedule for when we can actually do something with it
        if ( m_submitQueue.isEmpty() && m_lastSubmissionFinishTime + m_fakeQueue.getFirst()->length() > currentTime + when )
            when = m_lastSubmissionFinishTime + m_fakeQueue.getFirst()->length() - currentTime;

        if ( when == 0 )
        {
            debug() << "Performing immediate submit" << endl;
            performSubmit();
            return true;
        }
        else
        {
            debug() << "Performing submit in " << when << " seconds" << endl;
            m_timer.start( when * 1000, true );
        }
    } else {
        debug() << "Nothing to schedule" << endl;
    }

    return false;
}
示例#12
0
void KDoubleSpinBox::setRange( double lower, double upper, double step,
			       int precision ) {
  lower = kMin(upper, lower);
  upper = kMax(upper, lower);
  setPrecision( precision, true ); // disable bounds checking, since
  setMinValue( lower );            // it's done in set{Min,Max}Value
  setMaxValue( upper );            // anyway and we want lower, upper
  setLineStep( step );             // and step to have the right precision
}
示例#13
0
// __________________________________________________________________________________________________
void KikiScrollMenu::nextItem ()
{
	if (circular)
		active_index = (active_index + 1) % all_menu_items.size();
	else
		active_index = kMin(active_index + 1, all_menu_items.size()-1);
	
	activeIndexChanged ();
}
示例#14
0
KateTextCursor KateSearch::getCursor( SearchFlags flags )
{
  if (flags.backward && !flags.selected && view()->hasSelection())
  {
    // We're heading backwards (and not within a selection),
    // the selection might start before the cursor.
    return kMin( KateTextCursor(view()->selStartLine(), view()->selStartCol()),
                 KateTextCursor(view()->cursorLine(), view()->cursorColumnReal()));
  }
  return KateTextCursor(view()->cursorLine(), view()->cursorColumnReal());
}
Position VisiblePosition::rangeCompliantEquivalent(const Position &pos)
{
    NodeImpl *node = pos.node();
    if (!node)
        return Position();

    // FIXME: This clamps out-of-range values.
    // Instead we should probably assert, and not use such values.

    long offset = pos.offset();
    if (!offsetInCharacters(node->nodeType()) && isAtomicNode(node) && offset > 0)
        return Position(node->parentNode(), node->nodeIndex() + 1);

    return Position(node, kMax(0L, kMin(offset, maxOffset(node))));
}
示例#16
0
 KateFileLoader (const TQString &filename, TQTextCodec *codec, bool removeTrailingSpaces)
   : m_file (filename)
   , m_buffer (kMin ((TQ_ULONG)m_file.size(), KATE_FILE_LOADER_BS))
   , m_codec (codec)
   , m_decoder (m_codec->makeDecoder())
   , m_position (0)
   , m_lastLineStart (0)
   , m_eof (false) // default to not eof
   , lastWasEndOfLine (true) // at start of file, we had a virtual newline
   , lastWasR (false) // we have not found a \r as last char
   , m_eol (-1) // no eol type detected atm
   , m_twoByteEncoding (TQString(codec->name()) == "ISO-10646-UCS-2")
   , m_binary (false)
   , m_removeTrailingSpaces (removeTrailingSpaces)
 {
   kdDebug (13020) << "OPEN USES ENCODING: " << m_codec->name() << endl;
 }
示例#17
0
Box3<Real> ContOrientedBox (int iQuantity, const Vector3<Real>* akPoint)
{
    Box3<Real> kBox = GaussPointsFit3<Real>(iQuantity,akPoint);

    // Let C be the box center and let U0, U1, and U2 be the box axes.  Each
    // input point is of the form X = C + y0*U0 + y1*U1 + y2*U2.  The
    // following code computes min(y0), max(y0), min(y1), max(y1), min(y2),
    // and max(y2).  The box center is then adjusted to be
    //   C' = C + 0.5*(min(y0)+max(y0))*U0 + 0.5*(min(y1)+max(y1))*U1 +
    //        0.5*(min(y2)+max(y2))*U2

    Vector3<Real> kDiff = akPoint[0] - kBox.Center;
    Vector3<Real> kMin(kDiff.Dot(kBox.Axis[0]),kDiff.Dot(kBox.Axis[1]),
        kDiff.Dot(kBox.Axis[2]));
    Vector3<Real> kMax = kMin;
    for (int i = 1; i < iQuantity; i++)
    {
        kDiff = akPoint[i] - kBox.Center;
        for (int j = 0; j < 3; j++)
        {
            Real fDot = kDiff.Dot(kBox.Axis[j]);
            if (fDot < kMin[j])
            {
                kMin[j] = fDot;
            }
            else if (fDot > kMax[j])
            {
                kMax[j] = fDot;
            }
        }
    }

    kBox.Center +=
        (((Real)0.5)*(kMin[0]+kMax[0]))*kBox.Axis[0] +
        (((Real)0.5)*(kMin[1]+kMax[1]))*kBox.Axis[1] +
        (((Real)0.5)*(kMin[2]+kMax[2]))*kBox.Axis[2];

    kBox.Extent[0] = ((Real)0.5)*(kMax[0] - kMin[0]);
    kBox.Extent[1] = ((Real)0.5)*(kMax[1] - kMin[1]);
    kBox.Extent[2] = ((Real)0.5)*(kMax[2] - kMin[2]);

    return kBox;
}
示例#18
0
QString KoPictureEps::readLine( const QByteArray& array, const uint start, const uint length, uint& pos, bool& lastCharWasCr )
{
    QString strLine;
    const uint finish = kMin( start + length, array.size() );
    for ( ; pos < finish; ++pos ) // We are starting at pos
    {
        const char ch = array[ pos ]; // Read one character
        if ( ch == '\n' )
        {
            if ( lastCharWasCr )
            {
                // We have a line feed following a Carriage Return
                // As the Carriage Return has already ended the previous line,
                // discard this Line Feed.
                lastCharWasCr = false;
            }
            else
            {
                // We have a normal Line Feed, therefore we end the line
                break;
            }
        }
        else if ( ch == '\r' )
        {
            // We have a Carriage Return, therefore we end the line
            lastCharWasCr = true;
            break;
        }
        else if ( ch == char(12) ) // Form Feed
        { // ### TODO: can a FF happen in PostScript?
            // Ignore the form feed
            continue;
        }
        else
        {
            strLine += ch;
            lastCharWasCr = false;
        }
    }
    return strLine;
}
示例#19
0
KateTextLine::Ptr KateBuffer::line_internal (KateBufBlock *buf, uint i)
{
  // update hl until this line + max KATE_HL_LOOKAHEAD
  KateBufBlock *buf2 = 0;
  while ((i >= m_lineHighlighted) && (buf2 = findBlock(m_lineHighlighted)))
  {
    uint end = kMin(i + KATE_HL_LOOKAHEAD, buf2->endLine());

    doHighlight ( buf2,
                  kMax(m_lineHighlighted, buf2->startLine()),
                  end,
                  false );

    m_lineHighlighted = end;
  }

  // update hl max
  if (m_lineHighlighted > m_lineHighlightedMax)
    m_lineHighlightedMax = m_lineHighlighted;

  return buf->line (i - buf->startLine());
}
示例#20
0
void KIntNumInput::setRange(int lower, int upper, int step, bool slider)
{
    upper = kMax(upper, lower);
    lower = kMin(upper, lower);
    m_spin->setMinValue(lower);
    m_spin->setMaxValue(upper);
    m_spin->setLineStep(step);

    step = m_spin->lineStep(); // maybe QRangeControl didn't like out lineStep?

    if(slider) {
	if (m_slider)
	    m_slider->setRange(lower, upper);
	else {
	    m_slider = new QSlider(lower, upper, step, m_spin->value(),
				   QSlider::Horizontal, this);
	    m_slider->setTickmarks(QSlider::Below);
	    connect(m_slider, SIGNAL(valueChanged(int)),
		    m_spin, SLOT(setValue(int)));
	}

	// calculate (upper-lower)/10 without overflowing int's:
        int major = calcDiffByTen( upper, lower );
	if ( major==0 ) major = step; // #### workaround Qt bug in 2.1-beta4

        m_slider->setSteps(step, major);
        m_slider->setTickInterval(major);
    }
    else {
        delete m_slider;
        m_slider = 0;
    }

    // check that reference point is still inside valid range:
    setReferencePoint( referencePoint() );

    layout(true);
}
示例#21
0
int ContainerAreaLayout::moveContainerPushRecursive(ItemList::const_iterator it,
                                                    int distance)
{
    if (distance == 0)
        return 0;

    const bool forward = distance > 0;

    int available; // Space available for the container to move.
    int moved;     // The actual distance the container will move.
    ContainerAreaLayoutItem* cur  = *it;
    forward ? ++it : --it;
    ContainerAreaLayoutItem* next = (it != m_items.constEnd()) ? *it : 0;

    if (!next)
    {
        available = forward ? rightR() - cur->rightR()
                            : -cur->leftR();
    }
    else
    {
        available = forward ? next->leftR()  - cur->rightR() - 1
                            : next->rightR() - cur->leftR()  + 1;

        if (!forward && distance < available
          || forward && distance > available)
            available += moveContainerPushRecursive(it, distance - available);
    }
    moved = forward ? kMin(distance, available)
                    : kMax(distance, available);

    QRect geom = cur->geometryR();
    geom.moveLeft(geom.left() + moved);
    cur->setGeometryR(geom);

    return moved;
}
示例#22
0
// __________________________________________________________________________________________________
bool KikiScrollMenu::handleKey ( const KKey & key )
{    
    std::string keyName = key.getUnmodifiedName ();

    if (keyName == "LEFT" || keyName == "RIGHT")
    {
		active_index += ((keyName == "LEFT") ? -1 : 1) * num_rows;
		if (circular)
		{
			if (active_index < 0)
				active_index += (int)all_menu_items.size();
			else if ((active_index) >= (int)all_menu_items.size())
				active_index -= (int)all_menu_items.size();
		}
		else
		{
			if (active_index < 0)
			{
				offset = index_offset = active_index = 0;
			}
			else
			{
				active_index = kMin(all_menu_items.size()-1, active_index);
			}
		}
		
		activeIndexChanged ();
		getEventWithName ("changed")->triggerActions();
	}
	else
	{
		return KikiMenu::handleKey (key);
	}

	return true;
}
示例#23
0
bool KateBuffer::doHighlight (KateBufBlock *buf, uint startLine, uint endLine, bool invalidate)
{
  // no hl around, no stuff to do
  if (!m_highlight)
    return false;

  /*if (m_highlight->foldingIndentationSensitive())
  {
    startLine=0;
    endLine=50;
  }*/

  // we tried to start in a line behind this buf block !
  if (startLine >= (buf->startLine()+buf->lines()))
    return false;

  //TQTime t;
  //t.start();
  //kdDebug (13020) << "HIGHLIGHTED START --- NEED HL, LINESTART: " << startLine << " LINEEND: " << endLine << endl;
  //kdDebug (13020) << "HL UNTIL LINE: " << m_lineHighlighted << " MAX: " << m_lineHighlightedMax << endl;
  //kdDebug (13020) << "HL DYN COUNT: " << KateHlManager::self()->countDynamicCtxs() << " MAX: " << m_maxDynamicContexts << endl;

  // see if there are too many dynamic contexts; if yes, invalidate HL of all documents
  if (KateHlManager::self()->countDynamicCtxs() >= m_maxDynamicContexts)
  {
    {
      if (KateHlManager::self()->resetDynamicCtxs())
      {
        kdDebug (13020) << "HL invalidated - too many dynamic contexts ( >= " << m_maxDynamicContexts << ")" << endl;

        // avoid recursive invalidation
        KateHlManager::self()->setForceNoDCReset(true);

        for (KateDocument *doc = KateFactory::self()->documents()->first(); doc; doc = KateFactory::self()->documents()->next())
          doc->makeAttribs();

        // doHighlight *shall* do his work. After invalidation, some highlight has
        // been recalculated, but *maybe not* until endLine ! So we shall force it manually...
        KateBufBlock *buf = 0;
        while ((endLine > m_lineHighlighted) && (buf = findBlock(m_lineHighlighted)))
        {
          uint end = kMin(endLine, buf->endLine());

          doHighlight ( buf,
                        kMax(m_lineHighlighted, buf->startLine()),
                        end,
                        false );

          m_lineHighlighted = end;
        }

        KateHlManager::self()->setForceNoDCReset(false);

        return false;
      }
      else
      {
        m_maxDynamicContexts *= 2;
        kdDebug (13020) << "New dynamic contexts limit: " << m_maxDynamicContexts << endl;
      }
    }
  }

  // get the previous line, if we start at the beginning of this block
  // take the last line of the previous block
  KateTextLine::Ptr prevLine = 0;

  if ((startLine == buf->startLine()) && buf->prev() && (buf->prev()->lines() > 0))
    prevLine = buf->prev()->line (buf->prev()->lines() - 1);
  else if ((startLine > buf->startLine()) && (startLine <= buf->endLine()))
    prevLine = buf->line(startLine - buf->startLine() - 1);
  else
    prevLine = new KateTextLine ();

  // does we need to emit a signal for the folding changes ?
  bool codeFoldingUpdate = false;

  // here we are atm, start at start line in the block
  uint current_line = startLine - buf->startLine();

  // do we need to continue
  bool stillcontinue=false;
  bool indentContinueWhitespace=false;
  bool indentContinueNextWhitespace=false;
  // loop over the lines of the block, from startline to endline or end of block
  // if stillcontinue forces us to do so
  while ( (current_line < buf->lines())
          && (stillcontinue || ((current_line + buf->startLine()) <= endLine)) )
  {
    // current line
    KateTextLine::Ptr textLine = buf->line(current_line);

    TQMemArray<uint> foldingList;
    bool ctxChanged = false;

    m_highlight->doHighlight (prevLine, textLine, &foldingList, &ctxChanged);

    //
    // indentation sensitive folding
    //
    bool indentChanged = false;
    if (m_highlight->foldingIndentationSensitive())
    {
      // get the indentation array of the previous line to start with !
      TQMemArray<unsigned short> indentDepth;
      indentDepth.duplicate (prevLine->indentationDepthArray());

      // current indentation of this line
      uint iDepth = textLine->indentDepth(m_tabWidth);
      if ((current_line+buf->startLine())==0)
      {
          indentDepth.resize (1, TQGArray::SpeedOptim);
          indentDepth[0] = iDepth;
      }

      textLine->setNoIndentBasedFoldingAtStart(prevLine->noIndentBasedFolding());
      // this line is empty, beside spaces, or has indentaion based folding disabled, use indentation depth of the previous line !
      kdDebug(13020)<<"current_line:"<<current_line + buf->startLine()<<" textLine->noIndentBasedFoldingAtStart"<<textLine->noIndentBasedFoldingAtStart()<<endl;
      if ( (textLine->firstChar() == -1) || textLine->noIndentBasedFoldingAtStart())
      {
        // do this to get skipped empty lines indent right, which was given in the indenation array
        if (!prevLine->indentationDepthArray().isEmpty())
        {
          iDepth = (prevLine->indentationDepthArray())[prevLine->indentationDepthArray().size()-1];
          kdDebug(13020)<<"reusing old depth as current"<<endl;
        }
        else
        {
          iDepth = prevLine->indentDepth(m_tabWidth);
          kdDebug(13020)<<"creating indentdepth for previous line"<<endl;
        }
      }

      kdDebug(13020)<<"iDepth:"<<iDepth<<endl;

      // query the next line indentation, if we are at the end of the block
      // use the first line of the next buf block
      uint nextLineIndentation = 0;
      bool nextLineIndentationValid=true;
      indentContinueNextWhitespace=false;
      if ((current_line+1) < buf->lines())
      {
        if (buf->line(current_line+1)->firstChar() == -1)
        {
          nextLineIndentation = iDepth;
          indentContinueNextWhitespace=true;
        }
        else
          nextLineIndentation = buf->line(current_line+1)->indentDepth(m_tabWidth);
      }
      else
      {
        KateBufBlock *blk = buf->next();

        if (blk && (blk->lines() > 0))
        {
          if (blk->line (0)->firstChar() == -1)
          {
            nextLineIndentation = iDepth;
            indentContinueNextWhitespace=true;
          }
          else
            nextLineIndentation = blk->line (0)->indentDepth(m_tabWidth);
        }
        else nextLineIndentationValid=false;
      }

      if  (!textLine->noIndentBasedFoldingAtStart()) {

        if ((iDepth > 0) && (indentDepth.isEmpty() || (indentDepth[indentDepth.size()-1] < iDepth)))
        {
          kdDebug(13020)<<"adding depth to \"stack\":"<<iDepth<<endl;
          indentDepth.resize (indentDepth.size()+1, TQGArray::SpeedOptim);
          indentDepth[indentDepth.size()-1] = iDepth;
        } else {
          if (!indentDepth.isEmpty())
          {
            for (int z=indentDepth.size()-1; z > -1; z--)
              if (indentDepth[z]>iDepth)
                indentDepth.resize(z, TQGArray::SpeedOptim);
            if ((iDepth > 0) && (indentDepth.isEmpty() || (indentDepth[indentDepth.size()-1] < iDepth)))
            {
              kdDebug(13020)<<"adding depth to \"stack\":"<<iDepth<<endl;
              indentDepth.resize (indentDepth.size()+1, TQGArray::SpeedOptim);
              indentDepth[indentDepth.size()-1] = iDepth;
              if (prevLine->firstChar()==-1) {

              }
            }
          }
        }
      }

      if (!textLine->noIndentBasedFolding())
      {
        if (nextLineIndentationValid)
        {
          //if (textLine->firstChar()!=-1)
          {
            kdDebug(13020)<<"nextLineIndentation:"<<nextLineIndentation<<endl;
            bool addindent=false;
            uint deindent=0;
            if (!indentDepth.isEmpty())
              kdDebug()<<"indentDepth[indentDepth.size()-1]:"<<indentDepth[indentDepth.size()-1]<<endl;
            if ((nextLineIndentation>0) && ( indentDepth.isEmpty() || (indentDepth[indentDepth.size()-1]<nextLineIndentation)))
            {
              kdDebug(13020)<<"addindent==true"<<endl;
              addindent=true;
            } else {
            if ((!indentDepth.isEmpty()) && (indentDepth[indentDepth.size()-1]>nextLineIndentation))
              {
                kdDebug(13020)<<"...."<<endl;
                for (int z=indentDepth.size()-1; z > -1; z--)
                {
                  kdDebug(13020)<<indentDepth[z]<<"  "<<nextLineIndentation<<endl;
                  if (indentDepth[z]>nextLineIndentation)
                    deindent++;
                }
              }
            }
/*        }
        if (textLine->noIndentBasedFolding()) kdDebug(13020)<<"=============================indentation based folding disabled======================"<<endl;
        if (!textLine->noIndentBasedFolding()) {*/
            if ((textLine->firstChar()==-1)) {
              updatePreviousNotEmptyLine(buf,current_line,addindent,deindent);
              codeFoldingUpdate=true;
            }
            else
            {
              addIndentBasedFoldingInformation(foldingList,addindent,deindent);
            }
          }
        }
      }
      indentChanged = !(indentDepth == textLine->indentationDepthArray());

      // assign the new array to the textline !
      if (indentChanged)
        textLine->setIndentationDepth (indentDepth);

      indentContinueWhitespace=textLine->firstChar()==-1;
    }
    bool foldingColChanged=false;
    bool foldingChanged = false; //!(foldingList == textLine->foldingListArray());
    if (foldingList.size()!=textLine->foldingListArray().size()) {
      foldingChanged=true;
    } else {
      TQMemArray<uint>::ConstIterator it=foldingList.begin();
      TQMemArray<uint>::ConstIterator it1=textLine->foldingListArray();
      bool markerType=true;
      for(;it!=foldingList.end();++it,++it1) {
        if  (markerType) {
          if ( ((*it)!=(*it1))) {
            foldingChanged=true;
            foldingColChanged=false;
            break;
          }
        } else {
            if ((*it)!=(*it1)) {
              foldingColChanged=true;
            }
        }
        markerType=!markerType;
      }
    }

    if (foldingChanged || foldingColChanged) {
      textLine->setFoldingList(foldingList);
      if (foldingChanged==false){
        textLine->setFoldingColumnsOutdated(textLine->foldingColumnsOutdated() | foldingColChanged);
      } else textLine->setFoldingColumnsOutdated(false);
    }
    bool retVal_folding = false;
    //perhaps make en enums out of the change flags
    m_regionTree.updateLine (current_line + buf->startLine(), &foldingList, &retVal_folding, foldingChanged,foldingColChanged);

    codeFoldingUpdate = codeFoldingUpdate | retVal_folding;

    // need we to continue ?
    stillcontinue = ctxChanged || indentChanged || indentContinueWhitespace || indentContinueNextWhitespace;

    // move around the lines
    prevLine = textLine;

    // increment line
    current_line++;
  }

  buf->markDirty ();

  // tag the changed lines !
  if (invalidate)
    emit tagLines (startLine, current_line + buf->startLine());

  // emit that we have changed the folding
  if (codeFoldingUpdate)
    emit codeFoldingUpdated();

  //kdDebug (13020) << "HIGHLIGHTED END --- NEED HL, LINESTART: " << startLine << " LINEEND: " << endLine << endl;
  //kdDebug (13020) << "HL UNTIL LINE: " << m_lineHighlighted << " MAX: " << m_lineHighlightedMax << endl;
  //kdDebug (13020) << "HL DYN COUNT: " << KateHlManager::self()->countDynamicCtxs() << " MAX: " << m_maxDynamicContexts << endl;
  //kdDebug (13020) << "TIME TAKEN: " << t.elapsed() << endl;

  // if we are at the last line of the block + we still need to continue
  // return the need of that !
  return stillcontinue && ((current_line+1) == buf->lines());
}
示例#24
0
// --------------------------------------------------------------------------------------------------------
void KPerspectiveProjection::setEyeDistance ( GLfloat ed )
{
    KVector lookAtPos = getLookAtPosition();
    eye_distance = kMin( kMax(znear, ed), 0.9 * zfar );
    setPosition(lookAtPos + eye_distance * getZVector());
}
示例#25
0
KDoubleNumInput::KDoubleNumInput(KNumInput* below, double value, QWidget* parent,
                                 const char* name)
    : KNumInput(below, parent, name)
{
    init( value, kMin(0.0, value), kMax(0.0, value), 0.01, 2 );
}
示例#26
0
void KDoubleNumInput::setReferencePoint( double ref )
{
    // clip to valid range:
    ref = kMin( maxValue(), kMax( minValue(), ref ) );
    d->referencePoint = ref;
}
示例#27
0
void KoXmlWriter::writeIndent()
{
    // +1 because of the leading '\n'
    m_dev->writeBlock( m_indentBuffer, kMin( indentLevel() + 1,
                                             s_indentBufferLength ) );
}
示例#28
0
bool KateSearch::doSearch( const TQString& text )
{
/*
  rodda: Still Working on this... :)

  bool result = false;

  if (m_searchResults.count()) {
    m_resultIndex++;
    if (m_resultIndex < (int)m_searchResults.count()) {
      s = m_searchResults[m_resultIndex];
      result = true;
    }

  } else {
    int temp = 0;
    do {*/

#if 0
  static int oldLine = -1;
  static int oldCol = -1;
#endif

  uint line = s.cursor.line();
  uint col = s.cursor.col();// + (result ? s.matchedLength : 0);
  bool backward = s.flags.backward;
  bool caseSensitive = s.flags.caseSensitive;
  bool regExp = s.flags.regExp;
  bool wholeWords = s.flags.wholeWords;
  uint foundLine, foundCol, matchLen;
  bool found = false;
  //kdDebug() << "Searching at " << line << ", " << col << endl;
//   kdDebug()<<"KateSearch::doSearch: "<<line<<", "<<col<<", "<<backward<<endl;

  if (backward)
  {
    KateDocCursor docCursor(line, col, doc());

    // If we're at the top of the document, we're not gonna find anything, so bail.
    if (docCursor.line() == 0 && docCursor.col() == 0)
      return false;

    // Move one step backward before searching, if this is a "find again", we don't
    // want to find the same match.
    docCursor.moveBackward(1);
    line = docCursor.line();
    col = docCursor.col();
  }

  do {
      if( regExp ) {
        m_re = TQRegExp( text, caseSensitive );
        found = doc()->searchText( line, col, m_re,
                                  &foundLine, &foundCol,
                                  &matchLen, backward );
      }
      else if ( wholeWords )
      {
        bool maybefound = false;
        do
        {
          maybefound = doc()->searchText( line, col, text,
                                  &foundLine, &foundCol,
                                  &matchLen, caseSensitive, backward );
          if ( maybefound )
          {
            found = (
                      ( foundCol == 0 ||
                        ! doc()->highlight()->isInWord( doc()->textLine( foundLine ).at( foundCol - 1 ) ) ) &&
                      ( foundCol + matchLen == doc()->lineLength( foundLine ) ||
                        ! doc()->highlight()->isInWord( doc()->textLine( foundLine ).at( foundCol + matchLen ) ) )
                    );
            if ( found )
            {
              break;
            }
            else if ( backward && foundCol == 0 ) // we are done on this line and want to avoid endless loops like in #137312
            {
              if ( line == 0 ) // we are completely done...
                break;
              else
                line--;
            }
            else
            {
              line = foundLine;
              col = foundCol + 1;
            }
          }
        } while ( maybefound );
      }
      else {
        found = doc()->searchText( line, col, text,
                                  &foundLine, &foundCol,
                                  &matchLen, caseSensitive, backward );
      }

    if ( found && s.flags.selected )
    {
      KateTextCursor start (s.selBegin);
      KateTextCursor end (s.selEnd);

      // recalc for block sel, to have start with lowest col, end with highest
      if (m_view->blockSelectionMode())
      {
        start.setCol (kMin(s.selBegin.col(), s.selEnd.col()));
        end.setCol (kMax(s.selBegin.col(), s.selEnd.col()));
      }

      if ( !s.flags.backward && KateTextCursor( foundLine, foundCol ) >= end
        ||  s.flags.backward && KateTextCursor( foundLine, foundCol ) < start )
      {
        found = false;
      }
      else if (m_view->blockSelectionMode())
      {
        if ((int)foundCol >= start.col() && (int)foundCol < end.col())
          break;
      }
    }

    line = foundLine;
    col = foundCol+1;
  }
  while (s.flags.selected && m_view->blockSelectionMode() && found);
  // in the case we want to search in selection + blockselection we need to loop

  if( !found ) return false;

  // save the search result
  s.cursor.setPos(foundLine, foundCol);
  s.matchedLength = matchLen;

  // we allready wrapped around one time
  if (s.wrapped)
  {
    if (s.flags.backward)
    {
      if ( (s.cursor.line() < s.wrappedEnd.line())
           || ( (s.cursor.line() == s.wrappedEnd.line()) && ((s.cursor.col()+matchLen) <= uint(s.wrappedEnd.col())) ) )
        return false;
    }
    else
    {
      if ( (s.cursor.line() > s.wrappedEnd.line())
           || ( (s.cursor.line() == s.wrappedEnd.line()) && (s.cursor.col() > s.wrappedEnd.col()) ) )
        return false;
    }
  }

//   kdDebug() << "Found at " << s.cursor.line() << ", " << s.cursor.col() << endl;


  //m_searchResults.append(s);

  if (arbitraryHLExample)  {
    KateArbitraryHighlightRange* hl = new KateArbitraryHighlightRange(new KateSuperCursor(m_doc, true, s.cursor), new KateSuperCursor(m_doc, true, s.cursor.line(), s.cursor.col() + s.matchedLength), this);
    hl->setBold();
    hl->setTextColor(Qt::white);
    hl->setBGColor(Qt::black);
    // destroy the highlight upon change
    connect(hl, TQT_SIGNAL(contentsChanged()), hl, TQT_SIGNAL(eliminated()));
    m_arbitraryHLList->append(hl);
  }

  return true;

    /* rodda: more of my search highlighting work

    } while (++temp < 100);

    if (result) {
      s = m_searchResults.first();
      m_resultIndex = 0;
    }
  }

  return result;*/
}
示例#29
0
文件: pak.cpp 项目: Uiomae/kio_pak
void PakProtocol::get(const KURL &url) {
	kdDebug(PAK_DEBUG_ID) << "ArchiveProtocol::get " << url << endl;

	QString path;
	KIO::Error errorNum;
	if ( !checkNewFile( url, path, errorNum ) )
	{
		if ( errorNum == KIO::ERR_CANNOT_OPEN_FOR_READING )
		{
			// If we cannot open, it might be a problem with the archive header (e.g. unsupported format)
			// Therefore give a more specific error message
			error( KIO::ERR_SLAVE_DEFINED,
					i18n( "Could not open the file, probably due to an unsupported file format.\n%1")
					.arg( url.prettyURL() ) );
			return;
		}
		else
		{
			// We have any other error
			error( errorNum, url.prettyURL() );
			return;
		}
	}
	kdDebug(PAK_DEBUG_ID) << "Continue getting" << endl;

	path = QString::fromLocal8Bit(remoteEncoding()->encode(path));

	kdDebug(PAK_DEBUG_ID) << "Path > " << path << endl;
	const KArchiveDirectory* root = _pakFile->directory();
	const KArchiveEntry* archiveEntry = root->entry( path );

	kdDebug(PAK_DEBUG_ID) << "Check if no archiveEntry > " << archiveEntry << endl;
	if ( !archiveEntry )
	{
		error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() );
		return;
	}
	kdDebug(PAK_DEBUG_ID) << "archiveEntry::name > " << archiveEntry->name() << endl;
	if ( archiveEntry->isDirectory() )
	{
		error( KIO::ERR_IS_DIRECTORY, url.prettyURL() );
		return;
	}
	const KArchiveFile* archiveFileEntry = static_cast<const KArchiveFile *>(archiveEntry);
	if ( !archiveEntry->symlink().isEmpty() )
	{
		kdDebug(7109) << "Redirection to " << archiveEntry->symlink() << endl;
		KURL realURL;
		if (archiveEntry->symlink().startsWith("/")) { // absolute path
			realURL.setPath(archiveEntry->symlink() ); // goes out of tar:/, back into file:
		} else {
			realURL = KURL( url, archiveEntry->symlink() );
		}
		kdDebug(7109) << "realURL= " << realURL << endl;
		redirection( realURL );
		finished();
		return;
	}

	//kdDebug(7109) << "Preparing to get the archive data" << endl;

	/*
	 * The easy way would be to get the data by calling archiveFileEntry->data()
	 * However this has drawbacks:
	 * - the complete file must be read into the memory
	 * - errors are skipped, resulting in an empty file
	 */

	QIODevice* io = 0;
	// Getting the device is hard, as archiveFileEntry->device() is not virtual!
	if ( url.protocol() == "pak" )
	{
		io = archiveFileEntry->device();
	}
	else
	{
		// Wrong protocol? Why was this not catched by checkNewFile?
		kdWarning(7109) << "Protocol " << url.protocol() << " not supported by this IOSlave; " << k_funcinfo << endl;
		error( KIO::ERR_UNSUPPORTED_PROTOCOL, url.protocol() );
		return;
	}

	if (!io)
	{
		error( KIO::ERR_SLAVE_DEFINED,
				i18n( "The archive file could not be opened, perhaps because the format is unsupported.\n%1" )
				.arg( url.prettyURL() ) );
		return;
	}

	if ( !io->open( IO_ReadOnly ) )
	{
		error( KIO::ERR_CANNOT_OPEN_FOR_READING, url.prettyURL() );
		return;
	}

	totalSize( archiveFileEntry->size() );

	// Size of a QIODevice read. It must be large enough so that the mime type check will not fail
	const int maxSize = 0x100000; // 1MB

	int bufferSize = kMin( maxSize, archiveFileEntry->size() );
	QByteArray buffer ( bufferSize );
	if ( buffer.isEmpty() && bufferSize > 0 )
	{
		// Something went wrong
		error( KIO::ERR_OUT_OF_MEMORY, url.prettyURL() );
		return;
	}

	bool firstRead = true;

	// How much file do we still have to process?
	int fileSize = archiveFileEntry->size();
	KIO::filesize_t processed = 0;

	while ( !io->atEnd() && fileSize > 0 )
	{
		if ( !firstRead )
		{
			bufferSize = kMin( maxSize, fileSize );
			buffer.resize( bufferSize, QGArray::SpeedOptim );
		}
		const Q_LONG read = io->readBlock( buffer.data(), buffer.size() ); // Avoid to use bufferSize here, in case something went wrong.
		if ( read != bufferSize )
		{
			kdWarning(7109) << "Read " << read << " bytes but expected " << bufferSize << endl;
			error( KIO::ERR_COULD_NOT_READ, url.prettyURL() );
			return;
		}
		if ( firstRead )
		{
			// We use the magic one the first data read
			// (As magic detection is about fixed positions, we can be sure that it is enough data.)
			KMimeMagicResult * result = KMimeMagic::self()->findBufferFileType( buffer, path );
			kdDebug(7109) << "Emitting mimetype " << result->mimeType() << endl;
			mimeType( result->mimeType() );
			firstRead = false;
		}
		data( buffer );
		processed += read;
		processedSize( processed );
		fileSize -= bufferSize;
	}
	io->close();
	delete io;

	data( QByteArray() );

	finished();

	/*kdDebug(PAK_DEBUG_ID) << "Entering get()" << endl;
	mimetype("text/plain");
	QCString str("Hello Pak World!!");
	data(str);
	finished();
	kdDebug(PAK_DEBUG_ID) << "Exiting get()" << endl;*/
}
示例#30
0
int main(int argc, char **argv)
{
    // nspluginviewer is a helper app, it shouldn't do session management at all
    setenv("SESSION_MANAGER", "", 1);

    // trap X errors
    kdDebug(1430) << "1 - XSetErrorHandler" << endl;
    XSetErrorHandler(x_errhandler);
    setvbuf(stderr, NULL, _IONBF, 0);

    kdDebug(1430) << "2 - parseCommandLine" << endl;
    parseCommandLine(argc, argv);

#if QT_VERSION < 0x030100
    // Create application
    kdDebug(1430) << "3 - XtToolkitInitialize" << endl;
    XtToolkitInitialize();
    g_appcon = XtCreateApplicationContext();
    Display *dpy = XtOpenDisplay(g_appcon, NULL, "nspluginviewer", "nspluginviewer", 0, 0, &argc, argv);

    _notifiers[0].setAutoDelete(TRUE);
    _notifiers[1].setAutoDelete(TRUE);
    _notifiers[2].setAutoDelete(TRUE);

    kdDebug(1430) << "4 - KXtApplication app" << endl;
    KLocale::setMainCatalogue("nsplugin");
    KXtApplication app(dpy, argc, argv, "nspluginviewer");
#else
    kdDebug(1430) << "3 - create QXtEventLoop" << endl;
    QXtEventLoop integrator("nspluginviewer");
    parseCommandLine(argc, argv);
    KLocale::setMainCatalogue("nsplugin");

    kdDebug(1430) << "4 - create KApplication" << endl;
    KApplication app(argc, argv, "nspluginviewer");
    GlibEvents glibevents;
#endif

    {
        KConfig cfg("kcmnspluginrc", true);
        cfg.setGroup("Misc");
        int v = KCLAMP(cfg.readNumEntry("Nice Level", 0), 0, 19);
        if(v > 0)
        {
            nice(v);
        }
        v = cfg.readNumEntry("Max Memory", 0);
        if(v > 0)
        {
            rlimit rl;
            memset(&rl, 0, sizeof(rl));
            if(0 == getrlimit(RLIMIT_AS, &rl))
            {
                rl.rlim_cur = kMin(v, int(rl.rlim_max));
                setrlimit(RLIMIT_AS, &rl);
            }
        }
    }

    // initialize the dcop client
    kdDebug(1430) << "5 - app.dcopClient" << endl;
    DCOPClient *dcop = app.dcopClient();
    if(!dcop->attach())
    {
        KMessageBox::error(NULL, i18n("There was an error connecting to the Desktop "
                                      "communications server. Please make sure that "
                                      "the 'dcopserver' process has been started, and "
                                      "then try again."),
                           i18n("Error Connecting to DCOP Server"));
        exit(1);
    }

    kdDebug(1430) << "6 - dcop->registerAs" << endl;
    if(g_dcopId)
        g_dcopId = dcop->registerAs(g_dcopId, false);
    else
        g_dcopId = dcop->registerAs("nspluginviewer");

    dcop->setNotifications(true);

    // create dcop interface
    kdDebug(1430) << "7 - new NSPluginViewer" << endl;
    NSPluginViewer *viewer = new NSPluginViewer("viewer", 0);

// start main loop
#if QT_VERSION < 0x030100
    kdDebug(1430) << "8 - XtAppProcessEvent" << endl;
    while(!g_quit)
        XtAppProcessEvent(g_appcon, XtIMAll);
#else
    kdDebug(1430) << "8 - app.exec()" << endl;
    app.exec();
#endif

    // delete viewer
    delete viewer;
}