/*!
    \property QxtSpanSlider::lowerValue
    \brief the lower value of the span
 */
int QxtSpanSlider::lowerValue() const
{
    return qMin(qxt_d().lower, qxt_d().upper);
}
Beispiel #2
0
QImage* MyTextEffect::drawImage()
{
    QFont myFont;
    QPen myPen;
    myPen.setJoinStyle( Qt::RoundJoin );
    QBrush myBrush( QColor(0,0,0,0) );
    QColor backgroundColor(0,0,0,0);
    int outline = 0;
    int align = 1;

    int arrowType = 0, arrowSize = 0, arrowPos = 0;

    QStringList sl = currentText.split("\n");
    while ( !sl.isEmpty() ) {
        if ( sl.last().trimmed().isEmpty() )
            sl.takeLast();
        else
            break;
    }
    if ( sl.count() ) {
        QStringList desc = sl[0].split("|");
        if ( desc.count() >= 9 ) {
            myFont.fromString( desc[0] );
            myFont.setPointSize( desc[1].toInt() );
            myFont.setBold( desc[2].toInt() );
            myFont.setItalic( desc[3].toInt() );

            QStringList fc = desc[4].split( "." );
            if ( fc.count() == 2 ) {
                QColor col;
                col.setNamedColor( fc[ 0 ] );
                col.setAlpha( fc[ 1 ].toInt() );
                myPen.setColor( col );
                myBrush.setColor( col );
            }

            QStringList bc = desc[5].split( "." );
            if ( bc.count() == 2 ) {
                backgroundColor.setNamedColor( bc[ 0 ] );
                backgroundColor.setAlpha( bc[ 1 ].toInt() );
            }

            align = desc[6].toInt();

            int osize = desc[7].toInt();
            if ( osize > 0 ) {
                QStringList oc = desc[8].split( "." );
                if ( oc.count() == 2 ) {
                    outline = osize;
                    myPen.setWidth( osize );
                    myFont.setStyleStrategy( QFont::ForceOutline );
                    QColor col;
                    col.setNamedColor( oc[ 0 ] );
                    col.setAlpha( oc[ 1 ].toInt() );
                    myPen.setColor( col );
                }
            }
        }
        if ( desc.count() >= 12 ) {
            arrowType = desc[9].toInt();
            arrowSize = desc[10].toInt();
            arrowPos = desc[11].toInt();
        }
        sl.takeFirst();
    }

    QImage *image = new QImage( 10, 10, QImage::Format_ARGB32_Premultiplied );
    QPainter painter;
    painter.begin( image );
    painter.setPen( myPen );
    painter.setBrush( myBrush );
    painter.setFont( myFont );
    QList<QRectF> br;
    QFontMetrics metrics( myFont );
    int h = sl.count() * metrics.lineSpacing();
    int w = 0;
    for ( int i = 0; i < sl.count(); ++i ) {
        QRectF minrect( 0, 0, 1, 1 );
        QRectF r = painter.boundingRect( minrect, Qt::AlignHCenter | Qt::AlignVCenter, sl[i] );
        if ( r.width() > w )
            w = r.width();
        br.append( r );
    }
    QRectF minrect( 0, 0, 1, 1 );
    int margin = qMax( painter.boundingRect( minrect, Qt::AlignHCenter | Qt::AlignVCenter, "M" ).width() / 3.0, 3.0 );

    painter.end();

    double x = ((double)outline + margin * 2) / 2.0;
    double y = x;
    w += 2 * x;
    h += 2 * y;
    if ( w > iwidth ) {
        x -= (w - iwidth) / 2.0;
        w = iwidth;
    }
    if ( h > iheight ) {
        y -= (h - iheight) / 2.0;
        h = iheight;
    }

    QPointF polygon[7];
    arrowSize = h * arrowSize / 100.0;
    int n = 0;
    int leftOffset = 0, topOffset = 0;
    int wMargin = 0, hMargin = 0;
    if (arrowType) {
        switch (arrowType) {
        case 1: {
            leftOffset = arrowSize;
            wMargin = arrowSize;
            polygon[n].setX(1 + arrowSize);
            polygon[n++].setY(1);

            polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0 - arrowSize / 2.0) ) );
            polygon[n++].setX(1 + arrowSize);
            polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0) ) );
            polygon[n++].setX(1);
            polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0 + arrowSize / 2.0) ) );
            polygon[n++].setX(1 + arrowSize);

            polygon[n].setX(1 + arrowSize);
            polygon[n++].setY(h - 1);
            polygon[n].setX(w - 1 + arrowSize);
            polygon[n++].setY(h - 1);
            polygon[n].setX(w - 1 + arrowSize);
            polygon[n++].setY(1);
            break;
        }
        case 2: {
            wMargin = arrowSize;
            polygon[n].setX(1);
            polygon[n++].setY(1);
            polygon[n].setX(1);
            polygon[n++].setY(h - 1);
            polygon[n].setX(w - 1);
            polygon[n++].setY(h - 1);

            polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0 + arrowSize / 2.0) ) );
            polygon[n++].setX(w - 1);
            polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0) ) );
            polygon[n++].setX(w - 1 + arrowSize);
            polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0 - arrowSize / 2.0) ) );
            polygon[n++].setX(w - 1);

            polygon[n].setX(w - 1);
            polygon[n++].setY(1);
            break;
        }
        case 3: {
            topOffset = arrowSize;
            hMargin = arrowSize;
            polygon[n].setX(1);
            polygon[n++].setY(1 + arrowSize);
            polygon[n].setX(1);
            polygon[n++].setY(h - 1 + arrowSize);
            polygon[n].setX(w - 1);
            polygon[n++].setY(h - 1 + arrowSize);
            polygon[n].setX(w - 1);
            polygon[n++].setY(1 + arrowSize);

            polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0 + arrowSize / 2.0) ) );
            polygon[n++].setY(1 + arrowSize);
            polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0) ) );
            polygon[n++].setY(1);
            polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0 - arrowSize / 2.0) ) );
            polygon[n++].setY(1 + arrowSize);
            break;
        }
        case 4: {
            hMargin = arrowSize;
            polygon[n].setX(1);
            polygon[n++].setY(1);
            polygon[n].setX(1);
            polygon[n++].setY(h - 1);

            polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0 - arrowSize / 2.0) ) );
            polygon[n++].setY(h - 1);
            polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0) ) );
            polygon[n++].setY(h - 1 + arrowSize);
            polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0 + arrowSize / 2.0) ) );
            polygon[n++].setY(h - 1);

            polygon[n].setX(w - 1);
            polygon[n++].setY(h - 1);
            polygon[n].setX(w - 1);
            polygon[n++].setY(1);
            break;
        }
        }
    }

    delete image;
    image = new QImage( w + wMargin, h + hMargin, QImage::Format_ARGB32_Premultiplied );
    image->fill( QColor(0,0,0,0) );
    painter.begin( image );
    painter.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing );
    if ( backgroundColor.alpha() > 0 ) {
        painter.setPen( QColor(0,0,0,0) );
        painter.setBrush( backgroundColor );
        if (arrowType) {
            painter.drawPolygon( polygon, 7 );
        }
        else {
            painter.drawRect( 1, 1, w - 2, h - 2 );
        }
    }
    painter.setPen( myPen );
    painter.setBrush( myBrush );
    painter.setFont( myFont );

    for ( int i = 0; i < sl.count(); ++i ) {
        QPointF point( 0, y + topOffset + metrics.ascent() );
        switch ( align ) {
        case 2: {
            point.setX( leftOffset + (double)w / 2.0 - br[i].width() / 2.0 );
            break;
        }
        case 3: {
            point.setX( leftOffset + w - x - br[i].width() );
            break;
        }
        default: {
            point.setX( leftOffset + x );
            break;
        }
        }
        if ( outline ) {
            QPainterPath myPath;
            myPath.addText( point, myFont, sl[i] );
            painter.drawPath( myPath );
        }
        else
            painter.drawText( point, sl[i] );
        y += metrics.lineSpacing();
    }
    painter.end();

    return image;
}
void QSearchReplacePanel::on_leFind_textEdited(const QString& text)
{
        bool hadSearch = m_search;
        QDocumentCursor cur = editor()->cursor();
        
        if ( m_search ) 
        {
                cur = m_search->cursor();
                
                m_search->setSearchText(text);
                
                if ( cbCursor->isChecked() )
                {
                        QDocumentCursor c = cur;
                        c.setColumnNumber(qMin(c.anchorColumnNumber(), c.columnNumber()));
                        
                        m_search->setCursor(c);
                }
        } else {
                // TODO : make incremental search optional
                init();
        }
        
        if ( text.isEmpty() )
        {
                leFind->setStyleSheet(QString());
                return;
        }
        
        m_search->setOption(QDocumentSearch::Silent, true);
        
        find(0);
        
        m_search->setOption(QDocumentSearch::Silent, false);
        
        if ( m_search->cursor().isNull() )
        {
                leFind->setStyleSheet("QLineEdit { background: red; color : white; }");
                
                if ( hadSearch )
                {
                        m_search->setCursor(cur);
                        
                        // figure out whether other matches are availables
                        QDocumentSearch::Options opts = m_search->options();
                        opts &= ~QDocumentSearch::HighlightAll;
                        opts |= QDocumentSearch::Silent;
                        
                        QDocumentSearch temp(editor(), text, opts);
                        temp.setOrigin(QDocumentCursor());
                        temp.setScope(m_search->scope());
                        temp.next(true);
                        
                        if ( temp.cursor().isValid() )
                        {
                                // other match found from doc start
                                leFind->setStyleSheet("QLineEdit { background: yellow; color : black; }");
                                m_search->setCursor(cur.document()->cursor(0,0));
                                find(0);
                        }
                }
        } else {
                leFind->setStyleSheet(QString());
                editor()->setCursor(m_search->cursor());
        }
}
Beispiel #4
0
void PageFormat::read(XmlReader& e, Score* score)
      {
      qreal _oddRightMargin  = 0.0;
      qreal _evenRightMargin = 0.0;
      bool landscape = false;
      QString type;

      while (e.readNextStartElement()) {
            const QStringRef& tag(e.name());
            if (tag == "pageFormat")            // obsolete
                  setSize(getPaperSize(e.readElementText()));
            else if (tag == "landscape")        // obsolete
                  landscape = e.readInt();
            else if (tag == "page-margins") {
                  type = e.attribute("type","both");
                  qreal lm = 0.0, rm = 0.0, tm = 0.0, bm = 0.0;
                  while (e.readNextStartElement()) {
                        const QStringRef& tag(e.name());
                        qreal val = e.readDouble() * 0.5 / PPI;
                        if (tag == "left-margin")
                              lm = val;
                        else if (tag == "right-margin")
                              rm = val;
                        else if (tag == "top-margin")
                              tm = val;
                        else if (tag == "bottom-margin")
                              bm = val;
                        else
                              e.unknown();
                        }
                  _twosided = type == "odd" || type == "even";
                  if (type == "odd" || type == "both") {
                        _oddLeftMargin   = lm;
                        _oddRightMargin  = rm;
                        _oddTopMargin    = tm;
                        _oddBottomMargin = bm;
                        }
                  if (type == "even" || type == "both") {
                        _evenLeftMargin   = lm;
                        _evenRightMargin  = rm;
                        _evenTopMargin    = tm;
                        _evenBottomMargin = bm;
                        }
                  }
            else if (tag == "page-height")
                  _size.rheight() = e.readDouble() * 0.5 / PPI;
            else if (tag == "page-width")
                  _size.rwidth() = e.readDouble() * .5 / PPI;
            else if (tag == "page-offset") {           // obsolete, moved to Score
                  QString val(e.readElementText());
                  if(score)
                        score->setPageNumberOffset(val.toInt());
                  }
            else
                  e.unknown();
            }
      if (landscape)
            _size.transpose();
      qreal w1 = _size.width() - _oddLeftMargin - _oddRightMargin;
      qreal w2 = _size.width() - _evenLeftMargin - _evenRightMargin;
      _printableWidth = qMin(w1, w2);     // silently adjust right margins
      }
qint64 Modulator::readData (char * data, qint64 maxSize)
{
  static int j0=-1;
  static double toneFrequency0;
  double toneFrequency;

  if(maxSize==0) return 0;
  Q_ASSERT (!(maxSize % static_cast<qint64> (bytesPerFrame ()))); // no torn frames
  Q_ASSERT (isOpen ());

  qint64 numFrames (maxSize / bytesPerFrame ());
  qint16 * samples (reinterpret_cast<qint16 *> (data));
  qint16 * end (samples + numFrames * (bytesPerFrame () / sizeof (qint16)));

//  qDebug () << "Modulator: " << numFrames << " requested, m_ic = " << m_ic << ", tune mode is " << m_tuning;
//  qDebug() << "C" << maxSize << numFrames << bytesPerFrame();
  switch (m_state)
  {
  case Synchronizing:
  {
    if (m_silentFrames)	{  // send silence up to first second
      numFrames = qMin (m_silentFrames, numFrames);
      for ( ; samples != end; samples = load (0, samples)) { // silence
	      }
      m_silentFrames -= numFrames;
      return numFrames * bytesPerFrame ();
    }

    Q_EMIT stateChanged ((m_state = Active));
    m_ramp = 0;		// prepare for CW wave shaping
  }
      // fall through

  case Active:
  {
    unsigned isym (m_tuning ? 0 : m_ic / (4.0 * m_nsps)); // Actual fsample=48000
    if (isym >= m_symbolsLength && icw[0] > 0) { // start CW condition
      // Output the CW ID
      m_dphi = m_twoPi * m_frequency / m_frameRate;
      unsigned const ic0 = m_symbolsLength * 4 * m_nsps;
      unsigned j (0);
      qint64 framesGenerated (0);

      while (samples != end) {
        m_phi += m_dphi;
        if (m_phi > m_twoPi) m_phi -= m_twoPi;

        qint16 sample ((SOFT_KEYING ? qAbs (m_ramp - 1) :
                                      (m_ramp ? 32767 : 0)) * qSin (m_phi));

        j = (m_ic - ic0 - 1) / m_nspd + 1;
        bool l0 (icw[j] && icw[j] <= 1); // first element treated specially as it's a count
        j = (m_ic - ic0) / m_nspd + 1;

        if ((m_ramp != 0 && m_ramp != std::numeric_limits<qint16>::min ()) ||
            !!icw[j] != l0) {
          if (!!icw[j] != l0) {
            Q_ASSERT (m_ramp == 0 || m_ramp == std::numeric_limits<qint16>::min ());
          }
          m_ramp += RAMP_INCREMENT; // ramp
        }

        if (j < NUM_CW_SYMBOLS) { // stop condition
          // if (!m_ramp && !icw[j])
          //   {
          // 	sample = 0;
          //   }

          samples = load (postProcessSample (sample), samples);
          ++framesGenerated;
          ++m_ic;
        }
      }

      if (j > static_cast<unsigned> (icw[0])) {
        Q_EMIT stateChanged ((m_state = Idle));
      }

      m_framesSent += framesGenerated;
      return framesGenerated * bytesPerFrame ();
    }

    double const baud (12000.0 / m_nsps);
	// fade out parameters (no fade out for tuning)
    unsigned const i0 = m_tuning ? 999 * m_nsps :
                                   (m_symbolsLength - 0.017) * 4.0 * m_nsps;
    unsigned const i1 = m_tuning ? 999 * m_nsps :
                                   m_symbolsLength * 4.0 * m_nsps;

    for (unsigned i = 0; i < numFrames; ++i) {
      isym = m_tuning ? 0 : m_ic / (4.0 * m_nsps); //Actual fsample=48000
      if (isym != m_isym0) {
        if(m_toneSpacing==0.0) {
          toneFrequency0=m_frequency + itone[isym]*baud;
        } else {
          toneFrequency0=m_frequency + itone[isym]*m_toneSpacing;
        }
        m_dphi = m_twoPi * toneFrequency0 / m_frameRate;
        m_isym0 = isym;
      }

      int j=m_ic/480;
      if(m_fSpread>0.0 and j!=j0) {
        float x1=(float)rand()/RAND_MAX;
        float x2=(float)rand()/RAND_MAX;
        toneFrequency = toneFrequency0 + 0.5*m_fSpread*(x1+x2-1.0);
        m_dphi = m_twoPi * toneFrequency / m_frameRate;
        j0=j;
      }

      m_phi += m_dphi;
      if (m_phi > m_twoPi) m_phi -= m_twoPi;
      if (m_ic > i0) m_amp = 0.98 * m_amp;
      if (m_ic > i1) m_amp = 0.0;

      samples = load (postProcessSample (m_amp * qSin (m_phi)), samples);
	    ++m_ic;
	  }

    if (m_amp == 0.0) { // TODO G4WJS: compare double with zero might not be wise
	    if (icw[0] == 0) {
        // no CW ID to send
        Q_EMIT stateChanged ((m_state = Idle));
        m_framesSent += numFrames;
        return numFrames * bytesPerFrame ();
      }

      m_phi = 0.0;
    }

	// done for this chunk - continue on next call
    m_framesSent += numFrames;
    return numFrames * bytesPerFrame ();
  }
    Q_EMIT stateChanged ((m_state = Idle));
    // fall through

  case Idle:
    break;
  }

  Q_ASSERT (Idle == m_state);
  return 0;
}
Beispiel #6
0
void FlatTextarea::processDocumentContentsChange(int position, int charsAdded) {
	int32 emojiPosition = 0, emojiLen = 0;
	const EmojiData *emoji = 0;

	QTextDocument *doc(document());

	while (true) {
		int32 start = position, end = position + charsAdded;
		QTextBlock from = doc->findBlock(start), till = doc->findBlock(end);
		if (till.isValid()) till = till.next();

		for (QTextBlock b = from; b != till; b = b.next()) {
			for (QTextBlock::Iterator iter = b.begin(); !iter.atEnd(); ++iter) {
				QTextFragment fragment(iter.fragment());
				if (!fragment.isValid()) continue;

				int32 fp = fragment.position(), fe = fp + fragment.length();
				if (fp >= end || fe <= start) {
					continue;
				}

				QString t(fragment.text());
				const QChar *ch = t.constData(), *e = ch + t.size();
				for (; ch != e; ++ch) {
					emoji = emojiFromText(ch, e, emojiLen);
					if (emoji) {
						emojiPosition = fp + (ch - t.constData());
						break;
					}
					if (ch + 1 < e && ch->isHighSurrogate() && (ch + 1)->isLowSurrogate()) ++ch;
				}
				if (emoji) break;
			}
			if (emoji) break;
		}
		if (emoji) {
			QTextCursor c(doc->docHandle(), emojiPosition);
			c.setPosition(emojiPosition + emojiLen, QTextCursor::KeepAnchor);
			int32 removedUpto = c.position();

			insertEmoji(emoji, c);

			for (Insertions::iterator i = _insertions.begin(), e = _insertions.end(); i != e; ++i) {
				if (i->first >= removedUpto) {
					i->first -= removedUpto - emojiPosition - 1;
				} else if (i->first >= emojiPosition) {
					i->second -= removedUpto - emojiPosition;
					i->first = emojiPosition + 1;
				} else if (i->first + i->second > emojiPosition + 1) {
					i->second -= qMin(removedUpto, i->first + i->second) - emojiPosition;
				}
			}

			charsAdded -= removedUpto - position;
			position = emojiPosition + 1;

			emoji = 0;
			emojiPosition = 0;
		} else {
			break;
		}
	}
}
Beispiel #7
0
/** Applies this axis' parameters to the graph
*
*/
void ScaleDetails::apply()
{
  if (m_modified && valid())
  {
    //as the classes are separate now this may cause a problem as ideally i'd get this from the axis tab,
    //but at the moment there's nothing to cause a problem as the only other cases that are used are Date
    //and Time and Mantid doesn't support them in data yet i've been told
    ScaleDraw::ScaleType type = m_graph->axisType(m_mappedaxis);

    double start = 0.0, end = 0.0, step = 0.0, breakLeft = -DBL_MAX, breakRight = DBL_MAX;
    if (type == ScaleDraw::Date)
    {
      ScaleDraw *sclDraw = dynamic_cast<ScaleDraw *>(m_graph->plotWidget()->axisScaleDraw(m_mappedaxis));
      QDateTime origin = sclDraw->dateTimeOrigin();
      start = (double)origin.secsTo(m_dteStartDateTime->dateTime());
      end = (double)origin.secsTo(m_dteEndDateTime->dateTime());
    } 
    else if (type == ScaleDraw::Time)
    {
      ScaleDraw *sclDraw = dynamic_cast<ScaleDraw *>(m_graph->plotWidget()->axisScaleDraw(m_mappedaxis));
      QTime origin = sclDraw->dateTimeOrigin().time();
      start = (double)origin.msecsTo(m_timStartTime->time());
      end = (double)origin.msecsTo(m_timEndTime->time());
    } 
    else
    {
      start = m_dspnStart->value();
      end = m_dspnEnd->value();
    }

    if (m_radStep->isChecked())
    {
      step = m_dspnStep->value();
      if (type == ScaleDraw::Time)
      {
        switch (m_cmbUnit->currentIndex())
        {
        case 0:
          break;
        case 1:
          step *= 1e3;
          break;
        case 2:
          step *= 6e4;
          break;
        case 3:
          step *= 36e5;
          break;
        }
      }
      else if (type == ScaleDraw::Date)
      {
        switch (m_cmbUnit->currentIndex())
        {
        case 0:
          step *= 86400;
          break;
        case 1:
          step *= 604800;
          break;
        }
      }
    }

    if (m_grpAxesBreaks->isChecked())
    {
      breakLeft = qMin(m_dspnBreakStart->value(), m_dspnBreakEnd->value());
      breakRight = qMax(m_dspnBreakStart->value(), m_dspnBreakEnd->value());
    }
    m_graph->setScale(m_mappedaxis, start, end, step, m_spnMajorValue->value(), m_cmbMinorValue->currentText().toInt(),
      m_cmbScaleType->currentIndex(), m_chkInvert->isChecked(), breakLeft, breakRight, m_spnBreakPosition->value(),
      m_dspnStepBeforeBreak->value(),m_dspnStepAfterBreak->value(), m_cmbMinorTicksBeforeBreak->currentText().toInt(),
      m_cmbMinorTicksAfterBreak->currentText().toInt(), m_chkLog10AfterBreak->isChecked(), m_spnBreakWidth->value(),
      m_chkBreakDecoration->isChecked(), m_dspnN->value());
    m_graph->changeIntensity(true);
    m_graph->notifyChanges();
    m_modified = false;
  }
}
void PlotConcavityPointSerieCurve::update( const ConcavityPointSerieCurve &curve, const Interval<qreal> &angularInterval )
{
	QVector<QPointF> datasMinConcavity(0);
	QVector<QPointF> datasMaxConcavity(0);
	QVector<QPointF> datasMinKnotArea(0);
	QVector<QPointF> datasMaxKnotArea(0);

	const int nbMaxConcavityPoints = curve.nbMaxConcavityPoints();
	const int nbMinConcavityPoints = curve.nbMinConcavityPoints();

	if ( nbMaxConcavityPoints || nbMinConcavityPoints )
	{
		const qreal minAngle = angularInterval.min();
		const qreal maxAngle = angularInterval.isValid() ? angularInterval.max() : angularInterval.max()+TWO_PI;

		int firstX, lastX;
		firstX = lastX = 0;
		if ( nbMaxConcavityPoints>0 && nbMinConcavityPoints>0 )
		{
			firstX = qMin(curve.maxConcavityPointsSerie().first().x,curve.minConcavityPointsSerie().first().x);
			lastX = qMax(curve.maxConcavityPointsSerie().last().x,curve.minConcavityPointsSerie().last().x);
		}
		else if ( nbMaxConcavityPoints>0 )
		{
			firstX = curve.maxConcavityPointsSerie().first().x;
			lastX = curve.maxConcavityPointsSerie().last().x;
		}
		else if ( nbMinConcavityPoints>0 )
		{
			firstX = curve.minConcavityPointsSerie().first().x;
			lastX = curve.minConcavityPointsSerie().last().x;
		}

		if ( curve.nbMinConcavityPoints() > 0 )
		{
			datasMinConcavity.reserve(curve.nbMinConcavityPoints());
			QVector<rCoord2D>::ConstIterator begin = curve.minConcavityPointsSerie().begin();
			const QVector<rCoord2D>::ConstIterator end = curve.minConcavityPointsSerie().end();
			while ( begin != end )
			{
				datasMinConcavity.append(QPointF(begin->x,begin->y));
				++begin;
			}
			datasMinKnotArea.resize(2);
			datasMinKnotArea[0] = QPointF( firstX, minAngle*RAD_TO_DEG_FACT );
			datasMinKnotArea[1] = QPointF( lastX, minAngle*RAD_TO_DEG_FACT );
		}
		if ( curve.nbMaxConcavityPoints() > 0 )
		{
			datasMaxConcavity.reserve(curve.nbMaxConcavityPoints());
			QVector<rCoord2D>::ConstIterator begin = curve.maxConcavityPointsSerie().begin();
			const QVector<rCoord2D>::ConstIterator end = curve.maxConcavityPointsSerie().end();
			while ( begin != end )
			{
				datasMaxConcavity.append(QPointF(begin->x,begin->y));
				++begin;
			}
			datasMaxKnotArea.resize(2);
			datasMaxKnotArea[0] = QPointF( firstX, maxAngle*RAD_TO_DEG_FACT );
			datasMaxKnotArea[1] = QPointF( lastX, maxAngle*RAD_TO_DEG_FACT );
		}
	}

	_minConcavityPointsData.setSamples(datasMinConcavity);
	_maxConcavityPointsData.setSamples(datasMaxConcavity);
	_minKnotAreaAngle.setSamples(datasMinKnotArea);
	_maxKnotAreaAngle.setSamples(datasMaxKnotArea);
}
void QgsGrassVectorMapLayer::load()
{
  QgsDebugMsg( "entered" );
  clear();

  if ( !mMap )
  {
    return;
  }

  // Attributes are not loaded for topo layers in which case field == 0
  if ( mField == 0 )
  {
    return;
  }

  QgsDebugMsg( QString( "cidxFieldIndex() = %1 cidxFieldNumCats() = %2" ).arg( cidxFieldIndex() ).arg( cidxFieldNumCats() ) );

  mFieldInfo = Vect_get_field( mMap->map(), mField ); // should work also with field = 0

  if ( !mFieldInfo )
  {
    QgsDebugMsg( "No field info -> no attribute table" );
  }
  else
  {
    QgsDebugMsg( "Field info found -> open database" );

    QFileInfo di( mMap->grassObject().mapsetPath() + "/vector/" + mMap->grassObject().name() + "/dbln" );
    mLastLoaded = di.lastModified();

    QString error;
    dbDriver *databaseDriver = openDriver( error );

    if ( !databaseDriver || !error.isEmpty() )
    {
      QgsDebugMsg( error );
    }
    else
    {
      QgsDebugMsg( "Database opened -> open select cursor" );
      QgsGrass::lock(); // not sure if lock is necessary
      dbString dbstr;
      db_init_string( &dbstr );
      db_set_string( &dbstr, ( char * )"select * from " );
      db_append_string( &dbstr, mFieldInfo->table );

      QgsDebugMsg( QString( "SQL: %1" ).arg( db_get_string( &dbstr ) ) );
      dbCursor databaseCursor;
      if ( db_open_select_cursor( databaseDriver, &dbstr, &databaseCursor, DB_SCROLL ) != DB_OK )
      {
        db_close_database_shutdown_driver( databaseDriver );
        QgsGrass::warning( "Cannot select attributes from table '" + QString( mFieldInfo->table ) + "'" );
      }
      else
      {
#ifdef QGISDEBUG
        int nRecords = db_get_num_rows( &databaseCursor );
        QgsDebugMsg( QString( "Number of records: %1" ).arg( nRecords ) );
#endif

        dbTable  *databaseTable = db_get_cursor_table( &databaseCursor );
        int nColumns = db_get_table_number_of_columns( databaseTable );

        // Read columns' description
        for ( int i = 0; i < nColumns; i++ )
        {
          QPair<double, double> minMax( DBL_MAX, -DBL_MAX );

          dbColumn *column = db_get_table_column( databaseTable, i );

          int ctype = db_sqltype_to_Ctype( db_get_column_sqltype( column ) );
          QVariant::Type qtype = QVariant::String; //default to string
          QgsDebugMsg( QString( "column = %1 ctype = %2" ).arg( db_get_column_name( column ) ).arg( ctype ) );

          QString ctypeStr;
          switch ( ctype )
          {
            case DB_C_TYPE_INT:
              ctypeStr = "integer";
              qtype = QVariant::Int;
              break;
            case DB_C_TYPE_DOUBLE:
              ctypeStr = "double";
              qtype = QVariant::Double;
              break;
            case DB_C_TYPE_STRING:
              ctypeStr = "string";
              qtype = QVariant::String;
              break;
            case DB_C_TYPE_DATETIME:
              ctypeStr = "datetime";
              qtype = QVariant::String;
              break;
          }
          mTableFields.append( QgsField( db_get_column_name( column ), qtype, ctypeStr,
                                         db_get_column_length( column ), db_get_column_precision( column ) ) );
          mMinMax << minMax;
          if ( G_strcasecmp( db_get_column_name( column ), mFieldInfo->key ) == 0 )
          {
            mKeyColumn = i;
          }
        }

        if ( mKeyColumn < 0 )
        {
          mTableFields.clear();
          QgsGrass::warning( QObject::tr( "Key column '%1' not found in the table '%2'" ).arg( mFieldInfo->key, mFieldInfo->table ) );
        }
        else
        {
          mHasTable = true;
          // Read attributes to the memory
          while ( true )
          {
            int more;

            if ( db_fetch( &databaseCursor, DB_NEXT, &more ) != DB_OK )
            {
              QgsDebugMsg( "Cannot fetch DB record" );
              break;
            }
            if ( !more )
            {
              break; // no more records
            }

            // Check cat value
            dbColumn *column = db_get_table_column( databaseTable, mKeyColumn );
            dbValue *value = db_get_column_value( column );

            if ( db_test_value_isnull( value ) )
            {
              continue;
            }
            int cat = db_get_value_int( value );
            if ( cat < 0 )
            {
              continue;
            }

            QList<QVariant> values;
            for ( int i = 0; i < nColumns; i++ )
            {
              column = db_get_table_column( databaseTable, i );
              int sqltype = db_get_column_sqltype( column );
              int ctype = db_sqltype_to_Ctype( sqltype );
              value = db_get_column_value( column );
              db_convert_value_to_string( value, sqltype, &dbstr );

              QgsDebugMsgLevel( QString( "column = %1 value = %2" ).arg( db_get_column_name( column ), db_get_string( &dbstr ) ), 3 );

              QVariant variant;
              if ( !db_test_value_isnull( value ) )
              {
                int iv;
                double dv;
                //layer.mAttributes[layer.nAttributes].values[i] = strdup( db_get_string( &dbstr ) );
                switch ( ctype )
                {
                  case DB_C_TYPE_INT:
                    iv = db_get_value_int( value );
                    variant = QVariant( iv );
                    mMinMax[i].first = qMin( mMinMax[i].first, ( double )iv );
                    mMinMax[i].second = qMin( mMinMax[i].second, ( double )iv );
                    break;
                  case DB_C_TYPE_DOUBLE:
                    dv = db_get_value_double( value );
                    variant = QVariant( dv );
                    mMinMax[i].first = qMin( mMinMax[i].first, dv );
                    mMinMax[i].second = qMin( mMinMax[i].second, dv );
                    break;
                  case DB_C_TYPE_STRING:
                    // Store as byte array so that codec may be used later
                    variant = QVariant( QByteArray( db_get_value_string( value ) ) );
                    break;
                  case DB_C_TYPE_DATETIME:
                    variant = QVariant( QByteArray( db_get_string( &dbstr ) ) );
                    break;
                  default:
                    variant = QVariant( QByteArray( db_get_string( &dbstr ) ) );
                }
              }
              QgsDebugMsgLevel( QString( "column = %1 variant = %2" ).arg( db_get_column_name( column ), variant.toString() ), 3 );
              values << variant;
            }
            mAttributes.insert( cat, values );
          }
        }
        mValid = true;
        db_close_cursor( &databaseCursor );
        db_close_database_shutdown_driver( databaseDriver );
        db_free_string( &dbstr );

        QgsDebugMsg( QString( "mTableFields.size = %1" ).arg( mTableFields.size() ) );
        QgsDebugMsg( QString( "number of attributes = %1" ).arg( mAttributes.size() ) );
      }
      QgsGrass::unlock();
    }
  }

  // Add cat if no attribute fields exist (otherwise qgis crashes)
  if ( mTableFields.size() == 0 )
  {
    mKeyColumn = 0;
    mTableFields.append( QgsField( "cat", QVariant::Int, "integer" ) );
    QPair<double, double> minMax( 0, 0 );

    if ( cidxFieldIndex() >= 0 )
    {
      int ncats, cat, type, id;

      ncats = Vect_cidx_get_num_cats_by_index( mMap->map(), cidxFieldIndex() );

      if ( ncats > 0 )
      {
        Vect_cidx_get_cat_by_index( mMap->map(), cidxFieldIndex(), 0, &cat, &type, &id );
        minMax.first = cat;

        Vect_cidx_get_cat_by_index( mMap->map(), cidxFieldIndex(), ncats - 1, &cat, &type, &id );
        minMax.second = cat;
      }
    }
    mMinMax << minMax;
  }
  mFields = mTableFields;
  mAttributeFields = mTableFields;

  QgsDebugMsg( QString( "layer loaded mTableFields.size() = %1 mAttributes.size() = %2" ).arg( mTableFields.size() ).arg( mAttributes.size() ) );
  mValid = true;
}
Beispiel #10
0
void TrayIcon::slotSetUnread(int unread)
{
    m_unread = unread;

    this->setToolTip( m_defaultIcon.name(), i18n("Akregator"), i18np( "1 unread article", "%1 unread articles", unread ) );

    if (unread <= 0 || !Settings::enableTrayIconUnreadArticleCount())
    {
        setIconByName( m_defaultIcon.name() );
    }
    else
    {
        // adapted from KMSystemTray::updateCount()
        int oldWidth = KIconLoader::SizeSmallMedium;

        QString countStr = QString::number( unread );
        QFont f = KGlobalSettings::generalFont();
        f.setBold(true);

        float pointSize = f.pointSizeF();
        QFontMetrics fm(f);
        int w = fm.width(countStr);
        if( w > (oldWidth - 2) )
        {
            pointSize *= float(oldWidth - 2) / float(w);
            f.setPointSizeF(pointSize);
        }

        // overlay
        QPixmap overlayImg( oldWidth, oldWidth );
        overlayImg.fill( Qt::transparent );

        QPainter p(&overlayImg);
        p.setFont(f);
        KColorScheme scheme(QPalette::Active, KColorScheme::View);

        fm = QFontMetrics(f);
        QRect boundingRect = fm.tightBoundingRect(countStr);
        boundingRect.adjust(0, 0, 0, 2);
        boundingRect.setHeight(qMin(boundingRect.height(), oldWidth));
        boundingRect.moveTo((oldWidth - boundingRect.width()) / 2,
                            ((oldWidth - boundingRect.height()) / 2) - 1);
        p.setOpacity(0.7);
        p.setBrush(scheme.background(KColorScheme::LinkBackground));
        p.setPen(scheme.background(KColorScheme::LinkBackground).color());
        p.drawRoundedRect(boundingRect, 2.0, 2.0);

        p.setBrush(Qt::NoBrush);
        p.setPen(scheme.foreground(KColorScheme::LinkText).color());
        p.setOpacity(1.0);
        p.drawText(overlayImg.rect(), Qt::AlignCenter, countStr);
        p.end();

        QPixmap iconPixmap = m_defaultIcon.pixmap( oldWidth, oldWidth );

        QPainter pp( &iconPixmap );
        pp.drawPixmap( 0, 0, overlayImg );
        pp.end();

        setIconByPixmap( iconPixmap );
    }
}
Beispiel #11
0
void StyleHelper::drawArrow(QStyle::PrimitiveElement element, QPainter *painter, const QStyleOption *option)
{
    // From windowsstyle but modified to enable AA
    if (option->rect.width() <= 1 || option->rect.height() <= 1)
        return;

    QRect r = option->rect;
    int size = qMin(r.height(), r.width());
    QPixmap pixmap;
    QString pixmapName;
    pixmapName.sprintf("arrow-%s-%d-%d-%d-%lld",
                       "$qt_ia",
                       uint(option->state), element,
                       size, option->palette.cacheKey());
    if (!QPixmapCache::find(pixmapName, pixmap)) {
        int border = size/5;
        int sqsize = 2*(size/2);
        QImage image(sqsize, sqsize, QImage::Format_ARGB32);
        image.fill(Qt::transparent);
        QPainter imagePainter(&image);
        imagePainter.setRenderHint(QPainter::Antialiasing, true);
        imagePainter.translate(0.5, 0.5);
        QPolygon a;
        switch (element) {
            case QStyle::PE_IndicatorArrowUp:
                a.setPoints(3, border, sqsize/2,  sqsize/2, border,  sqsize - border, sqsize/2);
                break;
            case QStyle::PE_IndicatorArrowDown:
                a.setPoints(3, border, sqsize/2,  sqsize/2, sqsize - border,  sqsize - border, sqsize/2);
                break;
            case QStyle::PE_IndicatorArrowRight:
                a.setPoints(3, sqsize - border, sqsize/2,  sqsize/2, border,  sqsize/2, sqsize - border);
                break;
            case QStyle::PE_IndicatorArrowLeft:
                a.setPoints(3, border, sqsize/2,  sqsize/2, border,  sqsize/2, sqsize - border);
                break;
            default:
                break;
        }

        int bsx = 0;
        int bsy = 0;

        if (option->state & QStyle::State_Sunken) {
            bsx = qApp->style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal);
            bsy = qApp->style()->pixelMetric(QStyle::PM_ButtonShiftVertical);
        }

        QRect bounds = a.boundingRect();
        int sx = sqsize / 2 - bounds.center().x() - 1;
        int sy = sqsize / 2 - bounds.center().y() - 1;
        imagePainter.translate(sx + bsx, sy + bsy);

        if (!(option->state & QStyle::State_Enabled)) {
            QColor foreGround(150, 150, 150, 150);
            imagePainter.setBrush(option->palette.mid().color());
            imagePainter.setPen(option->palette.mid().color());
        } else {
            QColor shadow(0, 0, 0, 100);
            imagePainter.translate(0, 1);
            imagePainter.setPen(shadow);
            imagePainter.setBrush(shadow);
            QColor foreGround(255, 255, 255, 210);
            imagePainter.drawPolygon(a);
            imagePainter.translate(0, -1);
            imagePainter.setPen(foreGround);
            imagePainter.setBrush(foreGround);
        }
        imagePainter.drawPolygon(a);
        imagePainter.end();
        pixmap = QPixmap::fromImage(image);
        QPixmapCache::insert(pixmapName, pixmap);
    }
    int xOffset = r.x() + (r.width() - size)/2;
    int yOffset = r.y() + (r.height() - size)/2;
    painter->drawPixmap(xOffset, yOffset, pixmap);
}
Beispiel #12
0
void GridWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);

    qreal wantedHeight = CELL_HEIGHT * (ROW_COUNT + 1);
    qreal wantedWidth = FIRST_COL_WIDTH + CELL_WIDTH * COL_COUNT;

    qreal scaleWidth = width()/wantedWidth;
    qreal scaleHeight = height()/ wantedHeight;
    qreal minScale = qMin(scaleWidth, scaleHeight);

    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.translate((width()-minScale*wantedWidth) /2,0);
    painter.scale(minScale,minScale);

    painter.fillRect(QRectF(0,0, wantedWidth, wantedHeight), QBrush(QColor("#FFF")));

    painter.setPen(textColor);
    painter.setFont(QFont("Segoe UI", 8));
    for(int row=1; row<ROW_COUNT+1; row++)
    {
        QRect textRect(0, row*CELL_HEIGHT, FIRST_COL_WIDTH, CELL_HEIGHT);
        QString rowLabel = QString("%1 - %2")
                .arg(1+(row-1)*32)
                .arg((row)*32);
        painter.drawText(textRect, rowLabel, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
    }
    for(int col=0; col<COL_COUNT; col++)
    {
        QRect textRect(FIRST_COL_WIDTH + col*CELL_WIDTH, 0, CELL_WIDTH, CELL_HEIGHT);
        QString rowLabel = QString("%1")
                .arg(col+1);
        painter.drawText(textRect, rowLabel, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
    }
    for(int row=0; row<ROW_COUNT; row++)
        for(int col=0; col<COL_COUNT; col++)
        {
            int address = row*COL_COUNT + col;
            QRect textRect(FIRST_COL_WIDTH + col*CELL_WIDTH, (row+1)*CELL_HEIGHT, CELL_WIDTH, CELL_HEIGHT);
            QString value = m_values[address];

            if(!value.isEmpty())
            {
                QColor fillColor = m_colors[address];

                QString rowLabel = value;
                painter.fillRect(textRect, fillColor);
                painter.drawText(textRect, rowLabel, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
            }

        }

    painter.setPen(gridLineColor);

    for(int row=0; row<ROW_COUNT + 1; row++)
    {
        QPoint start(0, row*CELL_HEIGHT);
        QPoint end(wantedWidth, row*CELL_HEIGHT);
        painter.drawLine(start, end);
    }
    for(int col=0; col<COL_COUNT + 1; col++)
    {
        QPoint start(FIRST_COL_WIDTH + col*CELL_WIDTH, 0);
        QPoint end(FIRST_COL_WIDTH + col*CELL_WIDTH, wantedHeight);
        painter.drawLine(start, end);
    }

    // Draw the highlight for the selected one
    if(m_selectedAddress>-1)
    {
        int col = m_selectedAddress % 32;
        int row = m_selectedAddress / 32;
        QRect textRect(FIRST_COL_WIDTH + col*CELL_WIDTH, (row+1)*CELL_HEIGHT, CELL_WIDTH, CELL_HEIGHT);
        painter.setPen(QColor(Qt::black));
        painter.drawRect(textRect);
    }
}
Beispiel #13
0
void AuroraeTheme::borders(int& left, int& top, int& right, int& bottom, bool maximized) const
{
    const qreal titleHeight = qMax((qreal)d->themeConfig.titleHeight(),
                                   d->themeConfig.buttonHeight()*buttonSizeFactor() +
                                   d->themeConfig.buttonMarginTop());
    if (maximized) {
        const qreal title = titleHeight + d->themeConfig.titleEdgeTopMaximized() + d->themeConfig.titleEdgeBottomMaximized();
        switch ((DecorationPosition)d->themeConfig.decorationPosition()) {
        case DecorationTop:
            left = right = bottom = 0;
            top = title;
            break;
        case DecorationBottom:
            left = right = top = 0;
            bottom = title;
            break;
        case DecorationLeft:
            top = right = bottom = 0;
            left = title;
            break;
        case DecorationRight:
            left = top = bottom = 0;
            right = title;
            break;
        default:
            left = right = bottom = top = 0;
            break;
        }
    } else {
        switch (d->borderSize) {
        case KDecoration2::BorderSize::Tiny:
            // TODO: this looks wrong
            if (isCompositingActive()) {
                left = qMin(0, (int)left - d->themeConfig.borderLeft() - d->themeConfig.paddingLeft());
                right = qMin(0, (int)right - d->themeConfig.borderRight() - d->themeConfig.paddingRight());
                bottom = qMin(0, (int)bottom - d->themeConfig.borderBottom() - d->themeConfig.paddingBottom());
            } else {
                left = qMin(0, (int)left - d->themeConfig.borderLeft());
                right = qMin(0, (int)right - d->themeConfig.borderRight());
                bottom = qMin(0, (int)bottom - d->themeConfig.borderBottom());
            }
            break;
        case KDecoration2::BorderSize::Large:
            left = right = bottom = top = 4;
            break;
        case KDecoration2::BorderSize::VeryLarge:
            left = right = bottom = top = 8;
            break;
        case KDecoration2::BorderSize::Huge:
            left = right = bottom = top = 12;
            break;
        case KDecoration2::BorderSize::VeryHuge:
            left = right = bottom = top = 23;
            break;
        case KDecoration2::BorderSize::Oversized:
            left = right = bottom = top = 36;
            break;
        case KDecoration2::BorderSize::Normal:
        default:
            left = right = bottom = top = 0;
        }
        const qreal title = titleHeight + d->themeConfig.titleEdgeTop() + d->themeConfig.titleEdgeBottom();
        switch ((DecorationPosition)d->themeConfig.decorationPosition()) {
        case DecorationTop:
            left   += d->themeConfig.borderLeft();
            right  += d->themeConfig.borderRight();
            bottom += d->themeConfig.borderBottom();
            top     = title;
            break;
        case DecorationBottom:
            left   += d->themeConfig.borderLeft();
            right  += d->themeConfig.borderRight();
            bottom  = title;
            top    += d->themeConfig.borderTop();
            break;
        case DecorationLeft:
            left    = title;
            right  += d->themeConfig.borderRight();
            bottom += d->themeConfig.borderBottom();
            top    += d->themeConfig.borderTop();
            break;
        case DecorationRight:
            left   += d->themeConfig.borderLeft();
            right   = title;
            bottom += d->themeConfig.borderBottom();
            top    += d->themeConfig.borderTop();
            break;
        default:
            left = right = bottom = top = 0;
            break;
        }
    }
}
void QSGPinchArea::updatePinch()
{
    Q_D(QSGPinchArea);
    if (d->touchPoints.count() == 0) {
        if (d->inPinch) {
            d->inPinch = false;
            QPointF pinchCenter = mapFromScene(d->sceneLastCenter);
            QSGPinchEvent pe(pinchCenter, d->pinchLastScale, d->pinchLastAngle, d->pinchRotation);
            pe.setStartCenter(d->pinchStartCenter);
            pe.setPreviousCenter(pinchCenter);
            pe.setPreviousAngle(d->pinchLastAngle);
            pe.setPreviousScale(d->pinchLastScale);
            pe.setStartPoint1(mapFromScene(d->sceneStartPoint1));
            pe.setStartPoint2(mapFromScene(d->sceneStartPoint2));
            pe.setPoint1(mapFromScene(d->lastPoint1));
            pe.setPoint2(mapFromScene(d->lastPoint2));
            emit pinchFinished(&pe);
            d->pinchStartDist = 0;
            d->pinchActivated = false;
            if (d->pinch && d->pinch->target())
                d->pinch->setActive(false);
        }
        d->initPinch = false;
        d->pinchRejected = false;
        d->stealMouse = false;
        setKeepMouseGrab(false);
        QSGCanvas *c = canvas();
        if (c && c->mouseGrabberItem() == this)
            ungrabMouse();
        return;
    }
    QTouchEvent::TouchPoint touchPoint1 = d->touchPoints.at(0);
    QTouchEvent::TouchPoint touchPoint2 = d->touchPoints.at(d->touchPoints. count() >= 2 ? 1 : 0);
    if (d->touchPoints.count() == 2
        && (touchPoint1.state() & Qt::TouchPointPressed || touchPoint2.state() & Qt::TouchPointPressed)) {
        d->id1 = touchPoint1.id();
        d->sceneStartPoint1 = touchPoint1.scenePos();
        d->sceneStartPoint2 = touchPoint2.scenePos();
        d->pinchActivated = true;
        d->initPinch = true;
    }
    if (d->pinchActivated && !d->pinchRejected){
        const int dragThreshold = QApplication::startDragDistance();
        QPointF p1 = touchPoint1.scenePos();
        QPointF p2 = touchPoint2.scenePos();
        qreal dx = p1.x() - p2.x();
        qreal dy = p1.y() - p2.y();
        qreal dist = sqrt(dx*dx + dy*dy);
        QPointF sceneCenter = (p1 + p2)/2;
        qreal angle = QLineF(p1, p2).angle();
        if (d->touchPoints.count() == 1) {
            // If we only have one point then just move the center
            if (d->id1 == touchPoint1.id())
                sceneCenter = d->sceneLastCenter + touchPoint1.scenePos() - d->lastPoint1;
            else
                sceneCenter = d->sceneLastCenter + touchPoint2.scenePos() - d->lastPoint2;
            angle = d->pinchLastAngle;
        }
        d->id1 = touchPoint1.id();
        if (angle > 180)
            angle -= 360;
        if (!d->inPinch || d->initPinch) {
            if (d->touchPoints.count() >= 2
                    && (qAbs(p1.x()-d->sceneStartPoint1.x()) > dragThreshold
                    || qAbs(p1.y()-d->sceneStartPoint1.y()) > dragThreshold
                    || qAbs(p2.x()-d->sceneStartPoint2.x()) > dragThreshold
                    || qAbs(p2.y()-d->sceneStartPoint2.y()) > dragThreshold)) {
                d->initPinch = false;
                d->sceneStartCenter = sceneCenter;
                d->sceneLastCenter = sceneCenter;
                d->pinchStartCenter = mapFromScene(sceneCenter);
                d->pinchStartDist = dist;
                d->pinchStartAngle = angle;
                d->pinchLastScale = 1.0;
                d->pinchLastAngle = angle;
                d->pinchRotation = 0.0;
                d->lastPoint1 = p1;
                d->lastPoint2 = p2;
                QSGPinchEvent pe(d->pinchStartCenter, 1.0, angle, 0.0);
                pe.setStartCenter(d->pinchStartCenter);
                pe.setPreviousCenter(d->pinchStartCenter);
                pe.setPreviousAngle(d->pinchLastAngle);
                pe.setPreviousScale(d->pinchLastScale);
                pe.setStartPoint1(mapFromScene(d->sceneStartPoint1));
                pe.setStartPoint2(mapFromScene(d->sceneStartPoint2));
                pe.setPoint1(mapFromScene(d->lastPoint1));
                pe.setPoint2(mapFromScene(d->lastPoint2));
                pe.setPointCount(d->touchPoints.count());
                emit pinchStarted(&pe);
                if (pe.accepted()) {
                    d->inPinch = true;
                    d->stealMouse = true;
                    QSGCanvas *c = canvas();
                    if (c && c->mouseGrabberItem() != this)
                        grabMouse();
                    setKeepMouseGrab(true);
                    if (d->pinch && d->pinch->target()) {
                        d->pinchStartPos = pinch()->target()->pos();
                        d->pinchStartScale = d->pinch->target()->scale();
                        d->pinchStartRotation = d->pinch->target()->rotation();
                        d->pinch->setActive(true);
                    }
                } else {
                    d->pinchRejected = true;
                }
            }
        } else if (d->pinchStartDist > 0) {
            qreal scale = dist ? dist / d->pinchStartDist : d->pinchLastScale;
            qreal da = d->pinchLastAngle - angle;
            if (da > 180)
                da -= 360;
            else if (da < -180)
                da += 360;
            d->pinchRotation += da;
            QPointF pinchCenter = mapFromScene(sceneCenter);
            QSGPinchEvent pe(pinchCenter, scale, angle, d->pinchRotation);
            pe.setStartCenter(d->pinchStartCenter);
            pe.setPreviousCenter(mapFromScene(d->sceneLastCenter));
            pe.setPreviousAngle(d->pinchLastAngle);
            pe.setPreviousScale(d->pinchLastScale);
            pe.setStartPoint1(mapFromScene(d->sceneStartPoint1));
            pe.setStartPoint2(mapFromScene(d->sceneStartPoint2));
            pe.setPoint1(touchPoint1.pos());
            pe.setPoint2(touchPoint2.pos());
            pe.setPointCount(d->touchPoints.count());
            d->pinchLastScale = scale;
            d->sceneLastCenter = sceneCenter;
            d->pinchLastAngle = angle;
            d->lastPoint1 = touchPoint1.scenePos();
            d->lastPoint2 = touchPoint2.scenePos();
            emit pinchUpdated(&pe);
            if (d->pinch && d->pinch->target()) {
                qreal s = d->pinchStartScale * scale;
                s = qMin(qMax(pinch()->minimumScale(),s), pinch()->maximumScale());
                pinch()->target()->setScale(s);
                QPointF pos = sceneCenter - d->sceneStartCenter + d->pinchStartPos;
                if (pinch()->axis() & QSGPinch::XAxis) {
                    qreal x = pos.x();
                    if (x < pinch()->xmin())
                        x = pinch()->xmin();
                    else if (x > pinch()->xmax())
                        x = pinch()->xmax();
                    pinch()->target()->setX(x);
                }
                if (pinch()->axis() & QSGPinch::YAxis) {
                    qreal y = pos.y();
                    if (y < pinch()->ymin())
                        y = pinch()->ymin();
                    else if (y > pinch()->ymax())
                        y = pinch()->ymax();
                    pinch()->target()->setY(y);
                }
                if (d->pinchStartRotation >= pinch()->minimumRotation()
                        && d->pinchStartRotation <= pinch()->maximumRotation()) {
                    qreal r = d->pinchRotation + d->pinchStartRotation;
                    r = qMin(qMax(pinch()->minimumRotation(),r), pinch()->maximumRotation());
                    pinch()->target()->setRotation(r);
                }
            }
        }
    }
}
void QModernProgressWidget::paintEvent(QPaintEvent *event) {
    QWidget::paintEvent(event);
    QPixmap m_pix(width(), height());

    //if (m_doRepaint) {
        m_doRepaint=false;
        QPen pen;
        pen.setWidthF(1.0);

        double wid=qMin(height(), width());
        double displayFrac=(double)(m_value-m_rangeMin)/(double)(m_rangeMax-m_rangeMin);
        int currentItem=qMax(0, qMin(m_items, (int)round(displayFrac*(double)m_items)));
        int lastItem=round(m_nonBackgroundRange*(double)m_items);
        if (m_spin) currentItem=m_spinItem;
        if (!m_spin) lastItem=currentItem;
        //if (!m_spin) std::cout<<"m_value="<<m_value<<"   currentItem="<<currentItem<<std::endl;
        QPointF center=QPointF(width()/2.0, height()/2.0);

        double rIn=wid/2.0*m_innerRadius;
        double rOut=wid/2.0*m_outerRadius;
        if (rIn>rOut) qSwap(rIn, rOut);

        //                           2*M_PI
        double strokeWidth=qMax(1.0, 6.283 * rIn/(1.75*(double)m_items));
        double dAngle=360.0/(double)m_items;

        //m_pix.fill(this, 0, 0);
        m_pix.fill(Qt::transparent);

        QPainter painter(&m_pix);

        if (m_mode==QModernProgressWidget::Strokes) {
            QPen strokePen=pen;
            strokePen.setWidthF(strokeWidth);
            strokePen.setCapStyle(Qt::RoundCap);
            strokePen.setJoinStyle(Qt::RoundJoin);
            painter.save();
                painter.setRenderHint(QPainter::Antialiasing, true);
                painter.translate(center);
                if (m_spin) painter.rotate(-dAngle*(double)currentItem);
                else painter.rotate(-180);
                for (int i=0; i<m_items; i++) {
                    strokePen.setColor(m_backgroundColor);
                    //double frac=(double)i/(double)(m_items-1.0);

                    if (i<lastItem) {
                        const double r=m_startColor.redF();
                        const double g=m_startColor.greenF();
                        const double b=m_startColor.blueF();
                        const double re=m_stopColor.redF();
                        const double ge=m_stopColor.greenF();
                        const double be=m_stopColor.blueF();
                        double f=(double)i/(m_nonBackgroundRange*(double)m_items);
                        if (f>1) f=1.0;
                        if (f<0) f=0;
                        f=1.0-f;
                        QColor col;
                        col.setRgbF(r+f*(re-r), g+f*(ge-g), b+f*(be-b));
                        strokePen.setColor(col);
                    }
                    //if (fabs(frac-displayFrac)<=1.0/(double)m_items) strokePen.setColor(m_indicatorColor);
                    if (i==0) strokePen.setColor(m_indicatorColor);
                    painter.setPen(strokePen);
                    painter.drawLine(QLineF(0, rIn, 0, rOut));
                    painter.rotate(dAngle);
                }
            painter.restore();
        } else if (m_mode==QModernProgressWidget::Circles) {
            painter.save();
                painter.setRenderHint(QPainter::Antialiasing, true);
                painter.translate(center);
                if (m_spin) painter.rotate(-dAngle*(double)currentItem);
                else painter.rotate(-180);
                for (int i=0; i<m_items; i++) {
                    //double frac=(double)i/(double)(m_items-1.0);

                    QColor col=m_backgroundColor;

                    if (i<lastItem) {
                        const double r=m_startColor.redF();
                        const double g=m_startColor.greenF();
                        const double b=m_startColor.blueF();
                        const double re=m_stopColor.redF();
                        const double ge=m_stopColor.greenF();
                        const double be=m_stopColor.blueF();
                        double f=(double)i/(m_nonBackgroundRange*(double)m_items);
                        if (f>1) f=1.0;
                        if (f<0) f=0;
                        f=1.0-f;
                        col.setRgbF(r+f*(re-r), g+f*(ge-g), b+f*(be-b));
                    }
                    //if (fabs(frac-displayFrac)<=1.0/(double)m_items) strokePen.setColor(m_indicatorColor);
                    if (i==0) col=m_indicatorColor;
                    QBrush circleBrush(col);
                    QPen circlePen=QPen(col.darker(150));
                    painter.setBrush(circleBrush);
                    if (m_darkCircleBorder) {
                        painter.setPen(circlePen);
                    } else {
                        painter.setPen(QColor(Qt::transparent));
                    }
                    double d=(rOut-rIn)/2.0;
                    painter.drawEllipse(0, (rIn+rOut)/2.0, d, d);
                    painter.rotate(dAngle);
                }
            painter.restore();
        } else if (m_mode==QModernProgressWidget::GradientRing) {
            painter.save();
                QPainterPath path;
                path.setFillRule( Qt::OddEvenFill );
                path.addEllipse( QPointF(0,0), rOut, rOut );
                path.addEllipse( QPointF(0,0), rIn, rIn );

                painter.translate(center);
                if (m_spin) painter.rotate(-dAngle*(double)currentItem);
                else painter.rotate(-90);

                // Draw the ring background
                painter.setPen( Qt::NoPen );
                painter.setBrush( m_backgroundColor );
                painter.setRenderHint( QPainter::Antialiasing );
                painter.drawPath( path );

                // Draw the ring foreground
                QConicalGradient gradient( QPointF(0,0), 0.0 );
                if (m_spin) {
                    gradient.setColorAt( 0.0, m_backgroundColor );
                    gradient.setColorAt( qMax(0.0,(double)lastItem/(double)m_items-0.05), m_indicatorColor );
                    gradient.setColorAt( (double)lastItem/(double)m_items, m_backgroundColor );
                    painter.setBrush( gradient );
                } else {
                    double gfrac=qMax(0.0, qMin(1.0, 1.0-displayFrac));
                    //std::cout<<gfrac<<std::endl;
                    if ((fabs(gfrac)<=0.02)) {
                        painter.setBrush(QBrush(m_indicatorColor));
                    } else if (fabs(gfrac)>0.85) {
                        /*QColor cColor=m_indicatorColor;
                        cColor.setRedF(cColor.redF()+fabs(gfrac)/0.85*(m_backgroundColor.redF()-cColor.redF()));
                        cColor.setGreenF(cColor.greenF()+fabs(gfrac)/0.85*(m_backgroundColor.greenF()-cColor.greenF()));
                        cColor.setBlueF(cColor.blueF()+fabs(gfrac)/0.85*(m_backgroundColor.blueF()-cColor.blueF()));*/
                        QColor cColor=linColor(m_indicatorColor, m_backgroundColor, (gfrac-0.85)/0.15);
                        gradient.setColorAt( 0.05, m_backgroundColor );
                        gradient.setColorAt( 0.0, cColor );
                        gradient.setColorAt( 0.8, m_backgroundColor );
                        gradient.setColorAt( gfrac, cColor );
                        painter.setBrush( gradient );
                    } else if (fabs(gfrac)<0.15) {
                        /*QColor cColor=m_backgroundColor;
                        cColor.setRedF(m_indicatorColor.redF()-fabs(gfrac)/0.15*(m_indicatorColor.redF()-cColor.redF()));
                        cColor.setGreenF(m_indicatorColor.greenF()-fabs(gfrac)/0.15*(m_indicatorColor.greenF()-cColor.greenF()));
                        cColor.setBlueF(m_indicatorColor.blueF()-fabs(gfrac)/0.15*(m_indicatorColor.blueF()-cColor.blueF()));*/
                        QColor cColor=linColor(m_indicatorColor, m_backgroundColor, gfrac/0.15);
                        gradient.setColorAt( 0.0, m_indicatorColor );
                        gradient.setColorAt( gfrac/2.0, cColor );
                        gradient.setColorAt( gfrac, m_indicatorColor );
                        painter.setBrush( gradient );
                    } else {
                        gradient.setColorAt( 0.0, m_indicatorColor );
                        gradient.setColorAt( 0.05, m_backgroundColor );
                        gradient.setColorAt( qMax(0.0, gfrac-0.05), m_backgroundColor );
                        gradient.setColorAt( qMin(1.0, gfrac), m_indicatorColor );
                        painter.setBrush( gradient );
                    }
                }
                painter.drawPath( path );
            painter.restore();
        }

        if (m_displayPercent && ( (m_mode==QModernProgressWidget::Circles) || (m_mode==QModernProgressWidget::Strokes) || (m_mode==QModernProgressWidget::GradientRing) ) ) {
            painter.save();
            QFont f=font();
            QString s="";
            if (m_percentageMode==QModernProgressWidget::Percent) {
                s=QString::number(100.0*(double)(m_value-m_rangeMin)/(double)(m_rangeMax-m_rangeMin), 'f', m_precision)+"%";
            } else {
                s=QString::number(m_value, 'f', m_precision)+m_suffix;
            }
            QRect bound=QFontMetrics(f).boundingRect("100%");
            double r=sqrt( (bound.width()/2.0)*(bound.width()/2.0) + (bound.height()/2.0)*(bound.height()/2.0) );
            while ((f.pointSize()>5)&&(r>rIn)) {
                f.setPointSizeF(f.pointSizeF()-0.5);
                bound=QFontMetrics(f).boundingRect("100%");
                r=sqrt( (bound.width()/2.0)*(bound.width()/2.0) + (bound.height()/2.0)*(bound.height()/2.0) );
            }
            bound=QFontMetrics(f).boundingRect(s);
            painter.setFont(f);
            painter.setPen(m_textColor);
            painter.drawText(width()/2-bound.width()/2, height()/2+QFontMetrics(f).ascent()/2, s);
            painter.restore();
        }
    //}
    QPainter p(this);
    p.drawPixmap(QPoint(0,0), m_pix);
}
Beispiel #16
0
//! Draw the sky grid in the current frame
void SkyGrid::draw(const StelCore* core) const
{
	const StelProjectorP prj = core->getProjection(frameType, frameType!=StelCore::FrameAltAz ? StelCore::RefractionAuto : StelCore::RefractionOff);
	if (!fader.getInterstate())
		return;

	bool withDecimalDegree = StelApp::getInstance().getFlagShowDecimalDegrees();;

	// Look for all meridians and parallels intersecting with the disk bounding the viewport
	// Check whether the pole are in the viewport
	bool northPoleInViewport = false;
	bool southPoleInViewport = false;
	Vec3f win;
	if (prj->project(Vec3f(0,0,1), win) && prj->checkInViewport(win))
		northPoleInViewport = true;
	if (prj->project(Vec3f(0,0,-1), win) && prj->checkInViewport(win))
		southPoleInViewport = true;
	// Get the longitude and latitude resolution at the center of the viewport
	Vec3d centerV;
	prj->unProject(prj->getViewportPosX()+prj->getViewportWidth()/2., prj->getViewportPosY()+prj->getViewportHeight()/2.+1., centerV);
	double lon2, lat2;
	StelUtils::rectToSphe(&lon2, &lat2, centerV);

	const double gridStepParallelRad = M_PI/180.*getClosestResolutionDMS(prj->getPixelPerRadAtCenter());
	double gridStepMeridianRad;
	if (northPoleInViewport || southPoleInViewport)
		gridStepMeridianRad = (frameType==StelCore::FrameAltAz || frameType==StelCore::FrameGalactic) ? M_PI/180.* 10. : M_PI/180.* 15.;
	else
	{
		const double closestResLon = (frameType==StelCore::FrameAltAz || frameType==StelCore::FrameGalactic) ? getClosestResolutionDMS(prj->getPixelPerRadAtCenter()*std::cos(lat2)) : getClosestResolutionHMS(prj->getPixelPerRadAtCenter()*std::cos(lat2));
		gridStepMeridianRad = M_PI/180.* ((northPoleInViewport || southPoleInViewport) ? 15. : closestResLon);
	}

	// Get the bounding halfspace
	const SphericalCap& viewPortSphericalCap = prj->getBoundingCap();

	// Compute the first grid starting point. This point is close to the center of the screen
	// and lies at the intersection of a meridian and a parallel
	lon2 = gridStepMeridianRad*((int)(lon2/gridStepMeridianRad+0.5));
	lat2 = gridStepParallelRad*((int)(lat2/gridStepParallelRad+0.5));
	Vec3d firstPoint;
	StelUtils::spheToRect(lon2, lat2, firstPoint);
	firstPoint.normalize();

	// Q_ASSERT(viewPortSphericalCap.contains(firstPoint));

	// Initialize a painter and set OpenGL state
	StelPainter sPainter(prj);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Normal transparency mode
	// OpenGL ES 2.0 doesn't have GL_LINE_SMOOTH
	#ifdef GL_LINE_SMOOTH
	if (QOpenGLContext::currentContext()->format().renderableType()==QSurfaceFormat::OpenGL)
		glEnable(GL_LINE_SMOOTH);
	#endif

	// make text colors just a bit brighter. (But if >1, QColor::setRgb fails and makes text invisible.)
	Vec4f textColor(qMin(1.0f, 1.25f*color[0]), qMin(1.0f, 1.25f*color[1]), qMin(1.0f, 1.25f*color[2]), fader.getInterstate());
	sPainter.setColor(color[0],color[1],color[2], fader.getInterstate());

	sPainter.setFont(font);
	ViewportEdgeIntersectCallbackData userData(&sPainter);
	userData.textColor = textColor;
	userData.frameType = frameType;

	/////////////////////////////////////////////////
	// Draw all the meridians (great circles)
	SphericalCap meridianSphericalCap(Vec3d(1,0,0), 0);
	Mat4d rotLon = Mat4d::zrotation(gridStepMeridianRad);
	Vec3d fpt = firstPoint;
	Vec3d p1, p2;
	int maxNbIter = (int)(M_PI/gridStepMeridianRad);
	int i;
	for (i=0; i<maxNbIter; ++i)
	{
		StelUtils::rectToSphe(&lon2, &lat2, fpt);
		userData.raAngle = lon2;

		meridianSphericalCap.n = fpt^Vec3d(0,0,1);
		meridianSphericalCap.n.normalize();
		if (!SphericalCap::intersectionPoints(viewPortSphericalCap, meridianSphericalCap, p1, p2))
		{
			if (viewPortSphericalCap.d<meridianSphericalCap.d && viewPortSphericalCap.contains(meridianSphericalCap.n))
			{
				// The meridian is fully included in the viewport, draw it in 3 sub-arcs to avoid length > 180.
				const Mat4d& rotLon120 = Mat4d::rotation(meridianSphericalCap.n, 120.*M_PI/180.);
				Vec3d rotFpt=fpt;
				rotFpt.transfo4d(rotLon120);
				Vec3d rotFpt2=rotFpt;
				rotFpt2.transfo4d(rotLon120);
				sPainter.drawGreatCircleArc(fpt, rotFpt, NULL, viewportEdgeIntersectCallback, &userData);
				sPainter.drawGreatCircleArc(rotFpt, rotFpt2, NULL, viewportEdgeIntersectCallback, &userData);
				sPainter.drawGreatCircleArc(rotFpt2, fpt, NULL, viewportEdgeIntersectCallback, &userData);
				fpt.transfo4d(rotLon);
				continue;
			}
			else
				break;
		}

		Vec3d middlePoint = p1+p2;
		middlePoint.normalize();
		if (!viewPortSphericalCap.contains(middlePoint))
			middlePoint*=-1.;

		// Draw the arc in 2 sub-arcs to avoid lengths > 180 deg
		sPainter.drawGreatCircleArc(p1, middlePoint, NULL, viewportEdgeIntersectCallback, &userData);
		sPainter.drawGreatCircleArc(p2, middlePoint, NULL, viewportEdgeIntersectCallback, &userData);

		fpt.transfo4d(rotLon);
	}

	if (i!=maxNbIter)
	{
		rotLon = Mat4d::zrotation(-gridStepMeridianRad);
		fpt = firstPoint;
		fpt.transfo4d(rotLon);
		for (int j=0; j<maxNbIter-i; ++j)
		{
			StelUtils::rectToSphe(&lon2, &lat2, fpt);
			userData.raAngle = lon2;

			meridianSphericalCap.n = fpt^Vec3d(0,0,1);
			meridianSphericalCap.n.normalize();
			if (!SphericalCap::intersectionPoints(viewPortSphericalCap, meridianSphericalCap, p1, p2))
				break;

			Vec3d middlePoint = p1+p2;
			middlePoint.normalize();
			if (!viewPortSphericalCap.contains(middlePoint))
				middlePoint*=-1;

			sPainter.drawGreatCircleArc(p1, middlePoint, NULL, viewportEdgeIntersectCallback, &userData);
			sPainter.drawGreatCircleArc(p2, middlePoint, NULL, viewportEdgeIntersectCallback, &userData);

			fpt.transfo4d(rotLon);
		}
	}

	/////////////////////////////////////////////////
	// Draw all the parallels (small circles)
	SphericalCap parallelSphericalCap(Vec3d(0,0,1), 0);
	rotLon = Mat4d::rotation(firstPoint^Vec3d(0,0,1), gridStepParallelRad);
	fpt = firstPoint;
	maxNbIter = (int)(M_PI/gridStepParallelRad)-1;
	for (i=0; i<maxNbIter; ++i)
	{
		StelUtils::rectToSphe(&lon2, &lat2, fpt);
		if (withDecimalDegree)
			userData.text = StelUtils::radToDecDegStr(lat2);
		else
			userData.text = StelUtils::radToDmsStrAdapt(lat2);

		parallelSphericalCap.d = fpt[2];
		if (parallelSphericalCap.d>0.9999999)
			break;

		const Vec3d rotCenter(0,0,parallelSphericalCap.d);
		if (!SphericalCap::intersectionPoints(viewPortSphericalCap, parallelSphericalCap, p1, p2))
		{
			if ((viewPortSphericalCap.d<parallelSphericalCap.d && viewPortSphericalCap.contains(parallelSphericalCap.n))
				|| (viewPortSphericalCap.d<-parallelSphericalCap.d && viewPortSphericalCap.contains(-parallelSphericalCap.n)))
			{
				// The parallel is fully included in the viewport, draw it in 3 sub-arcs to avoid lengths >= 180 deg
				static const Mat4d rotLon120 = Mat4d::zrotation(120.*M_PI/180.);
				Vec3d rotFpt=fpt;
				rotFpt.transfo4d(rotLon120);
				Vec3d rotFpt2=rotFpt;
				rotFpt2.transfo4d(rotLon120);
				sPainter.drawSmallCircleArc(fpt, rotFpt, rotCenter, viewportEdgeIntersectCallback, &userData);
				sPainter.drawSmallCircleArc(rotFpt, rotFpt2, rotCenter, viewportEdgeIntersectCallback, &userData);
				sPainter.drawSmallCircleArc(rotFpt2, fpt, rotCenter, viewportEdgeIntersectCallback, &userData);
				fpt.transfo4d(rotLon);
				continue;
			}
			else
				break;
		}

		// Draw the arc in 2 sub-arcs to avoid lengths > 180 deg
		Vec3d middlePoint = p1-rotCenter+p2-rotCenter;
		middlePoint.normalize();
		middlePoint*=(p1-rotCenter).length();
		middlePoint+=rotCenter;
		if (!viewPortSphericalCap.contains(middlePoint))
		{
			middlePoint-=rotCenter;
			middlePoint*=-1.;
			middlePoint+=rotCenter;
		}

		sPainter.drawSmallCircleArc(p1, middlePoint, rotCenter, viewportEdgeIntersectCallback, &userData);
		sPainter.drawSmallCircleArc(p2, middlePoint, rotCenter, viewportEdgeIntersectCallback, &userData);

		fpt.transfo4d(rotLon);
	}

	if (i!=maxNbIter)
	{
		rotLon = Mat4d::rotation(firstPoint^Vec3d(0,0,1), -gridStepParallelRad);
		fpt = firstPoint;
		fpt.transfo4d(rotLon);
		for (int j=0; j<maxNbIter-i; ++j)
		{
			StelUtils::rectToSphe(&lon2, &lat2, fpt);
			if (withDecimalDegree)
				userData.text = StelUtils::radToDecDegStr(lat2);
			else
				userData.text = StelUtils::radToDmsStrAdapt(lat2);

			parallelSphericalCap.d = fpt[2];
			const Vec3d rotCenter(0,0,parallelSphericalCap.d);
			if (!SphericalCap::intersectionPoints(viewPortSphericalCap, parallelSphericalCap, p1, p2))
			{
				if ((viewPortSphericalCap.d<parallelSphericalCap.d && viewPortSphericalCap.contains(parallelSphericalCap.n))
					 || (viewPortSphericalCap.d<-parallelSphericalCap.d && viewPortSphericalCap.contains(-parallelSphericalCap.n)))
				{
					// The parallel is fully included in the viewport, draw it in 3 sub-arcs to avoid lengths >= 180 deg
					static const Mat4d rotLon120 = Mat4d::zrotation(120.*M_PI/180.);
					Vec3d rotFpt=fpt;
					rotFpt.transfo4d(rotLon120);
					Vec3d rotFpt2=rotFpt;
					rotFpt2.transfo4d(rotLon120);
					sPainter.drawSmallCircleArc(fpt, rotFpt, rotCenter, viewportEdgeIntersectCallback, &userData);
					sPainter.drawSmallCircleArc(rotFpt, rotFpt2, rotCenter, viewportEdgeIntersectCallback, &userData);
					sPainter.drawSmallCircleArc(rotFpt2, fpt, rotCenter, viewportEdgeIntersectCallback, &userData);
					fpt.transfo4d(rotLon);
					continue;
				}
				else
					break;
			}

			// Draw the arc in 2 sub-arcs to avoid lengths > 180 deg
			Vec3d middlePoint = p1-rotCenter+p2-rotCenter;
			middlePoint.normalize();
			middlePoint*=(p1-rotCenter).length();
			middlePoint+=rotCenter;
			if (!viewPortSphericalCap.contains(middlePoint))
			{
				middlePoint-=rotCenter;
				middlePoint*=-1.;
				middlePoint+=rotCenter;
			}

			sPainter.drawSmallCircleArc(p1, middlePoint, rotCenter, viewportEdgeIntersectCallback, &userData);
			sPainter.drawSmallCircleArc(p2, middlePoint, rotCenter, viewportEdgeIntersectCallback, &userData);

			fpt.transfo4d(rotLon);
		}
	}
	// OpenGL ES 2.0 doesn't have GL_LINE_SMOOTH
	#ifdef GL_LINE_SMOOTH
	if (QOpenGLContext::currentContext()->format().renderableType()==QSurfaceFormat::OpenGL)
		glDisable(GL_LINE_SMOOTH);
	#endif
}
Beispiel #17
0
void Altimeter::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
    static const QPoint needle[3] = {
        QPoint(4, 8),
        QPoint(-4, 8),
        QPoint(0, -95)
    };
    static const QPoint needle2[3] = {
        QPoint(8, 8),
        QPoint(-8, 8),
        QPoint(0, -70)
    };
    QColor needleColor(255, 255, 255);
    QColor needleColor2(200, 200, 200);

    painter->setFont(font);

    int side = qMin(width(), height());
    painter->setRenderHint(QPainter::Antialiasing);
    painter->save();
    painter->scale(side / 200.0, side / 200.0);
    painter->save();
    painter->translate(100, 100);


    painter->setPen(Qt::white);
    if(!_label.isEmpty()) {
        int textwidth = painter->fontMetrics().width(_label);
        painter->drawText(-textwidth/2,-70, textwidth, 200, Qt::AlignCenter, _label);
    }
    int textwidth = painter->fontMetrics().width("Altitude");
    painter->drawText(-textwidth/2,-130, textwidth, 200, Qt::AlignCenter, "Altitude");

    // Pressure window
    painter->setBrush(Qt::black);
    painter->drawRect(30,-10,60,20);
    painter->setFont(pressureFont);
    QString pressureText = QString::number(_baroPressure);
    textwidth = painter->fontMetrics().width(pressureText);
    painter->drawText(30,-10, 60, 20, Qt::AlignRight | Qt::AlignVCenter, pressureText);

    painter->setFont(font);
    painter->setBrush(Qt::white);
    if(_thickBars > 0) {
        for (float i = 0 ; i <= _range1; i+=_thickBars) {
            painter->save();
            painter->rotate(value2Angle1(i));
            painter->drawRect(-1, -100, 2, 14);
            painter->restore();
        }
    }
    if(_thinBars > 0) {
        for (float i = 0 ; i <= _range2; i+=_thinBars) {
            painter->save();
            painter->rotate(value2Angle1(i));
            painter->drawRect(-0.3, -100, 0.6, 8);
            painter->restore();
        }
    }
    painter->setPen(QColor(200,200,200));

    if(_numbers != 0) {
        for (float i = 0 ; i < _range1; i+=_numbers) {
            painter->save();
            painter->rotate(value2Angle1(i));
            painter->save();
            QString lineNumber = QString::number(i*_numbersScale);
            painter->translate(0,-70);
            painter->rotate(-value2Angle1(i));
            int width = painter->fontMetrics().width(lineNumber);
            int height =painter->fontMetrics().height();
            painter->drawText(-width/2,-height/2,width,height, Qt::AlignCenter,  lineNumber);
            painter->restore();
            painter->restore();
        }
    }
    painter->setPen(Qt::NoPen);
    painter->setBrush(needleColor2);
    painter->save();
    painter->rotate(value2Angle2(_value));
    painter->drawConvexPolygon(needle2, 3);
    painter->restore();
    painter->setBrush(needleColor);
    painter->save();
    painter->rotate(value2Angle1(_value));
    painter->drawConvexPolygon(needle, 3);
    painter->restore();
    painter->setBrush(Qt::white);

    painter->restore();

    painter->restore();

    PanelItem::paint(painter, option, widget);
}
Beispiel #18
0
void SkyQPainter::initStarImages()
{

    const int starColorIntensity = Options::starColorIntensity();

    ColorMap.clear();
    switch( Options::starColorMode() ) {
    case 1: // Red stars.
        m_starColor = Qt::red;
        break;
    case 2: // Black stars.
        m_starColor = Qt::black;
        break;
    case 3: // White stars
        m_starColor = Qt::white;
        break;
    case 0:  // Real color
    default: // And use real color for everything else
        m_starColor = QColor();
        ColorMap.insert( 'O', QColor::fromRgb(   0,   0, 255 ) );
        ColorMap.insert( 'B', QColor::fromRgb(   0, 200, 255 ) );
        ColorMap.insert( 'A', QColor::fromRgb(   0, 255, 255 ) );
        ColorMap.insert( 'F', QColor::fromRgb( 200, 255, 100 ) );
        ColorMap.insert( 'G', QColor::fromRgb( 255, 255,   0 ) );
        ColorMap.insert( 'K', QColor::fromRgb( 255, 100,   0 ) );
        ColorMap.insert( 'M', QColor::fromRgb( 255,   0,   0 ) );
        break;
    }
    if ( ColorMap.isEmpty() ) {
        ColorMap.insert( 'O', m_starColor );
        ColorMap.insert( 'B', m_starColor );
        ColorMap.insert( 'A', m_starColor );
        ColorMap.insert( 'F', m_starColor );
        ColorMap.insert( 'G', m_starColor );
        ColorMap.insert( 'K', m_starColor );
        ColorMap.insert( 'M', m_starColor );
    }

    foreach( char color, ColorMap.keys() ) {
        QPixmap BigImage( 15, 15 );
        BigImage.fill( Qt::transparent );

        QPainter p;
        p.begin( &BigImage );

        if ( Options::starColorMode() == 0 ) {
            qreal h, s, v, a;
            p.setRenderHint( QPainter::Antialiasing, false );
            QColor starColor = ColorMap[color];
            starColor.getHsvF(&h, &s, &v, &a);
            for (int i = 0; i < 8; i++ ) {
                for (int j = 0; j < 8; j++ ) {
                    qreal x = i - 7;
                    qreal y = j - 7;
                    qreal dist = sqrt( x*x + y*y ) / 7.0;
                    starColor.setHsvF(h,
                                      qMin( qreal(1), dist < (10-starColorIntensity)/10.0 ? 0 : dist ),
                                      v,
                                      qMax( qreal(0), dist < (10-starColorIntensity)/20.0 ? 1 : 1-dist ) );
                    p.setPen( starColor );
                    p.drawPoint( i, j );
                    p.drawPoint( 14-i, j );
                    p.drawPoint( i, 14-j );
                    p.drawPoint (14-i, 14-j);
                }
            }
        } else {
            p.setRenderHint(QPainter::Antialiasing, true );
            p.setPen( QPen(ColorMap[color], 2.0 ) );
            p.setBrush( p.pen().color() );
            p.drawEllipse( QRectF( 2, 2, 10, 10 ) );
        }
        p.end();

        // Cache array slice
        QPixmap** pmap = imageCache[ harvardToIndex(color) ];
        for( int size = 1; size < nStarSizes; size++ ) {
            if( !pmap[size] )
                pmap[size] = new QPixmap();
            *pmap[size] = BigImage.scaled( size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation );
        }
    }
    starColorMode = Options::starColorMode();
}
Beispiel #19
0
double DysonCompressor::filter(Buffer &data, bool flush)
{
    if (!enabled)
        return 0.0;

    QMutexLocker locker(&mutex);

    if (!flush)
    {
        const int size = data.size() / sizeof(float);
        float *samples = (float *)data.data();

        const double targetlevel = MAXLEVEL * peakpercent / 100.0;
        const double rgainfilter = 1.0 / (releasetime * sampleRate);

        for (int pos = 0; pos < size; pos += channels)
        {
            float *currentsamples = samples + pos;

            double levelsq0 = 0.0;
            for (int c = 0; c < channels; ++c)
            {
                samplesdelayed[c][ndelayptr] = currentsamples[c];
                levelsq0 += (double)currentsamples[c] * (double)currentsamples[c];
            }

            if (++ndelayptr >= NDELAY)
                ndelayptr = 0;

            if (levelsq0 > rlevelsq0)
                rlevelsq0 = (levelsq0 * RLEVELSQ0FFILTER) + rlevelsq0 * (1.0 - RLEVELSQ0FFILTER);
            else
                rlevelsq0 = (levelsq0 * RLEVELSQ0FILTER) + rlevelsq0 * (1.0 - RLEVELSQ0FILTER);

            //AGC
            if (rlevelsq0 > FLOORLEVEL * FLOORLEVEL)
            {
                if (rlevelsq0 > rlevelsq1)
                    rlevelsq1 = rlevelsq0;
                else
                    rlevelsq1 = rlevelsq0 * RLEVELSQ1FILTER + rlevelsq1 * (1.0 - RLEVELSQ1FILTER);

                rlevelsqn[0] = rlevelsq1;
                for (int i = 0; i < NFILT-1; i++)
                {
                    if (rlevelsqn[i] > rlevelsqn[i+1])
                        rlevelsqn[i+1] = rlevelsqn[i];
                    else
                        rlevelsqn[i+1] = rlevelsqn[i] * RLEVELSQ1FILTER + rlevelsqn[i+1] * (1.0 - RLEVELSQ1FILTER);
                }

                double efilt = RLEVELSQEFILTER;
                double levelsqe = rlevelsqe[0] = rlevelsqn[NFILT-1];
                for (int i = 0; i < NEFILT-1; ++i)
                {
                    rlevelsqe[i+1] = rlevelsqe[i] * efilt +    rlevelsqe[i+1] * (1.0 - efilt);
                    if (rlevelsqe[i+1] > levelsqe)
                        levelsqe = rlevelsqe[i+1];
                    efilt *= 1.0 / 1.5;
                }

                double gain = targetlevel / sqrt(levelsqe);
                if (compressionratio < 0.99)
                {
                    if (compressionratio == 0.50)
                        gain = sqrt(gain);
                    else
                        gain = exp(log(gain) * compressionratio);
                }

                if (gain < rgain)
                    rgain = gain * RLEVELSQEFILTER / 2.0 + rgain * (1.0 - RLEVELSQEFILTER / 2.0);
                else
                    rgain = gain * rgainfilter + rgain * (1.0 - rgainfilter);

                lastrgain = rgain;
                if (gain < lastrgain)
                    lastrgain = gain;
            }

            float sampled[channels];
            for (int c = 0; c < channels; ++c)
                sampled[c] = samplesdelayed.at(c).at(ndelayptr);

            double fastgain = lastrgain;
            if (fastgain > MAXFASTGAIN)
                fastgain = MAXFASTGAIN;
            if (fastgain < 0.0001)
                fastgain = 0.0001;

            double qgain;
            if (fastgaincompressionratio == 0.25)
                qgain = sqrt(sqrt(fastgain));
            else if (fastgaincompressionratio == 0.5)
                qgain = sqrt(fastgain);
            else if (fastgaincompressionratio == 1.0)
                qgain = fastgain;
            else
                qgain = exp(log(fastgain) * fastgaincompressionratio);

            double tslowgain = lastrgain / qgain;
            if (tslowgain > MAXSLOWGAIN)
                tslowgain = MAXSLOWGAIN;
            if (tslowgain < rmastergain0)
                rmastergain0 = tslowgain;
            else
                rmastergain0 = tslowgain * RMASTERGAIN0FILTER + (1.0 - RMASTERGAIN0FILTER) * rmastergain0;

            const double npeakgain = rmastergain0 * qgain;

            float ngain = MAXLEVEL;

            double newsample[channels];
            for (int c = 0; c < channels; ++c)
            {
                newsample[c] = sampled[c] * npeakgain;

                double tmpgain = 1.0;
                if (fabs(newsample[c]) >= MAXLEVEL)
                    tmpgain = MAXLEVEL / fabs(newsample[c]);

                if (tmpgain < ngain)
                    ngain = tmpgain;
            }

            const double ngsq = ngain * ngain;
            if (ngsq <= rpeakgain0)
            {
                rpeakgain0      = ngsq /* * 0.50 + rpeakgain0 * 0.50 */;
                rpeaklimitdelay = peaklimitdelay;
            }
            else if (rpeaklimitdelay == 0)
            {
                const double tnrgain = (ngain < 1.0) ? ngain : 1.0;
                rpeakgain0 = tnrgain * RPEAKGAINFILTER + (1.0 - RPEAKGAINFILTER) * rpeakgain0;
            }

            if (rpeakgain0 <= rpeakgain1)
            {
                rpeakgain1 = rpeakgain0;
                rpeaklimitdelay = peaklimitdelay;
            }
            else if (rpeaklimitdelay == 0)
                rpeakgain1 = RPEAKGAINFILTER * rpeakgain0 + (1.0 - RPEAKGAINFILTER) * rpeakgain1;
            else
                --rpeaklimitdelay;

            const double sqrtrpeakgain = sqrt(rpeakgain1);
            for (int c = 0; c < channels; ++c)
                currentsamples[c] = newsample[c] * sqrtrpeakgain;
        }

        if (toRemove > 0)
        {
            const int realToRemove = qMin(size / channels, toRemove);
            data.remove(0, realToRemove * channels * sizeof(float));
            delayedSamples += realToRemove;
            toRemove -= realToRemove;
        }
    }
    else
    {
        data.resize(channels * sizeof(float) * delayedSamples);
        float *samples = (float *)data.data();
        for (int pos = 0; pos < delayedSamples; ++pos)
        {
            for (int c = 0; c < channels; ++c)
                samples[pos * channels + c] = samplesdelayed.at(c).at(ndelayptr);
            if (++ndelayptr >= NDELAY)
                ndelayptr = 0;
        }
        delayedSamples = 0;
    }

    return NDELAY / (double)sampleRate;
}
Beispiel #20
0
bool OpusDecoder::decode(const QString &sourceFile, const QString &outputFile, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;

	if(m_disableResampling)
	{
		args << "--no-resample";
	}

	args << QDir::toNativeSeparators(sourceFile);
	args << QDir::toNativeSeparators(outputFile);

	if(!startProcess(process, m_binary, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;
	int prevProgress = -1;

	QRegExp regExp("\\((\\d+)%\\)");

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("opusdec process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp.lastIndexIn(text) >= 0)
			{
				bool ok = false;
				int progress = regExp.cap(1).toInt(&ok);
				if(ok && (progress > prevProgress))
				{
					emit statusUpdated(progress);
					prevProgress = qMin(progress + 2, 99);
				}
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
	{
		return false;
	}
	
	return true;
}
Beispiel #21
0
// Stack Blur Algorithm by Mario Klingemann <[email protected]>
// fixed to handle alpha channel correctly by Zack Rusin
void fastbluralpha(QImage &img, int radius)
{
    if (radius < 1) {
        return;
    }

    QRgb *pix = (QRgb *)img.bits();
    int w   = img.width();
    int h   = img.height();
    int wm  = w - 1;
    int hm  = h - 1;
    int wh  = w * h;
    int div = radius + radius + 1;

    int *r = new int[wh];
    int *g = new int[wh];
    int *b = new int[wh];
    int *a = new int[wh];
    int rsum, gsum, bsum, asum, x, y, i, yp, yi, yw;
    QRgb p;
    int *vmin = new int[qMax(w, h)];

    int divsum = (div + 1) >> 1;
    divsum *= divsum;
    int *dv = new int[256 * divsum];
    for (i = 0; i < 256 * divsum; ++i) {
        dv[i] = (i / divsum);
    }

    yw = yi = 0;

    int **stack = new int *[div];
    for (int i = 0; i < div; ++i) {
        stack[i] = new int[4];
    }

    int stackpointer;
    int stackstart;
    int *sir;
    int rbs;
    int r1 = radius + 1;
    int routsum, goutsum, boutsum, aoutsum;
    int rinsum, ginsum, binsum, ainsum;

    for (y = 0; y < h; ++y) {
        rinsum = ginsum = binsum = ainsum
                                   = routsum = goutsum = boutsum = aoutsum
                                               = rsum = gsum = bsum = asum = 0;
        for (i = - radius; i <= radius; ++i) {
            p = pix[yi + qMin(wm, qMax(i, 0))];
            sir = stack[i + radius];
            sir[0] = qRed(p);
            sir[1] = qGreen(p);
            sir[2] = qBlue(p);
            sir[3] = qAlpha(p);

            rbs = r1 - abs(i);
            rsum += sir[0] * rbs;
            gsum += sir[1] * rbs;
            bsum += sir[2] * rbs;
            asum += sir[3] * rbs;

            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
                ainsum += sir[3];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
                aoutsum += sir[3];
            }
        }
        stackpointer = radius;

        for (x = 0; x < w; ++x) {

            r[yi] = dv[rsum];
            g[yi] = dv[gsum];
            b[yi] = dv[bsum];
            a[yi] = dv[asum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;
            asum -= aoutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];
            aoutsum -= sir[3];

            if (y == 0) {
                vmin[x] = qMin(x + radius + 1, wm);
            }
            p = pix[yw + vmin[x]];

            sir[0] = qRed(p);
            sir[1] = qGreen(p);
            sir[2] = qBlue(p);
            sir[3] = qAlpha(p);

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];
            ainsum += sir[3];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;
            asum += ainsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[(stackpointer) % div];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];
            aoutsum += sir[3];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];
            ainsum -= sir[3];

            ++yi;
        }
        yw += w;
    }
    for (x = 0; x < w; ++x) {
        rinsum = ginsum = binsum = ainsum
                                   = routsum = goutsum = boutsum = aoutsum
                                               = rsum = gsum = bsum = asum = 0;

        yp = - radius * w;

        for (i = -radius; i <= radius; ++i) {
            yi = qMax(0, yp) + x;

            sir = stack[i + radius];

            sir[0] = r[yi];
            sir[1] = g[yi];
            sir[2] = b[yi];
            sir[3] = a[yi];

            rbs = r1 - abs(i);

            rsum += r[yi] * rbs;
            gsum += g[yi] * rbs;
            bsum += b[yi] * rbs;
            asum += a[yi] * rbs;

            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
                ainsum += sir[3];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
                aoutsum += sir[3];
            }

            if (i < hm) {
                yp += w;
            }
        }

        yi = x;
        stackpointer = radius;

        for (y = 0; y < h; ++y) {
            pix[yi] = qRgba(dv[rsum], dv[gsum], dv[bsum], dv[asum]);

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;
            asum -= aoutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];
            aoutsum -= sir[3];

            if (x == 0) {
                vmin[y] = qMin(y + r1, hm) * w;
            }
            p = x + vmin[y];

            sir[0] = r[p];
            sir[1] = g[p];
            sir[2] = b[p];
            sir[3] = a[p];

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];
            ainsum += sir[3];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;
            asum += ainsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[stackpointer];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];
            aoutsum += sir[3];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];
            ainsum -= sir[3];

            yi += w;
        }
    }
    delete [] r;
    delete [] g;
    delete [] b;
    delete [] a;
    delete [] vmin;
    delete [] dv;

    for (int i = 0; i < div; ++i) {
        delete [] stack[i];
    }
    delete [] stack;
}
Beispiel #22
0
void Color_Wheel::setHue(qreal h)
{
    huem = qMax(0.0,qMin(1.0,h));
    render_rectangle();
    update();
}
Beispiel #23
0
void KPty::login(const char *user, const char *remotehost)
{
#ifdef HAVE_UTEMPTER
    Q_D(KPty);

    addToUtmp(d->ttyName, remotehost, d->masterFd);
    Q_UNUSED(user);
#else
# ifdef HAVE_UTMPX
    struct utmpx l_struct;
# else
    struct utmp l_struct;
# endif
    memset(&l_struct, 0, sizeof(l_struct));
    // note: strncpy without terminators _is_ correct here. man 4 utmp

    if (user)
      strncpy(l_struct.ut_name, user, sizeof(l_struct.ut_name));

    if (remotehost) {
      strncpy(l_struct.ut_host, remotehost, sizeof(l_struct.ut_host));
# ifdef HAVE_STRUCT_UTMP_UT_SYSLEN
      l_struct.ut_syslen = qMin(strlen(remotehost), sizeof(l_struct.ut_host));
# endif
    }

# ifndef __GLIBC__
    Q_D(KPty);
    const char *str_ptr = d->ttyName.data();
    if (!memcmp(str_ptr, "/dev/", 5))
        str_ptr += 5;
    strncpy(l_struct.ut_line, str_ptr, sizeof(l_struct.ut_line));
#  ifdef HAVE_STRUCT_UTMP_UT_ID
    strncpy(l_struct.ut_id,
            str_ptr + strlen(str_ptr) - sizeof(l_struct.ut_id),
            sizeof(l_struct.ut_id));
#  endif
# endif

# ifdef HAVE_UTMPX
    gettimeofday(&l_struct.ut_tv, 0);
# else
    l_struct.ut_time = time(0);
# endif

# ifdef HAVE_LOGIN
#  ifdef HAVE_LOGINX
    ::loginx(&l_struct);
#  else
    ::login(&l_struct);
#  endif
# else
#  ifdef HAVE_STRUCT_UTMP_UT_TYPE
    l_struct.ut_type = USER_PROCESS;
#  endif
#  ifdef HAVE_STRUCT_UTMP_UT_PID
    l_struct.ut_pid = getpid();
#   ifdef HAVE_STRUCT_UTMP_UT_SESSION
    l_struct.ut_session = getsid(0);
#   endif
#  endif
#  ifdef HAVE_UTMPX
    utmpxname(_PATH_UTMPX);
    setutxent();
    pututxline(&l_struct);
    endutxent();
    updwtmpx(_PATH_WTMPX, &l_struct);
#  else
    utmpname(_PATH_UTMP);
    setutent();
    pututline(&l_struct);
    endutent();
    updwtmp(_PATH_WTMP, &l_struct);
#  endif
# endif
#endif
}
Beispiel #24
0
void Color_Wheel::setSaturation(qreal s)
{
    sat = qMax(0.0,qMin(1.0,s));
    update();
}
Beispiel #25
0
void Window::paintEvent(QPaintEvent *){
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    int s = list.size();
    for (int i = 0; i < s; i++){
        if (list[i].selected){painter.setPen(QPen(Qt::red, list[i].width, Qt::SolidLine));}else{painter.setPen(QPen(Qt::black, list[i].width, Qt::SolidLine));}
        if (list[i].fill && list[i].shape != Curve){painter.setBrush(QBrush(Qt::white));}else{painter.setBrush(Qt::NoBrush);}
        if (list[i].shape == Line){
             painter.drawLine(list[i].ps[0],list[i].ps[1]);
        }else if (list[i].shape == Poly || list[i].shape == Diamond){
             painter.drawPolygon(list[i].ps.constData(), list[i].ps.size());
        }else if (list[i].shape == Circle){
            int r = qSqrt(qPow(list[i].ps[0].x()-list[i].ps[1].x(), 2)+qPow(list[i].ps[0].y()-list[i].ps[1].y(), 2));
            painter.drawEllipse(list[i].ps[0], r, r);
        }else if (list[i].shape == Curve){
            QPainterPath path;
            path.moveTo(list[i].ps[0]);
            path.cubicTo(list[i].ps[0], list[i].ps[2], list[i].ps[1]);
            painter.drawPath(path);
        }
    }
    if (hasMouseTracking()){
        QPoint qp = Window::mapFromGlobal(QCursor::pos());
        painter.setPen(QPen(Qt::gray, tool.width, Qt::DashLine));
        if (tool.fill && tool.shape != Curve){painter.setBrush(QBrush(Qt::white));}else{painter.setBrush(Qt::NoBrush);}
        if (tool.shape == Line){
            painter.drawLine(tool.ps.last(), qp);
        }else if (tool.shape == Poly){
            tool.ps.append(qp);
            painter.drawPolygon(tool.ps.constData(), tool.ps.size());
            tool.ps.removeLast();
        }else if (tool.shape == Diamond){
            tool.ps.append(qp);
            tool.ps.append(QPoint(2*qp.x()-tool.ps[0].x(), tool.ps[0].y()));
            tool.ps.append(QPoint(qp.x(), 2*tool.ps[0].y()-qp.y()));
            painter.drawPolygon(tool.ps.constData(), tool.ps.size());
            for (int i = 3; i > 0; i--){tool.ps.removeLast();}
        }else if (tool.shape == Circle){
           int r = qSqrt(qPow(tool.ps[0].x()-qp.x(), 2)+qPow(tool.ps[0].y()-qp.y(), 2));
           painter.drawEllipse(tool.ps[0], r, r);
        }else if (tool.shape == Curve){
           QPainterPath path;
           path.moveTo(tool.ps[0]);
           path.cubicTo(tool.ps[0], qp, tool.ps[1]);
           painter.drawPath(path);
        }else if (tool.shape == None && pressed){
            painter.setBrush(Qt::NoBrush);
            painter.setPen(QPen(Qt::gray, 1, Qt::SolidLine));
            for (int i = 0; i < s; i++){
               for (int j = list[i].ps.size() - 1; j >=0; j--){
                   painter.drawEllipse(list[i].ps[j], 3, 3);
               }
            }
            painter.setPen(QPen(Qt::gray, 1, Qt::DotLine));
            QPoint lt = QPoint(qMin(qp.x(), tool.ps.last().x()), qMin(qp.y(), tool.ps.last().y()));
            QPoint rb = QPoint(qMax(qp.x(), tool.ps.last().x()), qMax(qp.y(), tool.ps.last().y()));
            painter.drawRect(lt.x(), lt.y(), qAbs(lt.x()-rb.x()), qAbs(lt.y()-rb.y()));
        }
    }
    painter.end();
}
Beispiel #26
0
void Color_Wheel::setValue(qreal v)
{
    val = qMax(0.0,qMin(1.0,v));
    update();
}
Beispiel #27
0
quint32 AbstractSshChannel::maxDataSize() const
{
    return qMin(m_localWindowSize, maxPacketSize());
}
Beispiel #28
0
void QWSMouseHandler::limitToScreen(QPoint &position)
{
    position.setX(qMin(d_ptr->screen->deviceWidth() - 1, qMax(0, position.x())));
    position.setY(qMin(d_ptr->screen->deviceHeight() - 1, qMax(0, position.y())));
}
Beispiel #29
0
void AudioNoiseWidget::paintEvent(QPaintEvent *) {
	QPainter paint(this);
	QPalette pal;

	paint.fillRect(rect(), pal.color(QPalette::Background));

	AudioInputPtr ai = g.ai;
	if (ai.get() == NULL || ! ai->sppPreprocess)
		return;

	QPolygonF poly;

	ai->qmSpeex.lock();

	spx_int32_t ps_size = 0;
	speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_PSD_SIZE, &ps_size);

	STACKVAR(spx_int32_t, noise, ps_size);
	STACKVAR(spx_int32_t, ps, ps_size);

	speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_PSD, ps);
	speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_NOISE_PSD, noise);

	ai->qmSpeex.unlock();

	qreal sx, sy;

	sx = (static_cast<float>(width()) - 1.0f) / static_cast<float>(ps_size);
	sy = static_cast<float>(height()) - 1.0f;

	poly << QPointF(0.0f, height() - 1);
	float fftmul = 1.0 / (32768.0);
	for (int i=0; i < ps_size; i++) {
		qreal xp, yp;
		xp = i * sx;
		yp = sqrtf(sqrtf(static_cast<float>(noise[i]))) - 1.0f;
		yp = yp * fftmul;
		yp = qMin<qreal>(yp * 3000.0f, 1.0f);
		yp = (1 - yp) * sy;
		poly << QPointF(xp, yp);
	}

	poly << QPointF(width() - 1, height() - 1);
	poly << QPointF(0.0f, height() - 1);

	paint.setPen(Qt::blue);
	paint.setBrush(Qt::blue);
	paint.drawPolygon(poly);

	poly.clear();

	for (int i=0;i < ps_size; i++) {
		qreal xp, yp;
		xp = i * sx;
		yp = sqrtf(sqrtf(static_cast<float>(ps[i]))) - 1.0f;
		yp = yp * fftmul;
		yp = qMin(yp * 3000.0, 1.0);
		yp = (1 - yp) * sy;
		poly << QPointF(xp, yp);
	}

	paint.setPen(Qt::red);
	paint.drawPolyline(poly);
}
void QxtSpanSliderPrivate::triggerAction(QAbstractSlider::SliderAction action, bool main)
{
    int value = 0;
    bool no = false;
    bool up = false;
    const int min = qxt_p().minimum();
    const int max = qxt_p().maximum();
    const SpanHandle altControl = (mainControl == LowerHandle ? UpperHandle : LowerHandle);

    blockTracking = true;

    switch (action)
    {
    case QAbstractSlider::SliderSingleStepAdd:
        if ((main && mainControl == UpperHandle) || (!main && altControl == UpperHandle))
        {
            value = qBound(min, upper + qxt_p().singleStep(), max);
            up = true;
            break;
        }
        value = qBound(min, lower + qxt_p().singleStep(), max);
        break;
    case QAbstractSlider::SliderSingleStepSub:
        if ((main && mainControl == UpperHandle) || (!main && altControl == UpperHandle))
        {
            value = qBound(min, upper - qxt_p().singleStep(), max);
            up = true;
            break;
        }
        value = qBound(min, lower - qxt_p().singleStep(), max);
        break;
    case QAbstractSlider::SliderToMinimum:
        value = min;
        if ((main && mainControl == UpperHandle) || (!main && altControl == UpperHandle))
            up = true;
        break;
    case QAbstractSlider::SliderToMaximum:
        value = max;
        if ((main && mainControl == UpperHandle) || (!main && altControl == UpperHandle))
            up = true;
        break;
    case QAbstractSlider::SliderMove:
        if ((main && mainControl == UpperHandle) || (!main && altControl == UpperHandle))
            up = true;
    case QAbstractSlider::SliderNoAction:
        no = true;
        break;
    default:
        qWarning("QxtSpanSliderPrivate::triggerAction: Unknown action");
        break;
    }

    if (!no && !up)
    {
        if (movement == QxtSpanSlider::NoCrossing)
            value = qMin(value, upper);
        else if (movement == QxtSpanSlider::NoOverlapping)
            value = qMin(value, upper - 1);

        qxt_p().setLowerPosition(value);
    }
    else if (!no)
    {
        if (movement == QxtSpanSlider::NoCrossing)
            value = qMax(value, lower);
        else if (movement == QxtSpanSlider::NoOverlapping)
            value = qMax(value, lower + 1);

        qxt_p().setUpperPosition(value);
    }

    blockTracking = false;
    qxt_p().setLowerValue(lowerPos);
    qxt_p().setUpperValue(upperPos);
}