Example #1
0
void GlobalData::read()
{
  KConfig *config=KGlobal::config();

  // general...
  config->setGroup("General");
  defineClipboard = config->readBoolEntry("Lookup_Clipboard",false);
  headLayout = config->readNumEntry("Heading_Layout",0);
  if ((headLayout > 2)||(headLayout < 0))
    headLayout = 0;
  saveHistory = config->readBoolEntry("Save_History",true);
  maxHistEntrys = config->readNumEntry("Max_History_Entrys",500);
  if ((maxHistEntrys < 10)||(maxHistEntrys >5000))
    maxHistEntrys = 200;
  maxBrowseListEntrys = config->readNumEntry("Max_Browse_Entrys",15);
  if ((maxBrowseListEntrys < 1)||(maxBrowseListEntrys > 50))
    maxBrowseListEntrys = 15;
  maxDefinitions = config->readNumEntry("Max_Definitions",2000);
  if ((maxDefinitions < 100)||(maxDefinitions > 10000))
    maxDefinitions = 2000;

  //colors
  config->setGroup("Colors");
  useCustomColors=config->readBoolEntry("customColors", false);

  QColor defCol=KGlobalSettings::textColor();
  c_olors[Ctext]=config->readColorEntry("textColor",&defCol);
  c_olorNames[Ctext]=i18n("Text");

  defCol=KGlobalSettings::baseColor();
  c_olors[Cbackground]=config->readColorEntry("backgroundColor",&defCol);
  c_olorNames[Cbackground]=i18n("Background");

  defCol=KGlobalSettings::highlightedTextColor();
  c_olors[CheadingsText]=config->readColorEntry("headingsTextColor",&defCol);
  c_olorNames[CheadingsText]=i18n("Heading Text");

  defCol=KGlobalSettings::highlightColor();
  c_olors[CheadingsBackground]=config->readColorEntry("headingsBackgroundColor",&defCol);
  c_olorNames[CheadingsBackground]=i18n("Heading Background");

  defCol=KGlobalSettings::linkColor();
  c_olors[Clinks]=config->readColorEntry("linksColor",&defCol);
  c_olorNames[Clinks]=i18n("Link");

  defCol=KGlobalSettings::visitedLinkColor();
  c_olors[CvisitedLinks]=config->readColorEntry("linksColor",&defCol);
  c_olorNames[CvisitedLinks]=i18n("Followed Link");

  //fonts
  config->setGroup("Fonts");
  useCustomFonts=config->readBoolEntry("customFonts", false);

  QFont defFont=KGlobalSettings::generalFont();
  f_onts[Ftext]=config->readFontEntry("textFont",&defFont);
  f_ontNames[Ftext]=i18n("Text");

  defFont.setBold( true );
  defFont.setPointSize(defFont.pointSize()+2);
  f_onts[Fheadings]=config->readFontEntry("headingsFont",&defFont);
  f_ontNames[Fheadings]=i18n("Headings");

  // geometry...
  config->setGroup("Geometry");
  QSize invalid(-1,-1);
  optSize = config->readSizeEntry("Opt_Size",&invalid);
  setsSize = config->readSizeEntry("Sets_Size",&invalid);
  matchSize = config->readSizeEntry("Match_Size",&invalid);
  showMatchList = config->readBoolEntry("Show_MatchList",false);
  splitterSizes = config->readIntListEntry("Splitter_Sizes");

  config->setGroup("Query Combo");
  queryComboCompletionMode = (KGlobalSettings::Completion)config->readNumEntry("Completion_mode",
                                                                               KGlobalSettings::completionMode());

  config->setGroup("Query_History");
  queryHistory = config->readListEntry("History");

  config->setGroup("DictServer");
  server = config->readEntry("Server", "dict.org");
  port = config->readNumEntry("Port", 2628);
  if (port < 0)
    port = 2628;
  timeout = config->readNumEntry("Timeout",60);
  if (timeout < 0)
    timeout = 60;
  pipeSize = config->readNumEntry("Pipe_Size",256);
  if (pipeSize < 0)
    pipeSize = 256;
  idleHold = config->readNumEntry("Idle_Hold",30);
  if (idleHold < 0)
    idleHold = 30;
  encoding=config->readEntry("encoding", "utf8");
  authEnabled = config->readBoolEntry("Auth_Enabled",false);
  user = config->readEntry("User");
  secret = encryptStr(config->readEntry("Secret"));
  serverDatabases = config->readListEntry("Server_Databases");
  currentDatabase = config->readNumEntry("Current_Database",0);
  strategies = config->readListEntry("Strategies");
  if (strategies.isEmpty()) {
    strategies.append(i18n("Spell Check"));
    strategies.append(i18n("Exact"));
    strategies.append(i18n("Prefix"));
  } else {
    strategies.remove(strategies.begin());
    strategies.prepend(i18n("Spell Check"));
  }

  currentStrategy = config->readNumEntry("Current_Strategy",0);
  if (currentStrategy >= strategies.count())
      currentStrategy = 0;

  config->setGroup("Database_Sets");
  databaseSets.setAutoDelete(true);
  int num = config->readNumEntry("Num_Sets",0);
  QStringList* temp;
  QString strNum;
  while (num > 0) {
    temp = new QStringList();
    strNum.setNum(num);
    *temp = config->readListEntry(strNum);
    if (!temp->isEmpty()) {
      databaseSets.prepend(temp);
      num--;
    } else {
      delete temp;
      num = 0;       // stop reading...
    }
  }
  databases = serverDatabases;
  for (int i = databaseSets.count()-1;i>=0;i--)
    databases.prepend(databaseSets.at(i)->first());
  databases.prepend(i18n("All Databases"));
  if (currentDatabase >= databases.count())
    currentDatabase = 0;
}
Example #2
0
// common function for wheel up/down and key up/down
// delta is in wheel units: a delta of 120 means to increment by 1
void
SpinBox::increment(int delta,
                   int shift) // shift = 1 means to increment * 10, shift = -1 means / 10
{
    bool ok;
    QString str = text();
    //qDebug() << "increment from " << str;
    const double oldVal = str.toDouble(&ok);

    if (!ok) {
        // Not a valid double value, don't do anything
        return;
    }

    bool useCursorPositionIncr = appPTR->getCurrentSettings()->useCursorPositionIncrements();

    // First, treat the standard case: use the Knob increment
    if (!useCursorPositionIncr) {
        double val = oldVal;
        _imp->currentDelta += delta;
        double inc = std::pow(10., shift) * _imp->currentDelta * _imp->increment / 120.;
        double maxiD = 0.;
        double miniD = 0.;
        switch (_imp->type) {
        case eSpinBoxTypeDouble: {
            maxiD = _imp->maxi.toDouble();
            miniD = _imp->mini.toDouble();
            val += inc;
            _imp->currentDelta = 0;
            break;
        }
        case eSpinBoxTypeInt: {
            maxiD = _imp->maxi.toInt();
            miniD = _imp->mini.toInt();
            val += (int)inc;         // round towards zero
            // Update the current delta, which contains the accumulated error
            _imp->currentDelta -= ( (int)inc ) * 120. / _imp->increment;
            assert(std::abs(_imp->currentDelta) < 120);
            break;
        }
        }
        val = std::max( miniD, std::min(val, maxiD) );
        if (val != oldVal) {
            setValue(val);
            Q_EMIT valueChanged(val);
        }

        return;
    }

    // From here on, we treat the positin-based increment.

    if ( (str.indexOf( QLatin1Char('e') ) != -1) || (str.indexOf( QLatin1Char('E') ) != -1) ) {
        // Sorry, we don't handle numbers with an exponent, although these are valid doubles
        return;
    }

    _imp->currentDelta += delta;
    int inc_int = _imp->currentDelta / 120; // the number of integert increments
    // Update the current delta, which contains the accumulated error
    _imp->currentDelta -= inc_int * 120;

    if (inc_int == 0) {
        // Nothing is changed, just return
        return;
    }

    // Within the value, we modify:
    // - if there is no selection, the first digit right after the cursor (or if it is an int and the cursor is at the end, the last digit)
    // - if there is a selection, the first digit after the start of the selection
    int len = str.size(); // used for chopping spurious characters
    if (len <= 0) {
        return; // should never happen
    }
    // The position in str of the digit to modify in str() (may be equal to str.size())
    int pos = ( hasSelectedText() ? selectionStart() : cursorPosition() );
    //if (pos == len) { // select the last character?
    //    pos = len - 1;
    //}
    // The position of the decimal dot
    int dot = str.indexOf( QLatin1Char('.') );
    if (dot == -1) {
        dot = str.size();
    }

    // Now, chop trailing and leading whitespace (and update len, pos and dot)

    // Leading whitespace
    while ( len > 0 && str[0].isSpace() ) {
        str.remove(0, 1);
        --len;
        if (pos > 0) {
            --pos;
        }
        --dot;
        assert(dot >= 0);
        assert(len > 0);
    }
    // Trailing whitespace
    while ( len > 0 && str[len - 1].isSpace() ) {
        str.remove(len - 1, 1);
        --len;
        if (pos > len) {
            --pos;
        }
        if (dot > len) {
            --dot;
        }
        assert(len > 0);
    }
    assert( oldVal == str.toDouble() ); // check that the value hasn't changed due to whitespace manipulation

    // On int types, there should not be any dot
    if ( (_imp->type == eSpinBoxTypeInt) && (len > dot) ) {
        // Remove anything after the dot, including the dot
        str.resize(dot);
        len = dot;
    }

    // Adjust pos so that it doesn't point to a dot or a sign
    assert( 0 <= pos && pos <= str.size() );
    while ( pos < str.size() &&
            ( pos == dot || str[pos] == QLatin1Char('+') || str[pos] == QLatin1Char('-') ) ) {
        ++pos;
    }
    assert(len >= pos);

    // Set the shift (may have to be done twice due to the dot)
    pos -= shift;
    if (pos == dot) {
        pos -= shift;
    }

    // Now, add leading and trailing zeroes so that pos is a valid digit position
    // (beware of the sign!)
    // Trailing zeroes:
    // (No trailing zeroes on int, of course)
    assert( len == str.size() );
    if ( (_imp->type == eSpinBoxTypeInt) && (pos >= len) ) {
        // If this is an int and we are beyond the last position, change the last digit
        pos = len - 1;
        // also reset the shift if it was negative
        if (shift < 0) {
            shift = 0;
        }
    }
    while ( pos >= str.size() ) {
        assert(_imp->type == eSpinBoxTypeDouble);
        // Add trailing zero, maybe preceded by a dot
        if (pos == dot) {
            str.append( QLatin1Char('.') );
            ++pos; // increment pos, because we just added a '.', and next iteration will add a '0'
            ++len;
        } else {
            assert(pos > dot);
            str.append( QLatin1Char('0') );
            ++len;
        }
        assert( pos >= (str.size() - 1) );
    }
    // Leading zeroes:
    bool hasSign = ( str[0] == QLatin1Char('-') || str[0] == QLatin1Char('+') );
    while ( pos < 0 || ( pos == 0 && ( str[0] == QLatin1Char('-') || str[0] == QLatin1Char('+') ) ) ) {
        // Add leading zero
        str.insert( hasSign ? 1 : 0, QLatin1Char('0') );
        ++pos;
        ++dot;
        ++len;
    }
    assert( len == str.size() );
    assert( 0 <= pos && pos < str.size() && str[pos].isDigit() );

    QString noDotStr = str;
    int noDotLen = len;
    if (dot != len) {
        // Remove the dot
        noDotStr.remove(dot, 1);
        --noDotLen;
    }
    assert( (_imp->type == eSpinBoxTypeInt && noDotLen == dot) || noDotLen >= dot );
    double val = oldVal; // The value, as a double
    if ( (noDotLen > 16) && (16 >= dot) ) {
        // don't handle more than 16 significant digits (this causes over/underflows in the following)
        assert( noDotLen == noDotStr.size() );
        noDotLen = 16;
        noDotStr.resize(noDotLen);
    }
    qlonglong llval = noDotStr.toLongLong(&ok); // The value, as a long long int
    if (!ok) {
        // Not a valid long long value, don't do anything
        return;
    }
    int llpowerOfTen = dot - noDotLen; // llval must be post-multiplied by this power of ten
    assert(llpowerOfTen <= 0);
    // check that val and llval*10^llPowerOfTen are close enough (relative error should be less than 1e-8)
    assert(std::abs(val * std::pow(10., -llpowerOfTen) - llval) / std::max( qlonglong(1), std::abs(llval) ) < 1e-8);


    // If pos is at the end
    if ( pos == str.size() ) {
        switch (_imp->type) {
        case eSpinBoxTypeDouble:
            if ( dot == str.size() ) {
                str += QString::fromUtf8(".0");
                len += 2;
                ++pos;
            } else {
                str += QLatin1Char('0');
                ++len;
            }
            break;
        case eSpinBoxTypeInt:
            // take the character before
            --pos;
            break;
        }
    }

    // Compute the full value of the increment
    assert( len == str.size() );
    assert(pos != dot);
    assert( 0 <= pos && pos < len && str[pos].isDigit() );

    int powerOfTen = dot - pos - (pos < dot); // the power of ten
    assert( (_imp->type == eSpinBoxTypeDouble) || ( powerOfTen >= 0 && dot == str.size() ) );

    if (powerOfTen - llpowerOfTen > 16) {
        // too many digits to handle, don't do anything

        // (may overflow when adjusting llval)
        return;
    }

    double inc = inc_int * std::pow(10., (double)powerOfTen);

    // Check that we are within the authorized range
    double maxiD, miniD;
    switch (_imp->type) {
    case eSpinBoxTypeInt:
        maxiD = _imp->maxi.toInt();
        miniD = _imp->mini.toInt();
        break;
    case eSpinBoxTypeDouble:
    default:
        maxiD = _imp->maxi.toDouble();
        miniD = _imp->mini.toDouble();
        break;
    }
    val += inc;
    if ( (val < miniD) || (maxiD < val) ) {
        // out of the authorized range, don't do anything
        return;
    }

    // Adjust llval so that the increment becomes an int, and avoid rounding errors
    if (powerOfTen >= llpowerOfTen) {
        llval += inc_int * std::pow(10., powerOfTen - llpowerOfTen);
    } else {
        llval *= std::pow(10., llpowerOfTen - powerOfTen);
        llpowerOfTen -= llpowerOfTen - powerOfTen;
        llval += inc_int;
    }
    // check that val and llval*10^llPowerOfTen are still close enough (relative error should be less than 1e-8)
    assert(std::abs(val * std::pow(10., -llpowerOfTen) - llval) / std::max( qlonglong(1), std::abs(llval) ) < 1e-8);

    QString newStr;
    newStr.setNum(llval);
    bool newStrHasSign = newStr[0] == QLatin1Char('+') || newStr[0] == QLatin1Char('-');
    // the position of the decimal dot
    int newDot = newStr.size() + llpowerOfTen;
    // add leading zeroes if newDot is not a valid position (beware of sign!)
    while ( newDot <= int(newStrHasSign) ) {
        newStr.insert( int(newStrHasSign), QLatin1Char('0') );
        ++newDot;
    }
    assert( 0 <= newDot && newDot <= newStr.size() );
    assert( newDot == newStr.size() || newStr[newDot].isDigit() );
    if ( newDot != newStr.size() ) {
        assert(_imp->type == eSpinBoxTypeDouble);
        newStr.insert( newDot, QLatin1Char('.') );
    }
    // Check that the backed string is close to the wanted value (relative error should be less than 1e-8)
    assert( (newStr.toDouble() - val) / std::max( 1e-8, std::abs(val) ) < 1e-8 );
    // The new cursor position
    int newPos = newDot + (pos - dot);
    // Remove the shift (may have to be done twice due to the dot)
    newPos += shift;
    if (newPos == newDot) {
        // adjust newPos
        newPos += shift;
    }

    assert( 0 <= newDot && newDot <= newStr.size() );

    // Now, add leading and trailing zeroes so that newPos is a valid digit position
    // (beware of the sign!)
    // Trailing zeroes:
    while ( newPos >= newStr.size() ) {
        assert(_imp->type == eSpinBoxTypeDouble);
        // Add trailing zero, maybe preceded by a dot
        if (newPos == newDot) {
            newStr.append( QLatin1Char('.') );
        } else {
            assert(newPos > newDot);
            newStr.append( QLatin1Char('0') );
        }
        assert( newPos >= (newStr.size() - 1) );
    }
    // Leading zeroes:
    bool newHasSign = ( newStr[0] == QLatin1Char('-') || newStr[0] == QLatin1Char('+') );
    while ( newPos < 0 || ( newPos == 0 && ( newStr[0] == QLatin1Char('-') || newStr[0] == QLatin1Char('+') ) ) ) {
        // add leading zero
        newStr.insert( newHasSign ? 1 : 0, QLatin1Char('0') );
        ++newPos;
        ++newDot;
    }
    assert( 0 <= newPos && newPos < newStr.size() && newStr[newPos].isDigit() );

    // Set the text and cursor position
    //qDebug() << "increment setting text to " << newStr;
    setText(newStr, newPos);
    // Set the selection
    assert( newPos + 1 <= newStr.size() );
    setSelection(newPos + 1, -1);
    Q_EMIT valueChanged( value() );
} // increment
void ElevationProfileFloatItem::paintContent( QPainter *painter )
{
    // do not try to draw if not initialized
    if(!isInitialized()) {
        return;
    }
    painter->save();
    painter->setRenderHint( QPainter::Antialiasing, true );
    painter->setFont( font() );

    if ( ! ( m_activeDataSource->isDataAvailable() && m_eleData.size() > 0 ) ) {
        painter->setPen( QColor( Qt::black ) );
        QString text = tr( "Create a route or load a track from file to view its elevation profile." );
        painter->drawText( contentRect().toRect(), Qt::TextWordWrap | Qt::AlignCenter, text );
        painter->restore();
        return;
    }
    if ( m_zoomToViewport && ( m_lastVisiblePoint - m_firstVisiblePoint < 5 ) ) {
        painter->setPen( QColor( Qt::black ) );
        QString text = tr( "Not enough points in the current viewport.\nTry to disable 'Zoom to viewport'." );
        painter->drawText( contentRect().toRect(), Qt::TextWordWrap | Qt::AlignCenter, text );
        painter->restore();
        return;
    }

    QString intervalStr;
    int lastStringEnds;

    // draw viewport bounds
    if ( ! m_zoomToViewport && ( m_firstVisiblePoint > 0 || m_lastVisiblePoint < m_eleData.size() - 1 ) ) {
        QColor color( Qt::black );
        color.setAlpha( 64 );
        QRect rect;
        rect.setLeft( m_leftGraphMargin + m_eleData.value( m_firstVisiblePoint ).x() * m_eleGraphWidth / m_axisX.range() );
        rect.setTop( 0 );
        rect.setWidth( ( m_eleData.value( m_lastVisiblePoint ).x() - m_eleData.value( m_firstVisiblePoint ).x() ) * m_eleGraphWidth / m_axisX.range() );
        rect.setHeight( m_eleGraphHeight );
        painter->fillRect( rect, color );
    }

    // draw X and Y axis
    painter->setPen( Oxygen::aluminumGray4 );
    painter->drawLine( m_leftGraphMargin, m_eleGraphHeight, contentSize().width(), m_eleGraphHeight );
    painter->drawLine( m_leftGraphMargin, m_eleGraphHeight, m_leftGraphMargin, 0 );

    // draw Y grid and labels
    painter->setPen( QColor( Qt::black ) );
    QPen dashedPen( Qt::DashLine );
    dashedPen.setColor( Oxygen::aluminumGray4 );
    QRect labelRect( 0, 0, m_leftGraphMargin - 1, m_fontHeight + 2 );
    lastStringEnds = m_eleGraphHeight + m_fontHeight;
//     painter->drawText( m_leftGraphMargin + 1, m_fontHeight, "[" + m_axisY.unit() + "]" );
    foreach ( const AxisTick &tick, m_axisY.ticks() ) {
        const int posY = m_eleGraphHeight - tick.position;
        painter->setPen( dashedPen );
        painter->drawLine( m_leftGraphMargin, posY, contentSize().width(), posY );

        labelRect.moveCenter( QPoint( labelRect.center().x(), posY ) );
        if ( labelRect.top() < 0 ) {
            // don't cut off uppermost label
            labelRect.moveTop( 0 );
        }
        if ( labelRect.bottom() >= lastStringEnds ) {
            // Don't print overlapping labels
            continue;
        }
        lastStringEnds = labelRect.top();
        painter->setPen( QColor( Qt::black ) );
        intervalStr.setNum( tick.value * m_axisY.scale() );
        painter->drawText( labelRect, Qt::AlignRight, intervalStr );
    }

    // draw X grid and labels
    painter->setPen( QColor( Qt::black ) );
    labelRect.moveTop( m_eleGraphHeight + 1 );
    lastStringEnds = 0;
    foreach ( const AxisTick &tick, m_axisX.ticks() ) {
        const int posX = m_leftGraphMargin + tick.position;
        painter->setPen( dashedPen );
        painter->drawLine( posX, 0, posX, m_eleGraphHeight );

        intervalStr.setNum( tick.value * m_axisX.scale() );
        if ( tick.position == m_axisX.ticks().last().position ) {
            intervalStr += ' ' + m_axisX.unit();
        }
        labelRect.setWidth( QFontMetricsF( font() ).width( intervalStr ) * 1.5 );
        labelRect.moveCenter( QPoint( posX, labelRect.center().y() ) );
        if ( labelRect.right() > m_leftGraphMargin + m_eleGraphWidth ) {
            // don't cut off rightmost label
            labelRect.moveRight( m_leftGraphMargin + m_eleGraphWidth );
        }
        if ( labelRect.left() <= lastStringEnds ) {
            // Don't print overlapping labels
            continue;
        }
        lastStringEnds = labelRect.right();
        painter->setPen( QColor( Qt::black ) );
        painter->drawText( labelRect, Qt::AlignCenter, intervalStr );
    }

    // display elevation gain/loss data
    painter->setPen( QColor( Qt::black ) );
    intervalStr = tr( "Difference: %1 %2" )
                   .arg( QString::number( m_gain - m_loss, 'f', 0 ) )
                   .arg( m_axisY.unit() );
    intervalStr += QString::fromUtf8( "  (↗ %1 %3  ↘ %2 %3)" )
                   .arg( QString::number( m_gain, 'f', 0 ) )
                   .arg( QString::number( m_loss, 'f', 0 ) )
                   .arg( m_axisY.unit() );
    painter->drawText( contentRect().toRect(), Qt::AlignBottom | Qt::AlignCenter, intervalStr );

    // draw elevation profile
    painter->setPen( QColor( Qt::black ) );
    bool const highRes = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::HighResolution;
    QPen pen = painter->pen();
    pen.setWidth( highRes ? 2 : 1 );
    painter->setPen( pen );

    QLinearGradient fillGradient( 0, 0, 0, m_eleGraphHeight );
    QColor startColor = Oxygen::forestGreen4;
    QColor endColor = Oxygen::hotOrange4;
    startColor.setAlpha( 200 );
    endColor.setAlpha( 32 );
    fillGradient.setColorAt( 0.0, startColor );
    fillGradient.setColorAt( 1.0, endColor );
    QBrush brush = QBrush( fillGradient );
    painter->setBrush( brush );

    QPoint oldPos;
    oldPos.setX( m_leftGraphMargin );
    oldPos.setY( ( m_axisY.minValue() - m_axisY.minValue() )
                 * m_eleGraphHeight / ( m_axisY.range() / m_shrinkFactorY ) );
    oldPos.setY( m_eleGraphHeight - oldPos.y() );
    QPainterPath path;
    path.moveTo( oldPos.x(), m_eleGraphHeight );
    path.lineTo( oldPos.x(), oldPos.y() );

    const int start = m_zoomToViewport ? m_firstVisiblePoint : 0;
    const int end = m_zoomToViewport ? m_lastVisiblePoint : m_eleData.size() - 1;
    for ( int i = start; i <= end; ++i ) {
        QPoint newPos;
        if ( i == start ) {
            // make sure the plot always starts at the y-axis
            newPos.setX( 0 );
        } else {
            newPos.setX( ( m_eleData.value(i).x() - m_axisX.minValue() ) * m_eleGraphWidth / m_axisX.range() );
        }
        newPos.rx() += m_leftGraphMargin;
        if ( newPos.x() != oldPos.x() || newPos.y() != oldPos.y()  ) {
            newPos.setY( ( m_eleData.value(i).y() - m_axisY.minValue() )
                         * m_eleGraphHeight / ( m_axisY.range() * m_shrinkFactorY ) );
            newPos.setY( m_eleGraphHeight - newPos.y() );
            path.lineTo( newPos.x(), newPos.y() );
            oldPos = newPos;
        }
    }
    path.lineTo( oldPos.x(), m_eleGraphHeight );
    // fill
    painter->setPen( QPen( Qt::NoPen ) );
    painter->drawPath( path );
    // contour
    // "remove" the first and last path element first, they are only used to fill down to the bottom
    painter->setBrush( QBrush( Qt::NoBrush ) );
    path.setElementPositionAt( 0, path.elementAt( 1 ).x,  path.elementAt( 1 ).y );
    path.setElementPositionAt( path.elementCount()-1,
                               path.elementAt( path.elementCount()-2 ).x,
                               path.elementAt( path.elementCount()-2 ).y );
    painter->setPen( pen );
    painter->drawPath( path );

    pen.setWidth( 1 );
    painter->setPen( pen );

    // draw interactive cursor
    const GeoDataCoordinates currentPoint = m_markerPlacemark->coordinate();
    if ( currentPoint.isValid() ) {
        painter->setPen( QColor( Qt::white ) );
        painter->drawLine( m_leftGraphMargin + m_cursorPositionX, 0,
                           m_leftGraphMargin + m_cursorPositionX, m_eleGraphHeight );
        qreal xpos = m_axisX.minValue() + ( m_cursorPositionX / m_eleGraphWidth ) * m_axisX.range();
        qreal ypos = m_eleGraphHeight - ( ( currentPoint.altitude() - m_axisY.minValue() ) / ( qMax<qreal>( 1.0, m_axisY.range() ) * m_shrinkFactorY ) ) * m_eleGraphHeight;

        painter->drawLine( m_leftGraphMargin + m_cursorPositionX - 5, ypos,
                           m_leftGraphMargin + m_cursorPositionX + 5, ypos );
        intervalStr.setNum( xpos * m_axisX.scale(), 'f', 2 );
        intervalStr += ' ' + m_axisX.unit();
        int currentStringBegin = m_leftGraphMargin + m_cursorPositionX
                             - QFontMetricsF( font() ).width( intervalStr ) / 2;
        painter->drawText( currentStringBegin, contentSize().height() - 1.5 * m_fontHeight, intervalStr );

        intervalStr.setNum( currentPoint.altitude(), 'f', 1 );
        intervalStr += ' ' + m_axisY.unit();
        if ( m_cursorPositionX + QFontMetricsF( font() ).width( intervalStr ) + m_leftGraphMargin
                < m_eleGraphWidth ) {
            currentStringBegin = ( m_leftGraphMargin + m_cursorPositionX + 5 + 2 );
        } else {
            currentStringBegin = m_leftGraphMargin + m_cursorPositionX - 5
                                 - QFontMetricsF( font() ).width( intervalStr ) * 1.5;
        }
        // Make sure the text still fits into the window
        while ( ypos < m_fontHeight ) {
            ypos++;
        }
        painter->drawText( currentStringBegin, ypos + m_fontHeight / 2, intervalStr );
    }

    painter->restore();
}
Example #4
0
void ExportXML::save(const QString& f){
    //file=f;
    ProjetManager& PM = ProjetManager::getInstance();
    Agenda& A = Agenda::getInstance();
    QFile newfile(f);
    if (!newfile.open(QIODevice::WriteOnly | QIODevice::Text))
        throw AgendaException(QString("erreur sauvegarde tâches : ouverture fichier xml"));
    QXmlStreamWriter stream(&newfile);
    stream.setAutoFormatting(true);
    stream.writeStartDocument();
    stream.writeStartElement("projectcalendar");
    //Liste des projets dans la balise <projets>
    stream.writeStartElement("projets");
    for(ProjetManager::projets_iterator it1 = PM.begin_projets() ; it1 != PM.end_projets() ; ++it1){
        //chaque projet est dans une balise <projet>
        stream.writeStartElement("projet");
        stream.writeTextElement("identificateur",(*it1)->getId());
        stream.writeTextElement("titre",(*it1)->getTitre());
        stream.writeTextElement("description",(*it1)->getDesc());
        stream.writeTextElement("disponibilite",(*it1)->getDispo().toString(Qt::ISODate));
        stream.writeTextElement("echeance",(*it1)->getEcheance().toString(Qt::ISODate));
        //Liste des taches du projet et de leurs programmations dans une balise <taches>
        stream.writeStartElement("taches");
        for(Projet::taches_iterator it2 = (*it1)->begin_taches() ; it2 != (*it1)->end_taches() ; ++it2){
            //Chaque tache dans une balise <tache>
            stream.writeStartElement("tache");
            //Met l'attribut preemptive à true si tache préemptable, false sinon
            if (typeid(**it2) == typeid(TachePreemptable))
                stream.writeAttribute("preemptive", "true");
            else
                stream.writeAttribute("preemptive", "false");
            //Met l'attribut composite à true si tache composite, false sinon
            if (typeid(**it2) == typeid(TacheComposite))
                stream.writeAttribute("composite", "true");
            else
                stream.writeAttribute("composite", "false");
            //Met l'attribut unitaire à true si tache unitaire, false sinon
            if (typeid(**it2) == typeid(TacheUnitaire))
                stream.writeAttribute("unitaire", "true");
            else
                stream.writeAttribute("unitaire", "false");

            stream.writeTextElement("identificateur",(*it2)->getId());
            stream.writeTextElement("titre",(*it2)->getTitre());
            stream.writeTextElement("disponibilite",(*it2)->getDate().toString(Qt::ISODate));
            stream.writeTextElement("echeance",(*it2)->getEcheance().toString(Qt::ISODate));
            //Durée uniquement si tache unitaire
            if ((typeid(**it2) ==  typeid(TacheUnitaire)) || (typeid(**it2) == typeid(TachePreemptable))){
                QString str;
                str.setNum((*it2)->getDuree().getDureeEnMinutes());
                stream.writeTextElement("duree",str);
            }

            //Programmation si la tâche est programmée
            if ((*it2)->getStatus()){ // La Tache est programmée nous écrivons ici sa programmation
                Programmation* prog = A.trouverProgrammation(*it2);
                if (prog){
                    stream.writeStartElement("programmation");
                    stream.writeTextElement("date",prog->getDate().toString(Qt::ISODate));
                    stream.writeTextElement("heure", prog->getHoraire().toString());
                    stream.writeEndElement(); // Fin <programmation>
                }
            }

            stream.writeEndElement();// Fin <tache>
        }
        stream.writeEndElement(); // Fin <taches>
        stream.writeEndElement(); // Fin <projet>
    }
    stream.writeEndElement(); // Fin <projets>

    //Liste des précédences de Taches dans la balise <precedences>
    stream.writeStartElement("precedences");
    for(ProjetManager::projets_iterator it1 = PM.begin_projets() ; it1 != PM.end_projets() ; ++it1){ //Itération sur les projets
        for(Projet::taches_iterator it2 = (*it1)->begin_taches() ; it2 != (*it1)->end_taches() ; ++it2){ //Itération sur les taches du projet
            if ((*it2)->withPrecedence()){ //La tache a des contraintes de precedence
                stream.writeStartElement("precedence");
                stream.writeAttribute("id_projet", (*it1)->getId());
                stream.writeAttribute("id_tache", (*it2)->getId());
                for(precedences_iterator it3 = (*it2)->begin_precedences() ; it3 != (*it2)->end_precedences() ; ++it3) //Pour chaque tache, itération sur les taches précédentes
                    stream.writeTextElement("id_precedence", (*it3)->getId());
                stream.writeEndElement(); // Fin <precedence>
            }
        }
    }
    stream.writeEndElement(); // Fin <precedences>

    //Liste des composants pour les taches compositees
    stream.writeStartElement("composites");
    for(ProjetManager::projets_iterator it1 = PM.begin_projets() ; it1 != PM.end_projets() ; ++it1){ //Itération sur les projets
        for(Projet::taches_iterator it2 = (*it1)->begin_taches() ; it2 != (*it1)->end_taches() ; ++it2){ //Itération sur les taches du projet
            if (typeid(**it2) == typeid(TacheComposite)){
                soustaches_iterator it3 = (*it2)->begin_soustaches();
                if (it3 != (*it2)->end_soustaches()) { //on teste si la tache a des taches composants
                    stream.writeStartElement("composite");
                    stream.writeAttribute("id_projet", (*it1)->getId());
                    stream.writeAttribute("id_tache", (*it2)->getId());
                    for(it3 = (*it2)->begin_soustaches() ; it3 != (*it2)->end_soustaches() ; ++it3) //Pour chaque tache, itération sur les sous taches
                        stream.writeTextElement("id_composant", (*it3)->getId());
                    stream.writeEndElement(); // Fin <composite>
                }
            }
        }
    }
    stream.writeEndElement(); // Fin <composites>

    //Liste des activités et de leurs programmations
    stream.writeStartElement("activites");
    ActiviteManager& AM = ActiviteManager::getInstance();
    for(ActiviteManager::activites_iterator it1 = AM.begin_activites() ; it1 != AM.end_activites() ; ++it1){
        stream.writeStartElement("activite");
        //Met l'attribut reunion à true si c'est une reunion, false sinon
        if (typeid(**it1) == typeid(Reunion))
            stream.writeAttribute("reunion", "true");
        else
            stream.writeAttribute("reunion", "false");
        //Met l'attribut rdv à true si c'est un rdv, false sinon
        if (typeid(**it1) == typeid(Rdv))
            stream.writeAttribute("rdv", "true");
        else
            stream.writeAttribute("rdv", "false");
        stream.writeTextElement("identificateur",(*it1)->getId());
        stream.writeTextElement("titre",(*it1)->getTitre());
        stream.writeTextElement("disponibilite",(*it1)->getDate().toString(Qt::ISODate));
        stream.writeTextElement("echeance",(*it1)->getEcheance().toString(Qt::ISODate));
        QString str;
        str.setNum((*it1)->getDuree().getDureeEnMinutes());
        stream.writeTextElement("duree",str);
        stream.writeTextElement("lieu",(*it1)->getLieu());
        if (typeid(**it1) == typeid(Reunion)){ // C'est un réunion, on ajoute la liste des participants
            stream.writeStartElement("participants");
            //for(int i = 0 ; i < (*it1)->getNbParticipants() ; i++){
            for(participants_iterator it2 = (*it1)->begin_participants() ; it2 != (*it1)->end_participants() ; ++it2){
                stream.writeTextElement("participant",*it2);
            }
            stream.writeEndElement();// Fin <participants
        }
        if (typeid(**it1) == typeid(Rdv)){ //C'est un rdv, on ajoute l'interlocuteur du rdv
            stream.writeTextElement("interlocuteur", (*it1)->getInterlocuteur());
        }
        //Programmation si l'activité est programmée
        if ((*it1)->getStatus()){ // L'a Tache 'activité est programmée nous écrivons ici sa programmation
            Programmation* prog = A.trouverProgrammation(*it1);
            if (prog){
                stream.writeStartElement("programmation");
                stream.writeTextElement("date",prog->getDate().toString(Qt::ISODate));
                stream.writeTextElement("heure", prog->getHoraire().toString());
                stream.writeEndElement(); // Fin <programmation>
            }
        }
        stream.writeEndElement(); // Fin <activite>
    }
    stream.writeEndElement(); // Fin <activites>
    stream.writeEndElement(); // Fin <projectcalendar>
    stream.writeEndDocument();
    newfile.close();
}
Example #5
0
void FDialogPreview::GenPreview(QString name)
{
	QPixmap pm;
	QString Buffer = "";
	updtPix();
	if (name.isEmpty())
		return;
	QFileInfo fi = QFileInfo(name);
	if (fi.isDir())
		return;
	int w = pixmap()->width();
	int h = pixmap()->height();
	bool mode = false;
	QString ext = fi.suffix().toLower();
	QString formatD(FormatsManager::instance()->extensionListForFormat(FormatsManager::IMAGESIMGFRAME, 1));
 	QStringList formats = formatD.split("|");
	formats.append("pat");
	
	QStringList allFormatsV = LoadSavePlugin::getExtensionsForPreview(FORMATID_ODGIMPORT);
	if (ext.isEmpty())
		ext = getImageType(name);
	if (formats.contains(ext.toUtf8()))
	{
		ScImage im;
		//No doc to send data anyway, so no doc to get into scimage.
		CMSettings cms(0, "", Intent_Perceptual);
		cms.allowColorManagement(false);
		if (im.loadPicture(name, 1, cms, ScImage::Thumbnail, 72, &mode))
		{
			int ix,iy;
			if ((im.imgInfo.exifDataValid) && (!im.imgInfo.exifInfo.thumbnail.isNull()))
			{
				ix = im.imgInfo.exifInfo.width;
				iy = im.imgInfo.exifInfo.height;
			}
			else
			{
				ix = im.width();
				iy = im.height();
			}
			int xres = im.imgInfo.xres;
			int yres = im.imgInfo.yres;
			QString tmp = "";
			QString tmp2 = "";
			QImage im2 = im.scaled(w - 5, h - 44, Qt::KeepAspectRatio, Qt::SmoothTransformation);
			QPainter p;
			QBrush b(QColor(205,205,205), loadIcon("testfill.png"));
			// Qt4 FIXME imho should be better
			pm = *pixmap();
			p.begin(&pm);
			p.fillRect(0, 0, w, h-44, b);
			p.fillRect(0, h-44, w, 44, QColor(255, 255, 255));
			p.drawImage((w - im2.width()) / 2, (h - 44 - im2.height()) / 2, im2);
			p.drawText(2, h-29, tr("Size:")+" "+tmp.setNum(ix)+" x "+tmp2.setNum(iy));
			p.drawText(2, h-17, tr("Resolution:")+" "+tmp.setNum(xres)+" x "+tmp2.setNum(yres)+" "+ tr("DPI"));
			QString cSpace;
			if ((extensionIndicatesPDF(ext) || extensionIndicatesEPSorPS(ext)) && (im.imgInfo.type != ImageType7))
				cSpace = tr("Unknown");
			else
				cSpace=colorSpaceText(im.imgInfo.colorspace);
			p.drawText(2, h-5, tr("Colorspace:")+" "+cSpace);
			p.end();
			setPixmap(pm);
			repaint();
		}
	}
	else if (allFormatsV.contains(ext.toUtf8()))
	{
		FileLoader *fileLoader = new FileLoader(name);
		int testResult = fileLoader->TestFile();
		delete fileLoader;
		if ((testResult != -1) && (testResult >= FORMATID_ODGIMPORT))
		{
			const FileFormat * fmt = LoadSavePlugin::getFormatById(testResult);
			if( fmt )
			{
				QImage im = fmt->readThumbnail(name);
				if (!im.isNull())
				{
					QString desc = tr("Size:")+" ";
					desc += value2String(im.text("XSize").toDouble(), PrefsManager::instance()->appPrefs.docSetupPrefs.docUnitIndex, true, true);
					desc += " x ";
					desc += value2String(im.text("YSize").toDouble(), PrefsManager::instance()->appPrefs.docSetupPrefs.docUnitIndex, true, true);
					im = im.scaled(w - 5, h - 21, Qt::KeepAspectRatio, Qt::SmoothTransformation);
					QPainter p;
					QBrush b(QColor(205,205,205), loadIcon("testfill.png"));
					pm = *pixmap();
					p.begin(&pm);
					p.fillRect(0, 0, w, h-21, b);
					p.fillRect(0, h-21, w, 21, QColor(255, 255, 255));
					p.drawImage((w - im.width()) / 2, (h - 21 - im.height()) / 2, im);
					p.drawText(2, h-5, desc);
					p.end();
					setPixmap(pm);
					repaint();
				}
			}
		}
	}
	else if (ext.toUtf8() == "sml")
	{
		QPixmap pmi;
		QByteArray cf;
		if (loadRawText(name, cf))
		{
			QString f = QString::fromUtf8(cf.data());
			StencilReader *pre = new StencilReader();
			pmi = pre->createPreview(f);
			QImage im = pmi.toImage();
			im = im.scaled(w - 5, h - 21, Qt::KeepAspectRatio, Qt::SmoothTransformation);
			QPainter p;
			QBrush b(QColor(205,205,205), loadIcon("testfill.png"));
			pm = *pixmap();
			p.begin(&pm);
			p.fillRect(0, 0, w, h-21, b);
			p.fillRect(0, h-21, w, 21, QColor(255, 255, 255));
			p.drawImage((w - im.width()) / 2, (h - 21 - im.height()) / 2, im);
			QString desc = tr("Size:")+QString(" %1 x %2").arg(im.width()).arg(im.height());
			p.drawText(2, h-5, desc);
			p.end();
			setPixmap(pm);
			repaint();
			delete pre;
		}
	}
	else if (ext.toUtf8() == "shape")
	{
		QByteArray cf;
		if (loadRawText(name, cf))
		{
			QString f = QString::fromUtf8(cf.data());
			StencilReader *pre = new StencilReader();
			QString f2 = pre->createShape(f);
			ScPreview *pre2 = new ScPreview();
			QImage im = pre2->createPreview(f2);
			im = im.scaled(w - 5, h - 21, Qt::KeepAspectRatio, Qt::SmoothTransformation);
			QPainter p;
			QBrush b(QColor(205,205,205), loadIcon("testfill.png"));
			pm = *pixmap();
			p.begin(&pm);
			p.fillRect(0, 0, w, h-21, b);
			p.fillRect(0, h-21, w, 21, QColor(255, 255, 255));
			p.drawImage((w - im.width()) / 2, (h - 21 - im.height()) / 2, im);
			QString desc = tr("Size:")+QString(" %1 x %2").arg(im.width()).arg(im.height());
			p.drawText(2, h-5, desc);
			p.end();
			setPixmap(pm);
			repaint();
			delete pre;
			delete pre2;
		}
	}
	else if (ext.toUtf8() == "sce")
	{
		QByteArray cf;
		if (loadRawText(name, cf))
		{
			QString f;
			if (cf.left(16) == "<SCRIBUSELEMUTF8")
				f = QString::fromUtf8(cf.data());
			else
				f = cf.data();
			ScPreview *pre = new ScPreview();
			QImage im = pre->createPreview(f);
			im = im.scaled(w - 5, h - 21, Qt::KeepAspectRatio, Qt::SmoothTransformation);
			QPainter p;
			QBrush b(QColor(205,205,205), loadIcon("testfill.png"));
			pm = *pixmap();
			p.begin(&pm);
			p.fillRect(0, 0, w, h-21, b);
			p.fillRect(0, h-21, w, 21, QColor(255, 255, 255));
			p.drawImage((w - im.width()) / 2, (h - 21 - im.height()) / 2, im);
			QString desc = tr("Size:")+QString(" %1 x %2").arg(im.width()).arg(im.height());
			p.drawText(2, h-5, desc);
			p.end();
			setPixmap(pm);
			repaint();
			delete pre;
		}
	}
	else
	{
		ScSlaInfoReader slaInfos;
		if (slaInfos.readInfos(name))
		{
			QString Title = tr("Title:")+" ";
			QString ti2 = slaInfos.title();
			if (ti2.isEmpty())
				ti2= tr("No Title");
			Title += ti2+"\n";
			QString Author = tr("Author:")+" ";
			QString au2 = slaInfos.author();
			if (au2.isEmpty())
				au2 = tr("Unknown");
			Author += au2+"\n";
			QString Format =  tr("File Format:")+" ";
			QString fm2 = slaInfos.format();
			if (fm2.isEmpty())
				fm2 = tr("Unknown");
			Format += fm2;
			setText( tr("Scribus Document")+"\n\n"+Title+Author+Format);
		}
		else  if ((ext == "txt") || (ext == "html") || (ext == "xml"))
		{
			if (loadText(name, &Buffer))
				setText(Buffer.left(200));
		}
	}
}
Example #6
0
void MidiController::write(int level, Xml& xml) const
{
      ControllerType t = midiControllerType(_num);
      if(t == Velo)
        return;
        
      QString type(int2ctrlType(t));

      int h = (_num >> 8) & 0x7f;
      int l = _num & 0x7f;

      QString sl;
      if (isPerNoteController())
            sl = "pitch";
      else
            sl.setNum(l);

      xml.nput(level, "<Controller name=\"%s\"", Xml::xmlString(_name).toLatin1().constData());
      if(t != Controller7)
        xml.nput(" type=\"%s\"", type.toLatin1().constData());
      
      int mn = 0;
      int mx = 0; 
      switch (t) 
      {
            case RPN:
            case NRPN:
                  xml.nput(" h=\"%d\"", h);
                  xml.nput(" l=\"%s\"", sl.toLatin1().constData());
                  mx = 127;
                  break;
            case Controller7:
                  xml.nput(" l=\"%s\"", sl.toLatin1().constData());
                  mx = 127;
                  break;
            case Controller14:
            case RPN14:
            case NRPN14:
                  xml.nput(" h=\"%d\"", h);
                  xml.nput(" l=\"%s\"", sl.toLatin1().constData());
                  mx = 16383;
                  break;
            case Pitch:
                  mn = -8192;
                  mx = 8191;
                  break;
            case PolyAftertouch:
                  mn = 0;
                  mx = 127;
                  break;
            case Aftertouch: 
                  mn = 0;
                  mx = 127;
                  break;
            case Program:
            case Velo:        // Cannot happen
                  break;
      }
      
      if(t == Program)
      {
        if(_initVal != CTRL_VAL_UNKNOWN && _initVal != 0xffffff)
          xml.nput(" init=\"0x%x\"", _initVal);
      }
      else
      {
        if(_minVal != mn)     
          xml.nput(" min=\"%d\"", _minVal);
        if(_maxVal != mx)     
          xml.nput(" max=\"%d\"", _maxVal);
        
        if(_initVal != CTRL_VAL_UNKNOWN)     
          xml.nput(" init=\"%d\"", _initVal);
      }

      if(_showInTracks != (ShowInDrum | ShowInMidi))
          xml.nput(" showType=\"%d\"", _showInTracks);
        
      xml.put(" />");
}
void GImageSaver::ProcessImageAOIed(const GImageDouble & aoiImage)
{
	IncrementCountProcessed();
	QString fileName = m_Folder;
 	fileName += "\\";
	fileName += QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss.zzz");
	//fileName += ".png";
	QPixmap::fromImage(aoiImage).save(fileName + "_8bit.png");//Gael's original implementation which saves 8-bit QImage.
	
	
	//Shared things for next two if() statements: 
	double* doubleArrayToSave = aoiImage.DoubleArray().data();//Get access to desired DoubleArray.
	uint ulength = aoiImage.width()*aoiImage.height();
	int length = aoiImage.width()*aoiImage.height();
	QString height;
	QString width;
	height.setNum(aoiImage.height());
	width.setNum(aoiImage.width());
	if(m_SaveDouble){
		//2015-06-24 Bart: Trying again to save DoubleArray directly to avoid converting to 8-bit QImage first. 
		//Data is exported as raw binary data file, without separating rows or columns. 
		//The row and column sizes are saved in the file name, so you can reassemble the image later. 
		//Each pixel data point is a double, which is saved as 8 characters. 
		//This works, but double's are huge with unused bytes, so 500x500 AOI ends up taking about 2 megabytes on disk. 
		QFile fileHQ;
		fileHQ.setFileName(fileName + "_Double[width=" + width + ";height=" + height + "].dat");
		fileHQ.open(QFile::WriteOnly);
		//debugging tests: passed! 
		//qDebug()<<"File length should be "<<length<<" times sizeof(doule) = "<<sizeof(double);
		//qDebug()<<"Attempting to save high quality file, num bytes written:"<< //next line goes here
		fileHQ.write((const char*) doubleArrayToSave, ulength*sizeof(double));//following internet's example here...
		fileHQ.flush();
		fileHQ.close();
	}
	if(m_Save12bit){
		//2015-06-24 Bart: Now trying to save high quality image without huge file size! 
		//Goal here is ONLY to save raw imported camera images with 2-bytes/pixel; this will NOT work with processed optical depth, etc. 
		//Essentially, this is the reverse process of what I did with GUEyeImageDistributor:BufferToTreat() for 12-bit images. 
		QFile file12bit;
		file12bit.setFileName(fileName + "_2BytesPerPixel[width=" + width + ";height=" + height + "].dat");
		file12bit.open(QFile::WriteOnly);
		//file12bit.write(ByteArrayToSave);
		QDataStream out(&file12bit);
		//ushort tempvalue;
		for(int iTot=0; iTot<length; iTot++){
			//out << doubleArrayToSave[iTot];//testing,exports double values, appears to work because filesize is as large as expected.
			//qDebug()<<doubleArrayToSave[iTot];//testing
			//memcpy(&tempvalue,&doubleArrayToSave[iTot],sizeof(ushort));//get 2 byte unit from double
			//out << tempvalue;
			//qDebug() << tempvalue;

			//Try just forcing conversion to ushort: SEEMS TO WORK? 
			out << (ushort)doubleArrayToSave[iTot];
			//qDebug()<<(ushort)doubleArrayToSave[iTot];//testing
		}
		file12bit.flush();
		file12bit.close();

		//Trying some random things: 
		//Try PNG with quality set to 100 (highest value, lowest compression.): 
		//QPixmap::fromImage(aoiImage).save(fileName + "_PixMap100.png",0,100);//This saves 735 kB vs 19 kB PNGs with same information b/c least compressed? 
		//Try PGM format:  Saves as 8-bit because loaded from aoiImage. Can do 2-byte if could import values in different way! 
		//QPixmap::fromImage(aoiImage).save(fileName + "_PixMap100fromImage.pgm",0,100);//This saves QImage as 8-bit PGM format (245 kB vs 19 kB default PNG). 
		//Doesn't work... 
		//QPixmap MapToSave; 
		//qDebug()<<"Try to load map from data: " << MapToSave.loadFromData((const uchar*) doubleArrayToSave, length*sizeof(double));
		//MapToSave.save(fileName + "_PixMap100fromData.pgm",0,100);
	}
}
Example #8
0
void Wykres::paintEvent( QPaintEvent* event )
{
    if(Width != PARENT->width() || Height != PARENT->height())
    {
       this->resize(PARENT->width(),PARENT->height());
       //update();
    }
    if(rysuj)
    {
        x0 = 32;
        y0 = this->height()-x0;
        // Stops compiler from complaining about unused
        // variable
        Q_UNUSED( event );

        QPainter painter(this);
        painter.begin(this);
        QPen pen;

        painter.setPen(pen);
        //painter.setRenderHint (QPainter::Antialiasing);
        painter.setBrush(QBrush(Qt::red, Qt::SolidPattern));
        QPoint pointStart;
        QPoint pointStop;
        pointStart.setX(x0);
        pointStart.setY(0);
        pointStop.setX(x0);
        pointStop.setY(this->height()-(x0/6));
        painter.drawLine(pointStart, pointStop); //os pionowa
        pointStart.setX(x0/6);
        pointStart.setY(this->height()-x0);
        pointStop.setX(this->width());
        pointStop.setY(this->height()-x0);
        painter.drawLine(pointStart, pointStop);//os pozioma


        int nD = wyniki.size();
        int max = maxValue() + 1;
        QString s;
        int szerokosc = ((this->width()-x0)/nD) - 0.1*((this->width()-x0)/nD);
        int odstep = 0.1 * szerokosc;
        int X = x0+odstep;



        for(int i=0; i<nD; i++)
        {
            qDebug() << wyniki[i]->getValue() << "wydatek: " << wyniki[i]->getWydatek();
            if(wyniki[i]->getWydatek() == 1)
            {
                painter.setBrush(QBrush(Qt::red, Qt::SolidPattern));
            }
            else
            {
                painter.setBrush(QBrush(Qt::blue, Qt::SolidPattern));
            }
            double wart = wyniki[i]->getValue();
            int wysokosc = ((this->width() -(this->width()-y0)-15) * wart)/max;
            painter.drawRect(QRect(X,this->height()-x0,szerokosc,-wysokosc));
            painter.drawText(QRectF(X-szerokosc/2,this->height()-x0-wysokosc-15,szerokosc,13),10,s.setNum(wart)); //nad

            X += odstep + szerokosc;
        }
        X = x0+odstep;
        painter.translate(this->width()/2,this->height()/2);
        painter.save();
        painter.rotate(270);
        for(int i=0; i<nD; i++)
        {
            painter.drawText(QRect(-(y0+x0-2)/2,(-width()/2)+ X+szerokosc/2,30,10), Qt::AlignCenter, wyniki[i]->getData()); //pod
            X += odstep + szerokosc;
        }
        painter.restore();

        painter.end();
    }

}
Example #9
0
void
XmitDetails::updateStatus(bool daemonResponding,
        const XmitStatus & xmitStatus) {
    // Based on whether the daemon is responding and the CMU is responding to
    // the daemon, set the "responding" label, and set the enabled state for
    // the rest of the components.
    if (daemonResponding && xmitStatus.serialConnected()) {
        _ui.respondingLabel->setText("");
        _ui.statusFrame->setEnabled(true);
    } else {
        if (daemonResponding) {
            _ui.respondingLabel->setText("<font color='DarkRed'>"
                    "CMU not responding to hcr_xmitd!</font>");
        } else {
            _ui.respondingLabel->setText("<font color='DarkRed'>"
                    "No hcr_xmitd!</font>");
        }
        _ui.statusFrame->setEnabled(false);
    }

    // PSM power
    _ui.psmPowerIcon->
        setPixmap(xmitStatus.psmPowerOn() ? _greenLED : _redLED);

    // fault lights
    _ui.modulatorFaultIcon->
        setPixmap(xmitStatus.modulatorFault() ? _redLED : _greenLED);
    _ui.syncFaultIcon->
        setPixmap(xmitStatus.syncFault() ? _redLED : _greenLED);
    _ui.xmitterTempFaultIcon->
        setPixmap(xmitStatus.xmitterTempFault() ? _redLED : _greenLED);
    _ui.wgArcFaultIcon->
        setPixmap(xmitStatus.waveguideArcFault() ? _redLED : _greenLED);
    _ui.collectorCurrFaultIcon->
        setPixmap(xmitStatus.collectorCurrentFault() ? _redLED : _greenLED);
    _ui.bodyCurrFaultIcon->
        setPixmap(xmitStatus.bodyCurrentFault() ? _redLED : _greenLED);
    _ui.filamentLorFaultIcon->
        setPixmap(xmitStatus.filamentLorFault() ? _redLED : _greenLED);
    _ui.focusElectrodeLorFaultIcon->
        setPixmap(xmitStatus.focusElectrodeLorFault() ? _redLED : _greenLED);
    _ui.cathodeLorFaultIcon->
        setPixmap(xmitStatus.cathodeLorFault() ? _redLED : _greenLED);
    _ui.inverterOverloadFaultIcon->
        setPixmap(xmitStatus.inverterOverloadFault() ? _redLED : _greenLED);
    _ui.extInterlockFaultIcon->
        setPixmap(xmitStatus.externalInterlockFault() ? _redLED : _greenLED);
    _ui.eikInterlockFaultIcon->
        setPixmap(xmitStatus.eikInterlockFault() ? _redLED : _greenLED);
    // fault counts
    _ui.modulatorFaultCount->
        setText(_countLabel(xmitStatus.modulatorFaultCount()));
    _ui.syncFaultCount->
        setText(_countLabel(xmitStatus.syncFaultCount()));
    _ui.xmitterTempFaultCount->
        setText(_countLabel(xmitStatus.xmitterTempFaultCount()));
    _ui.wgArcFaultCount->
        setText(_countLabel(xmitStatus.waveguideArcFaultCount()));
    _ui.collectorCurrFaultCount->
        setText(_countLabel(xmitStatus.collectorCurrentFaultCount()));
    _ui.bodyCurrFaultCount->
        setText(_countLabel(xmitStatus.bodyCurrentFaultCount()));
    _ui.filamentLorFaultCount->
        setText(_countLabel(xmitStatus.filamentLorFaultCount()));
    _ui.focusElectrodeLorFaultCount->
        setText(_countLabel(xmitStatus.focusElectrodeLorFaultCount()));
    _ui.cathodeLorFaultCount->
        setText(_countLabel(xmitStatus.cathodeLorFaultCount()));
    _ui.inverterOverloadFaultCount->
        setText(_countLabel(xmitStatus.inverterOverloadFaultCount()));
    _ui.extInterlockFaultCount->
        setText(_countLabel(xmitStatus.externalInterlockFaultCount()));
    _ui.eikInterlockFaultCount->
        setText(_countLabel(xmitStatus.eikInterlockFaultCount()));

    // latest fault times
    _ui.modulatorFaultTime->
        setText(_faultTimeLabel(xmitStatus.modulatorFaultTime()));
    _ui.syncFaultTime->
        setText(_faultTimeLabel(xmitStatus.syncFaultTime()));
    _ui.xmitterTempFaultTime->
        setText(_faultTimeLabel(xmitStatus.xmitterTempFaultTime()));
    _ui.wgArcFaultTime->
        setText(_faultTimeLabel(xmitStatus.waveguideArcFaultTime()));
    _ui.collectorCurrFaultTime->
        setText(_faultTimeLabel(xmitStatus.collectorCurrentFaultTime()));
    _ui.bodyCurrFaultTime->
        setText(_faultTimeLabel(xmitStatus.bodyCurrentFaultTime()));
    _ui.filamentLorFaultTime->
        setText(_faultTimeLabel(xmitStatus.filamentLorFaultTime()));
    _ui.focusElectrodeLorFaultTime->
        setText(_faultTimeLabel(xmitStatus.focusElectrodeLorFaultTime()));
    _ui.cathodeLorFaultTime->
        setText(_faultTimeLabel(xmitStatus.cathodeLorFaultTime()));
    _ui.inverterOverloadFaultTime->
        setText(_faultTimeLabel(xmitStatus.inverterOverloadFaultTime()));
    _ui.extInterlockFaultTime->
        setText(_faultTimeLabel(xmitStatus.externalInterlockFaultTime()));
    _ui.eikInterlockFaultTime->
        setText(_faultTimeLabel(xmitStatus.eikInterlockFaultTime()));

    QString txt;
    // Text displays for voltage, currents, and temperature
    txt.setNum(xmitStatus.cathodeVoltage(), 'f', 1);
    _ui.cathodeVoltageValue->setText(txt);

    txt.setNum(xmitStatus.collectorCurrent(), 'f', 1);
    _ui.collectorCurrentValue->setText(txt);

    txt.setNum(xmitStatus.bodyCurrent(), 'f', 1);
    _ui.bodyCurrentValue->setText(txt);

    txt.setNum(xmitStatus.xmitterTemp(), 'f', 1);
    _ui.xmitterTempValue->setText(txt);
}
Example #10
0
bool Fixture::saveXML(QDomDocument* doc, QDomElement* wksp_root) const
{
    QDomElement root;
    QDomElement tag;
    QDomText text;
    QString str;

    Q_ASSERT(doc != NULL);

    /* Fixture Instance entry */
    root = doc->createElement(KXMLFixture);
    wksp_root->appendChild(root);

    /* Manufacturer */
    tag = doc->createElement(KXMLQLCFixtureDefManufacturer);
    root.appendChild(tag);

    if (m_fixtureDef != NULL)
        text = doc->createTextNode(m_fixtureDef->manufacturer());
    else
        text = doc->createTextNode(KXMLFixtureGeneric);

    tag.appendChild(text);

    /* Model */
    tag = doc->createElement(KXMLQLCFixtureDefModel);
    root.appendChild(tag);

    if (m_fixtureDef != NULL)
        text = doc->createTextNode(m_fixtureDef->model());
    else
        text = doc->createTextNode(KXMLFixtureGeneric);

    tag.appendChild(text);

    /* Fixture mode */
    tag = doc->createElement(KXMLQLCFixtureMode);
    root.appendChild(tag);

    if (m_fixtureMode != NULL)
        text = doc->createTextNode(m_fixtureMode->name());
    else
        text = doc->createTextNode(KXMLFixtureGeneric);

    tag.appendChild(text);

    /* ID */
    tag = doc->createElement(KXMLFixtureID);
    root.appendChild(tag);
    str.setNum(id());
    text = doc->createTextNode(str);
    tag.appendChild(text);

    /* Name */
    tag = doc->createElement(KXMLFixtureName);
    root.appendChild(tag);
    text = doc->createTextNode(m_name);
    tag.appendChild(text);

    /* Universe */
    tag = doc->createElement(KXMLFixtureUniverse);
    root.appendChild(tag);
    str.setNum(universe());
    text = doc->createTextNode(str);
    tag.appendChild(text);

    /* Address */
    tag = doc->createElement(KXMLFixtureAddress);
    root.appendChild(tag);
    str.setNum(address());
    text = doc->createTextNode(str);
    tag.appendChild(text);

    /* Channel count */
    tag = doc->createElement(KXMLFixtureChannels);
    root.appendChild(tag);
    str.setNum(channels());
    text = doc->createTextNode(str);
    tag.appendChild(text);

    return true;
}
Example #11
0
KstObject::UpdateType LFIIOSource::update( int u ) 
{
  Q_UNUSED( u )

  KstObject::UpdateType updateType =  KstObject::NO_CHANGE;
  QString               strTemplate;
  QString               strName;
  fitsfile*             ffits;
  char                  charTemplate[ FLEN_CARD ];
  char                  charName[ FLEN_CARD ];
  long                  lNumFrames;
  long                  lMaxRepeat = 1;
  long                  lRepeat;
  long                  lWidth;
  int                   iColNumber;
  int                   iNumCols;
  int                   iStatus = 0;
  int                   iResult = 0;
  int                   iTypeCode;
  int                   i;

  _valid  = false;

  if( !_filename.isNull( ) && !_filename.isEmpty( ) )
  {
    iResult = fits_open_table( &ffits, _filename.ascii( ), READONLY, &iStatus );
    if( iResult == 0 )
    {
      //
      // determine size of data...
      //
      iResult = fits_get_num_cols( ffits, &iNumCols, &iStatus );
      if( iResult == 0 )
      {
        iResult = fits_get_num_rows( ffits, &lNumFrames, &iStatus );
        if( iResult == 0 )
        {
          _strListColNames.clear( );

          _valid = true;

          //
	        // need to multiply lNumFrames by the maximum value of the vector repeat value...
	        //
          for( i=0; i<iNumCols; i++ )
          {
            iStatus = 0;
            
            sprintf( charTemplate, "%d", i+1 );
            iResult = fits_get_colname( ffits, CASEINSEN, charTemplate, charName, &iColNumber, &iStatus );
            if( iResult == 0 )
            { 
              strName = charName;
              _strListColNames.append( strName );
            }
            else
            {
              strName.setNum( i );
              _strListColNames.append( strName );
            }
              
            iStatus = 0;
            iResult = fits_get_coltype( ffits, i+1, &iTypeCode, &lRepeat, &lWidth, &iStatus );
            if( iResult == 0 )
            {
              if( lRepeat > lMaxRepeat )
              {
                lMaxRepeat = lRepeat;
              }
            }
          }

          if( lNumFrames * lMaxRepeat != _numFrames )
	        {
            _numCols   = iNumCols;
            _numFrames = lNumFrames * lMaxRepeat;
            updateType = KstObject::UPDATE;
          }
        }
      }
      iStatus = 0;
      fits_close_file( ffits, &iStatus );   
    }
  }
  
  return updateType;
}
Example #12
0
void SkyView::paintEvent(QPaintEvent *)
{
	// Draw stuff in drawing area
	int w= width();
	int h= height();
	QPainter painter(this);
	painter.setPen(Qt::gray);
	QRect r1(0, 0, w-1, h-1);
	QBrush br1(Qt::white);
	painter.fillRect(r1, br1);

	draw_arc(painter, w/2, h / 2, 6);

	// draw the 45 degree circle
	int i = min(w, h);
	draw_arc(painter, w / 2, h / 2, (unsigned)((i - RM) * 0.7));

	painter.setPen(Qt::black);
	draw_arc(painter, w / 2, h / 2, (unsigned)(i - RM));
	
	int x, y;
	pol2cart(w, h, 0, 0, &x, &y);
	painter.drawText(x, y, "N");
	pol2cart(w, h, 90, 0, &x, &y);
	painter.drawText(x + 2, y, "E");
	pol2cart(w, h, 180, 0, &x, &y);
	painter.drawText(x, y + 10, "S");
	pol2cart(w, h, 270, 0, &x, &y);
	painter.drawText(x - 5, y, "W");

	if(gpsdata == NULL)
		return;

	QFont serifFont("Times", 6);
	painter.setFont(serifFont);
	
	/* Now draw the satellites... */
	for (int i = 0; i < gpsdata->satellites_visible; i++) {
		QColor col;
		pol2cart(w, h, (double)gpsdata->azimuth[i], 
				 (double)gpsdata->elevation[i], &x, &y);
		if (gpsdata->ss[i] < 10) 
			col= Qt::black;
		else if (gpsdata->ss[i] < 30)
			col= Qt::red;
		else if (gpsdata->ss[i] < 35)
			col= Qt::yellow;
		else if (gpsdata->ss[i] < 40)
			col= Qt::darkGreen;
		else
			col= Qt::green;

		painter.setPen(col);
		br1.setColor(col);
		painter.setBrush(br1);

		if (gpsdata->PRN[i] > GPS_PRNMAX) {
				/* SBAS satellites */
			QPoint vertices[5];

			vertices[0].setX(x);
			vertices[0].setY(y-IDIAM);
			vertices[1].setX(x+IDIAM);
			vertices[1].setY(y);
			vertices[2].setX(x);
			vertices[2].setY(y+IDIAM);
			vertices[3].setX(x-IDIAM);
			vertices[3].setY(y);
			vertices[4].setX(x);
			vertices[4].setY(y-IDIAM);

	
			if (gpsdata->used[i])
				painter.drawPolygon(vertices, 4);
			else
				painter.drawPolyline(vertices, 5);
	
		} else {
				/* ordinary GPS satellites */
			if (gpsdata->used[i])
				painter.drawChord(x - IDIAM, y - IDIAM, 2 * IDIAM + 1, 2 * IDIAM + 1, 0, 360 * 64);
			else
				painter.drawArc(x - IDIAM, y - IDIAM, 2 * IDIAM + 1, 2 * IDIAM + 1, 0, 360 * 64);
		}
		QString buf;
		buf.setNum(gpsdata->PRN[i]);
		painter.setPen(Qt::black);
		painter.drawText(x, y+14, buf);
	}
}
Example #13
0
void DeepSkyComponent::loadData()
{

    KStarsData* data = KStarsData::Instance();
    //Check whether we need to concatenate a split NGC/IC catalog
    //(i.e., if user has downloaded the Steinicke catalog)
    mergeSplitFiles();

    QList< QPair<QString,KSParser::DataTypes> > sequence;
    QList<int> widths;
    sequence.append(qMakePair(QString("Flag"), KSParser::D_QSTRING));
    widths.append(1);

    sequence.append(qMakePair(QString("ID"), KSParser::D_INT));
    widths.append(4);

    sequence.append(qMakePair(QString("suffix"), KSParser::D_QSTRING));
    widths.append(1);

    sequence.append(qMakePair(QString("RA_H"), KSParser::D_INT));
    widths.append(2);

    sequence.append(qMakePair(QString("RA_M"),KSParser::D_INT));
    widths.append(2);

    sequence.append(qMakePair(QString("RA_S"),KSParser::D_FLOAT));
    widths.append(4);

    sequence.append(qMakePair(QString("D_Sign"),KSParser::D_QSTRING));
    widths.append(2);

    sequence.append(qMakePair(QString("Dec_d"),KSParser::D_INT));
    widths.append(2);

    sequence.append(qMakePair(QString("Dec_m"),KSParser::D_INT));
    widths.append(2);

    sequence.append(qMakePair(QString("Dec_s"),KSParser::D_INT));
    widths.append(2);

    sequence.append(qMakePair(QString("BMag"),KSParser::D_QSTRING));
    widths.append(6);

    sequence.append(qMakePair(QString("type"),KSParser::D_INT));
    widths.append(2);

    sequence.append(qMakePair(QString("a"),KSParser::D_FLOAT));
    widths.append(6);

    sequence.append(qMakePair(QString("b"),KSParser::D_FLOAT));
    widths.append(6);

    sequence.append(qMakePair(QString("pa"),KSParser::D_QSTRING));
    widths.append(4);

    sequence.append(qMakePair(QString("PGC"),KSParser::D_INT));
    widths.append(7);

    sequence.append(qMakePair(QString("other cat"),KSParser::D_QSTRING));
    widths.append(4);

    sequence.append(qMakePair(QString("other1"),KSParser::D_QSTRING));
    widths.append(6);

    sequence.append(qMakePair(QString("other2"),KSParser::D_QSTRING));
    widths.append(6);

    sequence.append(qMakePair(QString("Messr"),KSParser::D_QSTRING));
    widths.append(2);

    sequence.append(qMakePair(QString("MessrNum"),KSParser::D_INT));
    widths.append(4);

    sequence.append(qMakePair(QString("Longname"),KSParser::D_QSTRING));
    //No width to be appended for last sequence object

    QString file_name = KSPaths::locate(QStandardPaths::GenericDataLocation, QString("ngcic.dat") );
    KSParser deep_sky_parser(file_name, '#', sequence, widths);

    deep_sky_parser.SetProgress( i18n("Loading NGC/IC objects"), 13444, 10 );
    qDebug() << "Loading NGC/IC objects";

    QHash<QString,QVariant> row_content;
    while (deep_sky_parser.HasNextRow()) {
        row_content = deep_sky_parser.ReadNextRow();

        QString iflag;
        QString cat;
        iflag = row_content["Flag"].toString().mid( 0, 1 ); //check for NGC/IC catalog flag
        /*
        Q_ASSERT(iflag == "I" || iflag == "N" || iflag == " ");
        // (spacetime): ^ Why an assert? Change in implementation of ksparser
        //  might result in crash for no reason.
        // n.b. We also allow non-NGC/IC objects which have a blank iflag
        */

        float mag(1000.0);
        int type, ingc, imess(-1), pa;
        int pgc, ugc;
        QString ss, name, name2, longname;
        QString cat2;

        // Designation
        if ( iflag == "I" ) cat = "IC";
        else if ( iflag == "N" ) cat = "NGC";

        ingc = row_content["ID"].toInt();  // NGC/IC catalog number
        if ( ingc==0 ) cat.clear(); //object is not in NGC or IC catalogs

        QString suffix = row_content["suffix"].toString(); // multipliticity suffixes, eg: the 'A' in NGC 4945A

        Q_ASSERT( suffix.isEmpty() || ( suffix.at( 0 ) >= QChar( 'A' ) && suffix.at( 0 ) <= QChar( 'Z' ) ) || (suffix.at( 0 ) >= QChar( 'a' ) && suffix.at( 0 ) <= QChar( 'z' ) ) );

        //coordinates
        int rah = row_content["RA_H"].toInt();
        int ram = row_content["RA_M"].toInt();
        float ras = row_content["RA_S"].toFloat();
        QString sgn = row_content["D_Sign"].toString();
        int dd = row_content["Dec_d"].toInt();
        int dm = row_content["Dec_m"].toInt();
        int ds = row_content["Dec_s"].toInt();

        if ( !( (0.0 <= rah && rah < 24.0) ||
             (0.0 <= ram && ram < 60.0) ||
             (0.0 <= ras && ras < 60.0) ||
             (0.0 <= dd && dd <= 90.0) ||
             (0.0 <= dm && dm < 60.0) ||
               (0.0 <= ds && ds < 60.0) ) ) {
          qDebug() << "Bad coordinates while processing NGC/IC object: " << cat << ingc;
          qDebug() << "RA H:M:S = " << rah << ":" << ram << ":" << ras << "; Dec D:M:S = " << dd << ":" << dm << ":" << ds;
          Q_ASSERT( false );
        }

        //Ignore lines with no coordinate values if not debugging
        if (rah==0 && ram==0 && ras==0)
            continue;

        //B magnitude
        ss = row_content["BMag"].toString();
        if (ss == "") { mag = 99.9f; } else { mag = ss.toFloat(); }

        //object type
        type = row_content["type"].toInt();

        //major and minor axes
        float a = row_content["a"].toFloat();
        float b = row_content["b"].toFloat();

        //position angle.  The catalog PA is zero when the Major axis
        //is horizontal.  But we want the angle measured from North, so
        //we set PA = 90 - pa.
        ss = row_content["pa"].toString();
        if (ss == "" ) { pa = 90; } else { pa = 90 - ss.toInt(); }

        //PGC number
        pgc = row_content["PGC"].toInt();

        //UGC number
        if (row_content["other cat"].toString().trimmed() == "UGC") {
            ugc = row_content["other1"].toString().toInt();
        } else {
            ugc = 0;
        }

        //Messier number
        if ( row_content["Messr"].toString().trimmed() == "M" ) {
            cat2 = cat;
            if ( ingc == 0 ) cat2.clear();
            cat = 'M';
            imess = row_content["MessrNum"].toInt();
        }

        longname = row_content["Longname"].toString();

        dms r;
        r.setH( rah, ram, int(ras) );
        dms d( dd, dm, ds );

        if ( sgn == "-" ) { d.setD( -1.0*d.Degrees() ); }

        bool hasName = true;
        QString snum;
        if (cat=="IC" || cat=="NGC") {
            snum.setNum(ingc);
	    name = cat + ' ' + ( ( suffix.isEmpty() ) ? snum : ( snum + suffix ) );
        } else if (cat == "M") {
            snum.setNum( imess );
            name = cat + ' ' + snum; // Note: Messier has no suffixes
            if (cat2 == "NGC" || cat2 == "IC") {
                snum.setNum( ingc );
		name2 = cat2 + ' ' + ( ( suffix.isEmpty() ) ? snum : ( snum + suffix ) );
            } else {
                name2.clear();
            }
        }
        else {
            if (!longname.isEmpty()) name = longname;
            else {
                hasName = false;
                name = i18n( "Unnamed Object" );
            }
        }

        name = i18nc("object name (optional)", name.toLatin1().constData());
        if (!longname.isEmpty())
            longname = i18nc("object name (optional)", longname.toLatin1().constData());

        // create new deepskyobject
        DeepSkyObject *o = 0;
        if ( type==0 ) type = 1; //Make sure we use CATALOG_STAR, not STAR
        o = new DeepSkyObject( type, r, d, mag, name, name2, longname, cat, a, b, pa, pgc, ugc );
        o->EquatorialToHorizontal( data->lst(), data->geo()->lat() );

        // Add the name(s) to the nameHash for fast lookup -jbb
        if ( hasName) {
            nameHash[ name.toLower() ] = o;
            if ( ! longname.isEmpty() ) nameHash[ longname.toLower() ] = o;
            if ( ! name2.isEmpty() ) nameHash[ name2.toLower() ] = o;
        }

        Trixel trixel = m_skyMesh->index(o);

        //Assign object to general DeepSkyObjects list,
        //and a secondary list based on its catalog.
        m_DeepSkyList.append( o );
        appendIndex( o, &m_DeepSkyIndex, trixel );

        if ( o->isCatalogM()) {
            m_MessierList.append( o );
            appendIndex( o, &m_MessierIndex, trixel );
        }
        else if (o->isCatalogNGC() ) {
            m_NGCList.append( o );
            appendIndex( o, &m_NGCIndex, trixel );
        }
        else if ( o->isCatalogIC() ) {
            m_ICList.append( o );
            appendIndex( o, &m_ICIndex, trixel );
        }
        else {
            m_OtherList.append( o );
            appendIndex( o, &m_OtherIndex, trixel );
        }

        // JM: VERY INEFFICIENT. Disabling for now until we figure out how to deal with dups. QSet?
        //if ( ! name.isEmpty() && !objectNames(type).contains(name))
        if ( ! name.isEmpty() )
            objectNames(type).append( name );

        //Add long name to the list of object names
        //if ( ! longname.isEmpty() && longname != name  && !objectNames(type).contains(longname))
        if ( ! longname.isEmpty() && longname != name)
            objectNames(type).append( longname );

        deep_sky_parser.ShowProgress();
    }

    foreach(QStringList list, objectNames())
        list.removeDuplicates();
}
Example #14
0
QString Device::infoText()
{
  assert(m_deviceClass);

  QString t;
  QString str = QString::null;

  //
  // General Info
  //
  str += QString("<HTML><HEAD><TITLE>Device Info</TITLE></HEAD><BODY>");
  str += QString("<TABLE COLS=\"1\" WIDTH=\"100%\">");
  str += QString("<TR><TD BGCOLOR=\"darkblue\"><FONT COLOR=\"white\" SIZE=5>");
  str += name() + QString("</FONT></TD></TR></TABLE>");
  str += QString("<TABLE COLS=\"2\" WIDTH=\"100%\">");
  str += QString("<TR>\n");
  str += QString("<TD><B>Manufacturer</B></TD>");
  str += QString("<TD>") + m_deviceClass->manufacturer() + QString("</TD>");
  str += QString("</TR>");
  str += QString("<TR>");
  str += QString("<TD><B>Model</B></TD>");
  str += QString("<TD>") + m_deviceClass->model() + QString("</TD>");
  str += QString("</TR>");
  str += QString("<TR>");
  str += QString("<TD><B>Type</B></TD>");
  str += QString("<TD>") + m_deviceClass->type() + QString("</TD>");
  str += QString("</TR>");
  str += QString("<TR>");
  str += QString("<TD><B>Universe</B></TD>");
  t.sprintf("%d", universe() + 1);
  str += QString("<TD>") + t + QString("</TD>");
  str += QString("</TR>");
  str += QString("<TR>");
  str += QString("<TD><B>Address space</B></TD>");
  t.sprintf("%d - %d",
	    address() + 1, address() + m_deviceClass->channels()->count());
  str += QString("<TD>") + t + QString("</TD>");
  str += QString("</TR>");
  str += QString("</TABLE>");

  //
  // Channels
  //
  str += QString("<TABLE COLS=\"3\" WIDTH=\"100%\">");
  str += QString("<TR>");
  str += QString("<TD BGCOLOR=\"darkblue\">");
  str += QString("<FONT COLOR=\"white\" SIZE=\"3\">Channel</FONT>");
  str += QString("</TD>");
  str += QString("<TD BGCOLOR=\"darkblue\">");
  str += QString("<FONT COLOR=\"white\" SIZE=\"3\">DMX</FONT>");
  str += QString("</TD>");
  str += QString("</TR>");
  str += QString("<TD BGCOLOR=\"darkblue\">");
  str += QString("<FONT COLOR=\"white\" SIZE=\"3\">Name</FONT>");
  str += QString("</TD>");
  str += QString("</TR>");

  for (t_channel ch = 0; ch < (t_channel) m_deviceClass->channels()->count(); 
       ch++)
    {
      t.setNum(ch + 1);
      str += QString("<TR>");
      str += QString("<TD>" + t + "</TD>");
      t.setNum(address() + ch + 1);
      str += QString("<TD>" + t + "</TD>");
      str += QString("<TD>");
      str += m_deviceClass->channels()->at(ch)->name();
      str += QString("</TD>");
    }

  str += QString("</TR>");
  str += QString("</TABLE>");

  str += QString("</BODY></HTML>");

  return str;
}
Example #15
0
OptionsDialog::OptionsDialog(QWidget *parent, bool enableWallet) :
    QDialog(parent),
    ui(new Ui::OptionsDialog),
    model(0),
    mapper(0),
    fProxyIpValid(true)
{
    ui->setupUi(this);
    GUIUtil::restoreWindowGeometry("nOptionsDialogWindow", this->size(), this);

    /* Main elements init */
    ui->databaseCache->setMinimum(nMinDbCache);
    ui->databaseCache->setMaximum(nMaxDbCache);
    ui->threadsScriptVerif->setMinimum(-(int)boost::thread::hardware_concurrency());
    ui->threadsScriptVerif->setMaximum(MAX_SCRIPTCHECK_THREADS);

    /* Network elements init */
#ifndef USE_UPNP
    ui->mapPortUpnp->setEnabled(false);
#endif

    ui->proxyIp->setEnabled(false);
    ui->proxyPort->setEnabled(false);
    ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));

    connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
    connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));

    ui->proxyIp->installEventFilter(this);

    /* Window elements init */
#ifdef Q_OS_MAC
    /* remove Window tab on Mac */
    ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif

    /* remove Wallet tab in case of -disablewallet */
    if (!enableWallet) {
        ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWallet));
    }

    /* Display elements init */
    
    /* Number of displayed decimal digits selector */
    QString digits;
    for(int index = 2; index <=8; index++){
        digits.setNum(index);
        ui->digits->addItem(digits, digits);
    }
    
    /* Theme selector */
    ui->theme->addItem(QString("DASH-blue"), QVariant("drkblue"));
    ui->theme->addItem(QString("DASH-traditional"), QVariant("trad"));

    
    /* Language selector */
    QDir translations(":translations");
    ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
    foreach(const QString &langStr, translations.entryList())
    {
        QLocale locale(langStr);

        /** check if the locale name consists of 2 parts (language_country) */
        if(langStr.contains("_"))
        {
#if QT_VERSION >= 0x040800
            /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
            ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
            /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
            ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
        }
        else
        {
#if QT_VERSION >= 0x040800
            /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
            ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
            /** display language strings as "language (locale name)", e.g. "German (de)" */
            ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
        }
    }
#if QT_VERSION >= 0x040700
    ui->thirdPartyTxUrls->setPlaceholderText("https://example.com/tx/%s");
#endif

    ui->unit->setModel(new BitcoinUnits(this));

    /* Widget-to-option mapper */
    mapper = new QDataWidgetMapper(this);
    mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
    mapper->setOrientation(Qt::Vertical);

    /* setup/change UI elements when proxy IP is invalid/valid */
    connect(this, SIGNAL(proxyIpChecks(QValidatedLineEdit *, int)), this, SLOT(doProxyIpChecks(QValidatedLineEdit *, int)));
}
Example #16
0
void voucherItem::sToggleReceiving(QTreeWidgetItem *pItem)
{
  double n;
  QString s;
  XTreeWidgetItem* item = (XTreeWidgetItem*)pItem;
  if(item->id() == -1)
    return;
  if (item->text(3) == "Yes")
  {
    item->setText(3, "No");
    if (item->text(0) == "Receiving")
    {
    	n = _qtyToVoucher->toDouble();
    	_qtyToVoucher->setText(item->text(2));
    	n = n - _qtyToVoucher->toDouble();
    	_qtyToVoucher->setText(s.setNum(n));

      n = _uninvoicedReceived->toDouble();
      _uninvoicedReceived->setText(item->text(2));
      n = n + _uninvoicedReceived->toDouble();
      _uninvoicedReceived->setText(s.setNum(n));
    }
    else
    {
    	n = _qtyToVoucher->toDouble();
    	_qtyToVoucher->setText(item->text(2));
    	n = n - _qtyToVoucher->toDouble();
    	_qtyToVoucher->setText(s.setNum(n));

      n = _uninvoicedRejected->toDouble();
      _uninvoicedRejected->setText(item->text(2));
      n = n + _rejected->toDouble();
      _uninvoicedRejected->setText(s.setNum(n));
    }
  }
  else 
  {
    item->setText(3, "Yes");
    if (item->text(0) == "Receiving")
    {
    	n = _qtyToVoucher->toDouble();
    	_qtyToVoucher->setText(item->text(2));
    	n = n + _qtyToVoucher->toDouble();
    	_qtyToVoucher->setText(s.setNum(n));

      n = _uninvoicedReceived->toDouble();
      _uninvoicedReceived->setText(item->text(2));
      n = n - _uninvoicedReceived->toDouble();
      _uninvoicedReceived->setText(s.setNum(n));
    }
    else
    {
      n = _qtyToVoucher->toDouble();
      _qtyToVoucher->setText(item->text(2));
      n = n + _qtyToVoucher->toDouble();
      _qtyToVoucher->setText(s.setNum(n));

      n = _uninvoicedRejected->toDouble();
      _uninvoicedRejected->setText(item->text(2));
      n = n + _uninvoicedRejected->toDouble();
      _uninvoicedRejected->setText(s.setNum(n));
    }
  }

  // Check PO Close flag

  if ( ((_ordered->toDouble() <= (_received->toDouble() - _rejected->toDouble()))) && (_uninvoicedReceived->toDouble() == 0) && (_uninvoicedRejected->toDouble() == 0) )
        _closePoitem->setChecked(true);
  else
	_closePoitem->setChecked(false);
  
  // Save the voitem information
  if (_voitemid != -1)
  {
    q.prepare( "UPDATE voitem "
               "SET voitem_qty=:voitem_qty "
               "WHERE (voitem_id=:voitem_id);" );
    q.bindValue(":voitem_id", _voitemid);
  }
  else
  {
  // Get next voitem id
    q.prepare("SELECT NEXTVAL('voitem_voitem_id_seq') AS voitemid");
    q.exec();
    if (q.first())
      _voitemid = (q.value("voitemid").toInt());
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                  __FILE__, __LINE__);
      reject();
      return;
    }
    
    q.prepare( "INSERT INTO voitem "
               "(voitem_id, voitem_vohead_id, voitem_poitem_id, voitem_close, voitem_qty, voitem_freight) "
               "VALUES "
               "(:voitem_id, :vohead_id, :poitem_id, :voitem_close, :voitem_qty, :voitem_freight);" );
  }

  q.bindValue(":voitem_id", _voitemid);
  q.bindValue(":vohead_id", _voheadid);
  q.bindValue(":poitem_id", _poitemid);
  q.bindValue(":voitem_close", QVariant(_closePoitem->isChecked()));
  q.bindValue(":voitem_qty", _qtyToVoucher->toDouble());
  q.bindValue(":voitem_freight", _freightToVoucher->localValue());
  q.exec();
  if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                __FILE__, __LINE__);
    reject();
    return;
  }
  
  // Update the receipt record
  if (item->text(3) == "Yes")
  {
    if (item->altId() == 1)
      q.prepare( "UPDATE recv "
                 "SET recv_vohead_id=:vohead_id,recv_voitem_id=:voitem_id "
                 "WHERE (recv_id=:target_id);" );
    else if (item->altId() == 2)
      q.prepare( "UPDATE poreject "
                 "SET poreject_vohead_id=:vohead_id,poreject_voitem_id=:voitem_id "
                 "WHERE (poreject_id=:target_id);" );
  }
  else
  {
    if (item->altId() == 1)
      q.prepare( "UPDATE recv "
                 "SET recv_vohead_id=NULL,recv_voitem_id=NULL "
                 "WHERE ((recv_id=:target_id)"
                 "  AND  (recv_vohead_id=:vohead_id));" );
    else if (item->altId() == 2)
      q.prepare( "UPDATE poreject "
                 "SET poreject_vohead_id=NULL,poreject_voitem_id=NULL "
                 "WHERE ((poreject_id=:target_id)"
                 "  AND  (poreject_vohead_id=:vohead_id));" );
  }

  q.bindValue(":vohead_id", _voheadid);
  q.bindValue(":voitem_id", _voitemid);
  q.bindValue(":target_id", item->id());
  q.exec();
  if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                __FILE__, __LINE__);
    reject();
    return;
  }

}
Example #17
0
	QString FooTrack::lenghtInSeconds() const
	{
		QString lis;

		return lis.setNum(m_lenght);
	}
Example #18
0
  /**
   * Updates the tracking labels.
   *
   *
   * @param p
   */
  void TrackTool::updateLabels(QPoint p) {
    MdiCubeViewport *cvp = cubeViewport();

    clearLabels();

    if(cvp == NULL) {
      return;
    }

    double sample, line;
    cvp->viewportToCube(p.x(), p.y(), sample, line);
    if((sample < 0.5) || (line < 0.5) ||
        (sample > cvp->cubeSamples() + 0.5) ||
        (line > cvp->cubeLines() + 0.5)) {
      return;
    }

    int isamp = (int)(sample + 0.5);
    QString text;
    text.setNum(isamp);
    text = "S " + text;
    p_sampLabel->setText(text);

    int iline = (int)(line + 0.5);
    text.setNum(iline);
    text = "L " + text;
    p_lineLabel->setText(text);


    // Do we have a projection?
    if(cvp->projection() != NULL) {
      // Set up for projection types
      Projection::ProjectionType projType = cvp->projection()->projectionType();
      p_latLabel->show();
      p_lonLabel->show();

      if(cvp->projection()->SetWorld(sample, line)) {
        if (projType == Projection::Triaxial) {
          TProjection *tproj = (TProjection *) cvp->projection();
          double lat = tproj->Latitude();
          double lon = tproj->Longitude();
          p_latLabel->setText(QString("Lat %1").arg(lat));
          p_lonLabel->setText(QString("Lon %1").arg(lon));
        }
        else { // RingPlane TODO write out radius azimuth instead of lat/lon
          RingPlaneProjection *rproj = (RingPlaneProjection *) cvp->projection();
          double rad = rproj->RingRadius();
          double lon = rproj->RingLongitude();
          //??? p_latLabel->setToolTip("Radius Position");
          p_latLabel->setText(QString("Rad %1").arg(rad));
          p_lonLabel->setText(QString("Lon %1").arg(lon));
        }
      }
      else {
        p_latLabel->setText("Lat N/A");
        p_lonLabel->setText("Lon N/A");
      }
    }
    // Do we have a camera model?
    else if(cvp->camera() != NULL) {
      p_latLabel->show();
      p_lonLabel->show();

      if(cvp->camera()->SetImage(sample, line)) {
        if (cvp->camera()->target()->shape()->name() != "Plane") {
          double lat = cvp->camera()->UniversalLatitude();
          double lon = cvp->camera()->UniversalLongitude();
          p_latLabel->setText(QString("Lat %1").arg(lat));
          p_lonLabel->setText(QString("Lon %1").arg(lon));
        }
        else {
          double rad = cvp->camera()->LocalRadius().meters();
          double lon = cvp->camera()->UniversalLongitude();
          //??? p_latLabel->setToolTip("Radius Position");
          p_latLabel->setText(QString("Rad %1").arg(rad));
          p_lonLabel->setText(QString("Lon %1").arg(lon));
        }
      }
      else {
        p_latLabel->setText("Lat N/A");
        p_lonLabel->setText("Lon N/A");
      }
    }

    else {
      p_latLabel->hide();
      p_lonLabel->hide();
    }

    if(cvp->isGray()) {
      p_grayLabel->show();
      p_redLabel->hide();
      p_grnLabel->hide();
      p_bluLabel->hide();

      ViewportBuffer *grayBuf = cvp->grayBuffer();

      if(grayBuf->working()) {
        p_grayLabel->setText("BUSY");
      }
      else {
        const QRect rect(grayBuf->bufferXYRect());

        if(p.x() >= rect.left() && p.x() <= rect.right() &&
            p.y() >= rect.top() && p.y() <= rect.bottom()) {
          const int bufX = p.x() - rect.left();
          const int bufY = p.y() - rect.top();
          QString pixelString = IString(PixelToString(
                                                grayBuf->getLine(bufY)[bufX])).ToQt();
          p_grayLabel->setText(pixelString);
        }
      }
    }
    else {
      p_grayLabel->hide();
      p_redLabel->show();
      p_grnLabel->show();
      p_bluLabel->show();

      ViewportBuffer *redBuf = cvp->redBuffer();

      if(redBuf->working()) {
        p_grayLabel->setText("BUSY");
      }
      else {
        const QRect rRect = redBuf->bufferXYRect();

        if(p.x() >= rRect.left() && p.x() < rRect.right() &&
            p.y() >= rRect.top() && p.y() < rRect.bottom()) {
          const int rBufX = p.x() - rRect.left();
          const int rBufY = p.y() - rRect.top();
          QString rLab = "R ";
          rLab += IString(PixelToString(
                                  redBuf->getLine(rBufY)[rBufX])).ToQt();
          p_redLabel->setText(rLab);
        }
      }

      ViewportBuffer *greenBuf = cvp->greenBuffer();

      if(greenBuf->working()) {
        p_grayLabel->setText("BUSY");
      }
      else {
        const QRect gRect = greenBuf->bufferXYRect();

        if(p.x() >= gRect.left() && p.x() < gRect.right() &&
            p.y() >= gRect.top() && p.y() < gRect.bottom()) {
          const int gBufX = p.x() - gRect.left();
          const int gBufY = p.y() - gRect.top();
          QString gLab = "G ";
          gLab += IString(PixelToString(
                                  greenBuf->getLine(gBufY)[gBufX])).ToQt();
          p_grnLabel->setText(gLab);
        }
      }

      ViewportBuffer *blueBuf = cvp->blueBuffer();

      if(blueBuf->working()) {
        p_grayLabel->setText("BUSY");
      }
      else {
        const QRect bRect = blueBuf->bufferXYRect();

        if(p.x() >= bRect.left() && p.x() < bRect.right() &&
            p.y() >= bRect.top() && p.y() < bRect.bottom()) {
          const int bBufX = p.x() - bRect.left();
          const int bBufY = p.y() - bRect.top();
          QString bLab = "B ";
          bLab += IString(PixelToString(
                                  blueBuf->getLine(bBufY)[bBufX])).ToQt();
          p_bluLabel->setText(bLab);
        }
      }
    }
  }
Example #19
0
void autobots_toutiao::onStart()
{
  // 检查输入
  if (!CheckInput())
  {
    return;
  }

  // 更新界面输入
  UpdateData();
  
//   if (m_account_list.size() < m_comment_list.size())
//   {
//     QMessageBox::critical(this, QStringLiteral("提示"), QStringLiteral("用户账户太少")); 
//     return;
//   }

  control_status = true;

  // 循环发帖
  for (int i = 0; i < m_comment_list.size(); ++i)
  {
    if (!control_status)
    {
      break;
    }

    if (m_account_order >= m_account_list.size())
    {
      ui.lineEdit_msg->setText(QStringLiteral("账号不够用了"));
      return;
    }

    // 尝试登陆
    bool login_status = false;
    while (m_account_order < m_account_list.size())
    {
      QNetworkCookieJar* cookie = new QNetworkCookieJar();

      network.GetManager().setCookieJar(cookie);

      GetContent();

//       if (!RequestForRenren())
//       {
//         ui.lineEdit_msg->setText(QStringLiteral("请求失败..."));
//         continue;
//       }

      AccountParam ac = m_account_list.at(m_account_order);

      if (!AuthorByRenren(ac._id, ac._password))
      {
        ui.lineEdit_msg->setText(QStringLiteral("登陆失败..."));
        ui.tableWidget_account_id->item(m_account_order, 0)->setBackgroundColor(QColor(255,0,0, 180));
        m_account_order++;
        continue;
      }
      else
      {
        ui.lineEdit_msg->setText(QStringLiteral("登陆成功"));
        ui.tableWidget_account_id->item(m_account_order, 0)->setBackgroundColor(QColor(0,255,0, 180));
        m_account_order++;
        login_status = true;
        break;
      }
    }

    if (!login_status)
    {
      ui.lineEdit_msg->setText(QStringLiteral("账号登陆不成功,无法继续"));
      return;
    }

    QElapsedTimer t2;
    t2.start();
    while(t2.elapsed()<1000 )  
      QCoreApplication::processEvents();

    if (DoPostFatie(m_comment_list[i]))
    {
      m_comment_item_list[i]->setCheckState(Qt::Checked);
      //m_comment_item_list[i]->setBackgroundColor(QColor(0,255,0, 180));
    }
    else
    {
      continue;
    }

    t2.restart();
    while(t2.elapsed()<1000 )  
      QCoreApplication::processEvents();

    Logout();

    QString msg;
    msg.setNum(i+1);

    ui.lineEdit_msg->setText(QStringLiteral("第") + msg + QStringLiteral("次完成"));

    t2.restart();
    while(t2.elapsed()< m_interval*1000 )  // 时间间隔
    {
      ui.lineEdit_msg->setText(QString::number(t2.elapsed()));
      QCoreApplication::processEvents();   
    }
  }

  ui.lineEdit_msg->setText(QStringLiteral("已完成"));
}
Example #20
0
void AIMLEngine::addDirectory(const QString &directoryName)
{
    /*
     * Emit to anyone wanting to know that we're
     * going to be a while loading something
     */
    emit loading();
    emit addText("[Rebecca loading]");

    try
    {
        /*
         * Create and Load a AIML engine
         * if we don't have one.
         */
        if(!m_aiml)
        {
            initAIML();
        }

        /*
        * Get the GraphBuilder concrete class that
        * was created inside of AimlFacade.
        * DO NOT try to delete GraphBuilder.  Let
        * AimlFacade handle that when it falls out
        * of scope.
        */
        GraphBuilder &builder = m_aiml->getGraphBuilder();

        /*
         * Add the entire directory by extracting the
         * "char *" from the QString and passing it to
         * the AIML api
         */
        builder.addDirectory(directoryName.toAscii().data());

        /*
        * No other files to add to the internal queue.
        * So, let's create the AIML graph, the internal
        * data structures.
        */
        builder.createGraph();

        /*
        * Get the number of AIML categories loaded in total.
        */
        int size = builder.getSize();

        //Print out the number of categories loaded.
        emit addText("[Rebecca now fully loaded]");
        QString stringSize;
        stringSize.setNum(size);
        QString outputCategoriesLoaded("[Number of categories loaded: " + stringSize + "]");
        emit addText(outputCategoriesLoaded);

        /*
        * Emit to anyone wanting to know that we're
        * done loading
        */
        emit doneLoading();
    }
    /*
    * All the exceptions are grouped here but you
    * might not want this since it's a bit harder
    * to determine where they came from.
    */
    catch(FileNotFoundException &e)
    {
        emit addText("[A File Was Not Found Terminating]");
        QString exception("[");
        exception += e.what();
        exception += "]";
        emit addText(exception);

        /*
        * Emit to anyone wanting to know that we're
        * done loading
        */
        emit doneLoading();
    }
    catch(IllegalArgumentException &e)
    {
        emit addText("[IllegalArgument Found Terminating]");
        QString exception("[");
        exception += e.what();
        exception += "]";
        emit addText(exception);

        /*
        * Emit to anyone wanting to know that we're
        * done loading
        */
        emit doneLoading();
    }
    catch(InitializationException &e)
    {
        emit addText("[Initialization Exception Found Terminating]");
        QString exception("[");
        exception += e.what();
        exception += "]";
        emit addText(exception);

        /*
        * Emit to anyone wanting to know that we're
        * done loading
        */
        emit doneLoading();
    }
    catch(XMLErrorException &e)
    {
        emit addText("[XMLError Exception Found Terminating]");
        QString exception("[");
        exception += e.what();
        exception += "]";
        emit addText(exception);

        /*
        * Emit to anyone wanting to know that we're
        * done loading
        */
        emit doneLoading();
    }
    catch(Exception &e)
    {
        emit addText("[An uknown exception occured, Terminating program]");
        QString exception("[");
        exception += e.what();
        exception += "]";
        emit addText(exception);

        /*
        * Emit to anyone wanting to know that we're
        * done loading
        */
        emit doneLoading();
    }

}
Example #21
0
// -------------------  UpdateRGBGainCtrls  -----------------------
//
void properties::UpdateRGBGainCtrls ()
{
    if (m_bInit || !m_hCamera)
        return;

    QString strTemp;
    double dblEnable = 0.0;

    // get values
    m_maxRGBGain = IS_MAX_GAIN;
    m_minRGBGain = IS_MIN_GAIN;
    m_incRGBGain = 1;
    m_nRedGain = is_SetHardwareGain (m_hCamera, IS_GET_RED_GAIN, IS_IGNORE_PARAMETER,
                                     IS_IGNORE_PARAMETER, IS_IGNORE_PARAMETER);
    m_nGreenGain = is_SetHardwareGain (m_hCamera, IS_GET_GREEN_GAIN, IS_IGNORE_PARAMETER,
                                       IS_IGNORE_PARAMETER, IS_IGNORE_PARAMETER);
    m_nBlueGain = is_SetHardwareGain (m_hCamera, IS_GET_BLUE_GAIN, IS_IGNORE_PARAMETER,
                                      IS_IGNORE_PARAMETER, IS_IGNORE_PARAMETER);
    is_SetAutoParameter (m_hCamera, IS_GET_ENABLE_AUTO_WHITEBALANCE, &dblEnable, NULL);

    // set text
    strTemp.setNum ((short int)m_minRGBGain, 10);
    textMinRGBGain->setText (strTemp);
    strTemp.setNum ((short int)m_maxRGBGain, 10);
    textMaxRGBGain->setText (strTemp);

    m_bInit = TRUE;
    // update slider controls
    // red
    sliderRed->setMinimum (m_minRGBGain);
    sliderRed->setMaximum (m_maxRGBGain);
    sliderRed->setSingleStep (m_incRGBGain);
    sliderRed->setPageStep (4* m_incRGBGain);
    sliderRed->setValue (m_nRedGain);
    sliderRed->setEnabled ((m_SensorInfo.bRGain == TRUE) && (dblEnable == 0.0));
    // green
    sliderGreen->setMinimum (m_minRGBGain);
    sliderGreen->setMaximum (m_maxRGBGain);
    sliderGreen->setSingleStep (m_incRGBGain);
    sliderGreen->setPageStep (4* m_incRGBGain);
    sliderGreen->setValue (m_nGreenGain);
    sliderGreen->setEnabled ((m_SensorInfo.bGGain == TRUE) && (dblEnable == 0.0));
    // blue
    sliderBlue->setMinimum (m_minRGBGain);
    sliderBlue->setMaximum (m_maxRGBGain);
    sliderBlue->setSingleStep (m_incRGBGain);
    sliderBlue->setPageStep (4* m_incRGBGain);
    sliderBlue->setValue (m_nBlueGain);
    sliderBlue->setEnabled ((m_SensorInfo.bBGain == TRUE) && (dblEnable == 0.0));
    // update spin controls
    // red
    spinBoxRed->setMinimum (m_minRGBGain);
    spinBoxRed->setMaximum (m_maxRGBGain);
    spinBoxRed->setSingleStep (m_incRGBGain);
    spinBoxRed->setValue (m_nRedGain);
    spinBoxRed->setEnabled ((m_SensorInfo.bRGain == TRUE) && (dblEnable == 0.0));
    // green
    spinBoxGreen->setMinimum (m_minRGBGain);
    spinBoxGreen->setMaximum (m_maxRGBGain);
    spinBoxGreen->setSingleStep (m_incRGBGain);
    spinBoxGreen->setValue (m_nGreenGain);
    spinBoxGreen->setEnabled ((m_SensorInfo.bGGain == TRUE) && (dblEnable == 0.0));
    // blue
    spinBoxBlue->setMinimum (m_minRGBGain);
    spinBoxBlue->setMaximum (m_maxRGBGain);
    spinBoxBlue->setSingleStep (m_incRGBGain);
    spinBoxBlue->setValue (m_nBlueGain);
    spinBoxBlue->setEnabled ((m_SensorInfo.bBGain == TRUE) && (dblEnable == 0.0));
    m_bInit = FALSE;
}
Example #22
0
void CheckDocument::buildErrorList(ScribusDoc *doc)
{
// 	bool resultError = false;
	m_Doc = doc;
	disconnect(curCheckProfile, SIGNAL(activated(const QString&)),
	           this, SLOT(newScan(const QString&)));
	curCheckProfile->clear();
	clearErrorList();

	if (m_Doc==0)
		return;

	minResDPI = qRound(doc->checkerProfiles[doc->curCheckProfile].minResolution);
	maxResDPI = qRound(doc->checkerProfiles[doc->curCheckProfile].maxResolution);
	
	CheckerPrefsList::Iterator it;
	CheckerPrefsList::Iterator itend=doc->checkerProfiles.end();
	for (it = doc->checkerProfiles.begin(); it != itend ; ++it)
		curCheckProfile->addItem(it.key());
	setCurrentComboItem(curCheckProfile, doc->curCheckProfile);

	if ((doc->docItemErrors.count() == 0)
		 && (doc->masterItemErrors.count() == 0)
		 && (doc->docLayerErrors.count() == 0))
	{
		QTreeWidgetItem * documentItem = new QTreeWidgetItem( reportDisplay );
		documentItem->setText(COLUMN_ITEM, tr( "Document" ) );
		documentItem->setIcon(COLUMN_ITEM, noErrors );
		documentItem->setText(COLUMN_PROBLEM, tr( "No Problems found" ) );
		ignoreErrors->setText( tr("OK"));
	}
	else
	{
// 		resultError = true;
		bool hasError = false;
// 		globalGraveError = false;
		bool layoutGraveError = false;
		itemError = false;
// 		QTreeWidgetItem * pagep = 0;
		// LAYERS **********************************************8
		QTreeWidgetItem * layerItem = new QTreeWidgetItem(reportDisplay);
		layerItem->setText(COLUMN_ITEM, tr("Layers"));

		if (doc->docLayerErrors.count() != 0)
		{
			QMap<int, errorCodes>::Iterator docLayerErrorsIt;
			errorCodes::Iterator layerErrorsIt;

			for (docLayerErrorsIt = doc->docLayerErrors.begin();
				 docLayerErrorsIt != doc->docLayerErrors.end();
				 ++docLayerErrorsIt)
			{
				QTreeWidgetItem * layer = new QTreeWidgetItem(layerItem);//, pagep );
				for (layerErrorsIt = docLayerErrorsIt.value().begin();
					 layerErrorsIt != docLayerErrorsIt.value().end(); ++layerErrorsIt)
				{
					QTreeWidgetItem * errorText = new QTreeWidgetItem( layer, 0 );
					switch (layerErrorsIt.key())
					{
						case Transparency:
							errorText->setText(COLUMN_ITEM, tr("Transparency used"));
							errorText->setIcon(COLUMN_ITEM, graveError );
							layoutGraveError = true;
							break;
						case BlendMode:
							errorText->setText(COLUMN_ITEM, tr("Blendmode used"));
							errorText->setIcon(COLUMN_ITEM, graveError );
							layoutGraveError = true;
							break;
						case OffConflictLayers:
							errorText->setText(COLUMN_ITEM, tr("Print/Visible Mismatch"));
							errorText->setIcon(COLUMN_ITEM, onlyWarning );
							layoutGraveError = true;
							break;
						default:
							break;
					}
				}
				layer->setText(COLUMN_ITEM,tr("Layer \"%1\"").arg(doc->layerName(docLayerErrorsIt.key())));
//				layer->setIcon(COLUMN_ITEM, graveError );
				if (layoutGraveError)
					layer->setIcon(COLUMN_ITEM, graveError );
				else
					layer->setIcon(COLUMN_ITEM, onlyWarning );
				layer->setText(COLUMN_PROBLEM, tr("Issue(s): %1").arg(doc->docLayerErrors[docLayerErrorsIt.key()].count()));
				layer->setExpanded(true);
// 				pagep = layer;
// 				globalGraveError = true;
			}
			layerItem->setExpanded(true);
		}
		// END of LAYERS

		// Master Pages *****************************************************
		QTreeWidgetItem * masterPageRootItem = new QTreeWidgetItem(reportDisplay);
		masterPageRootItem->setText(COLUMN_ITEM, tr("Master Pages"));
		int mpErrorCount = 0;

		for (int mPage = 0; mPage < doc->MasterPages.count(); ++mPage)
		{
			QString tmp;
			hasError = false;
			pageGraveError = false;
			QTreeWidgetItem * page = new QTreeWidgetItem( masterPageRootItem);//, pagep );
			masterPageMap.insert(page, doc->MasterPages.at(mPage));
// 			pagep = page;
			QMap<int, errorCodes>::Iterator masterItemErrorsIt;
			for (masterItemErrorsIt = doc->masterItemErrors.begin();
				 masterItemErrorsIt != doc->masterItemErrors.end();
				 ++masterItemErrorsIt)
			{
				if ((doc->MasterItems.at(masterItemErrorsIt.key())->OwnPage == mPage)
					|| (doc->MasterItems.at(masterItemErrorsIt.key())->OnMasterPage == doc->MasterPages.at(mPage)->pageName()))
				{
					hasError = true;
					QTreeWidgetItem * object = new QTreeWidgetItem( page);
					masterPageItemMap.insert(object, doc->MasterItems.at(masterItemErrorsIt.key()));
					object->setText(COLUMN_ITEM, doc->MasterItems.at(masterItemErrorsIt.key())->itemName());
					errorCodes::Iterator it3;
					if (masterItemErrorsIt.value().count() == 1)
					{
						it3 = masterItemErrorsIt.value().begin();
						buildItem(object, it3.key(), doc->MasterItems.at(masterItemErrorsIt.key()));
					}
					else
					{
						for (it3 = masterItemErrorsIt.value().begin(); it3 != masterItemErrorsIt.value().end(); ++it3)
						{
							QTreeWidgetItem * errorText = new QTreeWidgetItem( object, 0 );
							buildItem(errorText, it3.key(), doc->MasterItems.at(masterItemErrorsIt.key()));
						}
						object->setExpanded( true );
					}
					object->setIcon(COLUMN_ITEM, itemError ? graveError : onlyWarning);
				}
			}
			if (hasError)
			{
				++mpErrorCount;
				page->setIcon(COLUMN_ITEM, pageGraveError ? graveError : onlyWarning);
				page->setExpanded( true );
			}
			else
				page->setIcon(COLUMN_ITEM, noErrors );
			page->setText(COLUMN_ITEM, doc->MasterPages.at(mPage)->pageName());
		}
		masterPageRootItem->setExpanded(true);
		masterPageRootItem->setText(COLUMN_PROBLEM, tr("Issue(s): %1").arg(mpErrorCount));
		// END of MASTER PAGES

		// PAGES ********************************8
		for (int aPage = 0; aPage < doc->DocPages.count(); ++aPage)
		{
			QString tmp;
			hasError = false;
			pageGraveError = false;
			QTreeWidgetItem * page = new QTreeWidgetItem( reportDisplay);//, pagep );
			pageMap.insert(page, doc->DocPages.at(aPage));
// 			pagep = page;
			QMap<int, errorCodes>::Iterator docItemErrorsIt;
			for (docItemErrorsIt = doc->docItemErrors.begin();
				 docItemErrorsIt != doc->docItemErrors.end();
				 ++docItemErrorsIt)
			{
				if (doc->DocItems.at(docItemErrorsIt.key())->OwnPage == aPage)
				{
					hasError = true;
					itemError = false;
					QTreeWidgetItem * object = new QTreeWidgetItem(page);
					object->setText(COLUMN_ITEM, doc->DocItems.at(docItemErrorsIt.key())->itemName());
					itemMap.insert(object, doc->DocItems.at(docItemErrorsIt.key()));
					errorCodes::Iterator it3;
					if (docItemErrorsIt.value().count() == 1)
					{
						it3 = docItemErrorsIt.value().begin();
						buildItem(object, it3.key(), doc->DocItems.at(docItemErrorsIt.key()));
					}
					else
					{
						for (it3 = docItemErrorsIt.value().begin(); it3 != docItemErrorsIt.value().end(); ++it3)
						{
							QTreeWidgetItem * errorText = new QTreeWidgetItem( object);
							buildItem(errorText, it3.key(), doc->DocItems.at(docItemErrorsIt.key()));
						}
						object->setExpanded( true );
					}
					object->setIcon(COLUMN_ITEM, itemError ? graveError : onlyWarning);
				}
			}
			if (hasError)
			{
				page->setIcon(COLUMN_ITEM, itemError ? graveError : onlyWarning);
				page->setExpanded( true );
			}
			else
				page->setIcon( 0, noErrors );
			page->setText(COLUMN_ITEM, tr("Page ")+tmp.setNum(aPage+1));
		}
		// END of PAGES

		// FREE ITEMS **********************************************8888
		QMap<int, errorCodes>::Iterator freeItemsErrorsIt;
		bool hasfreeItems = false;
		for (freeItemsErrorsIt = doc->docItemErrors.begin();
			 freeItemsErrorsIt != doc->docItemErrors.end();
			 ++freeItemsErrorsIt)
		{
			if (doc->DocItems.at(freeItemsErrorsIt.key())->OwnPage == -1)
			{
				hasfreeItems = true;
				break;
			}
		}
		if (hasfreeItems)
		{
			bool hasError = false;
			bool pageGraveError = false;
			QTreeWidgetItem * freeItem = new QTreeWidgetItem( reportDisplay);//, pagep );
// 			pagep = page;
			for (freeItemsErrorsIt = doc->docItemErrors.begin();
				 freeItemsErrorsIt != doc->docItemErrors.end();
				 ++freeItemsErrorsIt)
			{
				if (doc->DocItems.at(freeItemsErrorsIt.key())->OwnPage == -1)
				{
					hasError = true;
					QTreeWidgetItem * object = new QTreeWidgetItem(freeItem);
					object->setText(0, doc->DocItems.at(freeItemsErrorsIt.key())->itemName());
					itemMap.insert(object, doc->DocItems.at(freeItemsErrorsIt.key()));
					errorCodes::Iterator it3;
					if (freeItemsErrorsIt.value().count() == 1)
					{
						it3 = freeItemsErrorsIt.value().begin();
						buildItem(object, it3.key(), doc->DocItems.at(freeItemsErrorsIt.key()));
					}
					else
					{
						for (it3 = freeItemsErrorsIt.value().begin(); it3 != freeItemsErrorsIt.value().end(); ++it3)
						{
							QTreeWidgetItem * errorText = new QTreeWidgetItem( object);
							buildItem(errorText, it3.key(), doc->DocItems.at(freeItemsErrorsIt.key()));
						}
						object->setExpanded( true );
					}
					object->setIcon(COLUMN_ITEM, pageGraveError ? graveError : onlyWarning);
				}
			}
			if (hasError)
			{
				freeItem->setIcon(COLUMN_ITEM, pageGraveError ? graveError : onlyWarning );
				freeItem->setExpanded( true );
			}
			else
				freeItem->setIcon(COLUMN_ITEM, noErrors );
			freeItem->setText(COLUMN_ITEM, tr("Free Objects"));
		}
		// END of FREE ITEMS

// 		if (globalGraveError)
// 			documentItem->setIcon(COLUMN_ITEM, graveError );
// 		else
// 			documentItem->setIcon(COLUMN_ITEM, onlyWarning );
// 		documentItem->setText(COLUMN_PROBLEM, tr( "Problems found" ) );
// 		documentItem->setExpanded( true );
		ignoreErrors->setText( tr("&Ignore Errors"));
	}

	reportDisplay->resizeColumnToContents(COLUMN_ITEM);
	reportDisplay->resizeColumnToContents(COLUMN_PROBLEM);
	reportDisplay->resizeColumnToContents(COLUMN_LAYER);
// 	reportDisplay->resizeColumnToContents(COLUMN_INFO);
	connect(curCheckProfile, SIGNAL(activated(const QString&)), this, SLOT(newScan(const QString&)));
	connect(reportDisplay, SIGNAL(itemClicked(QTreeWidgetItem*, int)), this, SLOT(slotSelect(QTreeWidgetItem*)));
}
Example #23
0
void EFXEditor::fillSceneLists()
{
	Function* function;
	QTreeWidgetItem* item;
	QTreeWidgetItem* startItem = NULL;
	QTreeWidgetItem* stopItem = NULL;
	QString s;

	Q_ASSERT(m_efx != NULL);
  
	for (t_function_id id = 0; id < KFunctionArraySize; id++)
	{
		function = _app->doc()->function(id);
		if (function == NULL)
			continue;
	
		if (function->type() == Function::Scene)
		{
			/* Insert the function to start scene list */
			item = new QTreeWidgetItem(m_startSceneList);
			item->setText(KInitColumnName, function->name());
			item->setText(KInitColumnID, s.setNum(function->id()));

			/* Select the scene from the start scene list */
			if (m_efx->startScene() == function->id())
			{
				m_startSceneList->setCurrentItem(item);
				startItem = item;
			}

			/* Insert the function to stop scene list */
			item = new QTreeWidgetItem(m_stopSceneList);
			item->setText(KInitColumnName, function->name());
			item->setText(KInitColumnID, s.setNum(function->id()));

			/* Select the scene from the stop scene list */
			if (m_efx->stopScene() == function->id())
			{
				m_stopSceneList->setCurrentItem(item);
				stopItem = item;
			}
		}
	}
  
	/* Make sure that the selected start scene item is visible */
	if (startItem != NULL)
		m_startSceneList->scrollToItem(startItem);

	/* Make sure that the selected stop scene item is visible */
	if (stopItem != NULL)
		m_stopSceneList->scrollToItem(stopItem);

	/* Start scene enabled status */
	if (m_efx->startSceneEnabled() == true)
		m_startSceneGroup->setChecked(true);
	else
		m_startSceneGroup->setChecked(false);

	/* Stop scene enabled status */
	if (m_efx->stopSceneEnabled() == true)
		m_stopSceneGroup->setChecked(true);
	else
		m_stopSceneGroup->setChecked(false);

	m_stopSceneList->sortItems(KInitColumnName, Qt::AscendingOrder);
	m_startSceneList->sortItems(KInitColumnName, Qt::AscendingOrder);
}
Example #24
0
bool distributor::calcDist(MVar *arg, std::string &func) {
    differentialCalc::func FCTN = diffC.findVectorialFunc(func);
    if (FCTN != differentialCalc::NONE) {
        Function function;
        if (arg->getFunction(&function)) {
            MaceString MStr;
            std::vector<numReal> z;
            if (function.real()) {
                if (diffC.vectorialFunc(FCTN,function,z)) {
                    std::complex<double> p;
                    bool periodic = false;
                    if (FCTN == differentialCalc::ZEROES) periodic = function.period(p);
                    else if (FCTN == differentialCalc::EXTREMA) {
                        Function der;
                        derivative(der,function);
                        periodic = der.period(p);
                    }
                    else if (FCTN == differentialCalc::INFLEXION) {
                        Function der,der2;
                        derivative(der,function);
                        derivative(der2,der);
                        periodic = der2.period(p);
                    }
                    periodic = periodic && p.imag() < 0.000001;
                    for (int i = 0; i < z.size(); i++) {
                        MStr.str = MStr.str.append(z[i].print(6));
                        if (periodic) {
                            QString help;
                            help = help.setNum(p.real());
                            MStr.str = MStr.str.append(" + k*");
                            MStr.str = MStr.str.append(help);
                        }
                        MStr.str = MStr.str.append(", ");
                    }
                    if (z.size() == 0) MStr.str = "No points found  ";
                    MStr.str.chop(2);
                }
                else {
                    Function der;
                    if (derivative(der,function))
                        MStr.str = "No points found.";
                    else
                        validC->setErr(NOTDIFFBAR);
                }
                arg->setString(MStr);
                return true;
            }
            else validC->setErr(NOTREALFUNC);


        }
    }
    else {
        FCTN = diffC.findCplxFunc(func);
        if (FCTN != differentialCalc::NONE) {
            std::complex<double> z;
            Function function;
            if (arg->getFunction(&function)) {
                if (diffC.cplxFunc(FCTN,function,z)) {
                    numCplx nz;
                    nz.val = z;
                    arg->setNumCplx(nz);

                }
                else {
                    MaceString MStr;
                    MStr.str = "No period has been found.";
                    arg->setString(MStr);
                }
                return true;
            }
        }
    }
    return false;
}
Example #25
0
KviIdentityGeneralOptionsWidget::KviIdentityGeneralOptionsWidget(QWidget * parent)
: KviOptionsWidget(parent)
{
	m_szAltNicknames[0] = KVI_OPTION_STRING(KviOption_stringNickname2);
	m_szAltNicknames[1] = KVI_OPTION_STRING(KviOption_stringNickname3);
	m_szAltNicknames[2] = KVI_OPTION_STRING(KviOption_stringNickname4);


	createLayout();
	layout()->setMargin(10);

	KviTalGroupBox * gbox = addGroupBox(0,0,0,0,Qt::Horizontal,__tr2qs_ctx("Basic Properties","options"));
	KviTalHBox * hb = new KviTalHBox(gbox);
	hb->setSpacing(0);
	hb->setMargin(0);

	KviStringSelector * sel = addStringSelector(hb,__tr2qs_ctx("Nickname:","options"),KviOption_stringNickname1);
	sel->setMinimumLabelWidth(120);
	mergeTip(sel,__tr2qs_ctx("<center>Your <b>nickname</b> is your primary form of identification on IRC.<br>" \
			"Since servers cannot accept multiple users sharing the same nickname " \
			"(case insensitive), you can provide alternative nicknames to be used in case"\
			"the server refuses to accept the default one.</center>","options"));

	QValidator * v = new QRegExpValidator(QRegExp("[^-0-9 ][^ ]*"),hb);
	sel->setValidator(v);

	QPushButton * pb = new QPushButton(__tr2qs_ctx("Alternatives...","options"),hb);
	connect(pb,SIGNAL(clicked()),this,SLOT(setNickAlternatives()));

	sel = addStringSelector(gbox,__tr2qs_ctx("Username:"******"options"),KviOption_stringUsername);
	sel->setMinimumLabelWidth(120);
	mergeTip(sel,__tr2qs_ctx("<center>This is the <b>username</b> that you will use to connect to the server.<br>" \
				"In the past, it was used as a form of authentication, but it normally has no special use now.<br>" \
				"In addition to your nickname, you are identified on IRC by your <b>username@hostname</b>.</br>" \
				"Basically, you can enter any word you like here. :D</center>","options"));

	sel = addStringSelector(gbox,__tr2qs_ctx("Real name:","options"),KviOption_stringRealname);
	sel->setMinimumLabelWidth(120);

	mergeTip(sel,__tr2qs_ctx("<center>This text will appear when someone does a /WHOIS on you.<br>" \
				"It is intended to be your real name, but people tend to put random quotes and phrases here too.</center>","options"));


	QString szOptionalCtcpUserInfo = __tr2qs_ctx("This field is optional and will appear as part of the CTCP USERINFO reply.","options");
	QString szCenterBegin("<center>");
	QString szCenterEnd("</center>");
	QString szTrailing = "<br><br>" + szOptionalCtcpUserInfo + szCenterEnd;

	gbox = addGroupBox(0,1,0,1,Qt::Horizontal,__tr2qs_ctx("Profile","options"));

	hb = new KviTalHBox(gbox);
	hb->setSpacing(4);

	QLabel * l = new QLabel(__tr2qs_ctx("Age:","options"),hb);
	l->setMinimumWidth(120);

	m_pAgeCombo = new QComboBox(hb);
	QString szTip1 = szCenterBegin + __tr2qs_ctx("Here you can specify your age.","options") + szTrailing;
	KviTalToolTip::add(l,szTip1);
	KviTalToolTip::add(m_pAgeCombo,szTip1);
	m_pAgeCombo->addItem(__tr2qs_ctx("Unspecified","options"));
	unsigned int i;
	for(i=1;i<120;i++)
	{
		QString tmp;
		tmp.setNum(i);
        m_pAgeCombo->insertItem(m_pAgeCombo->count(),tmp);
	}

	bool bOk;
	i = KVI_OPTION_STRING(KviOption_stringCtcpUserInfoAge).toUInt(&bOk);
	if(!bOk)i = 0;
	if(i > 120)i = 120;
	m_pAgeCombo->setCurrentIndex(i);

	hb->setStretchFactor(m_pAgeCombo,1);


	hb = new KviTalHBox(gbox);
	hb->setSpacing(4);

	l = new QLabel(__tr2qs_ctx("Gender:","options"),hb);
	l->setMinimumWidth(120);

	m_pGenderCombo = new QComboBox(hb);
	QString szTip2 =  szCenterBegin + __tr2qs_ctx("Here you can specify your gender.","options") + szTrailing;
	KviTalToolTip::add(l,szTip2);
	KviTalToolTip::add(m_pGenderCombo,szTip2);
	m_pGenderCombo->addItem(__tr2qs_ctx("Unspecified","options"));
	m_pGenderCombo->addItem(__tr2qs_ctx("Female","options"));
	m_pGenderCombo->addItem(__tr2qs_ctx("Male","options"));

	if(KviQString::equalCI(KVI_OPTION_STRING(KviOption_stringCtcpUserInfoGender),"Male"))
		m_pGenderCombo->setCurrentIndex(2);
	else if(KviQString::equalCI(KVI_OPTION_STRING(KviOption_stringCtcpUserInfoGender),"Female"))
		m_pGenderCombo->setCurrentIndex(1);
	else
		m_pGenderCombo->setCurrentIndex(0);

	hb->setStretchFactor(m_pGenderCombo,1);

	sel = addStringSelector(gbox,__tr2qs_ctx("Location:","options"),KviOption_stringCtcpUserInfoLocation);
	sel->setMinimumLabelWidth(120);
	mergeTip(sel,szCenterBegin + __tr2qs_ctx("You can describe here your approximate physical location. " \
				"Something like \"Region, Country\" will be ok. Please note that this information will be viewable " \
				"by anyone so putting more data (like the exact address), generally, <b>is not a good idea</b>.","options") + szTrailing);

	sel = addStringSelector(gbox,__tr2qs_ctx("Languages:","options"),KviOption_stringCtcpUserInfoLanguages);
	sel->setMinimumLabelWidth(120);
	mergeTip(sel,szCenterBegin + __tr2qs_ctx("You can put here the short names of the languages you can speak. " \
				"An example might be \"EN,IT\" that would mean that you speak both Italian and English.","options") + szTrailing);

	sel = addStringSelector(gbox,__tr2qs_ctx("Other:","options"),KviOption_stringCtcpUserInfoOther);
	sel->setMinimumLabelWidth(120);
	mergeTip(sel,szCenterBegin + __tr2qs_ctx("You can put here some additional personal data. " \
				"It might be a funny quote or your homepage url... " \
				"Please note that this information will be viewable " \
				"by anyone so <b>don't put any sensible data</b> (passwords, telephone or credit card numbers).","options") + szTrailing);

	addRowSpacer(0,2,0,2);
}
/**
 * Implementation of the method used for RS_Export to communicate
 * with this filter.
 *
 * @param file Full path to the LFF file that will be written.
 */
bool RS_FilterLFF::fileExport(RS_Graphic& g, const QString& file, RS2::FormatType /*type*/) {

    RS_DEBUG->print("LFF Filter: exporting file '%s'...", file.toLatin1().data());
    RS_DEBUG->print("RS_FilterLFF::fileExport: open");

    QFile f(file);
    QTextStream ts(&f);
    ts.setCodec("UTF-8");
    if (f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {


        RS_DEBUG->print("RS_FilterLFF::fileExport: open: OK");

        RS_DEBUG->print("RS_FilterLFF::fileExport: header");

        // header:
        ts << "# Format:            LibreCAD Font 1\n";
        ts << QString("# Creator:           %1\n").arg(RS_SYSTEM->getAppName());
        ts << QString("# Version:           %1\n").arg(RS_SYSTEM->getAppVersion());

        QString ns = g.getVariableString("Names", "");
        if (!ns.isEmpty()) {
            QStringList names = ns.split(',');
            RS_DEBUG->print("002");
            for (int i = 0; i < names.size(); ++i) {
                ts << QString("# Name:              %1\n").arg(names.at(i));
            }
        }

        QString es = g.getVariableString("Encoding", "");
        ts << QString("# Encoding:          UTF-8\n");
        ts << QString("# LetterSpacing:     %1\n").arg(
                  g.getVariableDouble("LetterSpacing", 3.0));
        ts << QString("# WordSpacing:       %1\n").arg(
                  g.getVariableDouble("WordSpacing", 6.75));
        ts << QString("# LineSpacingFactor: %1\n").arg(
                  g.getVariableDouble("LineSpacingFactor", 1.0));
        QString dateline = QDate::currentDate().toString ("yyyy-MM-dd");
        ts << QString("# Created:           %1\n").arg(
                  g.getVariableString("Created", dateline));
        ts << QString("# Last modified:     %1\n").arg(dateline);

        QString sa = g.getVariableString("Authors", "");
        RS_DEBUG->print("authors: %s", sa.toLocal8Bit().data());
        if (!sa.isEmpty()) {
            QStringList authors = sa.split(',');
            RS_DEBUG->print("count: %d", authors.count());

            QString a;
            for (int i = 0; i < authors.size(); ++i) {
                ts << QString("# Author:            %1\n").arg(authors.at(i));
            }
        }
        es = g.getVariableString("License", "");
        if (!es.isEmpty()) {
            ts << QString("# License:           %1\n").arg(es);
        } else
            ts << "# License:           unknown\n";

        RS_DEBUG->print("RS_FilterLFF::fileExport: header: OK");

        // iterate through blocks (=letters of font)
        for (uint i=0; i<g.countBlocks(); ++i) {
            RS_Block* blk = g.blockAt(i);

            RS_DEBUG->print("block: %d", i);

            if (blk!=NULL) {
                RS_DEBUG->print("002a: %s",
                                (blk->getName().toLocal8Bit().data()));

                ts << QString("\n%1\n").arg(blk->getName());

                // iterate through entities of this letter:
                for (RS_Entity* e=blk->firstEntity(RS2::ResolveNone);
                     e!=NULL;
                     e=blk->nextEntity(RS2::ResolveNone)) {

                    if (!e->isUndone()) {

                        // lines:
                        if (e->rtti()==RS2::EntityLine) {
                            RS_Line* l = (RS_Line*)e;
                            ts << clearZeros(l->getStartpoint().x, 5) << ',';
                            ts << clearZeros(l->getStartpoint().y, 5) << ';';
                            ts << clearZeros(l->getEndpoint().x, 5) << ',';
                            ts << clearZeros(l->getEndpoint().y, 5) << '\n';
                        }
                        // arcs:
                        else if (e->rtti()==RS2::EntityArc) {
                            RS_Arc* a = (RS_Arc*)e;
                            ts << clearZeros(a->getStartpoint().x, 5) << ',';
                            ts << clearZeros(a->getStartpoint().y, 5) << ';';
                            ts << clearZeros(a->getEndpoint().x, 5) << ',';
                            ts << clearZeros(a->getEndpoint().y, 5) << ",A";
                            ts << clearZeros(a->getBulge(), 5) << '\n';
                        }
                        else if (e->rtti()==RS2::EntityBlock) {
                            RS_Block* b = (RS_Block*)e;
                            QString uCode;
                            uCode.setNum(b->getName().at(0).unicode(), 16);
                            if (uCode.length()<4) {
                                uCode = uCode.rightJustified(4, '0');
                            }
                            ts << QString("C%1\n").arg(uCode);
                        }
                        else if (e->rtti()==RS2::EntityPolyline) {
                            RS_Polyline* p = (RS_Polyline*)e;
                            ts << clearZeros(p->getStartpoint().x, 5) << ',';
                            ts << clearZeros(p->getStartpoint().y, 5);
                            for (RS_Entity* e2=p->firstEntity(RS2::ResolveNone);
                                 e2!=NULL;
                                 e2=p->nextEntity(RS2::ResolveNone)) {
                                if (e2->rtti()==RS2::EntityLine){
                                    RS_Line* l = (RS_Line*)e2;
                                    ts << ';' << clearZeros(l->getEndpoint().x, 5) << ',';
                                    ts << clearZeros(l->getEndpoint().y, 5);
                                } else if (e2->rtti()==RS2::EntityArc){
                                    RS_Arc* a = (RS_Arc*)e2;
                                    ts << ';' << clearZeros(a->getEndpoint().x, 5) << ',';
                                    ts << clearZeros(a->getEndpoint().y, 5) <<",A";
                                    ts << clearZeros(a->getBulge(), 5);
                                }
                            }
                            ts<<'\n';
                        }
                        // Ignore entities other than arcs / lines
                        else {}
                    }

                }
            }
        }
        f.close();
        RS_DEBUG->print("LFF Filter: exporting file: OK");
        return true;
    }
    else {
        RS_DEBUG->print("LFF Filter: exporting file failed");
    }

    return false;
}
OptionsWidget_messageColors::OptionsWidget_messageColors(QWidget * parent)
: KviOptionsWidget(parent)
{
	setObjectName("messages");

	createLayout();

	int i;
	m_pLastItem = 0;

	m_pListView = new MessageListWidget(this);
	m_pListViewItemDelegate = new MessageListWidgetItemDelegate(m_pListView);
	m_pListView->setItemDelegate(m_pListViewItemDelegate);
	m_pListView->setSelectionMode(QAbstractItemView::SingleSelection);
	m_pListView->setFont(KVI_OPTION_FONT(KviOption_fontIrcView));
	m_pListView->viewport()->setAutoFillBackground(false);

	addWidgetToLayout(m_pListView,0,0,2,0);

	KviTalVBox * box = new KviTalVBox(this);
	addWidgetToLayout(box,3,0,3,0);

	new QLabel(__tr2qs_ctx("Background:","options"),box);

	m_pBackListWidget = new KviTalListWidget(box);
	m_pBackListWidget->setMaximumWidth(150);
	m_pBackListWidgetDelegate = new MessageColorListWidgetItemDelegate(m_pBackListWidget);
	m_pBackListWidget->setItemDelegate(m_pBackListWidgetDelegate);

	m_pBackItems[16] = new MessageColorListWidgetItem(m_pBackListWidget,KviControlCodes::Transparent);
	for(i=0;i<16;i++)
	{
		m_pBackItems[i] = new MessageColorListWidgetItem(m_pBackListWidget,i);
	}

	new QLabel(__tr2qs_ctx("Foreground:","options"),box);

	m_pForeListWidget = new KviTalListWidget(box);
	m_pForeListWidget->setMaximumWidth(150);
	m_pForeListWidgetDelegate = new MessageColorListWidgetItemDelegate(m_pForeListWidget);
	m_pForeListWidget->setItemDelegate(m_pForeListWidgetDelegate);

	for(i=0;i<16;i++)
	{
		m_pForeItems[i] = new MessageColorListWidgetItem(m_pForeListWidget,i);
	}

	new QLabel(__tr2qs_ctx("Alert level:","options"),box);

	m_pLevelListWidget = new KviTalListWidget(box);
	m_pLevelListWidget->setMaximumWidth(150);

	for(i=0;i<6;i++)
	{
		QString tmpn;
		tmpn.setNum(i);
		new KviTalListWidgetText(m_pLevelListWidget,tmpn);
	}

	m_pIconButton = new QToolButton(box);
	connect(m_pIconButton,SIGNAL(clicked()),this,SLOT(iconButtonClicked()));

    m_pIconPopup = new QMenu(this);
	KviIconWidget * iw = new KviIconWidget(m_pIconPopup);
	connect(iw,SIGNAL(selected(KviIconManager::SmallIcon)),this,SLOT(newIconSelected(KviIconManager::SmallIcon)));
    m_pIconPopup->addAction(new QWidgetAction(iw));


	m_pEnableLogging = new QCheckBox(__tr2qs_ctx("Log this","options"),box);

	KviTalHBox * h = new KviTalHBox(this);
	addWidgetToLayout(h,0,1,3,1);
	QPushButton * b = new QPushButton(__tr2qs_ctx("Load From...","options"),h);
	connect(b,SIGNAL(clicked()),this,SLOT(load()));
	b = new QPushButton(__tr2qs_ctx("Save As...","options"),h);
	connect(b,SIGNAL(clicked()),this,SLOT(save()));


	for(i=0;i<KVI_NUM_MSGTYPE_OPTIONS;i++)
		new MessageListWidgetItem(m_pListView,i);

	layout()->setRowStretch(0,1);
	layout()->setColumnStretch(0,1);

	connect(m_pListView,SIGNAL(itemSelectionChanged ()),this,SLOT(itemChanged()));
	connect(m_pForeListWidget,SIGNAL(itemSelectionChanged ()),this,SLOT(colorChanged()));
	connect(m_pBackListWidget,SIGNAL(itemSelectionChanged ()),this,SLOT(colorChanged()));

	itemChanged();
}
Example #28
0
QString RenderCounter::toListStyleType(int value, int total, EListStyleType type)
{
    QString item;
    switch(type)
    {
        case LNONE:
            break;
        // Glyphs: (these values are not really used and instead handled by RenderGlyph)
        case LDISC:
            item = QChar(0x2022);
            break;
        case LCIRCLE:
            item = QChar(0x25e6);
            break;
        case LSQUARE:
            item = QChar(0x25a0);
            break;
        case LBOX:
            item = QChar(0x25a1);
            break;
        case LDIAMOND:
            item = QChar(0x25c6);
            break;
        // Numeric:
        case LDECIMAL:
            item.setNum(value);
            break;
        case DECIMAL_LEADING_ZERO:
        {
            int decimals = 2;
            int t = total / 100;
            while(t > 0)
            {
                t = t / 10;
                decimals++;
            }
            decimals = kMax(decimals, 2);
            QString num = QString::number(value);
            item.fill('0', decimals - num.length());
            item.append(num);
            break;
        }
        case ARABIC_INDIC:
            item = toArabicIndic(value);
            break;
        case LAO:
            item = toLao(value);
            break;
        case PERSIAN:
        case URDU:
            item = toPersianUrdu(value);
            break;
        case THAI:
            item = toThai(value);
            break;
        case TIBETAN:
            item = toTibetan(value);
            break;
        // Algoritmic:
        case LOWER_ROMAN:
            item = toRoman(value, false);
            break;
        case UPPER_ROMAN:
            item = toRoman(value, true);
            break;
        case HEBREW:
            item = toHebrew(value);
            break;
        case ARMENIAN:
            item = toArmenian(value);
            break;
        case GEORGIAN:
            item = toGeorgian(value);
            break;
        // Alphabetic:
        case LOWER_ALPHA:
        case LOWER_LATIN:
            item = toLowerLatin(value);
            break;
        case UPPER_ALPHA:
        case UPPER_LATIN:
            item = toUpperLatin(value);
            break;
        case LOWER_GREEK:
            item = toLowerGreek(value);
            break;
        case UPPER_GREEK:
            item = toUpperGreek(value);
            break;
        case HIRAGANA:
            item = toHiragana(value);
            break;
        case HIRAGANA_IROHA:
            item = toHiraganaIroha(value);
            break;
        case KATAKANA:
            item = toKatakana(value);
            break;
        case KATAKANA_IROHA:
            item = toKatakanaIroha(value);
            break;
        // Ideographic:
        case JAPANESE_FORMAL:
            item = toJapaneseFormal(value);
            break;
        case JAPANESE_INFORMAL:
            item = toJapaneseInformal(value);
            break;
        case SIMP_CHINESE_FORMAL:
            item = toSimpChineseFormal(value);
            break;
        case SIMP_CHINESE_INFORMAL:
            item = toSimpChineseInformal(value);
            break;
        case TRAD_CHINESE_FORMAL:
            item = toTradChineseFormal(value);
            break;
        case CJK_IDEOGRAPHIC:
        // CSS 3 List says treat as trad-chinese-informal
        case TRAD_CHINESE_INFORMAL:
            item = toTradChineseInformal(value);
            break;
        default:
            item.setNum(value);
            break;
    }
    return item;
}
Example #29
0
void QEncoder::stream()
{
  if (!m_streaming)
  {
    m_streaming = true;
    m_enc=new OggTheoraEncoder();
    m_enc->video_quality = m_Vquality->text().toInt();
    m_enc->video_bitrate = m_Vbitrate->text().toInt();
    if (m_Qfreej->IsAudioOn())
    {
      m_Qjack = m_Qfreej->getQjack();
      if (m_enc->audio = m_Qjack->getAudio())
      {
	m_enc->use_audio = true;
	(m_Qjack->getJack())->isEncoded(false);
	m_enc->audio_quality = m_Aquality->text().toInt();
// 	m_enc->audio_bitrate = m_Abitrate->text().toInt();
      }
    }
    else
      m_enc->audio = NULL;

    if (m_dumpButton->isChecked())
    {
      m_enc->set_filedump(m_FileName->text().toAscii());
    }
    if (m_IceButton->isChecked())
    {
      if(shout_set_host(m_enc->ice, m_Host->text().toAscii()))
	qDebug() << "shout_set_host: " << shout_get_error(m_enc->ice);

      if(shout_set_port(m_enc->ice, m_Port->text().toInt()))
	qDebug() << "shout_set_port: " << shout_get_error(m_enc->ice);

      if(shout_set_name(m_enc->ice, m_ShoutName->text().toAscii()))
	qDebug() << "shout_set_title: " << shout_get_error(m_enc->ice);

      if(shout_set_user(m_enc->ice, m_User->text().toAscii()))
	qDebug() << "shout_set_user: "******"shout_set_pass: "******"shout_set_mount: " << shout_get_error(m_enc->ice);
      if(shout_open(m_enc->ice) == SHOUTERR_SUCCESS) {
	qDebug() << "streaming on url: http://" << shout_get_host(m_enc->ice) << ":" \
	    << shout_get_port(m_enc->ice) <<  shout_get_mount(m_enc->ice);
	m_enc->write_to_stream = true;
      } else {
	qDebug() << "error connecting to server " << shout_get_host(m_enc->ice) << ":" \
	    << shout_get_error(m_enc->ice);
	m_enc->write_to_stream = false;
      }
    }
    m_freej->add_encoder(m_enc);	//also calls the OggTheoraEncoder::init method
    if (m_enc->audio)
    {
      m_enc->audio->Jack->isEncoded(true);	//starts to fill the audio encoder ring buffer
      QString val;
      val.setNum(m_enc->getAvBitRate(), 10);
      m_Abitrate->setText(val);
    }
    m_enc->active = true;
    m_streamButton->setText("Close to STOP");
    pollerRate->start(2000);
  }
  else
  {
    m_streaming = false;
    m_enc->stop();
    m_enc->active = false;
    deleteLater();
  }
}
Example #30
0
void GlobalData::write()
{
  KConfig *config=KGlobal::config();

  config->setGroup("General");
  config->writeEntry("Lookup_Clipboard",defineClipboard);
  config->writeEntry("Heading_Layout",headLayout);
  config->writeEntry("Save_History",saveHistory);
  config->writeEntry("Max_History_Entrys",maxHistEntrys);
  config->writeEntry("Max_Browse_Entrys",maxBrowseListEntrys);
  config->writeEntry("Max_Definitions",maxDefinitions);

  config->setGroup("Colors");
  config->writeEntry("customColors",useCustomColors);
  config->writeEntry("textColor", c_olors[Ctext]);
  config->writeEntry("backgroundColor", c_olors[Cbackground]);
  config->writeEntry("headingsTextColor", c_olors[CheadingsText]);
  config->writeEntry("headingsBackgroundColor", c_olors[CheadingsBackground]);
  config->writeEntry("linksColor", c_olors[Clinks]);
  config->writeEntry("visitedLinksColor", c_olors[CvisitedLinks]);

  config->setGroup("Fonts");
  config->writeEntry("customFonts", useCustomFonts);
  config->writeEntry("textFont", f_onts[Ftext]);
  config->writeEntry("headingsFont", f_onts[Fheadings]);

  config->setGroup("Geometry");
  config->writeEntry("Opt_Size",optSize);
  config->writeEntry("Sets_Size",setsSize);
  config->writeEntry("Match_Size",matchSize);
  config->writeEntry("Show_MatchList",showMatchList);
  config->writeEntry("Splitter_Sizes",splitterSizes);

  config->setGroup("Query Combo");
  config->writeEntry("Completion_mode", (int)queryComboCompletionMode);

  config->setGroup("Query_History");
  QStringList copy;
  if (saveHistory)
    copy = queryHistory;
  config->writeEntry("History",copy);

  config->setGroup("DictServer");
  config->writeEntry("Server", server);
  config->writeEntry("Port", port);
  config->writeEntry("Timeout",timeout);
  config->writeEntry("Pipe_Size",pipeSize);
  config->writeEntry("Idle_Hold",idleHold);
  config->writeEntry("encoding", encoding);
  config->writeEntry("Auth_Enabled",authEnabled);
  config->writeEntry("User", user);
  config->writeEntry("Secret", encryptStr(secret));
  config->writeEntry("Server_Databases",serverDatabases);
  config->writeEntry("Current_Database",currentDatabase);
  config->writeEntry("Strategies",strategies);
  config->writeEntry("Current_Strategy",currentStrategy);

  config->setGroup("Database_Sets");
  config->writeEntry("Num_Sets",databaseSets.count());
  QString strNum;
  for (unsigned int i = 0;i<databaseSets.count();i++)
    config->writeEntry(strNum.setNum(i+1),*databaseSets.at(i));
}