QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* parent )
    : QWidget( parent )
{
  mLayer = layer;

  if ( !layer )
  {
    return;
  }

  setupUi( this );


  mBackgroundColorButton->setColorDialogTitle(  tr( "Background color" ) );
  mBackgroundColorButton->setColorDialogOptions( QColorDialog::ShowAlphaChannel );
  mDiagramPenColorButton->setColorDialogTitle( tr( "Pen color" ) );
  mDiagramPenColorButton->setColorDialogOptions( QColorDialog::ShowAlphaChannel );

  mValueLineEdit->setValidator( new QDoubleValidator( mValueLineEdit ) );
  mMinimumDiagramScaleLineEdit->setValidator( new QDoubleValidator( mMinimumDiagramScaleLineEdit ) );
  mMaximumDiagramScaleLineEdit->setValidator( new QDoubleValidator( mMaximumDiagramScaleLineEdit ) );

  mDiagramUnitComboBox->insertItem( 0, tr( "mm" ), QgsDiagramSettings::MM );
  mDiagramUnitComboBox->insertItem( 1, tr( "Map units" ), QgsDiagramSettings::MapUnits );

  QGis::GeometryType layerType = layer->geometryType();
  if ( layerType == QGis::UnknownGeometry || layerType == QGis::NoGeometry )
  {
    mDisplayDiagramsGroupBox->setChecked( false );
    mDisplayDiagramsGroupBox->setEnabled( false );
  }

  //insert placement options

  if ( layerType == QGis::Point || layerType == QGis::Polygon )
  {
    mPlacementComboBox->addItem( tr( "Around Point" ), QgsDiagramLayerSettings::AroundPoint );
    mPlacementComboBox->addItem( tr( "Over Point" ), QgsDiagramLayerSettings::OverPoint );
  }

  if ( layerType == QGis::Line || layerType == QGis::Polygon )
  {
    mPlacementComboBox->addItem( tr( "Line" ), QgsDiagramLayerSettings::Line );
    mPlacementComboBox->addItem( tr( "Horizontal" ), QgsDiagramLayerSettings::Horizontal );
  }

  if ( layerType == QGis::Polygon )
  {
    mPlacementComboBox->addItem( tr( "Free" ), QgsDiagramLayerSettings::Free );
  }

  if ( layerType == QGis::Line )
  {
    mLineOptionsComboBox->addItem( tr( "On line" ), QgsDiagramLayerSettings::OnLine );
    mLineOptionsComboBox->addItem( tr( "Above line" ), QgsDiagramLayerSettings::AboveLine );
    mLineOptionsComboBox->addItem( tr( "Below Line" ), QgsDiagramLayerSettings::BelowLine );
    mLineOptionsComboBox->addItem( tr( "Map orientation" ), QgsDiagramLayerSettings::MapOrientation );
  }
  else
  {
    mLineOptionsComboBox->setVisible( false );
    mLineOptionsLabel->setVisible( false );
  }

  QPixmap pix = QgsApplication::getThemePixmap( "pie-chart" );
  mDiagramTypeComboBox->addItem( pix, tr( "Pie chart" ), DIAGRAM_NAME_PIE );
  pix = QgsApplication::getThemePixmap( "text" );
  mDiagramTypeComboBox->addItem( pix, tr( "Text diagram" ), DIAGRAM_NAME_TEXT );
  pix = QgsApplication::getThemePixmap( "histogram" );
  mDiagramTypeComboBox->addItem( pix, tr( "Histogram" ), DIAGRAM_NAME_HISTOGRAM );

  mLabelPlacementComboBox->addItem( tr( "Height" ), QgsDiagramSettings::Height );
  mLabelPlacementComboBox->addItem( tr( "x-height" ), QgsDiagramSettings::XHeight );

  mScaleDependencyComboBox->addItem( tr( "Area" ), true );
  mScaleDependencyComboBox->addItem( tr( "Diameter" ), false );

  mDataDefinedXComboBox->addItem( tr( "None" ), -1 );
  mDataDefinedYComboBox->addItem( tr( "None" ), -1 );

  //insert all attributes into the combo boxes
  const QgsFields& layerFields = layer->pendingFields();
  for ( int idx = 0; idx < layerFields.count(); ++idx )
  {
    QTreeWidgetItem *newItem = new QTreeWidgetItem( mAttributesTreeWidget );
    newItem->setText( 0, layerFields[idx].name() );
    newItem->setData( 0, Qt::UserRole, idx );
    newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled );
    if ( layerFields[idx].type() != QVariant::String )
    {
      mSizeAttributeComboBox->addItem( layerFields[idx].name(), idx );
    }

    mDataDefinedXComboBox->addItem( layerFields[idx].name(), idx );
    mDataDefinedYComboBox->addItem( layerFields[idx].name(), idx );
  }

  const QgsDiagramRendererV2* dr = layer->diagramRenderer();
  if ( !dr ) //no diagram renderer yet, insert reasonable default
  {
    mDisplayDiagramsGroupBox->setChecked( false );
    mFixedSizeCheckBox->setChecked( true );
    mDiagramUnitComboBox->setCurrentIndex( mDiagramUnitComboBox->findText( tr( "mm" ) ) );
    mLabelPlacementComboBox->setCurrentIndex( mLabelPlacementComboBox->findText( tr( "x-height" ) ) );
    mDiagramSizeSpinBox->setValue( 30 );
    mBarWidthSpinBox->setValue( 5 );
    mVisibilityGroupBox->setChecked( false );

    switch ( layerType )
    {
      case QGis::Point:
        mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 0 ) );
        break;
      case QGis::Line:
        mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 3 ) );
        mLineOptionsComboBox->setCurrentIndex( mLineOptionsComboBox->findData( 2 ) );
        break;
      case QGis::Polygon:
        mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 0 ) );
        break;
      case QGis::UnknownGeometry:
      case QGis::NoGeometry:
        break;
    }
    mBackgroundColorButton->setColor( QColor( 255, 255, 255, 255 ) );
  }
  else // already a diagram renderer present
  {
    mDisplayDiagramsGroupBox->setChecked( true );

    //single category renderer or interpolated one?
    mFixedSizeCheckBox->setChecked( dr->rendererName() == "SingleCategory" );

    //assume single category or linearly interpolated diagram renderer for now
    QList<QgsDiagramSettings> settingList = dr->diagramSettings();
    if ( settingList.size() > 0 )
    {
      mDiagramFont = settingList.at( 0 ).font;
      QSizeF size = settingList.at( 0 ).size;
      mBackgroundColorButton->setColor( settingList.at( 0 ).backgroundColor );
      mTransparencySlider->setValue( settingList.at( 0 ).transparency );
      mDiagramPenColorButton->setColor( settingList.at( 0 ).penColor );
      mPenWidthSpinBox->setValue( settingList.at( 0 ).penWidth );
      mDiagramSizeSpinBox->setValue(( size.width() + size.height() ) / 2.0 );
      mMinimumDiagramScaleLineEdit->setText( QString::number( settingList.at( 0 ).minScaleDenominator, 'f' ) );
      mMaximumDiagramScaleLineEdit->setText( QString::number( settingList.at( 0 ).maxScaleDenominator, 'f' ) );
      mVisibilityGroupBox->setChecked( settingList.at( 0 ).minScaleDenominator != -1 &&
                                       settingList.at( 0 ).maxScaleDenominator != -1 );
      if ( settingList.at( 0 ).sizeType == QgsDiagramSettings::MM )
      {
        mDiagramUnitComboBox->setCurrentIndex( 0 );
      }
      else
      {
        mDiagramUnitComboBox->setCurrentIndex( 1 );
      }

      if ( settingList.at( 0 ).labelPlacementMethod == QgsDiagramSettings::Height )
      {
        mLabelPlacementComboBox->setCurrentIndex( 0 );
      }
      else
      {
        mLabelPlacementComboBox->setCurrentIndex( 1 );
      }

      mOrientationLeftButton->setProperty( "direction", QgsDiagramSettings::Left );
      mOrientationRightButton->setProperty( "direction", QgsDiagramSettings::Right );
      mOrientationUpButton->setProperty( "direction", QgsDiagramSettings::Up );
      mOrientationDownButton->setProperty( "direction", QgsDiagramSettings::Down );
      switch ( settingList.at( 0 ).diagramOrientation )
      {
        case QgsDiagramSettings::Left:
          mOrientationLeftButton->setChecked( true );
          break;

        case QgsDiagramSettings::Right:
          mOrientationRightButton->setChecked( true );
          break;

        case QgsDiagramSettings::Up:
          mOrientationUpButton->setChecked( true );
          break;

        case QgsDiagramSettings::Down:
          mOrientationDownButton->setChecked( true );
          break;
      }

      mBarWidthSpinBox->setValue( settingList.at( 0 ).barWidth );

      mIncreaseSmallDiagramsGroupBox->setChecked( settingList.at( 0 ).minimumSize != 0 );
      mIncreaseMinimumSizeSpinBox->setValue( settingList.at( 0 ).minimumSize );

      if ( settingList.at( 0 ).scaleByArea )
      {
        mScaleDependencyComboBox->setCurrentIndex( 0 );
      }
      else
      {
        mScaleDependencyComboBox->setCurrentIndex( 1 );
      }

      QList< QColor > categoryColors = settingList.at( 0 ).categoryColors;
      QList< int > categoryIndices = settingList.at( 0 ).categoryIndices;
      QList< int >::const_iterator catIt = categoryIndices.constBegin();
      QList< QColor >::const_iterator coIt = categoryColors.constBegin();
      for ( ;catIt != categoryIndices.constEnd(); ++catIt, ++coIt )
      {
        QTreeWidgetItem *newItem = new QTreeWidgetItem( mDiagramAttributesTreeWidget );
        newItem->setText( 0, layer->pendingFields()[*catIt].name() );
        newItem->setData( 0, Qt::UserRole, *catIt );
        newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled );
        QColor col( *coIt );
        col.setAlpha( 255 );
        newItem->setBackground( 1, QBrush( col ) );
      }
    }

    if ( dr->rendererName() == "LinearlyInterpolated" )
    {
      const QgsLinearlyInterpolatedDiagramRenderer* lidr = dynamic_cast<const QgsLinearlyInterpolatedDiagramRenderer*>( dr );
      if ( lidr )
      {
        mDiagramSizeSpinBox->setEnabled( false );
        mValueLineEdit->setText( QString::number( lidr->upperValue(), 'f' ) );
        mSizeSpinBox->setValue(( lidr->upperSize().width() + lidr->upperSize().height() ) / 2 );
        mSizeAttributeComboBox->setCurrentIndex( mSizeAttributeComboBox->findData( lidr->classificationAttribute() ) );
      }
    }

    const QgsDiagramLayerSettings *dls = layer->diagramLayerSettings();
    if ( dls )
    {
      mDiagramDistanceSpinBox->setValue( dls->dist );
      mPrioritySlider->setValue( dls->priority );
      mDataDefinedXComboBox->setCurrentIndex( mDataDefinedXComboBox->findData( dls->xPosColumn ) );
      mDataDefinedYComboBox->setCurrentIndex( mDataDefinedYComboBox->findData( dls->yPosColumn ) );
      if ( dls->xPosColumn != -1 || dls->yPosColumn != -1 )
      {
        mDataDefinedPositionGroupBox->setChecked( true );
      }
      mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( dls->placement ) );
      mLineOptionsComboBox->setCurrentIndex( mLineOptionsComboBox->findData( dls->placementFlags ) );
    }

    if ( dr->diagram() )
    {
      QString diagramName = dr->diagram()->diagramName();
      mDiagramTypeComboBox->setCurrentIndex( mDiagramTypeComboBox->findData( diagramName ) );
      if ( mDiagramTypeComboBox->currentIndex() == -1 )
      {
        QMessageBox::warning( this, tr( "Unknown diagram type." ),
                              tr( "The diagram type '%1' is unknown. A default type is selected for you." ).arg( diagramName ), QMessageBox::Ok );
        mDiagramTypeComboBox->setCurrentIndex( mDiagramTypeComboBox->findData( DIAGRAM_NAME_PIE ) );
      }
    }
  } // if ( !dr )

  // Trigger a clicked event, so all the items get properly enabled and disabled
  on_mDisplayDiagramsGroupBox_toggled( mDisplayDiagramsGroupBox->isChecked() );
}
QList<Nepomuk2::Query::Term> PassDateValues::run(const QList<Nepomuk2::Query::Term> &match) const
{
    QList<Nepomuk2::Query::Term> rs;
    bool valid_input = true;
    bool progress = false;

    static const PassDatePeriods::Period periods[7] = {
        PassDatePeriods::Year, PassDatePeriods::Month, PassDatePeriods::Day,
        PassDatePeriods::DayOfWeek, PassDatePeriods::Hour, PassDatePeriods::Minute,
        PassDatePeriods::Second
    };
    // Conservative minimum values (not every calendar already reached year 2000+)
    static const int min_values[7] = {
        0 /* Y */, 1 /* M */, 1 /* D */, 1 /* DW */, 0 /* H */, 0 /* M */, 0 /* S */
    };
    // Conservative maximum values (some calendars may have months of 100+ days)
    static const int max_values[7] = {
        1<<30 /* Y */, 60 /* M */, 500 /* D */, 7 /* DW */, 24 /* H */, 60 /* M */, 60 /* S */
    };

    // See if a match sets a value for any period
    for (int i=0; i<7; ++i) {
        PassDatePeriods::Period period = periods[i];

        if (i < match.count() && match.at(i).isValid()) {
            const Nepomuk2::Query::Term &term = match.at(i);
            int value;

            if (!termIntValue(term, value)) {
                // The term is not a literal integer, but may be a typed comparison
                // (month or day names)
                if (!term.isComparisonTerm()) {
                    valid_input = false;
                    break;
                }

                Nepomuk2::Query::ComparisonTerm comparison = term.toComparisonTerm();

                if (comparison.property().uri() != PassDatePeriods::propertyUrl(period, false)) {
                    valid_input = false;
                    break;
                }

                // Keep the comparison, it is already good. No need to extract
                // its value only to build a new comparison exactly the same.
                rs.append(comparison);
                continue;
            }

            if (value < min_values[i] || value > max_values[i]) {
                valid_input = false;
                break;
            }

            if (period == PassDatePeriods::Hour && pm) {
                value += 12;
            }

            // Build a comparison of the right type
            Nepomuk2::Query::LiteralTerm value_term(value);
            progress = true;

            value_term.setPosition(term);

            rs.append(Nepomuk2::Query::ComparisonTerm(
                PassDatePeriods::propertyUrl(period, false),
                value_term,
                Nepomuk2::Query::ComparisonTerm::Equal
            ));

            rs.last().setPosition(term);
        }
    }

    if (!valid_input || !progress) {
        rs.clear();
    }

    return rs;
}
void StereotypeDefinitionParser::parseIconCommands(StereotypeIcon *stereotypeIcon)
{
    Token token;
    bool loop = true;
    IconShape iconShape;
    QList<ShapeValueF> parameters;

    typedef QList<IconCommandParameter> Parameters;
    static const IconCommandParameter SCALED(ShapeValueF::UnitScaled);
    static const IconCommandParameter FIX(ShapeValueF::UnitRelative);
    static const IconCommandParameter ABSOLUTE(ShapeValueF::UnitAbsolute);

    while (loop) {
        token = readNextToken();
        if (token.type() != Token::TokenKeyword) {
            loop = false;
        } else {
            switch (token.subtype()) {
            case KEYWORD_CIRCLE:
                parameters = parseIconCommandParameters(Parameters() << SCALED << SCALED << SCALED);
                iconShape.addCircle(ShapePointF(parameters.at(0), parameters.at(1)), parameters.at(2));
                expectSemicolonOrEndOfLine();
                break;
            case KEYWORD_ELLIPSE:
                parameters = parseIconCommandParameters(Parameters() << SCALED << SCALED << SCALED << SCALED);
                iconShape.addEllipse(ShapePointF(parameters.at(0), parameters.at(1)),
                                     ShapeSizeF(parameters.at(2), parameters.at(3)));
                expectSemicolonOrEndOfLine();
                break;
            case KEYWORD_LINE:
                parameters = parseIconCommandParameters(Parameters() << SCALED << SCALED << SCALED << SCALED);
                iconShape.addLine(ShapePointF(parameters.at(0), parameters.at(1)),
                                  ShapePointF(parameters.at(2), parameters.at(3)));
                expectSemicolonOrEndOfLine();
                break;
            case KEYWORD_RECT:
                parameters = parseIconCommandParameters(Parameters() << SCALED << SCALED << SCALED << SCALED);
                iconShape.addRect(ShapePointF(parameters.at(0), parameters.at(1)),
                                  ShapeSizeF(parameters.at(2), parameters.at(3)));
                expectSemicolonOrEndOfLine();
                break;
            case KEYWORD_ROUNDEDRECT:
                parameters = parseIconCommandParameters(Parameters() << SCALED << SCALED << SCALED << SCALED << FIX);
                iconShape.addRoundedRect(ShapePointF(parameters.at(0), parameters.at(1)),
                                         ShapeSizeF(parameters.at(2), parameters.at(3)), parameters.at(4));
                expectSemicolonOrEndOfLine();
                break;
            case KEYWORD_ARC:
            {
                parameters = parseIconCommandParameters(
                                 Parameters() << SCALED << SCALED << SCALED << SCALED << ABSOLUTE << ABSOLUTE);
                qreal startAngle = expectAbsoluteValue(parameters.at(4), d->m_scanner->sourcePos());
                qreal spanAngle = expectAbsoluteValue(parameters.at(5), d->m_scanner->sourcePos());
                iconShape.addArc(ShapePointF(parameters.at(0), parameters.at(1)),
                                 ShapeSizeF(parameters.at(2), parameters.at(3)), startAngle, spanAngle);
                expectSemicolonOrEndOfLine();
                break;
            }
            case KEYWORD_MOVETO:
                parameters = parseIconCommandParameters(Parameters() << SCALED << SCALED);
                iconShape.moveTo(ShapePointF(parameters.at(0), parameters.at(1)));
                expectSemicolonOrEndOfLine();
                break;
            case KEYWORD_LINETO:
                parameters = parseIconCommandParameters(Parameters() << SCALED << SCALED);
                iconShape.lineTo(ShapePointF(parameters.at(0), parameters.at(1)));
                expectSemicolonOrEndOfLine();
                break;
            case KEYWORD_ARCMOVETO:
            {
                parameters = parseIconCommandParameters(
                                 Parameters() << SCALED << SCALED << SCALED << SCALED << ABSOLUTE);
                qreal angle = expectAbsoluteValue(parameters.at(4), d->m_scanner->sourcePos());
                iconShape.arcMoveTo(ShapePointF(parameters.at(0), parameters.at(1)),
                                    ShapeSizeF(parameters.at(2), parameters.at(3)), angle);
                expectSemicolonOrEndOfLine();
                break;
            }
            case KEYWORD_ARCTO:
            {
                parameters = parseIconCommandParameters(
                                 Parameters() << SCALED << SCALED << SCALED << SCALED << ABSOLUTE << ABSOLUTE);
                qreal startAngle = expectAbsoluteValue(parameters.at(4), d->m_scanner->sourcePos());
                qreal sweepLength = expectAbsoluteValue(parameters.at(5), d->m_scanner->sourcePos());
                iconShape.arcTo(ShapePointF(parameters.at(0), parameters.at(1)),
                                ShapeSizeF(parameters.at(2), parameters.at(3)), startAngle, sweepLength);
                expectSemicolonOrEndOfLine();
                break;
            }
            case KEYWORD_CLOSE:
                iconShape.closePath();
                expectSemicolonOrEndOfLine();
                break;
            default:
                loop = false;
                break;
            }
        }
    }
    stereotypeIcon->setIconShape(iconShape);
    d->m_scanner->unread(token);
}
void VisualClusterTree::SetNodeColorStyle(const QString& style, const QColor& color)
{
	Log::Inst().Debug("VisualClusterTree::SetNodeColorStyle(...)");

	if(!m_activeSystem || !m_tree)
		return;

	if(style == "Single colour")
	{
		m_nodeColorStyle = VisualNode::SINGLE_COLOR;
		SetNodeColor(color);
		return;
	}
	else if(style == "Propogate continuous")
		m_nodeColorStyle = VisualNode::PROPOGATE_CONTINUOUS_COLOR;
	else if(style == "Propogate weighted")
		m_nodeColorStyle = VisualNode::PROPOGATE_WEIGHTED_COLOR;
	else if(style == "Propogate discrete")
		m_nodeColorStyle = VisualNode::PROPOGATE_DISCRETE_COLOR;

	// set node colors
	QList<VisualNode*> postOrderNodes = m_tree->PostOrder();
	if(postOrderNodes.size() == 1)
		return;	// there is only a root node

	foreach(VisualNode* node, postOrderNodes)
	{
		QColor nodeColor;
		if(node->IsLeaf())
		{
			// set color of node based on legend
			Sample sample;
			if(!m_activeSystem->GetSamples()->GetSample(node->GetName(), sample))
				Log::Inst().Error("Invalid sample specified setting node colour: " + node->GetName());

			nodeColor = sample.GetColor();
		}
		else
		{
			// set color of node based on color of children
			QList<VisualNode*> children = node->GetChildren();
			
			if(m_nodeColorStyle == VisualNode::PROPOGATE_DISCRETE_COLOR)
			{
				nodeColor = children.at(0)->GetColor();
				for(int j = 0; j < children.size(); ++j)
				{
					if(children.at(j)->GetColor() != nodeColor)
						nodeColor = Qt::black;
				}
			}
			else if(m_nodeColorStyle == VisualNode::PROPOGATE_CONTINUOUS_COLOR)
			{
				float red = 0.0f, green = 0.0f, blue = 0.0f;
				for(int j = 0; j < children.size(); ++j)
				{
					QColor color = children.at(j)->GetColor();
					red += color.redF();
					green += color.greenF();
					blue += color.blueF();
				}

				nodeColor.setRedF(red / children.size());
				nodeColor.setGreenF(green / children.size());
				nodeColor.setBlueF(blue / children.size());
			}
			else // m_nodeColorStyle == VisualNode::PROPOGATE_WEIGHTED_COLOR
			{
				float red = 0.0f, green = 0.0f, blue = 0.0f;
				uint totalWeight = 0;
				for(int j = 0; j < children.size(); ++j)
				{
					uint weight = children.at(j)->GetWeightedNumberOfSeqs();
					totalWeight += weight;

					QColor color = children.at(j)->GetColor();
					red += color.redF() * weight;
					green += color.greenF() * weight;
					blue += color.blueF() * weight;
				}

				nodeColor.setRedF(red / totalWeight);
				nodeColor.setGreenF(green / totalWeight);
				nodeColor.setBlueF(blue / totalWeight);
			}
		}

		node->SetColor(nodeColor);
		node->update();
	}
Example #5
0
ShapePropertiesDialog::ShapePropertiesDialog(ShapeAnnotation *pShapeAnnotation, MainWindow *pMainWindow)
  : QDialog(pMainWindow, Qt::WindowTitleHint)
{
  mpShapeAnnotation = pShapeAnnotation;
  mpLineAnnotation = dynamic_cast<LineAnnotation*>(mpShapeAnnotation);
  mpPolygonAnnotation = dynamic_cast<PolygonAnnotation*>(mpShapeAnnotation);
  mpRectangleAnnotation = dynamic_cast<RectangleAnnotation*>(mpShapeAnnotation);
  mpEllipseAnnotation = dynamic_cast<EllipseAnnotation*>(mpShapeAnnotation);
  mpTextAnnotation = dynamic_cast<TextAnnotation*>(mpShapeAnnotation);
  mpBitmapAnnotation = dynamic_cast<BitmapAnnotation*>(mpShapeAnnotation);
  mpMainWindow = pMainWindow;
  QString title = getTitle();
  setWindowTitle(QString(Helper::applicationName).append(" - ").append(title).append(" ").append(Helper::properties));
  setAttribute(Qt::WA_DeleteOnClose);
  // heading label
  mpShapePropertiesHeading = new Label(QString(title).append(" ").append(Helper::properties));
  mpShapePropertiesHeading->setFont(QFont(Helper::systemFontInfo.family(), Helper::headingFontSize));
  mpShapePropertiesHeading->setAlignment(Qt::AlignTop);
  // set seperator line
  mHorizontalLine = new QFrame();
  mHorizontalLine->setFrameShape(QFrame::HLine);
  mHorizontalLine->setFrameShadow(QFrame::Sunken);
  // Transformations Group Box
  mpTransformationGroupBox = new QGroupBox(tr("Transformation"));
  mpOriginXLabel = new Label(Helper::originX);
  mpOriginXSpinBox = new DoubleSpinBox;
  mpOriginXSpinBox->setRange(-std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
  mpOriginXSpinBox->setValue(mpShapeAnnotation->getOrigin().x());
  mpOriginXSpinBox->setSingleStep(1);
  mpOriginYLabel = new Label(Helper::originY);
  mpOriginYSpinBox = new DoubleSpinBox;
  mpOriginYSpinBox->setRange(-std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
  mpOriginYSpinBox->setValue(mpShapeAnnotation->getOrigin().y());
  mpOriginYSpinBox->setSingleStep(1);
  mpRotationLabel = new Label(Helper::rotation);
  mpRotationSpinBox = new DoubleSpinBox;
  mpRotationSpinBox->setRange(-std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
  mpRotationSpinBox->setValue(mpShapeAnnotation->getRotation());
  mpRotationSpinBox->setSingleStep(90);
  // set the Transformations Group Box layout
  QGridLayout *pTransformationGridLayout = new QGridLayout;
  pTransformationGridLayout->setColumnStretch(1, 1);
  pTransformationGridLayout->setColumnStretch(3, 1);
  pTransformationGridLayout->setColumnStretch(5, 1);
  pTransformationGridLayout->addWidget(mpOriginXLabel, 0, 0);
  pTransformationGridLayout->addWidget(mpOriginXSpinBox, 0, 1);
  pTransformationGridLayout->addWidget(mpOriginYLabel, 0, 2);
  pTransformationGridLayout->addWidget(mpOriginYSpinBox, 0, 3);
  pTransformationGridLayout->addWidget(mpRotationLabel, 0, 4);
  pTransformationGridLayout->addWidget(mpRotationSpinBox, 0, 5);
  mpTransformationGroupBox->setLayout(pTransformationGridLayout);
  // Extent Group Box
  mpExtentGroupBox = new QGroupBox(Helper::extent);
  // Extent1X
  QList<QPointF> extents = mpShapeAnnotation->getExtents();
  mpExtent1XLabel = new Label(Helper::extent1X);
  mpExtent1XSpinBox = new DoubleSpinBox;
  mpExtent1XSpinBox->setRange(-std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
  mpExtent1XSpinBox->setValue(extents.size() > 0 ? extents.at(0).x() : 0);
  mpExtent1XSpinBox->setSingleStep(10);
  mpExtent1YLabel = new Label(Helper::extent1Y);
  mpExtent1YSpinBox = new DoubleSpinBox;
  mpExtent1YSpinBox->setRange(-std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
  mpExtent1YSpinBox->setValue(extents.size() > 0 ? extents.at(0).y() : 0);
  mpExtent1YSpinBox->setSingleStep(10);
  mpExtent2XLabel = new Label(Helper::extent2X);
  mpExtent2XSpinBox = new DoubleSpinBox;
  mpExtent2XSpinBox->setRange(-std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
  mpExtent2XSpinBox->setValue(extents.size() > 0 ? extents.at(1).x() : 0);
  mpExtent2XSpinBox->setSingleStep(10);
  mpExtent2YLabel = new Label(Helper::extent2Y);
  mpExtent2YSpinBox = new DoubleSpinBox;
  mpExtent2YSpinBox->setRange(-std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
  mpExtent2YSpinBox->setValue(extents.size() > 0 ? extents.at(1).y() : 0);
  mpExtent2YSpinBox->setSingleStep(10);
  // set the extents Group Box layout
  QGridLayout *pExtentGroupBoxLayout = new QGridLayout;
  pExtentGroupBoxLayout->setColumnStretch(1, 1);
  pExtentGroupBoxLayout->setColumnStretch(3, 1);
  pExtentGroupBoxLayout->addWidget(mpExtent1XLabel, 0, 0);
  pExtentGroupBoxLayout->addWidget(mpExtent1XSpinBox, 0, 1);
  pExtentGroupBoxLayout->addWidget(mpExtent1YLabel, 0, 2);
  pExtentGroupBoxLayout->addWidget(mpExtent1YSpinBox, 0, 3);
  pExtentGroupBoxLayout->addWidget(mpExtent2XLabel, 1, 0);
  pExtentGroupBoxLayout->addWidget(mpExtent2XSpinBox, 1, 1);
  pExtentGroupBoxLayout->addWidget(mpExtent2YLabel, 1, 2);
  pExtentGroupBoxLayout->addWidget(mpExtent2YSpinBox, 1, 3);
  mpExtentGroupBox->setLayout(pExtentGroupBoxLayout);
  // Border style Group Box
  mpBorderStyleGroupBox = new QGroupBox(tr("Border Style"));
  // border pattern
  mpBorderPatternLabel = new Label(Helper::pattern);
  mpBorderPatternComboBox = new QComboBox;
  mpBorderPatternComboBox->addItem(StringHandler::getBorderPatternString(StringHandler::BorderNone));
  mpBorderPatternComboBox->addItem(StringHandler::getBorderPatternString(StringHandler::BorderRaised));
  mpBorderPatternComboBox->addItem(StringHandler::getBorderPatternString(StringHandler::BorderSunken));
  mpBorderPatternComboBox->addItem(StringHandler::getBorderPatternString(StringHandler::BorderEngraved));
  int currentIndex = mpBorderPatternComboBox->findText(StringHandler::getBorderPatternString(mpShapeAnnotation->getBorderPattern()), Qt::MatchExactly);
  if (currentIndex > -1)
    mpBorderPatternComboBox->setCurrentIndex(currentIndex);
  // radius
  mpRadiusLabel = new Label(Helper::radius);
  mpRadiusSpinBox = new DoubleSpinBox;
  mpRadiusSpinBox->setRange(0, std::numeric_limits<double>::max());
  mpRadiusSpinBox->setValue(mpShapeAnnotation->getRadius());
  mpRadiusSpinBox->setSingleStep(1);
  // set the border style Group Box layout
  QGridLayout *pBorderStyleGridLayout = new QGridLayout;
  pBorderStyleGridLayout->setColumnStretch(1, 1);
  pBorderStyleGridLayout->setColumnStretch(3, 1);
  pBorderStyleGridLayout->addWidget(mpBorderPatternLabel, 0, 0);
  pBorderStyleGridLayout->addWidget(mpBorderPatternComboBox, 0, 1);
  pBorderStyleGridLayout->addWidget(mpRadiusLabel, 0, 2);
  pBorderStyleGridLayout->addWidget(mpRadiusSpinBox, 0, 3);
  mpBorderStyleGroupBox->setLayout(pBorderStyleGridLayout);
  // Angle Group Box
  mpAngleGroupBox = new QGroupBox(tr("Angle"));
  // start angle
  mpStartAngleLabel = new Label(Helper::startAngle);
  mpStartAngleSpinBox = new DoubleSpinBox;
  mpStartAngleSpinBox->setRange(-std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
  mpStartAngleSpinBox->setValue(mpShapeAnnotation->getStartAngle());
  mpStartAngleSpinBox->setSingleStep(90);
  // end angle
  mpEndAngleLabel = new Label(Helper::endAngle);
  mpEndAngleSpinBox = new DoubleSpinBox;
  mpEndAngleSpinBox->setRange(-std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
  mpEndAngleSpinBox->setValue(mpShapeAnnotation->getEndAngle());
  mpEndAngleSpinBox->setSingleStep(90);
  // set the border style Group Box layout
  QGridLayout *pAngleGridLayout = new QGridLayout;
  pAngleGridLayout->setColumnStretch(1, 1);
  pAngleGridLayout->setColumnStretch(3, 1);
  pAngleGridLayout->addWidget(mpStartAngleLabel, 0, 0);
  pAngleGridLayout->addWidget(mpStartAngleSpinBox, 0, 1);
  pAngleGridLayout->addWidget(mpEndAngleLabel, 0, 2);
  pAngleGridLayout->addWidget(mpEndAngleSpinBox, 0, 3);
  mpAngleGroupBox->setLayout(pAngleGridLayout);
  // Text Group Box
  mpTextGroupBox = new QGroupBox(tr("Text"));
  mpTextTextBox = new QLineEdit(mpShapeAnnotation->getTextString());
  // set the Text Group Box layout
  QHBoxLayout *pTextGroupBoxLayout = new QHBoxLayout;
  pTextGroupBoxLayout->addWidget(mpTextTextBox);
  mpTextGroupBox->setLayout(pTextGroupBoxLayout);
  // Font Style Group Box
  mpFontAndTextStyleGroupBox = new QGroupBox(tr("Font && Text Style"));
  mpFontNameLabel = new Label(Helper::name);
  mpFontNameComboBox = new QFontComboBox;
  mpFontNameComboBox->insertItem(0, "Default");
  currentIndex = mpFontNameComboBox->findText(mpShapeAnnotation->getFontName(), Qt::MatchExactly);
  if (currentIndex > -1)
    mpFontNameComboBox->setCurrentIndex(currentIndex);
  else
    mpFontNameComboBox->setCurrentIndex(0);
  mpFontSizeLabel = new Label(Helper::size);
  mpFontSizeSpinBox = new DoubleSpinBox;
  mpFontSizeSpinBox->setRange(0, std::numeric_limits<double>::max());
  mpFontSizeSpinBox->setValue(mpShapeAnnotation->getFontSize());
  mpFontSizeSpinBox->setSingleStep(1);
  mpFontStyleLabel = new Label(tr("Style:"));
  mpTextBoldCheckBox = new QCheckBox(tr("Bold"));
  mpTextBoldCheckBox->setChecked(StringHandler::getFontWeight(mpShapeAnnotation->getTextStyles()) == QFont::Bold ? true : false);
  mpTextItalicCheckBox = new QCheckBox(tr("Italic"));
  mpTextItalicCheckBox->setChecked(StringHandler::getFontItalic(mpShapeAnnotation->getTextStyles()));
  mpTextUnderlineCheckBox = new QCheckBox(tr("Underline"));
  mpTextUnderlineCheckBox->setChecked(StringHandler::getFontUnderline(mpShapeAnnotation->getTextStyles()));
  mpTextHorizontalAlignmentLabel = new Label(tr("Horizontal Alignment:"));
  mpTextHorizontalAlignmentComboBox = new QComboBox;
  mpTextHorizontalAlignmentComboBox->addItem(StringHandler::getTextAlignmentString(StringHandler::TextAlignmentLeft));
  mpTextHorizontalAlignmentComboBox->addItem(StringHandler::getTextAlignmentString(StringHandler::TextAlignmentCenter));
  mpTextHorizontalAlignmentComboBox->addItem(StringHandler::getTextAlignmentString(StringHandler::TextAlignmentRight));
  currentIndex = mpTextHorizontalAlignmentComboBox->findText(StringHandler::getTextAlignmentString(mpShapeAnnotation->getTextHorizontalAlignment()), Qt::MatchExactly);
  if (currentIndex > -1)
    mpTextHorizontalAlignmentComboBox->setCurrentIndex(currentIndex);
  // set the Font Style Group Box layout
  QGridLayout *pFontAndTextStyleGroupBox = new QGridLayout;
  pFontAndTextStyleGroupBox->setColumnStretch(5, 1);
  pFontAndTextStyleGroupBox->addWidget(mpFontNameLabel, 0, 0);
  pFontAndTextStyleGroupBox->addWidget(mpFontNameComboBox, 0, 1, 1, 3);
  pFontAndTextStyleGroupBox->addWidget(mpFontSizeLabel, 0, 4);
  pFontAndTextStyleGroupBox->addWidget(mpFontSizeSpinBox, 0, 5);
  pFontAndTextStyleGroupBox->addWidget(mpFontStyleLabel, 1, 0);
  pFontAndTextStyleGroupBox->addWidget(mpTextBoldCheckBox, 1, 1);
  pFontAndTextStyleGroupBox->addWidget(mpTextItalicCheckBox, 1, 2);
  pFontAndTextStyleGroupBox->addWidget(mpTextUnderlineCheckBox, 1, 3);
  pFontAndTextStyleGroupBox->addWidget(mpTextHorizontalAlignmentLabel, 1, 4);
  pFontAndTextStyleGroupBox->addWidget(mpTextHorizontalAlignmentComboBox, 1, 5);
  mpFontAndTextStyleGroupBox->setLayout(pFontAndTextStyleGroupBox);
  // Line style Group Box
  mpLineStyleGroupBox = new QGroupBox(Helper::lineStyle);
  // Line Color
  mpLineColorLabel = new Label(Helper::color);
  mpLinePickColorButton = new QPushButton(Helper::pickColor);
  mpLinePickColorButton->setAutoDefault(false);
  connect(mpLinePickColorButton, SIGNAL(clicked()), SLOT(linePickColor()));
  setLineColor(mpShapeAnnotation->getLineColor());
  setLinePickColorButtonIcon();
  // Line Pattern
  mpLinePatternLabel = new Label(Helper::pattern);
  mpLinePatternComboBox = StringHandler::getLinePatternComboBox();
  currentIndex = mpLinePatternComboBox->findText(StringHandler::getLinePatternString(mpShapeAnnotation->getLinePattern()), Qt::MatchExactly);
  if (currentIndex > -1)
    mpLinePatternComboBox->setCurrentIndex(currentIndex);
  // Line Thickness
  mpLineThicknessLabel = new Label(Helper::thickness);
  mpLineThicknessSpinBox = new DoubleSpinBox;
  mpLineThicknessSpinBox->setRange(0, std::numeric_limits<double>::max());
  mpLineThicknessSpinBox->setValue(mpShapeAnnotation->getLineThickness());
  mpLineThicknessSpinBox->setSingleStep(0.25);
  // Line smooth
  mpLineSmoothLabel = new Label(Helper::smooth);
  mpLineSmoothCheckBox = new QCheckBox(Helper::bezier);
  if (mpShapeAnnotation->getSmooth() == StringHandler::SmoothBezier)
    mpLineSmoothCheckBox->setChecked(true);
  // set the Line style Group Box layout
  QGridLayout *pLineStyleGroupBoxLayout = new QGridLayout;
  pLineStyleGroupBoxLayout->setAlignment(Qt::AlignTop);
  pLineStyleGroupBoxLayout->setColumnStretch(1, 1);
  pLineStyleGroupBoxLayout->addWidget(mpLineColorLabel, 0, 0);
  pLineStyleGroupBoxLayout->addWidget(mpLinePickColorButton, 0, 1);
  pLineStyleGroupBoxLayout->addWidget(mpLinePatternLabel, 1, 0);
  pLineStyleGroupBoxLayout->addWidget(mpLinePatternComboBox, 1, 1);
  pLineStyleGroupBoxLayout->addWidget(mpLineThicknessLabel, 2, 0);
  pLineStyleGroupBoxLayout->addWidget(mpLineThicknessSpinBox, 2, 1);
  if (mpLineAnnotation || mpPolygonAnnotation)
  {
    pLineStyleGroupBoxLayout->addWidget(mpLineSmoothLabel, 3, 0);
    pLineStyleGroupBoxLayout->addWidget(mpLineSmoothCheckBox, 3, 1);
  }
  mpLineStyleGroupBox->setLayout(pLineStyleGroupBoxLayout);
  // Arrow style Group Box
  mpArrowStyleGroupBox = new QGroupBox(tr("Arrow Style"));
  // Start Arrow
  mpLineStartArrowLabel = new Label(Helper::startArrow);
  mpLineStartArrowComboBox = StringHandler::getStartArrowComboBox();
  currentIndex = mpLineStartArrowComboBox->findText(StringHandler::getArrowString(mpShapeAnnotation->getStartArrow()), Qt::MatchExactly);
  if (currentIndex > -1)
    mpLineStartArrowComboBox->setCurrentIndex(currentIndex);
  mpLineEndArrowLabel = new Label(Helper::endArrow);
  mpLineEndArrowComboBox = StringHandler::getEndArrowComboBox();
  currentIndex = mpLineEndArrowComboBox->findText(StringHandler::getArrowString(mpShapeAnnotation->getEndArrow()), Qt::MatchExactly);
  if (currentIndex > -1)
    mpLineEndArrowComboBox->setCurrentIndex(currentIndex);
  mpLineArrowSizeLabel = new Label(Helper::arrowSize);
  mpLineArrowSizeSpinBox = new DoubleSpinBox;
  mpLineArrowSizeSpinBox->setRange(0, std::numeric_limits<double>::max());
  mpLineArrowSizeSpinBox->setValue(mpShapeAnnotation->getArrowSize());
  mpLineArrowSizeSpinBox->setSingleStep(1);
  // set the Arrow style Group Box layout
  QGridLayout *pArrowStyleGroupBoxLayout = new QGridLayout;
  pArrowStyleGroupBoxLayout->setAlignment(Qt::AlignTop);
  pArrowStyleGroupBoxLayout->setColumnStretch(1, 1);
  pArrowStyleGroupBoxLayout->addWidget(mpLineStartArrowLabel, 0, 0);
  pArrowStyleGroupBoxLayout->addWidget(mpLineStartArrowComboBox, 0, 1);
  pArrowStyleGroupBoxLayout->addWidget(mpLineEndArrowLabel, 1, 0);
  pArrowStyleGroupBoxLayout->addWidget(mpLineEndArrowComboBox, 1, 1);
  pArrowStyleGroupBoxLayout->addWidget(mpLineArrowSizeLabel, 2, 0);
  pArrowStyleGroupBoxLayout->addWidget(mpLineArrowSizeSpinBox, 2, 1);
  mpArrowStyleGroupBox->setLayout(pArrowStyleGroupBoxLayout);
  // Fill style Group Box
  mpFillStyleGroupBox = new QGroupBox(Helper::fillStyle);
  // Fill Color
  mpFillColorLabel = new Label(Helper::color);
  mpFillPickColorButton = new QPushButton(Helper::pickColor);
  mpFillPickColorButton->setAutoDefault(false);
  connect(mpFillPickColorButton, SIGNAL(clicked()), SLOT(fillPickColor()));
  setFillColor(mpShapeAnnotation->getFillColor());
  setFillPickColorButtonIcon();
  // Fill Pattern
  mpFillPatternLabel = new Label(Helper::pattern);
  mpFillPatternComboBox = StringHandler::getFillPatternComboBox();
  currentIndex = mpFillPatternComboBox->findText(StringHandler::getFillPatternString(mpShapeAnnotation->getFillPattern()), Qt::MatchExactly);
  if (currentIndex > -1)
    mpFillPatternComboBox->setCurrentIndex(currentIndex);
  // set the Fill style Group Box layout
  QGridLayout *pFillStyleGroupBoxLayout = new QGridLayout;
  pFillStyleGroupBoxLayout->setAlignment(Qt::AlignTop);
  pFillStyleGroupBoxLayout->setColumnStretch(1, 1);
  pFillStyleGroupBoxLayout->addWidget(mpFillColorLabel, 0, 0);
  pFillStyleGroupBoxLayout->addWidget(mpFillPickColorButton, 0, 1);
  pFillStyleGroupBoxLayout->addWidget(mpFillPatternLabel, 1, 0);
  pFillStyleGroupBoxLayout->addWidget(mpFillPatternComboBox, 1, 1);
  mpFillStyleGroupBox->setLayout(pFillStyleGroupBoxLayout);
  // Image Group Box
  mpImageGroupBox = new QGroupBox(tr("Image"));
  mpFileLabel = new Label(Helper::file);
  mpFileTextBox = new QLineEdit(mpShapeAnnotation->getFileName());
  mpFileTextBox->setEnabled(false);
  mpBrowseFileButton = new QPushButton(Helper::browse);
  connect(mpBrowseFileButton, SIGNAL(clicked()), SLOT(browseImageFile()));
  mpStoreImageInModelCheckBox = new QCheckBox(tr("Store image in model"));
  mpStoreImageInModelCheckBox->setChecked(mpShapeAnnotation->getFileName().isEmpty());
  connect(mpStoreImageInModelCheckBox, SIGNAL(toggled(bool)), SLOT(storeImageInModelToggled(bool)));
  mpPreviewImageLabel = new Label;
  mpPreviewImageLabel->setAlignment(Qt::AlignCenter);
  mpPreviewImageLabel->setPixmap(QPixmap::fromImage(mpShapeAnnotation->getImage()));
  mpPreviewImageScrollArea = new QScrollArea;
  mpPreviewImageScrollArea->setMinimumSize(400, 150);
  mpPreviewImageScrollArea->setWidgetResizable(true);
  mpPreviewImageScrollArea->setWidget(mpPreviewImageLabel);
  // set the Image Group Box
  QGridLayout *pImageGroupBoxLayout = new QGridLayout;
  pImageGroupBoxLayout->addWidget(mpFileLabel, 0, 0);
  pImageGroupBoxLayout->addWidget(mpFileTextBox, 0, 1);
  pImageGroupBoxLayout->addWidget(mpBrowseFileButton, 0, 2);
  pImageGroupBoxLayout->addWidget(mpStoreImageInModelCheckBox, 1, 0, 1, 3);
  pImageGroupBoxLayout->addWidget(mpPreviewImageScrollArea, 2, 0, 1, 3);
  mpImageGroupBox->setLayout(pImageGroupBoxLayout);
  // Points Group Box
  mpPointsGroupBox = new QGroupBox(tr("Points"));
  mpPointsTableWidget = new QTableWidget;
  mpPointsTableWidget->setTextElideMode(Qt::ElideMiddle);
  mpPointsTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
  mpPointsTableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
  mpPointsTableWidget->setColumnCount(2);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
  mpPointsTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
#else /* Qt4 */
  mpPointsTableWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
#endif
  QStringList headerLabels;
  headerLabels << "X" << "Y";
  mpPointsTableWidget->setHorizontalHeaderLabels(headerLabels);
  // add points to points table widget
  QList<QPointF> points = mpShapeAnnotation->getPoints();
  mpPointsTableWidget->setRowCount(points.size());
  int rowIndex = 0;
  LineAnnotation::LineType lineType = LineAnnotation::ShapeType;
  if (mpLineAnnotation) lineType = mpLineAnnotation->getLineType();
  foreach (QPointF point, points)
  {
    QTableWidgetItem *pTableWidgetItemX = new QTableWidgetItem(QString::number(point.x()));
    if ((rowIndex == 0 || rowIndex == points.size() - 1) && (lineType == LineAnnotation::ConnectionType))
      pTableWidgetItemX->setFlags(Qt::NoItemFlags);
    else
      pTableWidgetItemX->setFlags(pTableWidgetItemX->flags() | Qt::ItemIsEditable);
    mpPointsTableWidget->setItem(rowIndex, 0, pTableWidgetItemX);
    QTableWidgetItem *pTableWidgetItemY = new QTableWidgetItem(QString::number(point.y()));
    if ((rowIndex == 0 || rowIndex == points.size() - 1) && (lineType == LineAnnotation::ConnectionType))
      pTableWidgetItemY->setFlags(Qt::NoItemFlags);
    else
      pTableWidgetItemY->setFlags(pTableWidgetItemY->flags() | Qt::ItemIsEditable);
    mpPointsTableWidget->setItem(rowIndex, 1, pTableWidgetItemY);
    rowIndex++;
  }
void ExoplanetsDialog::populateDiagramsList()
{
	Q_ASSERT(ui->comboAxisX);
	Q_ASSERT(ui->comboAxisY);

	QColor axisColor(Qt::white);
	QPen axisPen(axisColor, 1);

	ui->customPlot->setBackground(QBrush(QColor(86, 87, 90)));
	ui->customPlot->xAxis->setLabelColor(axisColor);
	ui->customPlot->xAxis->setTickLabelColor(axisColor);
	ui->customPlot->xAxis->setBasePen(axisPen);
	ui->customPlot->xAxis->setTickPen(axisPen);
	ui->customPlot->xAxis->setSubTickPen(axisPen);
	ui->customPlot->yAxis->setLabelColor(axisColor);
	ui->customPlot->yAxis->setTickLabelColor(axisColor);
	ui->customPlot->yAxis->setBasePen(axisPen);
	ui->customPlot->yAxis->setTickPen(axisPen);
	ui->customPlot->yAxis->setSubTickPen(axisPen);

	QComboBox* axisX = ui->comboAxisX;
	QComboBox* axisY = ui->comboAxisY;

	//Save the current selection to be restored later
	axisX->blockSignals(true);
	axisY->blockSignals(true);
	int indexX = axisX->currentIndex();
	int indexY = axisY->currentIndex();	
	QVariant selectedAxisX = axisX->itemData(indexX);
	QVariant selectedAxisY = axisY->itemData(indexY);
	axisX->clear();
	axisY->clear();

	QList<axisPair> axis;
	axis.append(qMakePair(q_("Orbital Eccentricity"), 0));
	axis.append(qMakePair(q_("Orbit Semi-Major Axis, AU"), 1));
	axis.append(qMakePair(q_("Planetary Mass, Mjup"), 2));
	axis.append(qMakePair(q_("Planetary Radius, Rjup"), 3));
	axis.append(qMakePair(q_("Orbital Period, days"), 4));
	axis.append(qMakePair(q_("Angular Distance, arcsec"), 5));
	axis.append(qMakePair(q_("Effective temperature of host star, K"), 6));
	axis.append(qMakePair(q_("Year of Discovery"), 7));
	axis.append(qMakePair(q_("Metallicity of host star"), 8));
	axis.append(qMakePair(q_("V magnitude of host star, mag"), 9));
	axis.append(qMakePair(q_("RA (J2000) of star, deg"), 10));
	axis.append(qMakePair(q_("Dec (J2000) of star, deg"), 11));
	axis.append(qMakePair(q_("Distance to star, pc"), 12));
	axis.append(qMakePair(q_("Mass of host star, Msol"), 13));
	axis.append(qMakePair(q_("Radius of host star, Rsol"), 14));

	for(int i=0; i<axis.size(); ++i)
	{
		axisX->addItem(axis.at(i).first, axis.at(i).second);
		axisY->addItem(axis.at(i).first, axis.at(i).second);
	}

	//Restore the selection
	indexX = axisX->findData(selectedAxisX, Qt::UserRole, Qt::MatchCaseSensitive);
	if (indexX<0)
		indexX = 1;
	indexY = axisY->findData(selectedAxisY, Qt::UserRole, Qt::MatchCaseSensitive);
	if (indexY<0)
		indexY = 0;
	axisX->setCurrentIndex(indexX);
	axisY->setCurrentIndex(indexY);
	axisX->blockSignals(false);
	axisY->blockSignals(false);
}
static QString generateInterfaceXml(const QMetaObject *mo, int flags, int methodOffset, int propOffset)
{
    QString retval;

    // start with properties:
    if (flags & (QDBusConnection::ExportScriptableProperties |
                 QDBusConnection::ExportNonScriptableProperties)) {
        for (int i = propOffset; i < mo->propertyCount(); ++i) {
            static const char *accessvalues[] = {0, "read", "write", "readwrite"};

            QMetaProperty mp = mo->property(i);

            if (!((mp.isScriptable() && (flags & QDBusConnection::ExportScriptableProperties)) ||
                  (!mp.isScriptable() && (flags & QDBusConnection::ExportNonScriptableProperties))))
                continue;

            int access = 0;
            if (mp.isReadable())
                access |= 1;
            if (mp.isWritable())
                access |= 2;

            int typeId = qDBusNameToTypeId(mp.typeName());
            if (!typeId)
                continue;
            const char *signature = QDBusMetaType::typeToSignature(typeId);
            if (!signature)
                continue;

            retval += QString::fromLatin1("    <property name=\"%1\" type=\"%2\" access=\"%3\"")
                      .arg(QLatin1String(mp.name()))
                      .arg(QLatin1String(signature))
                      .arg(QLatin1String(accessvalues[access]));

            if (QDBusMetaType::signatureToType(signature) == QVariant::Invalid) {
                const char *typeName = QVariant::typeToName(QVariant::Type(typeId));
                retval += QString::fromLatin1(">\n      <annotation name=\"com.trolltech.QtDBus.QtTypeName\" value=\"%3\"/>\n    </property>\n")
                          .arg(typeNameToXml(typeName));
            } else {
                retval += QLatin1String("/>\n");
            }
        }
    }

    // now add methods:
    for (int i = methodOffset; i < mo->methodCount(); ++i) {
        QMetaMethod mm = mo->method(i);
        QByteArray signature = mm.signature();
        int paren = signature.indexOf('(');

        bool isSignal;
        if (mm.methodType() == QMetaMethod::Signal)
            // adding a signal
            isSignal = true;
        else if (mm.access() == QMetaMethod::Public && (mm.methodType() == QMetaMethod::Slot || mm.methodType() == QMetaMethod::Method))
            isSignal = false;
        else
            continue;           // neither signal nor public slot

        if (isSignal && !(flags & (QDBusConnection::ExportScriptableSignals |
                                   QDBusConnection::ExportNonScriptableSignals)))
            continue;           // we're not exporting any signals
        if (!isSignal && (!(flags & (QDBusConnection::ExportScriptableSlots | QDBusConnection::ExportNonScriptableSlots)) &&
                          !(flags & (QDBusConnection::ExportScriptableInvokables | QDBusConnection::ExportNonScriptableInvokables))))
            continue;           // we're not exporting any slots or invokables

        QString xml = QString::fromLatin1("    <%1 name=\"%2\">\n")
                      .arg(isSignal ? QLatin1String("signal") : QLatin1String("method"))
                      .arg(QLatin1String(signature.left(paren)));

        // check the return type first
        int typeId = qDBusNameToTypeId(mm.typeName());
        if (typeId) {
            const char *typeName = QDBusMetaType::typeToSignature(typeId);
            if (typeName) {
                xml += QString::fromLatin1("      <arg type=\"%1\" direction=\"out\"/>\n")
                       .arg(typeNameToXml(typeName));

                // do we need to describe this argument?
                if (QDBusMetaType::signatureToType(typeName) == QVariant::Invalid)
                    xml += QString::fromLatin1("      <annotation name=\"com.trolltech.QtDBus.QtTypeName.Out0\" value=\"%1\"/>\n")
                        .arg(typeNameToXml(QVariant::typeToName(QVariant::Type(typeId))));
            } else
                continue;
        }
        else if (*mm.typeName())
            continue;           // wasn't a valid type

        QList<QByteArray> names = mm.parameterNames();
        QList<int> types;
        int inputCount = qDBusParametersForMethod(mm, types);
        if (inputCount == -1)
            continue;           // invalid form
        if (isSignal && inputCount + 1 != types.count())
            continue;           // signal with output arguments?
        if (isSignal && types.at(inputCount) == QDBusMetaTypeId::message)
            continue;           // signal with QDBusMessage argument?
        if (isSignal && mm.attributes() & QMetaMethod::Cloned)
            continue;           // cloned signal?

        int j;
        bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
        for (j = 1; j < types.count(); ++j) {
            // input parameter for a slot or output for a signal
            if (types.at(j) == QDBusMetaTypeId::message) {
                isScriptable = true;
                continue;
            }

            QString name;
            if (!names.at(j - 1).isEmpty())
                name = QString::fromLatin1("name=\"%1\" ").arg(QLatin1String(names.at(j - 1)));

            bool isOutput = isSignal || j > inputCount;

            const char *signature = QDBusMetaType::typeToSignature(types.at(j));
            xml += QString::fromLatin1("      <arg %1type=\"%2\" direction=\"%3\"/>\n")
                   .arg(name)
                   .arg(QLatin1String(signature))
                   .arg(isOutput ? QLatin1String("out") : QLatin1String("in"));

            // do we need to describe this argument?
            if (QDBusMetaType::signatureToType(signature) == QVariant::Invalid) {
                const char *typeName = QVariant::typeToName( QVariant::Type(types.at(j)) );
                xml += QString::fromLatin1("      <annotation name=\"com.trolltech.QtDBus.QtTypeName.%1%2\" value=\"%3\"/>\n")
                       .arg(isOutput ? QLatin1String("Out") : QLatin1String("In"))
                       .arg(isOutput && !isSignal ? j - inputCount : j - 1)
                       .arg(typeNameToXml(typeName));
            }
        }

        int wantedMask;
        if (isScriptable)
            wantedMask = isSignal ? QDBusConnection::ExportScriptableSignals
                                  : QDBusConnection::ExportScriptableSlots;
        else
            wantedMask = isSignal ? QDBusConnection::ExportNonScriptableSignals
                                  : QDBusConnection::ExportNonScriptableSlots;
        if ((flags & wantedMask) != wantedMask)
            continue;

        if (qDBusCheckAsyncTag(mm.tag()))
            // add the no-reply annotation
            xml += QLatin1String("      <annotation name=\"" ANNOTATION_NO_WAIT "\""
                                 " value=\"true\"/>\n");

        retval += xml;
        retval += QString::fromLatin1("    </%1>\n")
                  .arg(isSignal ? QLatin1String("signal") : QLatin1String("method"));
    }

    return retval;
}
Example #8
0
void Statistic::onReport()
{
  ui.curOperationLabel->setText(trUtf8("Анализ отчета..."));
  setCursor(Qt::WaitCursor);
	CXSettings* settings = CXSettings::inst();

	settings->setValue(E_StartDate, QDateTime(ui.mStartDateEdit->date(), ui.mStartTimeEdit->time()));
	settings->setValue(E_EndDate, QDateTime(ui.mEndDateEdit->date(), ui.mEndTimeEdit->time()));

	QStringList xmlFiles;
#ifdef DEBUG_VER
  QString tmp = "D:/CNC_stat";
#else
  QString tmp = QApplication::applicationDirPath();
#endif
	QDir logsDir(tmp + "/" + LOG_PATH);
	//QDir logsDir(QApplication::applicationDirPath() + "/" + LOG_PATH);
	QString tempFileName;
	QStringList dirs = logsDir.entryList(QDir::Dirs);
	for (int i = 0; i < dirs.count(); ++i)
	{
		tempFileName = logsDir.path() + "/" + dirs.at(i) + "/report.xml";

		if (QFile::exists(tempFileName)) xmlFiles.append(tempFileName);
	}

	QList <SXReportError> errorList = Engine::generateReport(xmlFiles, settings->value(E_StartDate).toDateTime(), settings->value(E_EndDate).toDateTime());

//#ifndef QT_NO_DEBUG
//	ui.mErrorTree->clear();
//
//	QTreeWidgetItem* newItem = NULL;
//	QTreeWidgetItem* childItem = NULL;
//	QString lastFilename = "";
//
//	for (int i = 0; i < errorList.count(); ++i)
//	{
//		const SXReportError& curErrorData = errorList.at(i);
//
//		if ((newItem == NULL) || ((newItem != NULL) && (lastFilename != curErrorData.mFileName)))
//		{
//			newItem = new QTreeWidgetItem(ui.mErrorTree);
//			lastFilename = curErrorData.mFileName;
//			newItem->setText(0, lastFilename);
//		}
//
//		childItem = new QTreeWidgetItem(newItem);
//		childItem->setForeground(0, Qt::red);
//		childItem->setText(0, curErrorData.mError);
//
//		ui.mErrorTree->addTopLevelItem(newItem);
//	}
//#else
	QFile errorLog("errors.log");
	errorLog.open(QIODevice::WriteOnly);

	QTextStream textStream(&errorLog);
	textStream.setCodec(QTextCodec::codecForName("UTF-8"));

	for (int i = 0; i < errorList.count(); ++i)
	{
		const SXReportError& curErrorData = errorList.at(i);

		textStream << curErrorData.mFileName << "\t-\t";
		textStream << curErrorData.mError << "\n";
	}
//#endif

	ui.mReportView->setHtml(Engine::getReportText());
	ui.curOperationLabel->setText(trUtf8("Нет текущих операций"));
	setCursor(Qt::ArrowCursor);
}
Example #9
0
mresult ApptModel::checkAppt(const QList<inf_appt> &listAppt)
{
  qint64 now = QDateTime::currentMSecsSinceEpoch();
  QList <inf_appt> toRemove;
  QList <inf_appt> toRemoveBlack;
  QList <inf_appt> toAppend;
  inf_appt A,B;
  qint64 start = 0,end = 0,alarm = 0;

  for (int i = 0; i < black.size(); ++i) {
    A = black.at(i);
    start = A.getmalarmInstStart().toLongLong();
    end = start + A.getmdur().toLongLong();
    if(!listAppt.contains(A)) {
      if (now > end) {
        toRemoveBlack.append(A);
      }
    }
  }
  for (int i = 0; i < listAppt.size(); ++i) {
    A = listAppt.at(i);
    start = A.getmalarmInstStart().toLongLong();
    end = start + A.getmdur().toLongLong();
    alarm = A.getmnextAlarm().toLongLong();
    if (black.contains(A)) {
      toRemove.append(A);
      continue;
    }
    if(alarm > now) {
      toRemove.append(A);
    } else {
      if(alarm > now) {
        toAppend.append(A);
      }
      if((alarm == 0) &&
          ((now < start) || (now > end))) {
        toRemove.append(A);
      } else {
        toAppend.append(A);
      }
    }
  }

  for (int i = 0; i < Appt.size(); ++i) {
    A = Appt.at(i);
    if (!listAppt.contains(A)) {
      toRemove.append(A);
    }
  }

  for (int i = 0; i < toRemove.size(); ++i) {
    inf_appt rm = toRemove.at(i);
    if(Appt.contains(rm)) {
      int ind = Appt.indexOf(rm);
      beginRemoveRows(QModelIndex(), ind, ind);
      Appt.removeAll(rm);
      endRemoveRows();
    }
  }

  int k = 0;
  for (int i = 0; i < toAppend.size(); ++i) {
    A = toAppend.at(i);
    k = 0;
    if(!Appt.contains(A)) {
      for ( int j = 0; j < Appt.size(); ++j) {
        B = Appt.at(j);
        //qDebug() << A.getmname() <<A.getmalarmInstStart() << B.getmalarmInstStart()<< B.getmname();
        if(A.getmalarmInstStart().toLongLong() < B.getmalarmInstStart().toLongLong()) {
          k = j + 1;
        }
      }
      beginInsertRows(QModelIndex(), k, k );
      //qDebug() << k<< A.getmname();
      Appt.insert(k,A);
      endInsertRows();
    }
  }


//    for (int i = 0; i < toAppend.size(); ++i) {
//        inf in = toAppend.at(i);
//        if(!Appt.contains(in)){
//            beginInsertRows(QModelIndex(), Appt.size() + 1, Appt.size() +1 );
//            Appt.append(in);
//            endInsertRows();
//        }
//    }

  for (int i = 0; i < toRemoveBlack.size(); ++i) {
    inf_appt rm = toRemoveBlack.at(i);
    black.removeAll(rm);
  }
  //qDebug() <<toAppend.size()<<toRemove.size()<<black.size() << Appt.size();
  mresult r;
  r.setresult(Appt.size(),toAppend.size(),toRemove.size(),black.size());
  return r;
}
Example #10
0
bool SlimServerInfo::SetupDevices( void )
{
    DEBUGF("");
    QByteArray response;
    QList<QByteArray> respList;
    QByteArray cmd;

    cli->EmitCliInfo( "Analyzing Attached Players" );

    //    int loopCounter = 0;
    //    while(loopCounter++ < 5 ) {

    if( playerCount <= 0 ) { // we have a problem
        DEBUGF( "NO DEVICES" );
        return false;
    }
    DEBUGF("player count is:" << playerCount);

    for( int i = 0; i < playerCount; i++ ) {
        cmd = QString( "player id %1 ?\n" ).arg( i ).toAscii();
        if( !cli->SendBlockingCommand( cmd ) )
            return false;
        response = cli->GetResponse();
        DEBUGF(response);

        respList.clear();
        respList = response.split( ' ' );

        QString thisId;
        if( respList.at( 3 ).contains( ':' ) )
            thisId = respList.at( 3 ).toLower().toPercentEncoding(); // escape encode the MAC address if necessary
        else
            thisId = respList.at( 3 ).toLower();

        cmd = QString( "player name %1 ?\n" ).arg( i ).toAscii();

        if( !cli->SendBlockingCommand( cmd ) )
            return false;
        response = cli->GetResponse();
        respList.clear();
        respList = response.split( ' ' );
        DEBUGF(response);
        QString thisName = respList.at( 3 );
        //            GetDeviceNameList().insert( thisName, thisId );  // insert hash of key=Devicename value=MAC address

        cmd = QString( "player ip %1 ?\n" ).arg( i ).toAscii();

        if( !cli->SendBlockingCommand( cmd ) )
            return false;
        response = cli->GetResponse();
        DEBUGF(response);
        respList.clear();
        respList = response.split( ' ' );
        QString deviceIP = respList.at( 3 );
        deviceIP = deviceIP.section( QString( "%3A" ), 0, 0 );
        DEBUGF( thisId.toAscii() << " | " << thisName.toAscii()  << " | " << deviceIP.toAscii()  << " | " << i );
        deviceList.insert( thisId, new SlimDevice( thisId.toAscii(), thisName.toAscii(), deviceIP.toAscii(), QByteArray::number( i ) ) );
    }
    if(!deviceList.contains( cli->GetMACAddress().toLower()))
        return false;
    else
        return true;
}
Example #11
0
void Ball::doCollision()
{
    if(!stopped){

    if(birdDeadCounter>0)
    {
        --birdDeadCounter;
        if(birdDeadCounter<=0)
        {
            scene()->removeItem(removeBird);
        }
    }

    //check ob es eine Kollision gibt
    QList<QGraphicsItem*> collideList = scene()->collidingItems(this);


    //if(!(collideList.isEmpty()))
    for(int i=0; i<collideList.size(); ++i)
    {

        //finde Typ des kollidierenden Objectes heraus (BorderLine oder GroundMaterial)
        int sw = collideList.at(i)->type();

        switch(sw)
        {
            case CourtElement::borderline_type: //Kollision mit Spielfeldrand, abprallen
            {
                //Jetzt weis man, dass es eine Borderline ist, also caste QGraphicsItem* in BorderLine*
                BorderLine* borderline = static_cast<BorderLine*>(collideList.at(i));
                int angle = borderline->getAngle();

                if(canCollide<=0)
                {
                    emit soundPlay(SoundEngine::borderCollisionSound);

                    //angle ist relativ zu 3 Uhr (Uhrzeigersinn), rotation ist relativ zu 12 Uhr (Uhrzeigersinn)
                    setRotation(2*(angle+90.0-rotation()) + rotation());

                    speed = speed * borderline->getReflectionCoefficient();

                    canCollide = 3;
                }
            }
            break;

            case CourtElement::groundmaterial_type:
            {
                GroundMaterial* groundmaterial = static_cast<GroundMaterial*>(collideList.at(i));

                double maxspeed = groundmaterial->getMaxSpeed();
                double minspeed = groundmaterial->getMinSpeed();
                double friction = groundmaterial->getFrictionCoefficient();

                switch(groundmaterial->getMaterial())
                {
                    case GroundMaterial::water_material:
                    {
                        emit soundPlay(SoundEngine::waterSound);
                        speed -= friction*speed;

                        if(speed<minspeed)
                        {
                            speed = 0.0;

                            emit ballInWater();
                        }
                    }
                    break;

                    case GroundMaterial::nonNewtonian_material:

                        if(speed > minspeed)
                        {
                            speed -= speed*friction;
                        }
                        else if(speed<minspeed)
                        {
                            speed = 0.0;
                            emit soundPlay(SoundEngine::lavaSound);
                            emit ballInWater(); //Ist ja im Prinzip das gleiche wie bei Wasser
                        }
                    break;

                    case GroundMaterial::hole_material:

                        if(speed<maxspeed)
                        {
                            emit soundPlay(SoundEngine::cheeringSound);
                            speed = 0.0;
                            stopped=true;
                            emit ballInHole();
                        }

                    break;

                    case GroundMaterial::grass_material:
                    {
                       speed -= friction;

                        if(speed<minspeed)
                        {
                            speed = 0.0;
                            if(!stopped) emit ballStopped();
                            stopped = true;
                        }
                    }
                    break;

                    case GroundMaterial::sand_material:
                    {
                        emit(soundPlay(SoundEngine::sandSound));
                        speed -= 1.5*friction;

                        if(speed<minspeed)
                        {
                            speed = 0.0;
                            if(!stopped) emit ballStopped();
                            stopped = true;
                        }
                    }
                    break;

                    //unused materials:
                    /*
                    case GroundMaterial::speedUp_material:
                    case GroundMaterial::concrete_material:
                    case GroundMaterial::wood_material:
                    */

                    default: break;
                }
            }
            break;

            case 7: //Vogel abgeschossen! (7 = Pixmap)
            {
                if (isBirdDead == false)
                {
                    emit soundPlay(SoundEngine::birdHitSound);
                    emit birdHit();
                    isBirdDead = true;
                }
                removeBird = static_cast<QGraphicsPixmapItem*>(collideList.at(i));
                removeBird->setPixmap(birdDeadPicture);
                birdDeadCounter = 30;


            }
            break;

            default: break;
        }
    }
  }
}
Example #12
0
bool CSVToolWindow::importStart()
{
  QString mapname = atlasWindow()->map();
  CSVAtlas *atlas = _atlasWindow->getAtlas();

  if (mapname.isEmpty())
  {
    QStringList mList = atlas->mapList();

    if(mList.isEmpty())
    {
      _msghandler->message(QtWarningMsg, tr("No Maps Loaded"),
                           tr("<p>There are no maps loaded to select from. "
                              "Either load an atlas that contains maps or "
                              "create a new one before continuing."));
      return false;
    }

    mList.sort();
    bool valid;
    mapname = QInputDialog::getItem(this, tr("Select Map"), tr("Select Map:"),
                                    mList, 0, FALSE, &valid);
    if (!valid)
      return false;
  }

  CSVMap map = atlas->map(mapname);
  map.simplify();
  QList<CSVMapField> fields = map.fields();

  if (map.name() != mapname || fields.isEmpty())
  {
    _msghandler->message(QtWarningMsg, tr("Invalid Map"),
                         tr("<p>The selected map does not appear to be valid."));
    return false;
  }

  CSVMap::Action action = map.action();
  if (action != CSVMap::Insert)
  {
    _msghandler->message(QtWarningMsg, tr("Action not implemented"),
                         tr("<p>The action %1 for this map is not supported.")
                         .arg(CSVMap::actionToName(action)));
    return false;
  }

  if (!_data || _data->rows() < 1)
  {
    _msghandler->message(QtWarningMsg, tr("No data"),
                         tr("<p>There are no data to process. "
                            "Load a CSV file before continuing."));
    return false;
  }

  int total = _data->rows();
  int current = 0, error = 0, ignored = 0;

  if (! _log)
    _log = new LogWindow(this);

  if(usetransaction) QSqlQuery begin("BEGIN;");

  QString errMsg;
  if(!map.sqlPre().trimmed().isEmpty())
  {
    if(usetransaction) QSqlQuery savepoint("SAVEPOINT presql;");
    QSqlQuery pre;
    if(!pre.exec(map.sqlPre()))
    {
      errMsg = QString("ERROR Running Pre SQL query: %1").arg(pre.lastError().text());
      _log->_log->append("\n\n----------------------\n");
      _log->_log->append(errMsg);
      _log->show();
      _log->raise();
      if(map.sqlPreContinueOnError())
      {
        _log->_log->append(tr("\n\nContinuing with rest of import\n\n"));
        if(usetransaction) QSqlQuery sprollback("ROLLBACK TO SAVEPOINT presql;");
        if(usetransaction) QSqlQuery savepoint("RELEASE SAVEPOINT presql;");
      }
      else
      {
        if(usetransaction) QSqlQuery rollback("ROLLBACK;");
        _msghandler->message(QtWarningMsg, tr("Error"),
                             tr("<p>There was an error running the Pre SQL "
                                "query. Please see the log for more details. "
                                "Aborting transaction."));
        return false;
      }
    }
  }

  QString progresstext(tr("Importing %1: %2 rows out of %3"));
  int expected = total;
  QProgressDialog *progress = new QProgressDialog(progresstext
                                        .arg(map.name()).arg(0).arg(expected),
                                        tr("Cancel"), 0, expected, this);
  progress->setWindowModality(Qt::WindowModal);
  bool userCanceled = false;

  QString query;
  QString front;
  QString back;
  QString value;
  QString label;
  QVariant var;

  QStringList errorList;

  for(current = 0; current < total; ++current)
  {
    if(usetransaction) QSqlQuery savepoint("SAVEPOINT csvinsert;");
    if(action == CSVMap::Insert)
    {
      query = QString("INSERT INTO %1 ").arg(map.table());
      front = "(";
      back = " VALUES(";
      QList<CSVMapField> fields = map.fields();
      QMap<QString,QVariant> values;
      for (int i = 0; i < fields.size(); i++)
      {
        switch(fields.at(i).action())
        {
          case CSVMapField::Action_UseColumn:
          {
            value = _data->value(current, fields.at(i).column()-1);
            if(value.isNull())
            {
              switch (fields.at(i).ifNullAction())
              {
                case CSVMapField::UseDefault:
                  continue;
                case CSVMapField::UseEmptyString:
                {
                  var = QVariant(QString(""));
                  break;
                }
                case CSVMapField::UseAlternateValue:
                {
                  var = QVariant(fields.at(i).valueAlt());
                  break;
                }
                case CSVMapField::UseAlternateColumn:
                {
                  value = _data->value(current, fields.at(i).columnAlt()-1);
                  if(value.isNull())
                  {
                    switch (fields.at(i).ifNullActionAlt())
                    {
                      case CSVMapField::UseDefault:
                        continue;
                      case CSVMapField::UseEmptyString:
                      {
                        var = QVariant(QString(""));
                        break;
                      }
                      case CSVMapField::UseAlternateValue:
                      {
                        var = QVariant(fields.at(i).valueAlt());
                        break;
                      }
                      default: // Nothing
                        var = QVariant(QString::null);
                    }
                  }
                  else
                    var = QVariant(value);
                  break;
                }
                default: // Nothing
                  var = QVariant(QString::null);
              }
            }
            else
              var = QVariant(value);
            break;
          }
          case CSVMapField::Action_UseEmptyString:
          {
            var = QVariant(QString(""));
            break;
          }
          case CSVMapField::Action_UseAlternateValue:
          {
            var = QVariant(fields.at(i).valueAlt());
            break;
          }
          case CSVMapField::Action_UseNull:
          {
            var = QVariant(QString::null);
            break;
          }
          default:
            continue;
        }

        label = ":" + fields.at(i).name();
        if(!values.empty())
        {
          front += ", ";
          back  += ", ";
        }
        values.insert(label, var);
        front += fields.at(i).name();
        back  += label;
      }

      if(values.empty())
      {
        ignored++;
        errMsg = QString("IGNORED Record %1: There are no columns to insert").arg(current+1);
        errorList.append(errMsg);
        continue;
      }

      front += ") ";
      back += ")";
      query += front + back;
      QSqlQuery qry;
      qry.prepare(query);

      QMap<QString,QVariant>::iterator vit;
      for(vit = values.begin(); vit != values.end(); ++vit)
        qry.bindValue(vit.key(), vit.value());

      if(!qry.exec())
      {
        if(usetransaction) QSqlQuery sprollback("ROLLBACK TO SAVEPOINT csvinsert;");
        error++;
        errMsg = QString("ERROR Record %1: %2").arg(current+1).arg(qry.lastError().text());
        errorList.append(errMsg);
      }
    }
    if (progress->wasCanceled())
    {
      userCanceled = true;
      break;
    }
    if(! (current % 1000))
    {
      progress->setLabelText(progresstext.arg(map.name()).arg(current).arg(expected));
      progress->setValue(current);
    }
  }
  progress->setValue(total);

  if (error || ignored || userCanceled)
  {
    _log->_log->append(tr("Map: %1\n"
                          "Table: %2\n"
                          "Method: %3\n\n"
                          "Total Records: %4\n"
                          "# Processed:   %5\n"
                          "# Ignored:     %6\n"
                          "# Errors:      %7\n\n")
                          .arg(map.name()).arg(map.table())
                          .arg(CSVMap::actionToName(map.action()))
                          .arg(total).arg(current).arg(ignored).arg(error));
    _log->_log->append(errMsg);
    _log->_log->append(errorList.join("\n"));
    _log->show();
    _log->raise();
    if (_msghandler &&  // log messages there's a non-interactive message handler
        qobject_cast<XAbstractMessageHandler*>(_msghandler) &&
        ! qobject_cast<InteractiveMessageHandler*>(_msghandler))
      _msghandler->message(error ? QtCriticalMsg : QtWarningMsg,
                           tr("Import Processing Status"),
                           _log->_log->toPlainText());
  }

  if (! userCanceled && ! map.sqlPost().trimmed().isEmpty())
  {
    QSqlQuery post;
    if(!post.exec(map.sqlPost()))
    {
      errMsg = QString("ERROR Running Post SQL query: %1").arg(post.lastError().text());
      _log->_log->append("\n\n----------------------\n");
      _log->_log->append(errMsg);
      _log->show();
      _log->raise();
      if(usetransaction) QSqlQuery rollback("ROLLBACK;");
      _msghandler->message(QtCriticalMsg, tr("Error"),
                           tr("<p>There was an error running the post sql "
                              "query and changes were rolled back. "
                              "Please see the log for more details."));
      return false;
    }
  }

  if (userCanceled)
  {
    if(usetransaction) QSqlQuery rollback("ROLLBACK;");
    _log->_log->append(tr("\n\nImport canceled by user. Changes were rolled back."));

    return false;
  }

  if(usetransaction) QSqlQuery commit("COMMIT");
  if (! error)
  {
    _msghandler->message(QtDebugMsg, tr("Import Complete"),
                         tr("The import of %1 completed successfully.")
                         .arg(_currentDir));
    return true;
  }

  return false;
}
Example #13
0
//恢复数据
int CardDoc::resumeDataFromZip(const QString &zipPath)
{
//	removeTempFile();
	QDir dir;
	bool exist = dir.exists("tmp1");

	if (!exist)
	{
		//创建tmp文件夹
		dir.mkdir("tmp1");
	}

	try
	{
		ACUnZip(zipPath.toStdString(), "tmp1\\");

		QFile file("tmp1\\paperSet.dat");
		if (!file.open(QIODevice::ReadOnly))
		{
			file.close();
			removeTempFile("tmp1");
			return 0;
		}

		QDataStream data;
		data.setDevice(&file);
		data.setVersion(QDataStream::Qt_4_8);

		quint32 magic;
		data >> magic;

		//判断是否为可识别格式
		if (magic != (quint32)PAPERSET_MAGIC_NUM)
		{
			file.close();
			removeTempFile("tmp1");
			return 0;
		}

		quint32 version;
		data >> version;

		//判断是否为可识别版本
		if (version != (quint32)VERSION)
		{
			file.close();
			removeTempFile("tmp1");
			return 0;
		}

		int type;
		data >> type;

		if (type != m_acType)
		{
			removeTempFile("tmp1");
			return 0;
		}
		//m_acType = type;

		QString courseName;
		data >> courseName;
	
		vector<PaperSet> paperSet;

		QList<QString> setId;
		QList<int> dpi;
		QList<int> pageCount;
		QList<QString> pageId;
		QList<bool> isPositive;
		int setSize;
		int pageIdx = 0;

		data >> setSize >> setId >> dpi
			 >> pageCount >> pageId >> isPositive;

		for (int i = 0; i < setSize; ++i)
		{
			PaperSet set;
			set.setId = setId.at(i);
			set.dpi = dpi.at(i);

			for (int j = 0; j < pageCount.at(i); ++j, ++pageIdx)
			{
				PaperPage page;
				page.pageId = pageId.at(pageIdx);
				page.isPositive = isPositive.at(pageIdx);
				set.page.push_back(page);
			}

			paperSet.push_back(set);
		}

		int find = isCourseExist(courseName);

		if (find > -1)
		{
			m_course.at(find).set.clear();
			m_course.at(find).set = paperSet;
		}
		else
		{
			Course course;
			course.courseName = courseName;
			course.set = paperSet;
			m_course.push_back(course);
		}

		file.close();
		//文件确认无误后,将tmp1文件夹删除,并解压到tmp中
		removeTempFile("tmp1");
		ACUnZip(zipPath.toStdString(), "tmp\\");
		QFile::remove("tmp\\paperSet.dat");
	}
	catch (exception)
	{
		return 0;
	}

	return 1;
	
}
Example #14
0
bool Global::sendMemoEMail(const QString mailPrefixMessage, const QList<RepoChanges> & repoChanges) {
    QStringList attachments;
    const QString tmpPath = QString(BOXIT_STATUS_TMP) + "/" + QString::number(qrand()) + "_" + QDateTime::currentDateTime().toString(Qt::ISODate);
    bool success = true;

    // Create working folder
    if (QDir(tmpPath).exists() && !Global::rmDir(tmpPath)) {
        cerr << "error: failed to remove folder '" << tmpPath.toUtf8().data() << "'" << endl;
        return false;
    }

    if (!QDir().mkpath(tmpPath)) {
        cerr << "error: failed to create folder '" << tmpPath.toUtf8().data() << "'" << endl;
        return false;
    }

    QString message = mailPrefixMessage;

    for (int i = 0; i < repoChanges.size(); ++i) {
        const RepoChanges *repo = &repoChanges.at(i);

        message += QString(" - %1 %2 %3:  %4 new and %5 removed package(s)\n").arg(repo->branchName, repo->repoName, repo->repoArchitecture,
                                                                                QString::number(repo->addedPackages.size()),
                                                                                QString::number(repo->removedPackages.size()));

        // Create attachment file
        QFile file(QString(tmpPath) + "/" + repo->branchName + "_" + repo->repoName + "_" + repo->repoArchitecture);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            success = false;
            goto remove_tmp_dir;
        }

        QTextStream out(&file);
        if (!repo->addedPackages.isEmpty()) {
            out << "[New Packages]\n" << repo->addedPackages.join("\n");

            if (!repo->removedPackages.isEmpty())
                out << "\n\n\n";
        }

        if (!repo->removedPackages.isEmpty())
            out << "[Removed Packages]\n" << repo->removedPackages.join("\n");

        file.close();

        // Add to list
        attachments.append(file.fileName());
    }


    // Send e-mail
    if (!Global::sendMemoEMail(message, attachments)) {
        cerr << "error: failed to send e-mail!" << endl;
        success = false;
        goto remove_tmp_dir;
    }


remove_tmp_dir:

    // Remove working folder again
    if (QDir(tmpPath).exists() && !Global::rmDir(tmpPath))
        cerr << "error: failed to remove folder '" << tmpPath.toUtf8().data() << "'" << endl;

    return success;
}
Example #15
0
void MediaObject::enqueue(const QList<MediaSource> &sources)
{
    for (int i = 0; i < sources.count(); ++i) {
        enqueue(sources.at(i));
    }
}
void tst_QBluetoothLocalDevice::tst_hostModes()
{
    QFETCH(QBluetoothLocalDevice::HostMode, hostModeExpected);

    if (!QBluetoothLocalDevice::allDevices().count())
        QSKIP("Skipping test due to missing Bluetooth device");

    QBluetoothLocalDevice localDevice;
    QSignalSpy hostModeSpy(&localDevice, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode)));
    // there should be no changes yet
    QVERIFY(hostModeSpy.isValid());
    QVERIFY(hostModeSpy.isEmpty());

    QTest::qWait(1000);

    localDevice.setHostMode(hostModeExpected);
    // wait for the device to switch bluetooth mode.
    QTest::qWait(1000);
    if (hostModeExpected != localDevice.hostMode()) {
        QTRY_VERIFY(hostModeSpy.count() > 0);
    }
    // test the actual signal values.
    QVERIFY(hostModeSpy.count() > 0);
    QList<QVariant> arguments = hostModeSpy.takeFirst();
    QBluetoothLocalDevice::HostMode hostMode = qvariant_cast<QBluetoothLocalDevice::HostMode>(arguments.at(0));
    QCOMPARE(hostModeExpected, hostMode);
    // test actual
    QCOMPARE(hostModeExpected, localDevice.hostMode());
}
Example #17
0
void MediaObject::enqueue(const QList<QUrl> &urls)
{
    for (int i = 0; i < urls.count(); ++i) {
        enqueue(urls.at(i));
    }
}
Example #18
0
void QueueModel::sort(int column, Qt::SortOrder order)
{
    QSqlQuery query;
    QString orderByClause;
    QString artistOrder = "ASC";
    QString titleOrder = "ASC";
    QString discIdOrder = "ASC";
    QString sortField = "artist";
    switch (column) {
    case 3:
        if (order == Qt::AscendingOrder)
            artistOrder == "ASC";
        else
            artistOrder == "DESC";
        orderByClause = " ORDER BY dbsongs.artist " + artistOrder + ", dbsongs.title " + titleOrder + ", dbsongs.discid " + discIdOrder;
        break;
    case 4:
        sortField = "title";
        if (order == Qt::AscendingOrder)
            titleOrder == "ASC";
        else
            titleOrder == "DESC";
        orderByClause = " ORDER BY dbsongs.title " + titleOrder + ", dbsongs.artist " + artistOrder + ", dbsongs.discid " + discIdOrder;
        break;
    case 5:
        sortField = "discid";
        if (order == Qt::AscendingOrder)
            discIdOrder == "ASC";
        else
            discIdOrder == "DESC";
        orderByClause = " ORDER BY dbsongs.discid " + discIdOrder + ", dbsongs.artist " + artistOrder + ", dbsongs.title " + titleOrder;
        break;
    default:
        return;
    }

    QList<int> qSongIds;
    QString sql = "SELECT queuesongs.qsongid FROM queuesongs,dbsongs WHERE queuesongs.singer == " + QString::number(singer()) + " AND dbsongs.songid == queuesongs.song " + orderByClause;
    query.exec(sql);
    while (query.next())
        qSongIds << query.value(0).toInt();
    query.exec("BEGIN TRANSACTION");
    for (int i=0; i < qSongIds.size(); i++)
    {
        sql = "UPDATE queuesongs SET position = " + QString::number(i) + " WHERE qsongid == " + QString::number(qSongIds.at(i));
        query.exec(sql);
    }
    query.exec("COMMIT TRANSACTION");
    select();
    emit queueModified(singer());
}
Example #19
0
void PainterThread::drawAttrib(QPainter *p, Attributes *attrib)
{
    if (attrib->getType() == TObsAgent)
        return;

    //---- Desenha o atributo
    p->begin(attrib->getImage());

    p->setPen(Qt::NoPen); //defaultPen);

	//@RAIAN: Desenhando a vizinhanca
	if (attrib->getType() == TObsNeighborhood)
	{
		QColor color(Qt::white);
                QVector<QMap<QString, QList<double> > > *neighborhoods = attrib->getNeighValues();
		QVector<ObsLegend> *vecLegend = attrib->getLegend();

		QPen pen = p->pen();
		pen.setStyle(Qt::SolidLine);
		pen.setWidth(attrib->getWidth());

        // int random = qrand() % 256;
		double xCell = -1.0, yCell = -1.0;

		for (int pos = 0; pos < neighborhoods->size(); pos++)
		{
            QMap<QString, QList<double> > neigh = neighborhoods->at(pos);

			xCell = attrib->getXsValue()->at(pos);
			yCell = attrib->getYsValue()->at(pos);

			if ((xCell >= 0) && (yCell >=0))
			{
                QMap<QString, QList<double> >::Iterator itNeigh = neigh.begin();

				while (itNeigh != neigh.end())
				{
					QString neighID = itNeigh.key();
					QList<double> neighbor = itNeigh.value();

					double xNeigh = neighbor.at(0);
					double yNeigh = neighbor.at(1);
					double weight = neighbor.at(2);

					if (vecLegend->isEmpty())
					{
						weight = weight - attrib->getMinValue();
						double c = weight * attrib->getVal2Color();
						if (c >= 0 && c <= 255)
						{
							color.setRgb(c, c, c);
						}
						else
						{
							color.setRgb(255, 255, 255);
						}

						pen.setColor(color);
					}
					else
					{
						for (int j = 0; j < vecLegend->size(); j++)
						{
							ObsLegend leg = vecLegend->at(j);
							if (attrib->getGroupMode() == 3)
							{
								if (weight == leg.getTo().toDouble())
								{
									pen.setColor(leg.getColor());
									break;
								}
							}
							else
							{
								if ((leg.getFrom().toDouble() <= weight) && (weight < leg.getTo().toDouble()))
								{
									pen.setColor(leg.getColor());
									break;
								}
							}
						}
					}
					p->setPen(pen);

					if ((xNeigh >= 0) && (yNeigh >= 0))
					{
						drawNeighborhood(p, xCell, yCell, xNeigh, yNeigh);
					}

					itNeigh++;
				}
			}
		}
	}
	//@RAIAN: FIM
	else
	{
		if (attrib->getDataType() == TObsNumber)
		{
			QColor color(Qt::white);
			QVector<double> *values = attrib->getNumericValues();
			QVector<ObsLegend> *vecLegend = attrib->getLegend();

			double x = -1.0, y = -1.0, v = 0.0;

			int vSize = values->size();
			int xSize = attrib->getXsValue()->size();
			int ySize = attrib->getYsValue()->size();

			for (int pos = 0; (pos < vSize && pos < xSize && pos < ySize); pos++)
			{
				v = values->at(pos);

				// Corrige o bug gerando quando um agente morre
				if (attrib->getXsValue()->isEmpty() || attrib->getXsValue()->size() == pos)
					break;

				x = attrib->getXsValue()->at(pos);
				y = attrib->getYsValue()->at(pos);

				if (vecLegend->isEmpty())
				{
					v = v - attrib->getMinValue();

					double c = v * attrib->getVal2Color();
					if ((c >= 0) && (c <= 255))
					{
						color.setRgb(c, c, c);
					}
					else
					{
						color.setRgb(255, 255, 255);
					}
					p->setBrush(color);
				}
				else
				{
					for (int j = 0; j < vecLegend->size(); j++)
					{
						p->setBrush(Qt::white);

						const ObsLegend &leg = vecLegend->at(j);
						if (attrib->getGroupMode() == TObsUniqueValue) // valor ?nico 3
						{
							if (v == leg.getToNumber())
							{
								p->setBrush(leg.getColor());
								break;
							}
						}
						else
						{
							if ((leg.getFromNumber() <= v) && (v < leg.getToNumber()))
							{
								p->setBrush(leg.getColor());
								break;
							}
						}
					}
				}
				if ((x >= 0) && (y >= 0))
					draw(p, attrib->getType(), x, y);
			}
		}
		else if (attrib->getDataType() == TObsText)
		{
			QVector<QString> *values = attrib->getTextValues();
			QVector<ObsLegend> *vecLegend = attrib->getLegend();

            int random = qrand() % 256;
			double x = -1.0, y = -1.0;

			int vSize = values->size();
			int xSize = attrib->getXsValue()->size();
			int ySize = attrib->getYsValue()->size();

			for (int pos = 0; (pos < vSize && pos < xSize && pos < ySize); pos++)
			{
				const QString & v = values->at(pos);

				// Corrige o bug gerando quando um agente morre
				if (attrib->getXsValue()->isEmpty() || attrib->getXsValue()->size() == pos)
					break;

				x = attrib->getXsValue()->at(pos);
				y = attrib->getYsValue()->at(pos);

				if (vecLegend->isEmpty())
				{
					p->setBrush(QColor(random, random, random));
				}
				else
				{
					p->setBrush(Qt::white);
					for (int j = 0; j < vecLegend->size(); j++)
					{
						const ObsLegend &leg = vecLegend->at(j);
						if (v == leg.getFrom())
						{
							p->setBrush(leg.getColor());
							break;
						}
					}
				}

				if ((x >= 0) && (y >= 0))
					draw(p, attrib->getType(), x, y);
			}
		}
	}
    p->end();
}
Example #20
0
void MainWindow::loadComPorts()
{
    ui->menuFile->clear();

    m_comPorts = new QActionGroup(this);
    m_comPorts->setExclusive(true);

    QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();

    for (int i = 0; i < ports.size(); i++) {
        QString fullName;
        QString friendName = ports.at(i).friendName;
        QString name = ports.at(i).portName;
        if (name.contains("LPT")) {
            continue;
        }

#ifdef Q_OS_WIN
        name.remove("\\\\.\\");
        fullName = QString("%1").arg(friendName);
#else

#ifdef Q_OS_LINUX
        name.prepend("/dev/");
#endif

        if (friendName.size() > 0) {
            fullName = QString("%1 (%2)").arg(friendName)
                                         .arg(name);
        } else {
            QChar num = name.at(name.size() - 1);

            if (name.contains("ttyS")) {
                fullName = QString("Serial Port %1 (%2)").arg(num).arg(name);
            } else if (name.contains("ttyACM")) {
                fullName = QString("Serial ACM %1 (%2)").arg(num).arg(name);
            } else if (name.contains("ttyUSB")) {
                fullName = QString("Serial USB %1 (%2)").arg(num).arg(name);
            }
        }
#endif

        QAction * com = new QAction(fullName, this);
        com->setToolTip(name);
        com->setCheckable(true);

        if (com->toolTip() == m_tty) {
            com->setChecked(true);
        }

        m_comPorts->addAction(com);

    }

    connect(m_comPorts, SIGNAL(triggered(QAction*)),
            this, SLOT(comAction_triggered(QAction*)));

    ui->menuFile->addActions(m_comPorts->actions());
    ui->menuFile->addSeparator();
    ui->menuFile->addAction(ui->actionRefresh);
    ui->menuFile->addSeparator();
    ui->menuFile->addAction(ui->actionQuit);
}
Example #21
0
void MainWindow::do_ShowResultFileInfo()
{
    for(int i=0; i<10; i++)
    {
        //显示目标数
        this->msgLabel->setText((tr("找到目标数:")+QString::number(GotResultFileNum)));
        //
        if(msgProgressBar->isHidden()==false)
        {
            this->msgPBCnt++; if(this->msgPBCnt>=400)
            {
                this->msgPBCnt = 0;
            }
            msgProgressBar->setValue(msgPBCnt);
        }
        if(this->ListResultFileInfo.size()==0)
        {
            if(m_resizeColumns)
            {
                ui->tableView_result->resizeColumnsToContents();
                m_resizeColumns = false;
            }
            return;
        }
        QString dirName=this->ListResultFileInfo.first().dirName;
        QList<TFileInfo> namelist = this->ListResultFileInfo.first().namelist;

        this->ListResultFileInfo.removeFirst();

        for (int i = 0; i < namelist.size(); ++i) {
            QList <QStandardItem*> list;

            QString name = namelist.at(i).Name.trimmed();
            list.append( new QStandardItem(name));
            list.append( new QStandardItem(dirName));

            int nLine = namelist.at(i).Line;
            if(0!=nLine)
            {
                list.append(new QStandardItem(QString::number(nLine)));
            }
            else
            {
                list.append(new QStandardItem(""));
            }

            list.append( new QStandardItem(namelist.at(i).strLine));
            QString filename = dirName.trimmed() + QDir::separator() + name;
            QFileInfo fileInfo(filename);
            if(fileInfo.exists())
            {
                list.append(new QStandardItem(fileInfo.lastModified().toString("yyyy-MM-dd hh:mm")));
            }

            modelResult->appendRow(list);
            m_resizeColumns = true;
            if(i>=500 && (i%500)==0)
            {
                qApp->processEvents();
                if(true == m_stop_ShowResult)
                {
                    m_stop_ShowResult = false;
                    return;
                }
            }
        }
    }
}
K3AboutApplication::K3AboutApplication( const KAboutData *aboutData, QWidget *parent, bool modal )
  :K3AboutDialog( Tabbed|Product, aboutData->programName(), parent ),
   d( 0 )
{
  setButtons( Close );
  setDefaultButton( Close );
  setModal( modal );

  if( aboutData == 0 )
    aboutData = KGlobal::mainComponent().aboutData();

  if( !aboutData )
  {
    // Recovery
    setProduct(KGlobal::caption(), i18n("??"), QString(), QString());
    K3AboutContainer *appPage = addContainerPage( i18n("&About"));

    QString appPageText =
      i18n("No information available.\n"
     "The supplied KAboutData object does not exist.");
    QLabel *appPageLabel = new QLabel( "\n\n\n\n"+appPageText+"\n\n\n\n", 0 );
    appPage->addWidget( appPageLabel );
    return;
  }

  setProduct( aboutData->programName(), aboutData->version(),
        QString(), QString() );

  if ( aboutData->programLogo().canConvert<QPixmap>() )
    setProgramLogo( aboutData->programLogo().value<QPixmap>() );
  else if ( aboutData->programLogo().canConvert<QImage>() )
    setProgramLogo( QPixmap::fromImage(aboutData->programLogo().value<QImage>() ) );

  QString appPageText = aboutData->shortDescription() + '\n';

  if (!aboutData->otherText().isEmpty())
    appPageText += '\n' + aboutData->otherText() + '\n';

  if (!aboutData->copyrightStatement().isEmpty())
    appPageText += '\n' + aboutData->copyrightStatement() + '\n';

  K3AboutContainer *appPage = addContainerPage( i18n("&About"));

  QLabel *appPageLabel = new QLabel( appPageText, 0 );
  appPage->addWidget( appPageLabel );

  if (!aboutData->homepage().isEmpty())
  {
    QLabel *url = new QLabel(appPage);
    url->setOpenExternalLinks(true);
    url->setTextInteractionFlags(Qt::LinksAccessibleByMouse);
    url->setText(QString("<a href=\"%1\">%1</a>").arg(aboutData->homepage()));
    appPage->addWidget( url );
  }

  int authorCount = aboutData->authors().count();
  if (authorCount)
  {
    QString authorPageTitle = authorCount == 1 ?
      i18n("A&uthor") : i18n("A&uthors");
    K3AboutContainer *authorPage = addScrolledContainerPage( authorPageTitle, Qt::AlignLeft, Qt::AlignLeft );

    if (!aboutData->customAuthorTextEnabled() || !aboutData->customAuthorRichText().isEmpty ())
    {
      QString text;
      QLabel* activeLabel = new QLabel( authorPage );
      activeLabel->setOpenExternalLinks(true);
      activeLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse);
      if (!aboutData->customAuthorTextEnabled())
      {
        if ( aboutData->bugAddress().isEmpty() || aboutData->bugAddress() == "submit@bugs.kde.org")
          text = i18n( "Please use <a href=\"http://bugs.kde.org\">http://bugs.kde.org</a> to report bugs.\n" );
        else {
          if( aboutData->authors().count() == 1 && ( aboutData->authors().first().emailAddress() == aboutData->bugAddress() ) )
          {
            text = i18n( "Please report bugs to <a href=\"mailto:%1\">%2</a>.\n" ,  aboutData->authors().first().emailAddress() ,  aboutData->authors().first().emailAddress() );
          }
          else {
            text = i18n( "Please report bugs to <a href=\"mailto:%1\">%2</a>.\n" , aboutData->bugAddress(), aboutData->bugAddress() );
          }
        }
      }
      else
      {
        text = aboutData->customAuthorRichText();
      }
      activeLabel->setText( text );
      authorPage->addWidget( activeLabel );
    }

    QList<KAboutPerson> lst = aboutData->authors();
    for (int i = 0; i < lst.size(); ++i)
    {
      authorPage->addPerson( lst.at(i).name(), lst.at(i).emailAddress(),
      lst.at(i).webAddress(), lst.at(i).task() );
    }
  }

  int creditsCount = aboutData->credits().count();
  if (creditsCount)
  {
    K3AboutContainer *creditsPage = addScrolledContainerPage( i18n("&Thanks To") );

    QList<KAboutPerson> lst = aboutData->credits();
    for (int i = 0; i < lst.size(); ++i)
    {
      creditsPage->addPerson( lst.at(i).name(), lst.at(i).emailAddress(),
           lst.at(i).webAddress(), lst.at(i).task() );
    }
  }

  const QList<KAboutPerson> translatorList = aboutData->translators();

  if(translatorList.count() > 0)
  {
      QString text = "<qt>";

      QList<KAboutPerson>::ConstIterator it;
      for(it = translatorList.begin(); it != translatorList.end(); ++it)
      {
        text += QString("<p>%1<br>&nbsp;&nbsp;&nbsp;"
            "<a href=\"mailto:%2\">%2</a></p>")
            .arg((*it).name())
            .arg((*it).emailAddress())
            .arg((*it).emailAddress());
      }

      text += KAboutData::aboutTranslationTeam() + "</qt>";
      addTextPage( i18n("T&ranslation"), text, true);
  }

  if (!aboutData->license().isEmpty() )
  {
    addLicensePage( i18n("&License Agreement"), aboutData->license() );
  }
  // Make sure the dialog has a reasonable width
  setInitialSize( QSize(400,1) );
}
void QCustomGraphicsRectItem::setActionIcons(const QList<QIcon> &icons)
{
    m_actionCopy->setIcon( icons.at( 0 ) );
    m_actionRemove->setIcon( icons.at( 1 ) );
}
Example #24
0
        void paintEvent(QPaintEvent *event)
        {
            Q_UNUSED (event)

            // XXX Maybe we should cache this and recompute separately for
            //     transform changes, shape movement and viewport changes?

            // Draw a white background.
            QPainter painter(this);
            painter.setRenderHint(QPainter::Antialiasing);
            painter.setPen(Qt::white);
            painter.setBrush(Qt::white);
            QRectF drawingRect = QRectF(0, 0, width(), height());
            painter.drawRect(drawingRect);

            if (m_canvasview == NULL)
            {
                return;
            }

            // Compute the diagram bounds.
            Canvas *canvas = m_canvasview->canvas();
            QRectF diagramBounds =  diagramBoundingRect(canvas->items());
            double buffer = 50;
            diagramBounds.adjust(-buffer, -buffer, buffer, buffer);

            // Compute the scale to with the drawing into the overview rect.
            qreal xscale = drawingRect.width() / diagramBounds.width();
            qreal yscale = drawingRect.height() /  diagramBounds.height();

            // Choose the smallest of the two scale values.
            qreal scale = std::min(xscale, yscale);

            // Scale uniformly, and transform to center in the overview.
            QTransform scaleTransform = QTransform::fromScale(scale, scale);
            QRectF targetRect = scaleTransform.mapRect(diagramBounds);
            QPointF diff = drawingRect.center() - targetRect.center();
            m_transform = QTransform();
            m_transform.translate(diff.x(), diff.y());
            m_transform.scale(scale, scale);

            // Draw edges in overview for each connector on the canvas.
            painter.setPen(QColor(0, 0, 0, 100));
            QList<CanvasItem *> items = canvas->items();
            for (int i = 0; i < items.count(); ++i)
            {
                Connector *connector = dynamic_cast<Connector *> (items.at(i));
                if (connector)
                {
                    QPair<ShapeObj *, ShapeObj *> endShapes =
                            connector->getAttachedShapes();
                    if (!endShapes.first || !endShapes.second)
                    {
                        continue;
                    }

                    QLineF line(endShapes.first->centrePos(),
                                endShapes.second->centrePos());
                    painter.drawLine(m_transform.map(line));
                }
            }

            // Draw Rectangles in overview for each shape on the canvas.
            painter.setPen(Qt::black);
            painter.setBrush(Qt::darkGray);
            QRectF shapeRect;
            for (int i = 0; i < items.count(); ++i)
            {
                ShapeObj *shape = dynamic_cast<ShapeObj *> (items.at(i));
                if (shape)
                {
                    shapeRect.setSize(shape->size());
                    shapeRect.moveCenter(shape->centrePos());
                    painter.drawRect(m_transform.mapRect(shapeRect));
                }
            }

            // Show where the visible viewport is (by making everything
            // outside this have a light grey overlay).
            QColor grey(0, 0, 0, 60);
            painter.setPen(QPen(Qt::transparent));
            painter.setBrush(QBrush(grey));
            QRectF viewRect = m_transform.mapRect(m_canvasview->viewportRect());
            QPolygon polygon = QPolygon(drawingRect.toRect()).subtracted(
                    QPolygon(viewRect.toRect()));
            painter.drawPolygon(polygon);
        }
Playlist::Playlist(QWidget *parent) :
	QTableWidget(parent), track(-1)
{
	// Initialize values for the Header (label and horizontal resize mode)
	QStringList labels = (QStringList() << "#" << tr("Title") << tr("Album") << tr("Length") << tr("Artist") << tr("Rating") << tr("Year"));
	const QStringList untranslatedLabels = (QStringList() << "#" << "Title" << "Album" << "Length" << "Artist" << "Rating" << "Year");
	// Test: 0 = Fixed, n>0 = real ratio for each column
	const QList<int> ratios(QList<int>() << 0 << 5 << 4 << 1 << 3 << 0 << 0);

	this->setColumnCount(labels.size());
	this->setColumnHidden(5, true);
	this->setColumnHidden(6, true);
	this->setShowGrid(false);
	Settings *settings = Settings::getInstance();
	this->setStyleSheet(settings->styleSheet(this));
	this->verticalScrollBar()->setStyleSheet(settings->styleSheet(this->verticalScrollBar()));
	this->setAlternatingRowColors(settings->colorsAlternateBG());

	// Select only one row, not cell by cell
	this->setSelectionMode(QAbstractItemView::ExtendedSelection);
	this->setSelectionBehavior(QAbstractItemView::SelectRows);
	this->setItemDelegate(new NoFocusItemDelegate(this));

	/// test
	this->setAcceptDrops(true);

	verticalHeader()->setVisible(false);
	this->setHorizontalHeader(new QHeaderView(Qt::Horizontal, this));
	horizontalHeader()->setStyleSheet(settings->styleSheet(horizontalHeader()));
	horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
	horizontalHeader()->setHighlightSections(false);
	horizontalHeader()->setMovable(true);

	this->installEventFilter(horizontalHeader());

	// Context menu on header of columns
	QList<QAction*> actionColumns;
	columns = new QMenu(this);

	for (int i = 0; i < labels.size(); i++) {
		QString label = labels.at(i);
		QTableWidgetItem *item = new QTableWidgetItem(label);

		// Stores original text to switch between translations on the fly
		// Might evolve latter, start to be "unreadable"
		item->setData(Qt::UserRole+1, untranslatedLabels.at(i));
		item->setData(Qt::UserRole+2, ratios.at(i));
		this->setHorizontalHeaderItem(i, item);

		// Match actions with columns using index of labels
		QAction *actionColumn = new QAction(label, this);
		actionColumn->setData(i);
		actionColumn->setEnabled(actionColumn->text() != tr("Title"));
		actionColumn->setCheckable(true);
		actionColumn->setChecked(!isColumnHidden(i));
		actionColumns.append(actionColumn);

		// Then populate the context menu
		columns->addAction(actionColumn);
	}

	// Load columns state
	QByteArray state = settings->value("playlistColumnsState").toByteArray();
	if (!state.isEmpty()) {
		horizontalHeader()->restoreState(state);
		for (int i = 0; i < horizontalHeader()->count(); i++) {
			bool hidden = horizontalHeader()->isSectionHidden(i);
			setColumnHidden(i, hidden);
			columns->actions().at(i)->setChecked(!hidden);
		}
	}

	// Link this playlist with the Settings instance to change fonts at runtime
	connect(settings, SIGNAL(currentFontChanged()), this, SLOT(highlightCurrentTrack()));

	// Change track
	// no need to cast parent as a TabPlaylist instance
	connect(this, SIGNAL(itemDoubleClicked(QTableWidgetItem*)), parent, SLOT(changeTrack(QTableWidgetItem*)));

	// Hide the selected column in context menu
	connect(horizontalHeader(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showColumnsMenu(QPoint)));
	connect(columns, SIGNAL(triggered(QAction*)), this, SLOT(toggleSelectedColumn(QAction*)));
	connect(horizontalHeader(), SIGNAL(sectionMoved(int,int,int)), this, SLOT(saveColumnsState(int,int,int)));
}
Example #26
0
void TrackerClient::httpRequestDone(bool error)
{
    if (lastTrackerRequest) {
        emit stopped();
        return;
    }

    if (error) {
        emit connectionError(http.error());
        return;
    }

    QByteArray response = http.readAll();
    http.abort();

    BencodeParser parser;
    if (!parser.parse(response)) {
        qWarning("Error parsing bencode response from tracker: %s",
                 qPrintable(parser.errorString()));
        http.abort();
        return;
    }

    QMap<QByteArray, QVariant> dict = parser.dictionary();

    if (dict.contains("failure reason")) {
        // no other items are present
        emit failure(QString::fromUtf8(dict.value("failure reason").toByteArray()));
        return;
    }

    if (dict.contains("warning message")) {
        // continue processing
        emit warning(QString::fromUtf8(dict.value("warning message").toByteArray()));
    }

    if (dict.contains("tracker id")) {
        // store it
        trackerId = dict.value("tracker id").toByteArray();
    }

    if (dict.contains("interval")) {
        // Mandatory item
        if (requestIntervalTimer != -1)
            killTimer(requestIntervalTimer);
        requestIntervalTimer = startTimer(dict.value("interval").toInt() * 1000);
    }

    if (dict.contains("peers")) {
        // store it
        peers.clear();
        QVariant peerEntry = dict.value("peers");
        if (peerEntry.type() == QVariant::List) {
            QList<QVariant> peerTmp = peerEntry.toList();
            for (int i = 0; i < peerTmp.size(); ++i) {
                TorrentPeer tmp;
                QMap<QByteArray, QVariant> peer = qvariant_cast<QMap<QByteArray, QVariant> >(peerTmp.at(i));
                tmp.id = QString::fromUtf8(peer.value("peer id").toByteArray());
                tmp.address.setAddress(QString::fromUtf8(peer.value("ip").toByteArray()));
                tmp.port = peer.value("port").toInt();
                peers << tmp;
            }
        } else {
            QByteArray peerTmp = peerEntry.toByteArray();
            for (int i = 0; i < peerTmp.size(); i += 6) {
                TorrentPeer tmp;
                uchar *data = (uchar *)peerTmp.constData() + i;
                tmp.port = (int(data[4]) << 8) + data[5];
                uint ipAddress = 0;
                ipAddress += uint(data[0]) << 24;
                ipAddress += uint(data[1]) << 16;
                ipAddress += uint(data[2]) << 8;
                ipAddress += uint(data[3]);
                tmp.address.setAddress(ipAddress);
                peers << tmp;
            }
        }
        emit peerListUpdated(peers);
    }
}
Example #27
0
void EraserTool::mouseMoveEvent( QMouseEvent *event )
{
    Layer* layer = mEditor->layers()->currentLayer();

    if ( event->buttons() & Qt::LeftButton )
    {
        if ( layer->type() == Layer::BITMAP || layer->type() == Layer::VECTOR )
        {
            drawStroke();
        }
        if ( layer->type() == Layer::VECTOR )
        {
            qreal radius = ( properties.width / 2 ) / mEditor->view()->scaling();
            QList<VertexRef> nearbyVertices = ( ( LayerVector * )layer )->getLastVectorImageAtFrame( mEditor->currentFrame(), 0 )
                ->getVerticesCloseTo( getCurrentPoint(), radius );
            for ( int i = 0; i < nearbyVertices.size(); i++ )
            {
                ( ( LayerVector * )layer )->getLastVectorImageAtFrame( mEditor->currentFrame(), 0 )->setSelected( nearbyVertices.at( i ), true );
            }
            //update();
            mScribbleArea->setAllDirty();
        }
    }
}
Example #28
0
void Inspector::setElements(const QList<Element*>& l)
      {
      if (_inspectorEdit)     // if within an inspector-originated edit
            return;

      Element* e = l.isEmpty() ? 0 : l[0];
      if (e == 0 || _element == 0 || (_el != l)) {
            _el = l;
            ie = 0;
            _element = e;

            if (_element == 0)
                  ie = new InspectorEmpty(this);

            bool sameTypes = true;
            for (Element* ee : _el) {
                  if (_element->type() != ee->type())
                        sameTypes = false;
                  else {
                        // HACK:
                        if (ee->isNote() && toNote(ee)->chord()->isGrace() != toNote(_element)->chord()->isGrace())
                              sameTypes = false;
                        }
                  }
            if (!sameTypes)
                  ie = new InspectorGroupElement(this);
            else if (_element) {
                  switch(_element->type()) {
                        case Element::Type::FBOX:
                        case Element::Type::VBOX:
                              ie = new InspectorVBox(this);
                              break;
                        case Element::Type::TBOX:
                              ie = new InspectorTBox(this);
                              break;
                        case Element::Type::HBOX:
                              ie = new InspectorHBox(this);
                              break;
                        case Element::Type::ARTICULATION:
                              ie = new InspectorArticulation(this);
                              break;
                        case Element::Type::SPACER:
                              ie = new InspectorSpacer(this);
                              break;
                        case Element::Type::NOTE:
                              ie = new InspectorNote(this);
                              break;
                        case Element::Type::ACCIDENTAL:
                              ie = new InspectorAccidental(this);
                              break;
                        case Element::Type::REST:
                              ie = new InspectorRest(this);
                              break;
                        case Element::Type::CLEF:
                              ie = new InspectorClef(this);
                              break;
                        case Element::Type::TIMESIG:
                              ie = new InspectorTimeSig(this);
                              break;
                        case Element::Type::KEYSIG:
                              ie = new InspectorKeySig(this);
                              break;
                        case Element::Type::TUPLET:
                              ie = new InspectorTuplet(this);
                              break;
                        case Element::Type::BEAM:
                              ie = new InspectorBeam(this);
                              break;
                        case Element::Type::IMAGE:
                              ie = new InspectorImage(this);
                              break;
                        case Element::Type::LASSO:
                              ie = new InspectorLasso(this);
                              break;
                        case Element::Type::VOLTA_SEGMENT:
                              ie = new InspectorVolta(this);
                              break;
                        case Element::Type::OTTAVA_SEGMENT:
                              ie = new InspectorOttava(this);
                              break;
                        case Element::Type::TRILL_SEGMENT:
                              ie = new InspectorTrill(this);
                              break;
                        case Element::Type::HAIRPIN_SEGMENT:
                              ie = new InspectorHairpin(this);
                              break;
                        case Element::Type::TEXTLINE_SEGMENT:
                        case Element::Type::PEDAL_SEGMENT:
                              ie = new InspectorTextLine(this);
                              break;
                        case Element::Type::SLUR_SEGMENT:
                        case Element::Type::TIE_SEGMENT:
                              ie = new InspectorSlurTie(this);
                              break;
                        case Element::Type::BAR_LINE:
                              ie = new InspectorBarLine(this);
                              break;
                        case Element::Type::JUMP:
                              ie = new InspectorJump(this);
                              break;
                        case Element::Type::MARKER:
                              ie = new InspectorMarker(this);
                              break;
                        case Element::Type::GLISSANDO:
                        case Element::Type::GLISSANDO_SEGMENT:
                              ie = new InspectorGlissando(this);
                              break;
                        case Element::Type::TEMPO_TEXT:
                              ie = new InspectorTempoText(this);
                              break;
                        case Element::Type::DYNAMIC:
                              ie = new InspectorDynamic(this);
                              break;
                        case Element::Type::AMBITUS:
                              ie = new InspectorAmbitus(this);
                              break;
                        case Element::Type::FRET_DIAGRAM:
                              ie = new InspectorFretDiagram(this);
                              break;
                        case Element::Type::LAYOUT_BREAK:
                              ie = new InspectorBreak(this);
                              break;
                        case Element::Type::BEND:
                              ie = new InspectorBend(this);
                              break;
                        case Element::Type::TREMOLOBAR:
                              ie = new InspectorTremoloBar(this);
                              break;
                        case Element::Type::ARPEGGIO:
                              ie = new InspectorArpeggio(this);
                              break;
                        case Element::Type::BREATH:
                              ie = new InspectorCaesura(this);
                              break;
                        case Element::Type::LYRICS:
                              ie = new InspectorLyric(this);
                              break;
                        case Element::Type::STAFF_TEXT:
                              ie = new InspectorStafftext(this);
                              break;
                        case Element::Type::STAFFTYPE_CHANGE:
                              ie = new InspectorStaffTypeChange(this);
                              break;
                        case Element::Type::BRACKET:
                              ie = new InspectorBracket(this);
                              break;
                        case Element::Type::INSTRUMENT_NAME:
                              ie = new InspectorIname(this);
                              break;
                        default:
                              if (_element->isText())
                                    ie = new InspectorText(this);
                              else
                                    ie = new InspectorElement(this);
                              break;
                        }
                  }
            QWidget* ww = sa->takeWidget();
            if (ww)
                  ww->deleteLater();
            sa->setWidget(ie);

            //focus policies were set by hand in each inspector_*.ui. this code just helps keeping them like they are
            //also fixes mac problem. on Mac Qt::TabFocus doesn't work, but Qt::StrongFocus works
            QList<QWidget*> widgets = ie->findChildren<QWidget*>();
            for (int i = 0; i < widgets.size(); i++) {
                  QWidget* currentWidget = widgets.at(i);
                  switch (currentWidget->focusPolicy()) {
                        case Qt::WheelFocus:
                        case Qt::StrongFocus:
                              if (currentWidget->inherits("QComboBox")                  ||
                                  currentWidget->parent()->inherits("QAbstractSpinBox") ||
                                  currentWidget->inherits("QAbstractSpinBox")           ||
                                  currentWidget->inherits("QLineEdit")) ; //leave it like it is
                              else
                                   currentWidget->setFocusPolicy(Qt::TabFocus);
                              break;
                        case Qt::NoFocus:
                        case Qt::ClickFocus:
                                    currentWidget->setFocusPolicy(Qt::NoFocus);
                              break;
                        case Qt::TabFocus:
                              break;
                        }
                  }
            }
      _element = e;
      ie->setElement();
      }
Example #29
0
QWizardPage *AddFeedWizard::createNameFeedPage()
{
  QWizardPage *page = new QWizardPage;
  page->setTitle(tr("Create New Feed"));
  page->setFinalPage(false);

  nameFeedEdit_ = new LineEdit(this);

  foldersTree_ = new QTreeWidget(this);
  foldersTree_->setObjectName("foldersTree_");
  foldersTree_->setColumnCount(2);
  foldersTree_->setColumnHidden(1, true);
  foldersTree_->header()->hide();

  QStringList treeItem;
  treeItem << tr("Feeds") << "Id";
  foldersTree_->setHeaderLabels(treeItem);

  treeItem.clear();
  treeItem << tr("All Feeds") << "0";
  QTreeWidgetItem *treeWidgetItem = new QTreeWidgetItem(treeItem);
  treeWidgetItem->setIcon(0, QIcon(":/images/folder"));
  foldersTree_->addTopLevelItem(treeWidgetItem);
  foldersTree_->setCurrentItem(treeWidgetItem);

  QSqlQuery q;
  QQueue<int> parentIds;
  parentIds.enqueue(0);
  while (!parentIds.empty()) {
    int parentId = parentIds.dequeue();
    QString qStr = QString("SELECT text, id FROM feeds WHERE parentId='%1' AND (xmlUrl='' OR xmlUrl IS NULL)").
        arg(parentId);
    q.exec(qStr);
    while (q.next()) {
      QString folderText = q.value(0).toString();
      QString folderId = q.value(1).toString();

      QStringList treeItem;
      treeItem << folderText << folderId;
      QTreeWidgetItem *treeWidgetItem = new QTreeWidgetItem(treeItem);

      treeWidgetItem->setIcon(0, QIcon(":/images/folder"));

      QList<QTreeWidgetItem *> treeItems =
            foldersTree_->findItems(QString::number(parentId),
                                                       Qt::MatchFixedString | Qt::MatchRecursive,
                                                       1);
      treeItems.at(0)->addChild(treeWidgetItem);
      if (folderId.toInt() == curFolderId_)
        foldersTree_->setCurrentItem(treeWidgetItem);
      parentIds.enqueue(folderId.toInt());
    }
  }

  foldersTree_->expandAll();
  foldersTree_->sortByColumn(0, Qt::AscendingOrder);

  ToolButton *newFolderButton = new ToolButton(this);
  newFolderButton->setIcon(QIcon(":/images/addT"));
  newFolderButton->setToolTip(tr("New Folder..."));
  newFolderButton->setAutoRaise(true);

  QHBoxLayout *newFolderLayout = new QHBoxLayout;
  newFolderLayout->setMargin(0);
  newFolderLayout->addWidget(newFolderButton);
  newFolderLayout->addStretch();
  QVBoxLayout *newFolderVLayout = new QVBoxLayout;
  newFolderVLayout->setMargin(2);
  newFolderVLayout->addStretch();
  newFolderVLayout->addLayout(newFolderLayout);

  foldersTree_->setLayout(newFolderVLayout);

  QVBoxLayout *layout = new QVBoxLayout;
  layout->addWidget(new QLabel(tr("Displayed name:")));
  layout->addWidget(nameFeedEdit_);
  layout->addWidget(new QLabel(tr("Location:")));
  layout->addWidget(foldersTree_);
  page->setLayout(layout);

  connect(nameFeedEdit_, SIGNAL(textChanged(const QString&)),
          this, SLOT(nameFeedEditChanged(const QString&)));
  connect(newFolderButton, SIGNAL(clicked()),
          this, SLOT(newFolder()));

  return page;
}
Example #30
0
UIYabause::UIYabause( QWidget* parent )
	: QMainWindow( parent )
{
	mInit = false;
   search.clear();
	searchType = 0;

	// setup dialog
	setupUi( this );
	toolBar->insertAction( aFileSettings, mFileSaveState->menuAction() );
	toolBar->insertAction( aFileSettings, mFileLoadState->menuAction() );
	toolBar->insertSeparator( aFileSettings );
	setAttribute( Qt::WA_DeleteOnClose );
#ifdef USE_UNIFIED_TITLE_TOOLBAR
	setUnifiedTitleAndToolBarOnMac( true );
#endif
	fSound->setParent( 0, Qt::Popup );
	fVideoDriver->setParent( 0, Qt::Popup );
	fSound->installEventFilter( this );
	fVideoDriver->installEventFilter( this );
	// Get Screen res list
	getSupportedResolutions();
	// fill combo driver
	cbVideoDriver->blockSignals( true );
	for ( int i = 0; VIDCoreList[i] != NULL; i++ )
		cbVideoDriver->addItem( VIDCoreList[i]->Name, VIDCoreList[i]->id );
	cbVideoDriver->blockSignals( false );
	// create glcontext
	mYabauseGL = new YabauseGL( this );
	// and set it as central application widget
	setCentralWidget( mYabauseGL );
	// create log widget
	teLog = new QTextEdit( this );
	teLog->setReadOnly( true );
	teLog->setWordWrapMode( QTextOption::NoWrap );
	teLog->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOn );
	teLog->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOn );
	mLogDock = new QDockWidget( this );
	mLogDock->setWindowTitle( "Log" );
	mLogDock->setWidget( teLog );
	addDockWidget( Qt::BottomDockWidgetArea, mLogDock );
	mLogDock->setVisible( false );
	// create emulator thread
	mYabauseThread = new YabauseThread( this );
	// create hide mouse timer
	hideMouseTimer = new QTimer();
	// connectionsdd
	connect( mYabauseThread, SIGNAL( requestSize( const QSize& ) ), this, SLOT( sizeRequested( const QSize& ) ) );
	connect( mYabauseThread, SIGNAL( requestFullscreen( bool ) ), this, SLOT( fullscreenRequested( bool ) ) );
	connect( mYabauseThread, SIGNAL( requestVolumeChange( int ) ), this, SLOT( on_sVolume_valueChanged( int ) ) );
	connect( aViewLog, SIGNAL( toggled( bool ) ), mLogDock, SLOT( setVisible( bool ) ) );
	connect( mLogDock->toggleViewAction(), SIGNAL( toggled( bool ) ), aViewLog, SLOT( setChecked( bool ) ) );
	connect( mYabauseThread, SIGNAL( error( const QString&, bool ) ), this, SLOT( errorReceived( const QString&, bool ) ) );
	connect( mYabauseThread, SIGNAL( pause( bool ) ), this, SLOT( pause( bool ) ) );
	connect( mYabauseThread, SIGNAL( reset() ), this, SLOT( reset() ) );
	connect( hideMouseTimer, SIGNAL( timeout() ), this, SLOT( hideMouse() ));

	// Load shortcuts
	VolatileSettings* vs = QtYabause::volatileSettings();
	QList<QAction *> actions = findChildren<QAction *>();
	foreach ( QAction* action, actions )
	{
		if (action->text().isEmpty())
			continue;

		QString text = vs->value(QString("Shortcuts/") + action->text(), "").toString();
		if (text.isEmpty())
			continue;
		action->setShortcut(text);
	}

	// retranslate widgets
	QtYabause::retranslateWidget( this );

	QList<QAction *> actionList = menubar->actions();
	for(int i = 0;i < actionList.size();i++) {
		addAction(actionList.at(i));
	}

	restoreGeometry( vs->value("General/Geometry" ).toByteArray() );
	mYabauseGL->setMouseTracking(true);
	setMouseTracking(true);
	showMenuBarHeight = menubar->height();
	translations = QtYabause::getTranslationList();
}