Exemplo n.º 1
0
QRectF KoReportDesignerItemLabel::getTextRect()
{
    return QFontMetrics(font()).boundingRect(x(), y(), 0, 0, textFlags(), m_text->value().toString());
}
Exemplo n.º 2
0
SequenceDialog::SequenceDialog(QWidget &parent, CaptureFile &cf, seq_analysis_info_t *sainfo) :
    WiresharkDialog(parent, cf),
    ui(new Ui::SequenceDialog),
    sainfo_(sainfo),
    num_items_(0),
    packet_num_(0),
    node_label_w_(20)
{
    ui->setupUi(this);
    QCustomPlot *sp = ui->sequencePlot;
    setWindowSubtitle(sainfo ? tr("Call Flow") : tr("Flow"));

    if (!sainfo_) {
        sainfo_ = sequence_analysis_info_new();
        sainfo_->type = SEQ_ANALYSIS_ANY;
        sainfo_->all_packets = TRUE;
    } else {
        num_items_ = sequence_analysis_get_nodes(sainfo_);
    }

    seq_diagram_ = new SequenceDiagram(sp->yAxis, sp->xAxis2, sp->yAxis2);
    sp->addPlottable(seq_diagram_);
    sp->axisRect()->setRangeDragAxes(sp->xAxis2, sp->yAxis);

    sp->xAxis->setVisible(false);
    sp->xAxis->setPadding(0);
    sp->xAxis->setLabelPadding(0);
    sp->xAxis->setTickLabelPadding(0);
    sp->xAxis2->setVisible(true);
    sp->yAxis2->setVisible(true);

    one_em_ = QFontMetrics(sp->yAxis->labelFont()).height();
    ui->horizontalScrollBar->setSingleStep(100 / one_em_);
    ui->verticalScrollBar->setSingleStep(100 / one_em_);

    sp->setInteractions(QCP::iRangeDrag);

    ui->gridLayout->setSpacing(0);
    connect(sp->yAxis, SIGNAL(rangeChanged(QCPRange)), sp->yAxis2, SLOT(setRange(QCPRange)));

    ctx_menu_.addAction(ui->actionReset);
    ctx_menu_.addSeparator();
    ctx_menu_.addAction(ui->actionMoveRight10);
    ctx_menu_.addAction(ui->actionMoveLeft10);
    ctx_menu_.addAction(ui->actionMoveUp10);
    ctx_menu_.addAction(ui->actionMoveDown10);
    ctx_menu_.addAction(ui->actionMoveRight1);
    ctx_menu_.addAction(ui->actionMoveLeft1);
    ctx_menu_.addAction(ui->actionMoveUp1);
    ctx_menu_.addAction(ui->actionMoveDown1);
    ctx_menu_.addSeparator();
    ctx_menu_.addAction(ui->actionGoToPacket);

    ui->showComboBox->blockSignals(true);
    ui->showComboBox->setCurrentIndex(0);
    ui->showComboBox->blockSignals(false);
    ui->addressComboBox->blockSignals(true);
    ui->addressComboBox->setCurrentIndex(0);
    ui->addressComboBox->blockSignals(false);

    QComboBox *fcb = ui->flowComboBox;
    fcb->addItem(ui->actionFlowAny->text(), SEQ_ANALYSIS_ANY);
    fcb->addItem(ui->actionFlowTcp->text(), SEQ_ANALYSIS_TCP);

    ui->flowComboBox->blockSignals(true);
    ui->flowComboBox->setCurrentIndex(sainfo_->type);

    if (sainfo_->type == SEQ_ANALYSIS_VOIP) {
        ui->controlFrame->hide();
    } else {
        ui->flowComboBox->blockSignals(false);
    }

    QPushButton *save_bt = ui->buttonBox->button(QDialogButtonBox::Save);
    save_bt->setText(tr("Save As" UTF8_HORIZONTAL_ELLIPSIS));

    // XXX Use recent settings instead
    resize(parent.width(), parent.height() * 4 / 5);

    connect(ui->horizontalScrollBar, SIGNAL(valueChanged(int)), this, SLOT(hScrollBarChanged(int)));
    connect(ui->verticalScrollBar, SIGNAL(valueChanged(int)), this, SLOT(vScrollBarChanged(int)));
    connect(sp->xAxis2, SIGNAL(rangeChanged(QCPRange)), this, SLOT(xAxisChanged(QCPRange)));
    connect(sp->yAxis, SIGNAL(rangeChanged(QCPRange)), this, SLOT(yAxisChanged(QCPRange)));
    connect(sp, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(diagramClicked(QMouseEvent*)));
    connect(sp, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMoved(QMouseEvent*)));
    connect(sp, SIGNAL(mouseRelease(QMouseEvent*)), this, SLOT(mouseReleased(QMouseEvent*)));
    connect(this, SIGNAL(goToPacket(int)), seq_diagram_, SLOT(setSelectedPacket(int)));

    disconnect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));

    fillDiagram();
}
Exemplo n.º 3
0
void DeviceItemDelegate::paint(QPainter* p, const QStyleOptionViewItem& opt, const QModelIndex& index) const {
  // Is it a device or a library item?
  if (index.data(DeviceManager::Role_State).isNull()) {
    LibraryItemDelegate::paint(p, opt, index);
    return;
  }

  // Draw the background
  const QStyleOptionViewItemV3* vopt = qstyleoption_cast<const QStyleOptionViewItemV3*>(&opt);
  const QWidget* widget = vopt->widget;
  QStyle* style = widget->style() ? widget->style() : QApplication::style();
  style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, p, widget);

  p->save();

  // Font for the status line
  QFont status_font(opt.font);

#ifdef Q_OS_WIN32
  status_font.setPointSize(status_font.pointSize() - 1);
#else
  status_font.setPointSize(status_font.pointSize() - 2);
#endif

  const int text_height = QFontMetrics(opt.font).height() +
                          QFontMetrics(status_font).height();

  QRect line1(opt.rect);
  QRect line2(opt.rect);
  line1.setTop(line1.top() + (opt.rect.height() - text_height) / 2);
  line2.setTop(line1.top() + QFontMetrics(opt.font).height());
  line1.setLeft(line1.left() + DeviceManager::kDeviceIconSize + kIconPadding);
  line2.setLeft(line2.left() + DeviceManager::kDeviceIconSize + kIconPadding);

  // Change the color for selected items
  if (opt.state & QStyle::State_Selected) {
    p->setPen(opt.palette.color(QPalette::HighlightedText));
  }

  // Draw the icon
  p->drawPixmap(opt.rect.topLeft(), index.data(Qt::DecorationRole).value<QPixmap>());

  // Draw the first line (device name)
  p->drawText(line1, Qt::AlignLeft | Qt::AlignTop, index.data().toString());

  // Draw the second line (status)
  DeviceManager::State state =
      static_cast<DeviceManager::State>(index.data(DeviceManager::Role_State).toInt());
  QVariant progress = index.data(DeviceManager::Role_UpdatingPercentage);
  QString status_text;

  if (progress.isValid()) {
    status_text = tr("Updating %1%...").arg(progress.toInt());
  } else {
    switch (state) {
      case DeviceManager::State_Remembered:
        status_text = tr("Not connected");
        break;

      case DeviceManager::State_NotMounted:
        status_text = tr("Not mounted - double click to mount");
        break;

      case DeviceManager::State_NotConnected:
        status_text = tr("Double click to open");
        break;

      case DeviceManager::State_Connected: {
        QVariant song_count = index.data(DeviceManager::Role_SongCount);
        if (song_count.isValid()) {
          int count = song_count.toInt();
          if (count == 1) // TODO: Fix this properly
            status_text = tr("%1 song").arg(count);
          else
            status_text = tr("%1 songs").arg(count);
        } else {
          status_text = index.data(DeviceManager::Role_MountPath).toString();
        }
        break;
      }
    }
  }

  if (opt.state & QStyle::State_Selected)
    p->setPen(opt.palette.color(QPalette::HighlightedText));
  else
    p->setPen(opt.palette.color(QPalette::Dark));
  p->setFont(status_font);
  p->drawText(line2, Qt::AlignLeft | Qt::AlignTop, status_text);

  p->restore();
}
Exemplo n.º 4
0
PreFlightMiscPage::PreFlightMiscPage(QWidget *parent) :
  QWidget(parent)
{
  setObjectName("PreFlightMiscPage");
  setWindowFlags( Qt::Tool );
  setWindowModality( Qt::WindowModal );
  setAttribute(Qt::WA_DeleteOnClose);
  setWindowTitle( tr("PreFlight - Common") );

  if( parent )
    {
      resize( parent->size() );
    }

  // Layout used by scroll area
  QHBoxLayout *sal = new QHBoxLayout;

  // new widget used as container for the dialog layout.
  QWidget* sw = new QWidget;

  // Scroll area
  QScrollArea* sa = new QScrollArea;
  sa->setWidgetResizable( true );
  sa->setFrameStyle( QFrame::NoFrame );
  sa->setWidget( sw );

#ifdef QSCROLLER
  QScroller::grabGesture( sa->viewport(), QScroller::LeftMouseButtonGesture );
#endif

#ifdef QTSCROLLER
  QtScroller::grabGesture( sa->viewport(), QtScroller::LeftMouseButtonGesture );
#endif

  // Add scroll area to its own layout
  sal->addWidget( sa );

  QHBoxLayout *contentLayout = new QHBoxLayout(this);

  // Pass scroll area layout to the content layout.
  contentLayout->addLayout( sal, 10 );

  // Top layout's parent is the scroll widget
  QGridLayout *topLayout = new QGridLayout(sw);

  int row = 0;

  QLabel *lbl = new QLabel(tr("Minimal arrival altitude:"));
  topLayout->addWidget(lbl, row, 0);

  // get current set altitude unit. This unit must be considered during
  // storage. The internal storage is always in meters.
  m_altUnit = Altitude::getUnit();

  // Input accept only feet and meters all other make no sense. Therefore all
  // other (FL) is treated as feet.
  m_edtMinimalArrival = new NumberEditor;
  m_edtMinimalArrival->setDecimalVisible( false );
  m_edtMinimalArrival->setPmVisible( false );
  m_edtMinimalArrival->setRange( 0, 9999);
  m_edtMinimalArrival->setMaxLength(4);
  m_edtMinimalArrival->setSuffix(" " + Altitude::getUnitText());

  QRegExpValidator* eValidator = new QRegExpValidator( QRegExp( "([0-9]{1,4})" ), this );
  m_edtMinimalArrival->setValidator( eValidator );

  int maw = QFontMetrics(font()).width("9999 ft") + 10;
  m_edtMinimalArrival->setMinimumWidth( maw );

  topLayout->addWidget(m_edtMinimalArrival, row, 1);
  topLayout->setColumnStretch(2, 2);
  row++;

  lbl = new QLabel(tr("Arrival altitude display:"));
  topLayout->addWidget(lbl, row, 0);
  m_edtArrivalAltitude = new QComboBox;
  m_edtArrivalAltitude->addItem( tr("Landing Target"), GeneralConfig::landingTarget );
  m_edtArrivalAltitude->addItem( tr("Next Target"), GeneralConfig::nextTarget );
  topLayout->addWidget(m_edtArrivalAltitude, row, 1);
  row++;

  lbl = new QLabel(tr("QNH:"));
  topLayout->addWidget(lbl, row, 0);

  m_edtQNH = new NumberEditor;
  m_edtQNH->setDecimalVisible( false );
  m_edtQNH->setPmVisible( false );
  m_edtQNH->setRange( 0, 9999);
  m_edtQNH->setMaxLength(4);
  m_edtQNH->setSuffix(" hPa");

  eValidator = new QRegExpValidator( QRegExp( "([0-9]{1,4})" ), this );
  m_edtQNH->setValidator( eValidator );

  int mqw = QFontMetrics(font()).width("9999 hPa") + 10;
  m_edtQNH->setMinimumWidth( mqw );

  topLayout->addWidget(m_edtQNH, row, 1);
  row++;

  lbl = new QLabel(tr("LD average time") + ":");
  topLayout->addWidget(lbl, row, 0);

  m_edtLDTime = new NumberEditor;
  m_edtLDTime->setDecimalVisible( false );
  m_edtLDTime->setPmVisible( false );
  m_edtLDTime->setRange( 5, 600 );
  m_edtLDTime->setMaxLength(3);
  m_edtLDTime->setSuffix(" s");
  m_edtLDTime->setTitle( tr("LD average time") );
  m_edtLDTime->setTip( "5 ... 600 s" );

  eValidator = new QRegExpValidator( QRegExp( "([0-9]{1,3})" ), this );
  m_edtLDTime->setValidator( eValidator );

  topLayout->addWidget(m_edtLDTime, row, 1);
  row++;

  topLayout->setRowMinimumHeight(row, 10);
  row++;

  m_chkLogAutoStart = new QCheckBox(tr("Autostart IGC logger"));
  topLayout->addWidget(m_chkLogAutoStart, row, 0 );

  // get current used horizontal speed unit. This unit must be considered
  // during storage.
  m_speedUnit = Speed::getHorizontalUnit();

  m_logAutoStartSpeed = new DoubleNumberEditor( this );
  m_logAutoStartSpeed->setDecimalVisible( true );
  m_logAutoStartSpeed->setPmVisible( false );
  m_logAutoStartSpeed->setMaxLength(4);
  m_logAutoStartSpeed->setRange( 1.0, 99.9);
  m_logAutoStartSpeed->setPrefix( "> " );
  m_logAutoStartSpeed->setSuffix( QString(" ") + Speed::getHorizontalUnitText() );
  m_logAutoStartSpeed->setDecimals( 1 );

  int mlw = QFontMetrics(font()).width("99.9" + Speed::getHorizontalUnitText()) + 10;
  m_logAutoStartSpeed->setMinimumWidth( mlw );

  topLayout->addWidget( m_logAutoStartSpeed, row, 1 );
  row++;

  lbl = new QLabel(tr("B-Record Interval:"));
  topLayout->addWidget(lbl, row, 0);

  m_bRecordInterval = new NumberEditor;
  m_bRecordInterval->setDecimalVisible( false );
  m_bRecordInterval->setPmVisible( false );
  m_bRecordInterval->setRange( 1, 60);
  m_bRecordInterval->setTip("1...60 s");
  m_bRecordInterval->setMaxLength(2);
  m_bRecordInterval->setSuffix(" s");

  eValidator = new QRegExpValidator( QRegExp( "([0-9]{1,2})" ), this );
  m_bRecordInterval->setValidator( eValidator );

  int mbrw = QFontMetrics(font()).width("99 s") + 10;
  m_bRecordInterval->setMinimumWidth( mbrw );

  topLayout->addWidget(m_bRecordInterval, row, 1);
  row++;

  lbl = new QLabel(tr("K-Record Interval:"));
  topLayout->addWidget(lbl, row, 0);

  m_kRecordInterval = new NumberEditor;
  m_kRecordInterval->setDecimalVisible( false );
  m_kRecordInterval->setPmVisible( false );
  m_kRecordInterval->setRange( 0, 300);
  m_kRecordInterval->setTip("0...300 s");
  m_kRecordInterval->setMaxLength(3);
  m_kRecordInterval->setSuffix(" s");
  m_kRecordInterval->setSpecialValueText(tr("Off"));

  eValidator = new QRegExpValidator( QRegExp( "([0-9]{1,2})" ), this );
  m_kRecordInterval->setValidator( eValidator );

  int mkrw = QFontMetrics(font()).width("999 s") + 10;
  m_kRecordInterval->setMinimumWidth( mkrw );

  topLayout->addWidget(m_kRecordInterval, row, 1);
  row++;

  topLayout->setRowMinimumHeight(row, 10);
  row++;

  topLayout->setRowStretch(row, 10);

  QPushButton *help = new QPushButton(this);
  help->setIcon(QIcon(GeneralConfig::instance()->loadPixmap("help32.png")));
  help->setIconSize(QSize(Layout::getButtonSize(12), Layout::getButtonSize(12)));
  help->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::QSizePolicy::Preferred);

  QPushButton *cancel = new QPushButton(this);
  cancel->setIcon(QIcon(GeneralConfig::instance()->loadPixmap("cancel.png")));
  cancel->setIconSize(QSize(Layout::getButtonSize(12), Layout::getButtonSize(12)));
  cancel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::QSizePolicy::Preferred);

  QPushButton *ok = new QPushButton(this);
  ok->setIcon(QIcon(GeneralConfig::instance()->loadPixmap("ok.png")));
  ok->setIconSize(QSize(Layout::getButtonSize(12), Layout::getButtonSize(12)));
  ok->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::QSizePolicy::Preferred);

  QLabel *titlePix = new QLabel(this);
  titlePix->setAlignment( Qt::AlignCenter );
  titlePix->setPixmap( _globalMapConfig->createGlider(315, 1.6) );

  connect(help, SIGNAL(pressed()), this, SLOT(slotHelp()));
  connect(ok, SIGNAL(pressed()), this, SLOT(slotAccept()));
  connect(cancel, SIGNAL(pressed()), this, SLOT(slotReject()));

  QVBoxLayout *buttonBox = new QVBoxLayout;
  buttonBox->setSpacing(0);
  buttonBox->addWidget(help, 1);
  buttonBox->addStretch(2);
  buttonBox->addWidget(cancel, 1);
  buttonBox->addSpacing(30);
  buttonBox->addWidget(ok, 1);
  buttonBox->addStretch(2);
  buttonBox->addWidget(titlePix);
  contentLayout->addLayout(buttonBox);

  load();
}
Exemplo n.º 5
0
void clsImprimirVehiculos::ImprimirLista(QString strFiltro)
{
    printer = new QPrinter(QPrinter::PrinterResolution);
    printer->setPageSize(QPrinter::A4);

    QPrintDialog printDialog(printer);

    if (printDialog.exec())
    {
        printer->setPageMargins(20,20,15,20,QPrinter::Millimeter);

        QPainter painter(printer);
        painter.setRenderHint(QPainter::Antialiasing);
        QList<QStringList> pages;
        penInicial = painter.pen();
        brushInicial = painter.brush();
        fuenteInicial = painter.font();
        fuenteTitulo = painter.font();
        fuenteMedTitulo = painter.font();
        fuenteNegrita = painter.font();
        fuenteTitulo.setPointSize(20);
        fuenteNegrita.setBold(true);
        fuenteTitulo.setBold(true);
        fuenteMedTitulo.setBold(true);
        fuenteMedTitulo.setPointSize(15);
        fuenteNegrita.setPointSize(10);
        fuenteInicial.setPointSize(10);

        AnchoMat = 0;

        QStringList listaEntradas;
        QString entrada;

        clsVehiculos Vehiculo;
        QVector<QStringList> listaVehiculos = Vehiculo.ListaVehiculos(strFiltro);

        for (int i=0;i<listaVehiculos.size();i++)
        {
            QStringList strVehiculos = listaVehiculos.at(i);

            if (AnchoMat < QFontMetrics(fuenteInicial).width(strVehiculos.at(0)))
                AnchoMat = QFontMetrics(fuenteInicial).width(strVehiculos.at(0));

            entrada = strVehiculos.at(0) + "-|-" + strVehiculos.at(1) + "-|-" + strVehiculos.at(2) + "-|-" + strVehiculos.at(3);

            listaEntradas << entrada;
        }

        maxAlt = painter.window().height();
        maxAnch = painter.window().width();
        Espacio = (maxAlt*3)/257;

        titulo = QObject::tr("Listado de Vehículos");

        rectTitulo = QRect(0,0,maxAnch,(maxAlt*15)/257);
        rectFecha = QRect(0,0,maxAnch,(maxAlt*5)/257);
        rectPie = QRect(0,0,maxAnch,(maxAlt*5)/257);

        painter.setFont(fuenteNegrita);

        rectCabecera = QRect(0,0,maxAnch,QFontMetrics(painter.font()).height()+(maxAlt/257));

        rectfuenteNegrita = QRect(0,0,maxAnch,QFontMetrics(painter.font()).height()+(maxAlt/257));

        AnchoMat = qMax(AnchoMat,QFontMetrics(painter.font()).width(QObject::tr("Código")));
        AnchoFMat = QFontMetrics(painter.font()).width(QObject::tr("Fecha Matricula"));
        AnchoCol = (maxAnch - (AnchoMat + AnchoFMat + 3*Espacio))/2;

        painter.setFont(fuenteInicial);

        rectfuenteInicial = QRect(0,0,maxAnch,QFontMetrics(painter.font()).height()+(maxAlt/257));

        maxAltDispo = maxAlt - (rectTitulo.height()+rectFecha.height()+rectPie.height()+rectCabecera.height());

        colorLinea=0;

        yLinea = 0;

        DividirEnPaginasLV(&painter,&pages,listaEntradas);
        ImprimirPaginasLV(&painter,pages);
    }
}
void WidgetTimeCoursePlot::paintEvent(QPaintEvent *e)
{
  QPainter p(this);
  QRectF rc_plot = rect();
  int nMargin = 10;
  rc_plot.adjust(nMargin, nMargin, -nMargin, -nMargin);
  rc_plot.adjust(15, 15, -25, -27);

  if (m_data.isEmpty())
  {
    p.fillRect(rc_plot, Qt::black);
    return;
  }

  QFont fnt = font();
  fnt.setPixelSize(11);
  int nTextLen = qMax(QFontMetrics(fnt).width(QString::number(m_dMax)),
                      QFontMetrics(fnt).width(QString::number(m_dMin)));
  rc_plot.adjust(nTextLen+6, 0, 0, 0);
  p.fillRect(rc_plot.adjusted(-1, -1, 1, 1), Qt::black);

  double dMin = m_dMin, dMax = m_dMax;
  if (m_bAutoScale)
  {
    dMin = dMax = m_data[0];
    for (int i = 1; i < m_data.size(); i++)
    {
      if (dMin > m_data[i])
        dMin = m_data[i];
      else if (dMax < m_data[i])
        dMax = m_data[i];
    }
    dMax += (dMax-dMin)/4;
    double old_min = dMin;
    dMin -= (dMax-dMin)/4;
    if (dMin < 0 && old_min >= 0)
      dMin = 0;
  }
  if (dMin == dMax)
    dMax += 1;
  double dSpacing = rc_plot.width() / (m_data.size()-1);
  p.setRenderHint(QPainter::Antialiasing);
  QPointF* pts = new QPointF[m_data.size()];
  for (int i = 0; i < m_data.size(); i++)
  {
    pts[i] = QPointF(rc_plot.left() + dSpacing*i,
                     rc_plot.bottom() - (m_data[i]-dMin)/(dMax-dMin)*rc_plot.height());
  }
  p.setPen(QPen(QBrush(Qt::yellow), 2));
  p.drawPolyline(pts, m_data.size());

  // draw cursor
  p.setPen(QPen(QBrush(Qt::red), 2));
  p.drawLine(pts[m_nCurrentFrame] - QPointF(0, 20),
             pts[m_nCurrentFrame] + QPointF(0, qMin(20., rc_plot.bottom()-pts[m_nCurrentFrame].y())));
  delete[] pts;

  // draw Y metrics
  p.setPen(QPen(Qt::black));
  p.setFont(fnt);
  double nMetricInterval = 30;
  double dMetricStep =  (dMax - dMin) / (rc_plot.height() / nMetricInterval);
  dMetricStep = MyUtils::RoundToGrid( dMetricStep );
  double dMetricPos = (int)(dMin/dMetricStep)*dMetricStep;
  double y = rc_plot.bottom()-(dMetricPos-dMin)/(dMax-dMin)*rc_plot.height();
  while (y > rc_plot.top())
  {
    if (y <= rc_plot.bottom())
    {
      QString strg = QString::number(dMetricPos);
      p.drawText(QRectF(rect().left(), y-10, rc_plot.left()-5-rect().left(), 20),
                 Qt::AlignVCenter | Qt::AlignRight, strg);
    }
    dMetricPos += dMetricStep;
    y = rc_plot.bottom()-(dMetricPos-dMin)/(dMax-dMin)*rc_plot.height();
  }

  p.save();
  p.translate(0, rc_plot.top()+rc_plot.height()/2);
  p.rotate(-90);
  p.drawText(QRect(-100, 0, 200, 20), Qt::AlignCenter, "Signal Intensity");
  p.restore();

  // draw X metrics
  nMetricInterval = 50;
  double dTR = 1; // m_dTR;
  dMetricStep =  (m_data.size()-1)*dTR / (rc_plot.width() / nMetricInterval);
  dMetricStep = MyUtils::RoundToGrid( dMetricStep );
  dMetricPos = 0;
  double x = rc_plot.left();
  while (x < rc_plot.right())
  {
    QString strg = QString::number(dMetricPos);
    p.drawText(QRectF(x-100, rc_plot.bottom()+5, 200, 20),
               Qt::AlignTop | Qt::AlignHCenter, strg);

    dMetricPos += dMetricStep;
    x = rc_plot.left() + dMetricPos/((m_data.size()-1)*dTR)*rc_plot.width();
  }

  QRectF rc = rect().adjusted(0, 0, 0, -3);
  p.drawText(rc, Qt::AlignBottom | Qt::AlignHCenter, "Frame ");

  // draw current stats
  QString strg = QString("Signal intensity:%1   Frame: %3")
                 .arg(m_data[m_nCurrentFrame])
              //   .arg(m_nCurrentFrame*m_dTR/1000)
                 .arg(m_nCurrentFrame);
  rc = rect().adjusted(0, 5, 0, 0);
  p.drawText(rc, Qt::AlignHCenter | Qt::AlignTop, strg);
  m_rectPlot = rc_plot;
}
Exemplo n.º 7
0
void
MenuItem::drawLabel( QPainter* p )
{
	RasterOp origRasterOp = p->rasterOp();
	if( m_mouseOver )
	{
// 		p->setRasterOp( OrROP );
	}
	// Prepare the title and desc
	
	// This is the available width that we can print text. This is the place just next to the pixmap
	uint availableWidth = geometry().width() - ( 2 * m_offset ) - pixmap()->width() - ( 4 * m_secOffset );
	
	// If there's a sub menu we'll draw an arrow in this button, so texts area gets smaller
	if( m_sub )
		availableWidth -= KGlobal::iconLoader()->loadIcon( m_arrowIcon, KIcon::Toolbar ).width() - m_secOffset;
	
	// Titles will be printed in one line definetely, so squeze it to fit
	QString s_title = KStringHandler::rPixelSqueeze( title(), p->fontMetrics(), availableWidth );

	// Draw the icon
	p->drawPixmap( m_offset + m_secOffset,
				   m_offset + m_secOffset,
				   *pixmap() );

	if( !description().isNull() )
	{
		// Write the description with smaller font
		QFont smallerFont = p->font();
	
		// Make the font smaller by m_descFontOffset points
		smallerFont.setPointSize( smallerFont.pointSize() - m_descFontOffset );

		////// MOVE LINE SPLICING CODE TO ABOVE
		// Let's see if we can use more than one line, because descriptions
		// are more likely to be longer
		
		// Active area height = total widget height - 2 * primary offset
		int activeAreaHeight = geometry().height() - 2 * m_offset;
		// Available desc height = Active area height - title height
		int availableDescHeight = activeAreaHeight - p->fontMetrics().height();
		// One desc line height
		int descLineHeight = QFontMetrics( smallerFont ).height();
		// Let's see how many desc lines are available
		int lineCount =  availableDescHeight / descLineHeight;

		// Prepare each line of text
		QString desc = description().stripWhiteSpace();
		QString line = desc;
		QStringList lines;

		if( lineCount > 1 )
		{
			for( int j = 0; j < lineCount; j++ )
			{
				uint size = QFontMetrics( smallerFont ).width( desc );
	
				if( ( j + 1 ) != lineCount )
				{
					while( size > availableWidth )
					{
							// Remove the last word untill it fits in one line
						line = line.section( " ", 0, -2 );
						size = QFontMetrics( smallerFont ).width( line );
					}
				}
				else
				{
					// This is the last available line, so squeze the rest
					line = KStringHandler::rPixelSqueeze( desc,
														  p->fontMetrics(),
														  availableWidth
														);
				}
				lines.push_back( line );
				desc = desc.mid( line.length() ).stripWhiteSpace();
				line = desc;
				if( line.isEmpty() ) break;
			}
		}
		else
		{
			lines.push_back( KStringHandler::rPixelSqueeze( desc,
															p->fontMetrics(),
															availableWidth ) );
		}
	
		uint totalTextHeight = p->fontMetrics().height() + 
							   lines.count() * descLineHeight;
		int offset = ( geometry().height() - totalTextHeight ) / 2;
	
		// Write the title of the cell 
		p->drawText( QRect( m_offset + pixmap()->width() + 2 * m_secOffset,
							offset,
							availableWidth,
							p->fontMetrics().height()
					  	),
					 		Qt::AlignLeft, s_title );
	
		// Print each line of the comment
		QFont origFont = p->font();
		QPen origPen = p->pen();
		p->setFont( smallerFont );
		p->setPen( highlightColor().light( 300 ) );
		int i = 0;
		int titleHeight = QFontMetrics( origFont ).height();
		QStringList::Iterator it;
		for( it = lines.begin(); it != lines.end(); ++it, i++ )
		{
			int lineOffset = i * p->fontMetrics().height();
			p->drawText( m_offset + pixmap()->width() + 2 * m_secOffset,
					 	offset + titleHeight + lineOffset,
					 	availableWidth,
					 	p->fontMetrics().height(),
					 	Qt::AlignLeft,
					 	*it );
		}
		
		// Restore to original font and pen
		p->setFont( origFont );
		p->setPen( origPen );
	}
	else
	{
		int offset = ( geometry().height() - p->fontMetrics().height() ) / 2;

		// Write the title of the cell 
		p->drawText( QRect( m_offset + pixmap()->width() + 2 * m_secOffset,
							offset,
							availableWidth,
							p->fontMetrics().height()
						  ),
				 			Qt::AlignLeft, s_title );
	}

	if( m_mouseOver )
	{
		p->setRasterOp( origRasterOp );
	}
}
Exemplo n.º 8
0
void GraphScale::Draw(QPainter &painter)
{
    double scale;
    int x,y,w,w_max,font_h = QFontMetrics(font).height();

    painter.setPen(pen);
    painter.setFont(font);

    switch (pos)
    {
      case pos_bottom:
        scale = graph->w / (vmax-vmin);
        painter.drawLine(graph->xo,graph->yo,graph->xo+graph->w,graph->yo);
        for (double v=vmin;v<=vmax;v+=vinc)
        {
            QString s = (labdps<0 ? QString("%1").arg(v/labdiv) : QString("%1").arg(v/labdiv, 0, 'f', labdps)) + labsuffix;

            x=graph->xo + (v-vmin)*scale;
        //printf("x=%d\n",x);
            painter.drawLine(x,graph->yo,x,graph->yo + 10);
            x=x - QFontMetrics(font).boundingRect(s).width()/2;
            painter.drawText(x,graph->yo + 10 + font_h,s);
        }
        break;

    case pos_left:
        scale = graph->h / (vmax-vmin);
        painter.drawLine(graph->xo,graph->yo,graph->xo,graph->yo-graph->h);
        w_max=0;
        for (double v=vmin;v<=vmax;v+=vinc)
        {
            QString s = (labdps<0 ? QString("%1").arg(v/labdiv) : QString("%1").arg(v/labdiv, 0, 'f', labdps)) + labsuffix;
            y=graph->yo - (v-vmin)*scale;
            painter.drawLine(graph->xo,y,graph->xo-10,y);
            w = QFontMetrics(font).boundingRect(s).width();
            x=graph->xo - 12 - w;
            painter.drawText(x,y + font_h/2.5,s);
            if (w>w_max) w_max=w;
        }
        if (!title.isEmpty())
        {
            x=graph->xo;
            y=graph->yo - graph->h/2.0;
            w=QFontMetrics(font).boundingRect(title).width();
            painter.save();
            painter.translate(x,y);
            painter.rotate(-90.0);
            painter.drawText(-w/2.0,-w_max-font_h-4,title);
            painter.restore();
        }
        break;

    case pos_right:
        scale = graph->h / (vmax-vmin);
        painter.drawLine(graph->xo+graph->w,graph->yo,graph->xo+graph->w,graph->yo-graph->h);
        w_max=0;
        for (double v=vmin;v<=vmax;v+=vinc)
        {
//printf("scalev=%lf\n",v);
            QString s = (labdps<0 ? QString("%1").arg(v/labdiv) : QString("%1").arg(v/labdiv, 0, 'f', labdps)) + labsuffix;
            x=graph->xo + graph->w;
            y=graph->yo - (v-vmin)*scale;
            w = QFontMetrics(font).boundingRect(s).width();
            painter.drawLine(x,y,x+10,y);
            painter.drawText(x+12,y + font_h/2.5,s);
            if (w>w_max) w_max=w;
        }
        if (!title.isEmpty())
        {
            x=graph->xo + graph->w;
            y=graph->yo - graph->h/2.0;
            w=QFontMetrics(font).boundingRect(title).width();
            painter.save();
            painter.translate(x,y);
            painter.rotate(90.0);
            painter.drawText(-w/2.0,-w_max-font_h-4,title);
            painter.restore();
        }
        break;

      default: break;
    }
}
Exemplo n.º 9
0
PageOutput::PageOutput(MainWindow* main_window)
	: QWidget(main_window->centralWidget()) {

	m_main_window = main_window;

	m_old_container = (enum_container) 0;
	m_old_container_av = 0;

	// main codecs
	// (initializer lists should use explicit types for Clang)
	m_containers = {
		ContainerData({"Matroska (MKV)", "matroska", QStringList({"mkv"}), tr("%1 files", "This appears in the file dialog, e.g. 'MP4 files'").arg("Matroska") + " (*.mkv)",
			{VIDEO_CODEC_H264, VIDEO_CODEC_VP8, VIDEO_CODEC_THEORA},
			{AUDIO_CODEC_VORBIS, AUDIO_CODEC_MP3, AUDIO_CODEC_AAC, AUDIO_CODEC_UNCOMPRESSED}}),
		ContainerData({"MP4", "mp4", QStringList({"mp4"}), tr("%1 files", "This appears in the file dialog, e.g. 'MP4 files'").arg("MP4") + " (*.mp4)",
			{VIDEO_CODEC_H264},
			{AUDIO_CODEC_VORBIS, AUDIO_CODEC_MP3, AUDIO_CODEC_AAC}}),
		ContainerData({"WebM", "webm", QStringList({"webm"}), tr("%1 files", "This appears in the file dialog, e.g. 'MP4 files'").arg("WebM") + " (*.webm)",
			{VIDEO_CODEC_VP8},
			{AUDIO_CODEC_VORBIS}}),
		ContainerData({"OGG", "ogg", QStringList({"ogg"}), tr("%1 files", "This appears in the file dialog, e.g. 'MP4 files'").arg("OGG") + " (*.ogg)",
			{VIDEO_CODEC_THEORA},
			{AUDIO_CODEC_VORBIS}}),
		ContainerData({tr("Other..."), "other", QStringList(), "", std::set<enum_video_codec>({}), std::set<enum_audio_codec>({})}),
	};
	m_video_codecs = {
		{"H.264"       , "libx264"  },
		{"VP8"         , "libvpx"   },
		{"Theora"      , "libtheora"},
		{tr("Other..."), "other"    },
	};
	m_audio_codecs = {
		{"Vorbis"          , "libvorbis"   },
		{"MP3"             , "libmp3lame"  },
		{"AAC"             , "libvo_aacenc"},
		{tr("Uncompressed"), "pcm_s16le"   },
		{tr("Other...")    , "other"       },
	};

	// alternative aac codec
	if(!AVCodecIsInstalled(m_audio_codecs[AUDIO_CODEC_AAC].avname)) {
		m_audio_codecs[AUDIO_CODEC_AAC].avname = "aac";
	}

	// load AV container list
	m_containers_av.clear();
	for(AVOutputFormat *format = av_oformat_next(NULL); format != NULL; format = av_oformat_next(format)) {
		if(format->video_codec == AV_CODEC_ID_NONE)
			continue;
		ContainerData c;
		c.name = format->long_name;
		c.avname = format->name;
		c.suffixes = QString(format->extensions).split(',', QString::SkipEmptyParts);
		if(c.suffixes.isEmpty()) {
			c.filter = "";
		} else {
			c.filter = tr("%1 files", "This appears in the file dialog, e.g. 'MP4 files'").arg(c.avname) + " (*." + c.suffixes[0];
			for(int i = 1; i < c.suffixes.size(); ++i) {
				c.suffixes[i] = c.suffixes[i].trimmed(); // needed because libav/ffmpeg isn't very consistent when they say 'comma-separated'
				c.filter += " *." + c.suffixes[i];
			}
			c.filter += ")";
		}
		m_containers_av.push_back(c);
	}
	std::sort(m_containers_av.begin(), m_containers_av.end());

	// load AV codec list
	m_video_codecs_av.clear();
	m_audio_codecs_av.clear();
	for(AVCodec *codec = av_codec_next(NULL); codec != NULL; codec = av_codec_next(codec)) {
		if(!av_codec_is_encoder(codec))
			continue;
		if(codec->type == AVMEDIA_TYPE_VIDEO && VideoEncoder::AVCodecIsSupported(codec->name)) {
			VideoCodecData c;
			c.name = codec->long_name;
			c.avname = codec->name;
			m_video_codecs_av.push_back(c);
		}
		if(codec->type == AVMEDIA_TYPE_AUDIO && AudioEncoder::AVCodecIsSupported(codec->name)) {
			AudioCodecData c;
			c.name = codec->long_name;
			c.avname = codec->name;
			m_audio_codecs_av.push_back(c);
		}
	}
	std::sort(m_video_codecs_av.begin(), m_video_codecs_av.end());
	std::sort(m_audio_codecs_av.begin(), m_audio_codecs_av.end());

	if(m_containers_av.empty()) {
		Logger::LogError("[PageOutput::PageOutput] " + tr("Error: Could not find any suitable container in libavformat!"));
		throw LibavException();
	}
	if(m_video_codecs_av.empty()) {
		Logger::LogError("[PageOutput::PageOutput] " + tr("Error: Could not find any suitable video codec in libavcodec!"));
		throw LibavException();
	}
	if(m_audio_codecs_av.empty()) {
		Logger::LogError("[PageOutput::PageOutput] " + tr("Error: Could not find any suitable audio codec in libavcodec!"));
		throw LibavException();
	}

	m_profile_box = new ProfileBox(this, "output-profiles", &LoadProfileSettingsCallback, &SaveProfileSettingsCallback, this);

	QGroupBox *groupbox_file = new QGroupBox(tr("File"), this);
	{
		QLabel *label_file = new QLabel(tr("Save as:"), groupbox_file);
		m_lineedit_file = new QLineEdit(groupbox_file);
		m_lineedit_file->setToolTip(tr("The recording will be saved to this location."));
		QPushButton *button_browse = new QPushButton(tr("Browse..."), groupbox_file);
		m_checkbox_separate_files = new QCheckBox(tr("Separate file per segment"), groupbox_file);
		m_checkbox_separate_files->setToolTip(tr("If checked, a separate video file will be created every time you pause and resume the recording.\n"
												 "If the original file name is 'test.mkv', the segments will be saved as 'test-YYYY-MM-DD_HH.MM.SS.mkv'."));
		QLabel *label_container = new QLabel(tr("Container:"), groupbox_file);
		m_combobox_container = new QComboBox(groupbox_file);
		for(unsigned int i = 0; i < CONTAINER_COUNT; ++i) {
			QString name = "\u200e" + m_containers[i].name + "\u200e";
			if(i != CONTAINER_OTHER && !AVFormatIsInstalled(m_containers[i].avname))
				name += " \u200e" + tr("(not installed)") + "\u200e";
			m_combobox_container->addItem(name);
		}
		m_combobox_container->setToolTip(tr("The container (file format) that will be used to save the recording.\n"
											"Note that not all codecs are supported by all containers, and that not all media players can read all file formats.\n"
											"- Matroska (MKV) supports all the codecs, but is less well-known.\n"
											"- MP4 is the most well-known format and will play on almost any modern media player, but supports only H.264 video\n"
											"   (and many media players only support AAC audio).\n"
											"- WebM is intended for embedding video into websites (with the HTML5 <video> tag). The format was created by Google.\n"
											"   WebM is supported by default in Firefox, Chrome and Opera, and plugins are available for Internet Explorer and Safari.\n"
											"   It supports only VP8 and Vorbis.\n"
											"- OGG supports only Theora and Vorbis."));
		m_label_container_av = new QLabel(tr("Container name:"), groupbox_file);
		m_combobox_container_av = new QComboBox(groupbox_file);
		for(unsigned int i = 0; i < m_containers_av.size(); ++i) {
			ContainerData &c = m_containers_av[i];
			m_combobox_container_av->addItem(c.avname);
		}
		m_combobox_container_av->setToolTip(tr("For advanced users. You can use any libav/ffmpeg format, but many of them are not useful or may not work."));

		connect(m_combobox_container, SIGNAL(activated(int)), this, SLOT(OnUpdateSuffixAndContainerFields()));
		connect(m_combobox_container_av, SIGNAL(activated(int)), this, SLOT(OnUpdateSuffixAndContainerFields()));
		connect(button_browse, SIGNAL(clicked()), this, SLOT(OnBrowse()));

		QGridLayout *layout = new QGridLayout(groupbox_file);
		layout->addWidget(label_file, 0, 0);
		layout->addWidget(m_lineedit_file, 0, 1);
		layout->addWidget(button_browse, 0, 2);
		layout->addWidget(m_checkbox_separate_files, 1, 0, 1, 3);
		layout->addWidget(label_container, 2, 0);
		layout->addWidget(m_combobox_container, 2, 1, 1, 2);
		layout->addWidget(m_label_container_av, 3, 0);
		layout->addWidget(m_combobox_container_av, 3, 1, 1, 2);
	}
	QGroupBox *groupbox_video = new QGroupBox(tr("Video"), this);
	{
		QLabel *label_video_codec = new QLabel(tr("Codec:"), groupbox_video);
		m_combobox_video_codec = new QComboBox(groupbox_video);
		for(unsigned int i = 0; i < VIDEO_CODEC_COUNT; ++i) {
			m_combobox_video_codec->addItem(m_video_codecs[i].name);
		}
		m_combobox_video_codec->setToolTip(tr("The codec that will be used to compress the video stream.\n"
											  "- H.264 (libx264) is by far the best codec - high quality and very fast.\n"
											  "- VP8 (libvpx) is quite good but also quite slow.\n"
											  "- Theora (libtheora) isn't really recommended because the quality isn't very good."));
		m_label_video_codec_av = new QLabel(tr("Codec name:"), groupbox_video);
		m_combobox_video_codec_av = new QComboBox(groupbox_video);
		for(unsigned int i = 0; i < m_video_codecs_av.size(); ++i) {
			VideoCodecData &c = m_video_codecs_av[i];
			m_combobox_video_codec_av->addItem(c.avname);
		}
		m_combobox_video_codec_av->setToolTip(tr("For advanced users. You can use any libav/ffmpeg video codec, but many of them are not useful or may not work."));
		m_label_video_kbit_rate = new QLabel(tr("Bit rate (in kbps):"), groupbox_video);
		m_lineedit_video_kbit_rate = new QLineEdit(groupbox_video);
		m_lineedit_video_kbit_rate->setToolTip(tr("The video bit rate (in kilobit per second). A higher value means a higher quality."
												  "\nIf you have no idea where to start, try 5000 and change it if needed."));
		m_label_h264_crf = new QLabel(tr("Constant rate factor:", "libx264 setting: don't translate this unless you can come up with something sensible"), groupbox_video);
		m_slider_h264_crf = new QSlider(Qt::Horizontal, groupbox_video);
		m_slider_h264_crf->setRange(0, 51);
		m_slider_h264_crf->setSingleStep(1);
		m_slider_h264_crf->setPageStep(5);
		m_slider_h264_crf->setToolTip(tr("This setting changes the video quality. A lower value means a higher quality.\n"
										 "The allowed range is 0-51 (0 means lossless, the default is 23)."));
		m_label_h264_crf_value = new QLabel(groupbox_video);
		m_label_h264_crf_value->setNum(m_slider_h264_crf->value());
		m_label_h264_crf_value->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
		m_label_h264_crf_value->setMinimumWidth(QFontMetrics(m_label_h264_crf_value->font()).width("99") + 2);
		m_label_h264_preset = new QLabel(tr("Preset:", "libx264 setting: don't translate this unless you can come up with something sensible"), groupbox_video);
		m_combobox_h264_preset = new QComboBox(groupbox_video);
		for(unsigned int i = 0; i < H264_PRESET_COUNT; ++i) {
			m_combobox_h264_preset->addItem(EnumToString((enum_h264_preset) i));
		}
		m_combobox_h264_preset->setToolTip(tr("The encoding speed. A higher speed uses less CPU (making higher recording frame rates possible),\n"
											  "but results in larger files. The quality shouldn't be affected too much."));
		m_label_vp8_cpu_used = new QLabel(tr("CPU used:", "libvpx setting: don't translate this unless you can come up with something sensible"), groupbox_video);
		m_combobox_vp8_cpu_used = new QComboBox(groupbox_video);
		m_combobox_vp8_cpu_used->addItem("5 (" + tr("fastest") + ")");
		m_combobox_vp8_cpu_used->addItem("4");
		m_combobox_vp8_cpu_used->addItem("3");
		m_combobox_vp8_cpu_used->addItem("2");
		m_combobox_vp8_cpu_used->addItem("1");
		m_combobox_vp8_cpu_used->addItem("0 (" + tr("slowest") + ")");
		m_combobox_vp8_cpu_used->setToolTip(tr("The encoding speed. A higher value uses *less* CPU time. (I didn't choose the name, this is the name\n"
											   "used by the VP8 encoder). Higher values result in lower quality video, unless you increase the bit rate too."));
		m_label_video_options = new QLabel(tr("Custom options:"), groupbox_video);
		m_lineedit_video_options = new QLineEdit(groupbox_video);
		m_lineedit_video_options->setToolTip(tr("Custom codec options separated by commas (e.g. option1=value1,option2=value2,option3=value3)"));
		m_checkbox_video_allow_frame_skipping = new QCheckBox(tr("Allow frame skipping"), groupbox_video);
		m_checkbox_video_allow_frame_skipping->setToolTip(tr("If checked, the video encoder will be allowed to skip frames if the input frame rate is\n"
															 "lower than the output frame rate. If not checked, input frames will be duplicated to fill the holes.\n"
															 "This increases the file size and CPU usage, but reduces the latency for live streams in some cases.\n"
															 "It shouldn't affect the appearance of the video."));

		connect(m_combobox_video_codec, SIGNAL(activated(int)), this, SLOT(OnUpdateVideoCodecFields()));
		connect(m_slider_h264_crf, SIGNAL(valueChanged(int)), m_label_h264_crf_value, SLOT(setNum(int)));

		QGridLayout *layout = new QGridLayout(groupbox_video);
		layout->addWidget(label_video_codec, 0, 0);
		layout->addWidget(m_combobox_video_codec, 0, 1, 1, 2);
		layout->addWidget(m_label_video_codec_av, 1, 0);
		layout->addWidget(m_combobox_video_codec_av, 1, 1, 1, 2);
		layout->addWidget(m_label_video_kbit_rate, 2, 0);
		layout->addWidget(m_lineedit_video_kbit_rate, 2, 1, 1, 2);
		layout->addWidget(m_label_h264_crf, 3, 0);
		layout->addWidget(m_slider_h264_crf, 3, 1);
		layout->addWidget(m_label_h264_crf_value, 3, 2);
		layout->addWidget(m_label_h264_preset, 4, 0);
		layout->addWidget(m_combobox_h264_preset, 4, 1, 1, 2);
		layout->addWidget(m_label_vp8_cpu_used, 5, 0);
		layout->addWidget(m_combobox_vp8_cpu_used, 5, 1, 1, 2);
		layout->addWidget(m_label_video_options, 6, 0);
		layout->addWidget(m_lineedit_video_options, 6, 1, 1, 2);
		layout->addWidget(m_checkbox_video_allow_frame_skipping, 7, 0, 1, 3);
	}
	m_groupbox_audio = new QGroupBox(tr("Audio"));
	{
		QLabel *label_audio_codec = new QLabel(tr("Codec:"), m_groupbox_audio);
		m_combobox_audio_codec = new QComboBox(m_groupbox_audio);
		for(unsigned int i = 0; i < AUDIO_CODEC_COUNT; ++i) {
			m_combobox_audio_codec->addItem(m_audio_codecs[i].name);
		}
		m_combobox_audio_codec->setToolTip(tr("The codec that will be used to compress the audio stream. You shouldn't worry too much about\n"
											  "this, because the size of the audio data is usually negligible compared to the size of the video data.\n"
											  "And if you're only recording your own voice (i.e. no music), the quality won't matter that much anyway.\n"
											  "- Vorbis (libvorbis) is great, this is the recommended codec.\n"
											  "- MP3 (libmp3lame) is reasonably good.\n"
											  "- AAC is a good codec, but the implementations used here (libvo_aacenc or the experimental ffmpeg aac encoder)\n"
											  "   are pretty bad. Only use it if you have no other choice.\n"
											  "- Uncompressed will simply store the sound data without compressing it. The file will be quite large, but it's very fast."));
		m_label_audio_codec_av = new QLabel(tr("Codec name:"), m_groupbox_audio);
		m_combobox_audio_codec_av = new QComboBox(m_groupbox_audio);
		for(unsigned int i = 0; i < m_audio_codecs_av.size(); ++i) {
			AudioCodecData &c = m_audio_codecs_av[i];
			m_combobox_audio_codec_av->addItem(c.avname);
		}
		m_combobox_audio_codec_av->setToolTip(tr("For advanced users. You can use any libav/ffmpeg audio codec, but many of them are not useful or may not work."));
		m_label_audio_kbit_rate = new QLabel(tr("Bit rate (in kbps):"), m_groupbox_audio);
		m_lineedit_audio_kbit_rate = new QLineEdit(m_groupbox_audio);
		m_lineedit_audio_kbit_rate->setToolTip(tr("The audio bit rate (in kilobit per second). A higher value means a higher quality. The typical value is 128."));
		m_label_audio_options = new QLabel(tr("Custom options:"), m_groupbox_audio);
		m_lineedit_audio_options = new QLineEdit(m_groupbox_audio);
		m_lineedit_audio_options->setToolTip(tr("Custom codec options separated by commas (e.g. option1=value1,option2=value2,option3=value3)"));

		connect(m_combobox_audio_codec, SIGNAL(activated(int)), this, SLOT(OnUpdateAudioCodecFields()));

		QGridLayout *layout = new QGridLayout(m_groupbox_audio);
		layout->addWidget(label_audio_codec, 0, 0);
		layout->addWidget(m_combobox_audio_codec, 0, 1);
		layout->addWidget(m_label_audio_codec_av, 1, 0);
		layout->addWidget(m_combobox_audio_codec_av, 1, 1);
		layout->addWidget(m_label_audio_kbit_rate, 2, 0);
		layout->addWidget(m_lineedit_audio_kbit_rate, 2, 1);
		layout->addWidget(m_label_audio_options, 3, 0);
		layout->addWidget(m_lineedit_audio_options, 3, 1);
	}
	QPushButton *button_back = new QPushButton(g_icon_go_previous, tr("Back"), this);
	QPushButton *button_continue = new QPushButton(g_icon_go_next, tr("Continue"), this);

	connect(button_back, SIGNAL(clicked()), m_main_window, SLOT(GoPageInput()));
	connect(button_continue, SIGNAL(clicked()), this, SLOT(OnContinue()));

	QVBoxLayout *layout = new QVBoxLayout(this);
	layout->addWidget(m_profile_box);
	layout->addWidget(groupbox_file);
	layout->addWidget(groupbox_video);
	layout->addWidget(m_groupbox_audio);
	layout->addStretch();
	{
		QHBoxLayout *layout2 = new QHBoxLayout();
		layout->addLayout(layout2);
		layout2->addWidget(button_back);
		layout2->addWidget(button_continue);
	}

	OnUpdateContainerFields();
	OnUpdateVideoCodecFields();
	OnUpdateAudioCodecFields();

}
Exemplo n.º 10
0
/** ***************************************************************************/
void ProposalList::ItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &options, const QModelIndex &index) const {

    painter->save();

    QStyleOptionViewItem option = options;
    initStyleOption(&option, index);

    /*
     * fm(x) := fontmetrics of x
     * DR := DisplayRole
     * TR := ToolTipRole
     *  +---------------------+----------------------------------------+
     *  |                     |                                        |
     *  |   +-------------+   |                                        |
     *  |   |             |   |                                        |
     *  |   |             |   |a*fm(DR)/(fm(DR)+fm(TR))    DisplayRole |
     * a|   |     icon    |   |                                        |
     *  |   |             |   |                                        |
     *  |   |             |   +----------------------------------------+
     *  |   |             |   |                                        |
     *  |   +-------------+   |a*fm(TR)/(fm(DR)+fm(TR))  ToolTipRole+x |
     *  |                     |                                        |
     * +---------------------------------------------------------------+
     */


    // Avoid ugly dark blue mouseover background
    // TODO: QT_MINREL 5.7 setFlag
    option.state &= ~QStyle::State_MouseOver;

    // Draw selection
    option.widget->style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, option.widget);

    // Draw icon
    if ( drawIcon ){
        QRect iconRect = QRect(
                    QPoint((option.rect.height() - option.decorationSize.width())/2 + option.rect.x(),
                           (option.rect.height() - option.decorationSize.height())/2 + option.rect.y()),
                    option.decorationSize);
        QPixmap pixmap;
        QString iconPath = index.data(Qt::DecorationRole).value<QString>();
        QString cacheKey = QString("%1%2%3").arg(option.decorationSize.width(), option.decorationSize.height()).arg(iconPath);
        if ( !QPixmapCache::find(cacheKey, &pixmap) ) {
            pixmap = QPixmap(iconPath).scaled(option.decorationSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            QPixmapCache::insert(cacheKey, pixmap);
        }
        painter->drawPixmap(iconRect, pixmap);
    }

    // Calculate text rects
    QFont font1 = option.font;
    QFont font2 = option.font;
    font2.setPixelSize(12);
    QFontMetrics fontMetrics1 = QFontMetrics(font1);
    QFontMetrics fontMetrics2 = QFontMetrics(font2);
    QRect contentRect = option.rect;
    contentRect.setLeft(drawIcon ? option.rect.height() : 0);
    contentRect.setTop(option.rect.y()+option.rect.height()/2-(fontMetrics1.height()+fontMetrics2.height())/2);
    contentRect.setBottom(option.rect.y()+option.rect.height()/2+(fontMetrics1.height()+fontMetrics2.height())/2);
    QRect textRect = contentRect.adjusted(0,-2,0,-fontMetrics2.height()-2);
    QRect subTextRect = contentRect.adjusted(0,fontMetrics1.height()-2,0,-2);

    //    // Test
    //    painter->fillRect(iconRect, Qt::magenta);
    //    painter->fillRect(contentRect, Qt::red);
    //    painter->fillRect(textRect, Qt::blue);
    //    painter->fillRect(subTextRect, Qt::yellow);


    // Draw display role
    painter->setFont(font1);
    QString text = fontMetrics1.elidedText(index.data(Qt::DisplayRole).toString(),
                                           option.textElideMode,
                                           textRect.width());
    option.widget->style()->drawItemText(painter,
                                         textRect,
                                         option.displayAlignment,
                                         option.palette,
                                         option.state & QStyle::State_Enabled,
                                         text,
                                         (option.state & QStyle::State_Selected) ? QPalette::HighlightedText : QPalette::WindowText);

    // Draw tooltip role
    painter->setFont(font2);
    text = fontMetrics2.elidedText(index.data(option.state.testFlag(QStyle::State_Selected)? subTextRole : Qt::ToolTipRole).toString(),
                                   option.textElideMode,
                                   subTextRect.width());
    option.widget->style()->drawItemText(painter,
                                         subTextRect,
                                         Qt::AlignBottom|Qt::AlignLeft,
                                         option.palette,
                                         option.state & QStyle::State_Enabled,
                                         text,
                                         (option.state & QStyle::State_Selected) ? QPalette::HighlightedText : QPalette::WindowText);
    painter->restore();
}
Exemplo n.º 11
0
 QModelIndex PieView::indexAt(const QPoint &point) const
 {
     if (validItems == 0)
         return QModelIndex();

     // Transform the view coordinates into contents widget coordinates.
     int wx = point.x() + horizontalScrollBar()->value();
     int wy = point.y() + verticalScrollBar()->value();

     if (wx < totalSize) {
         double cx = wx - totalSize/2;
         double cy = totalSize/2 - wy; // positive cy for items above the center

         // Determine the distance from the center point of the pie chart.
         double d = pow(pow(cx, 2) + pow(cy, 2), 0.5);

         if (d == 0 || d > pieSize/2)
             return QModelIndex();

         // Determine the angle of the point.
         double angle = (180 / M_PI) * acos(cx/d);
         if (cy < 0)
             angle = 360 - angle;

         // Find the relevant slice of the pie.
         double startAngle = 0.0;

         for (int row = 0; row < model()->rowCount(rootIndex()); ++row) {

             QModelIndex index = model()->index(row, 1, rootIndex());
             double value = model()->data(index).toDouble();

             if (value > 0.0) {
                 double sliceAngle = 360*value/totalValue;

                 if (angle >= startAngle && angle < (startAngle + sliceAngle))
                     return model()->index(row, 1, rootIndex());

                 startAngle += sliceAngle;
             }
         }
     } else {
         double itemHeight = QFontMetrics(viewOptions().font).height();
         int listItem = int((wy - margin) / itemHeight);
         int validRow = 0;

         for (int row = 0; row < model()->rowCount(rootIndex()); ++row) {

             QModelIndex index = model()->index(row, 1, rootIndex());
             if (model()->data(index).toDouble() > 0.0) {

                 if (listItem == validRow)
                     return model()->index(row, 0, rootIndex());

                 // Update the list index that corresponds to the next valid row.
                 validRow++;
             }
         }
     }

     return QModelIndex();
 }
Exemplo n.º 12
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QImage PoleFigureImageUtilities::PaintPoleFigureOverlay(int imageWidth, int imageHeight, QString label, QImage image)
{
  int pxHigh = 0;
  int pxWide = 0;

  // Scale the Font Point size to something reasonable to the size of the image. Here our standard was 14Pt Font when the
  // Pole figure was 512 Pixels square.
  int fontPtSize = imageHeight / 32;

  QFont font("Ariel", fontPtSize, QFont::Bold);
  QFontMetrics metrics(font);
  pxHigh = metrics.height();
  pxWide = metrics.width(QString("Y"));

  int pxOffset = 2 * pxWide;
  int pyOffset = 2 * pxHigh;

  int pImageWidth = imageWidth + pxOffset * 2;
  int pImageHeight = imageHeight + pyOffset * 2;

  QImage pImage(pImageWidth, pImageHeight, QImage::Format_ARGB32_Premultiplied);
  pImage.fill(0xFFFFFFFF); // All white background

  // Create a Painter backed by a QImage to draw into
  QPainter painter;
  painter.begin(&pImage);
  painter.setRenderHint(QPainter::Antialiasing, true);
  qint32 penWidth = 1;

#if 0
  // DRAW A BORDER AROUND THE IMAGE FOR DEBUGGING
  QColor c(RgbColor::dRgb(255, 0, 0, 255));
  painter.setPen(QPen(c, penWidth, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin));

  painter.drawLine(0, 0, pImageWidth, 0); // Top
  painter.drawLine(0, 0, 0, pImageHeight); // Left
  painter.drawLine(pImageWidth, 0, pImageWidth, pImageHeight); // Right
  painter.drawLine(0, pImageHeight, pImageWidth, pImageHeight); // Bottom
  //-----------------
#endif

  painter.setFont(font);
//  metrics = painter.fontMetrics();
//  pxHigh = metrics.height();
//  pxWide = metrics.width(QString("Y"));

  // Draw the Pole Figure into the center of the canvas
  QPoint point(pxOffset, pyOffset);
  painter.drawImage(point, image);

  // Scale pen width based on the size of the image
  penWidth = imageHeight / 256;
  painter.setPen(QPen(QColor(0, 0, 0, 255), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));

  // Draw the Outer circular border around the pole figure
  QPainterPath circle;
  QPointF center(pImageWidth / 2, pImageHeight / 2);
  circle.addEllipse(center, imageWidth / 2, imageHeight / 2);
  painter.drawPath(circle);

  // Label the X Axis
  painter.drawText(pImageWidth - (pxWide * 1.5), pImageHeight / 2 + pxHigh / 3, "X");
  // Label the Y Axis
  pxWide = metrics.width(QString("Y"));
  painter.drawText(pImageWidth / 2 - pxWide / 2, pyOffset - penWidth - 1, "Y");

  // Draw the name of the Pole Figure
  int labelWidth = 0;
  int maxWidth = pImageWidth / 5; // No more than a Quarter of the width of the image
  while(labelWidth < maxWidth)
  {
    fontPtSize++;
    font = QFont("Ariel", fontPtSize, QFont::Bold);
    metrics = QFontMetrics(font);
    labelWidth = metrics.width(label); // Figure out which string is longer (pixel wise)
  }
  painter.setFont(font);
  pxHigh = metrics.height() + 2;
// pxWide = metrics.width(label);
  painter.drawText(pxOffset, pxHigh, label);

  // Draw slightly transparent lines
  //penWidth = 1;
  painter.setPen(QPen(QColor(0, 0, 0, 180), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
  // Draw the X Axis
  painter.drawLine(pxOffset, pImageHeight / 2, pImageWidth - pxOffset, pImageHeight / 2);
  // Draw the Y Axis
  painter.drawLine(pImageWidth / 2, pyOffset, pImageWidth / 2, pImageHeight - pyOffset);

  painter.end();
  return pImage;
}
Exemplo n.º 13
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QImage PoleFigureImageUtilities::GenerateScalarBar(int imageWidth, int imageHeight, PoleFigureConfiguration_t& config)
{
  int numColors = config.numColors;
  QImage pImage(imageWidth, imageHeight, QImage::Format_ARGB32_Premultiplied);
  pImage.fill(0xFFFFFFFF); // All white background

  // Create a Painter backed by a QImage to draw into
  QPainter painter;
  painter.begin(&pImage);
  painter.setRenderHint(QPainter::Antialiasing, true);

  int penWidth = 1;

#if 0
  // DRAW A BORDER AROUND THE IMAGE FOR DEBUGGING
  QColor c(RgbColor::dRgb(255, 0, 0, 255));
  painter.setPen(QPen(c, penWidth, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin));

  painter.drawLine(0, 0, imageWidth, 0); // Top
  painter.drawLine(0, 0, 0, imageHeight); // Left
  painter.drawLine(imageWidth, 0, imageWidth, imageHeight); // Right
  painter.drawLine(0, imageHeight, imageWidth, imageHeight); // Bottom
  //-----------------
#endif

  //Get all the colors that we will need
  QVector<DREAM3D::Rgb> colorTable(numColors);
  QVector<float> colors(3 * numColors, 0.0);
  DREAM3DColorTable::GetColorTable(numColors, colors); // Generate the color table values
  float r = 0.0, g = 0.0, b = 0.0;
  for (int i = 0; i < numColors; i++) // Convert them to QRgbColor values
  {
    r = colors[3 * i];
    g = colors[3 * i + 1];
    b = colors[3 * i + 2];
    colorTable[i] = RgbColor::dRgb(r * 255, g * 255, b * 255, 255);
  }

  // Now start from the bottom and draw colored lines up the scale bar
  // A Slight Indentation for the scalar bar
  float margin = 0.05f;
  float scaleBarRelativeWidth = 0.10f;
  float scaleBarRelativeHeight = 1.0f - (margin * 2);

  int colorHeight = int( (imageHeight * scaleBarRelativeHeight) / numColors);

  QPointF topLeft(imageWidth * margin, imageHeight * margin);
  QSizeF size(imageWidth * scaleBarRelativeWidth, imageHeight * scaleBarRelativeHeight);

  int yLinePos = topLeft.y();

  QPointF start = topLeft;
  QPointF end = topLeft;

  for(int i = numColors - 1; i >= 0; i--)
  {
    QColor c(colorTable[i]);
    painter.setPen(QPen(c, penWidth, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin));
    for(int j = 0; j < colorHeight; j++)
    {
      start.setY(yLinePos);
      end.setX(topLeft.x() + (imageWidth * scaleBarRelativeWidth));
      end.setY(yLinePos);
      painter.drawLine(start, end);
      yLinePos++;
    }
  }

  // Draw the border of the scale bar
  size = QSizeF(imageWidth * scaleBarRelativeWidth, numColors * colorHeight); // Add two pixel to the height so we don't over write part of the scale bar
  QRectF scaleBorder(topLeft, size);
  penWidth = 2;
  painter.setPen(QPen(QColor(0, 0, 0, 255), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
  painter.drawRect(scaleBorder);


  // Draw the Text Labels of the Scale Bar
  int startFontPtSize = 10;
  QFont font("Ariel", startFontPtSize, QFont::Bold);

  QFontMetrics metrics(font);
  int fontPixelsHeight = metrics.height();
  while(fontPixelsHeight < colorHeight * 2)
  {
    startFontPtSize++;
    font = QFont("Ariel", startFontPtSize, QFont::Bold);
    metrics = QFontMetrics(font);
    fontPixelsHeight = metrics.height();
  }
  painter.setFont(font);

  // Draw some more information to the right of the Scale Bar
  QString maxStr = QString::number(config.maxScale, 'f', 3);
  painter.drawText(topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10, topLeft.y() + fontPixelsHeight, maxStr);

  QString minStr = QString::number(config.minScale, 'f', 3);
  painter.drawText(topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10, topLeft.y() + size.height(), minStr);
  //------------------------------


  // Draw some statistics for the pole figures
  startFontPtSize = 8; // Set it to a rather large point size so we can fit the text perfectly. Only an insanely large Polefigure would go past this size
  int labelWidth = 0;

  // Make sure the size of font we just picked will allow the string to NOT be clipped because the rendered
  // pixel width is past the right side of the image
  int endOfStringYPos = topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10 + labelWidth;
  while(endOfStringYPos < imageWidth)
  {
    startFontPtSize++;
    font = QFont("Ariel", startFontPtSize, QFont::Bold);
    metrics = QFontMetrics(font);
    QString label("Upper & Lower");
    QString label2 = QString("Samples: ") + QString::number(config.eulers->getNumberOfTuples());
    fontPixelsHeight = metrics.height(); // Update the font height
    int labelWidth = metrics.width(label); // Figure out which string is longer (pixel wise)
    if (labelWidth < metrics.width(label2))
    {
      labelWidth = metrics.width(label2);
    }
    endOfStringYPos = topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10 + labelWidth;
  }
  startFontPtSize--;
  font = QFont("Ariel", startFontPtSize, QFont::Bold);
  metrics = QFontMetrics(font);
  QString label("Upper & Lower");
  QString label2 = QString("Samples: ") + QString::number(config.eulers->getNumberOfTuples());

  labelWidth = metrics.width(label);
  if (labelWidth < metrics.width(label2))
  {
    labelWidth = metrics.width(label2);
  }

  // Set the font into the Painter
  painter.setFont(font);

  QPointF statsPoint(topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10, imageHeight * .5);

  // Draw some more Statistics Text
  painter.drawText(statsPoint, label);
  statsPoint.setY(imageHeight * .5 + fontPixelsHeight);
  painter.drawText(statsPoint, label2);

  painter.end();
  // Scale the image down to 225 pixels
  return pImage;

}
Exemplo n.º 14
0
void NormalState::paintEvent(CoreEdit *ctxt, QPaintEvent *e)
{
	QPainter p( ctxt->viewport() );
	
	int xOffset = ctxt->horizontalScrollBar()->value() + 4;
	int yOffset = ctxt->verticalScrollBar()->value();
	
	if ( ctxt->highlightCurrentLine() )
	{
		QRect r(0,
				ctxt->cursorRect().y(),
				ctxt->viewport()->width(),
				QFontMetrics( ctxt->document()->defaultFont() ).lineSpacing() );
		
		p.fillRect(r, QColor(0x00, 0xff, 0xff, 0x30));
	}
	
	if ( ctxt->drawMargin() )
	{
		int margin = QFontMetrics(ctxt->font()).width(" ") * (ctxt->margin() + 1);
		
		margin -= xOffset;
		
		p.drawLine(	margin, 0,
					margin, ctxt->viewport()->height());
	}
	
	//I was forced to do these standard painting afterward so as to get rid
	//of some scrollbars bugs!!!
	
	QRect r = e->rect();
	p.translate(-xOffset, -yOffset);
	r.translate(xOffset, yOffset);
	
	QAbstractTextDocumentLayout::PaintContext ctx;
	ctx.palette = ctxt->palette();
	
	if ( ctxt->bCursor && ctxt->isEnabled() && ctxt->hasFocus() )
		ctx.cursorPosition = ctxt->textCursor().position();
	
	if ( ctxt->parenMatching() && !ctxt->curLine.isNull() )
	{
		QPen backupPen = p.pen();
		
		QPen newPen(Qt::DotLine);
		newPen.setWidth(0);
		newPen.setColor((ctxt->pMatcher ? ctxt->pMatcher->matchColor() : Qt::black));
		p.setPen(newPen);	
		
		const QFontMetrics fm = ctxt->fontMetrics();
		const int fontHeight = fm.height();
		const int x = ctxt->curLine.x1();// + (fm.width(" ") / 2);
		
		int y1 = ctxt->curLine.y1() + 1;
		int y2 = 0;
		
		for (int y = y1; y < ctxt->curLine.y2(); y += fontHeight)
		{
			QTextCursor cursor = ctxt->cursorForPosition(QPoint(x, y));	
			QChar ch = ParenMatcher::charFromCursor(cursor,
													QTextCursor::NextCharacter);
			
			if (ch.isSpace())
				y2 = y + fontHeight;
			
			else
			{
				QChar ch2 = ParenMatcher::charFromCursor(cursor,
												QTextCursor::PreviousCharacter);
				if (ch2 == '\t')
				{
					ch2 = ParenMatcher::charFromCursor(
									ctxt->cursorForPosition(QPoint(
												x - (ctxt->tabStopWidth() / 2),
												y) ),
									QTextCursor::NextCharacter);
					
					if (ch2 == '\t')
						y2 = y + fontHeight;
					else
					{
						if (y1 < y2)
						{
							QLine lineToPrint(x, y1, x, y2);
							lineToPrint.translate(xOffset, yOffset);
							p.drawLine(lineToPrint);
						}
						y1 = y + fontHeight;
					}
				} else {
					if (y1 < y2)
					{
						QLine lineToPrint(x, y1, x, y2);
						lineToPrint.translate(xOffset, yOffset);
						p.drawLine(lineToPrint);
					}
					y1 = y + fontHeight;
				}
			}
		}
		
		if (y1 < y2)
		{
			QLine lineToPrint(x, y1, x, y2);
			lineToPrint.translate(xOffset, yOffset);
			p.drawLine(lineToPrint);
		}
		
		p.setPen(backupPen);
	}
		
	p.setClipRect(r);
	ctx.clip = r;
	
	paintSelection(ctxt, p, xOffset, yOffset, ctx);
	
	ctxt->document()->documentLayout()->draw(&p, ctx);
}
Exemplo n.º 15
0
static void drawTextCommon(GraphicsContext* ctx, const TextRun& run, const FloatPoint& point, int from, int to, const QFont& font, bool isComplexText)
{
    if (to < 0)
        to = run.length();

    QPainter *p = ctx->platformContext();

    QPen textFillPen;
    if (ctx->textDrawingMode() & TextModeFill)
        textFillPen = fillPenForContext(ctx);

    QPen textStrokePen;
    if (ctx->textDrawingMode() & TextModeStroke)
        textStrokePen = strokePenForContext(ctx);

    String sanitized = Font::normalizeSpaces(run.characters(), run.length());
    QString string = fromRawDataWithoutRef(sanitized);
    QPointF pt(point.x(), point.y());

    if (from > 0 || to < run.length()) {
        if (isComplexText) {
            QTextLayout layout(string, font);
            QTextLine line = setupLayout(&layout, run);
            float x1 = line.cursorToX(from);
            float x2 = line.cursorToX(to);
            if (x2 < x1)
                qSwap(x1, x2);

            QFontMetrics fm(font);
            int ascent = fm.ascent();
            QRectF boundingRect(point.x() + x1, point.y() - ascent, x2 - x1, fm.height());
            QRectF clip = boundingRect;

            ContextShadow* ctxShadow = ctx->contextShadow();

            if (ctxShadow->m_type != ContextShadow::NoShadow) {
                qreal dx1 = 0, dx2 = 0, dy1 = 0, dy2 = 0;
                if (ctxShadow->offset().x() > 0)
                    dx2 = ctxShadow->offset().x();
                else
                    dx1 = -ctxShadow->offset().x();
                if (ctxShadow->offset().y() > 0)
                    dy2 = ctxShadow->offset().y();
                else
                    dy1 = -ctxShadow->offset().y();
                // expand the clip rect to include the text shadow as well
                clip.adjust(dx1, dx2, dy1, dy2);
                clip.adjust(-ctxShadow->m_blurDistance, -ctxShadow->m_blurDistance, ctxShadow->m_blurDistance, ctxShadow->m_blurDistance);
            }
            p->save();
            p->setClipRect(clip.toRect(), Qt::IntersectClip);
            pt.setY(pt.y() - ascent);

            if (ctxShadow->m_type != ContextShadow::NoShadow) {
                ContextShadow* ctxShadow = ctx->contextShadow();
                if (!ctxShadow->mustUseContextShadow(ctx)) {
                    p->save();
                    p->setPen(ctxShadow->m_color);
                    p->translate(ctxShadow->offset());
                    line.draw(p, pt);
                    p->restore();
                } else {
                    QPainter* shadowPainter = ctxShadow->beginShadowLayer(ctx, boundingRect);
                    if (shadowPainter) {
                        // Since it will be blurred anyway, we don't care about render hints.
                        shadowPainter->setFont(p->font());
                        shadowPainter->setPen(ctxShadow->m_color);
                        line.draw(shadowPainter, pt);
                        ctxShadow->endShadowLayer(ctx);
                    }
                }
            }
            p->setPen(textFillPen);
            line.draw(p, pt);
            p->restore();
            return;
        }
        int skipWidth = QFontMetrics(font).width(string, from, Qt::TextBypassShaping);
        pt.setX(pt.x() + skipWidth);
        string = fromRawDataWithoutRef(sanitized, from, to - from);
    }

    p->setFont(font);

    int flags = run.rtl() ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight;
    if (!isComplexText && !(ctx->textDrawingMode() & TextModeStroke))
        flags |= Qt::TextBypassShaping;

    QPainterPath textStrokePath;
    if (ctx->textDrawingMode() & TextModeStroke)
        textStrokePath.addText(pt, font, string);

    ContextShadow* ctxShadow = ctx->contextShadow();
    if (ctxShadow->m_type != ContextShadow::NoShadow) {
        if (ctx->textDrawingMode() & TextModeFill) {
            if (ctxShadow->m_type != ContextShadow::BlurShadow) {
                p->save();
                p->setPen(ctxShadow->m_color);
                p->translate(ctxShadow->offset());
                p->drawText(pt, string, flags, run.expansion());
                p->restore();
            } else {
                QFontMetrics fm(font);
                QRectF boundingRect(pt.x(), point.y() - fm.ascent(), fm.width(string, -1, flags), fm.height());
                QPainter* shadowPainter = ctxShadow->beginShadowLayer(ctx, boundingRect);
                if (shadowPainter) {
                    // Since it will be blurred anyway, we don't care about render hints.
                    shadowPainter->setFont(p->font());
                    shadowPainter->setPen(ctxShadow->m_color);
                    shadowPainter->drawText(pt, string, flags, run.expansion());
                    ctxShadow->endShadowLayer(ctx);
                }
            }
        } else if (ctx->textDrawingMode() & TextModeStroke) {
            if (ctxShadow->m_type != ContextShadow::BlurShadow) {
                p->translate(ctxShadow->offset());
                p->strokePath(textStrokePath, QPen(ctxShadow->m_color));
                p->translate(-ctxShadow->offset());
            } else {
                QFontMetrics fm(font);
                QRectF boundingRect(pt.x(), point.y() - fm.ascent(), fm.width(string, -1, flags), fm.height());
                QPainter* shadowPainter = ctxShadow->beginShadowLayer(ctx, boundingRect);
                if (shadowPainter) {
                    // Since it will be blurred anyway, we don't care about render hints.
                    shadowPainter->setFont(p->font());
                    shadowPainter->strokePath(textStrokePath, QPen(ctxShadow->m_color));
                    ctxShadow->endShadowLayer(ctx);
                }
            }
        }
    }

    if (ctx->textDrawingMode() & TextModeStroke)
        p->strokePath(textStrokePath, textStrokePen);

    if (ctx->textDrawingMode() & TextModeFill) {
        QPen previousPen = p->pen();
        p->setPen(textFillPen);
        p->drawText(pt, string, flags, run.expansion());
        p->setPen(previousPen);
    }
}
Exemplo n.º 16
0
void K3b::FillStatusDisplayWidget::paintEvent( QPaintEvent* )
{
    QPainter p( this );

    const QPalette::ColorGroup colorGroup = isEnabled() ? QPalette::Normal : QPalette::Disabled;

    const Msf docSize = d->doc->length();
    const Msf cdSize = d->cdSize;
    const Msf maxValue = (cdSize > docSize ? cdSize : docSize) + ( 10*60*75 );
    const Msf tolerance = 60*75;

    QBrush fillBrush;
    if( docSize <= cdSize - tolerance ) {
        fillBrush = KColorScheme( colorGroup, KColorScheme::Selection ).background( KColorScheme::PositiveBackground );
    }
    else if( docSize > cdSize + tolerance ) {
        fillBrush = KColorScheme( colorGroup, KColorScheme::Selection ).background( KColorScheme::NegativeBackground );
    }
    else {
        fillBrush = KColorScheme( colorGroup, KColorScheme::Selection ).background( KColorScheme::NeutralBackground );
    }

    const QPen normalPen = KColorScheme( colorGroup, KColorScheme::Window ).foreground( KColorScheme::NormalText ).color();
    const QPen fillPen = KColorScheme( colorGroup, KColorScheme::Selection ).foreground( KColorScheme::NormalText ).color();

    QStyleOptionProgressBarV2 sopb;
    sopb.direction = layoutDirection();
    sopb.fontMetrics = fontMetrics();
    sopb.palette = palette();
    sopb.palette.setBrush( QPalette::Highlight, fillBrush );
    sopb.rect = rect();
    sopb.state = isEnabled() ? QStyle::State_Enabled : QStyle::State_None;
    sopb.minimum = 0;
    sopb.maximum = maxValue.totalFrames();
    sopb.progress = docSize.totalFrames();
    style()->drawControl( QStyle::CE_ProgressBar, &sopb, &p );

    const QRect barRect = style()->subElementRect( QStyle::SE_ProgressBarContents, &sopb );

    // so split width() in maxValue pieces
    double one = (double)barRect.width() / (double)maxValue.totalFrames();

    QRect crect( barRect );
    crect.setWidth( (int)(one*(double)docSize.totalFrames()) );

    // ====================================================================================
    // Now the colored bar is painted
    // Continue with the texts
    // ====================================================================================

    // first we determine the text to display
    // ====================================================================================
    QString docSizeText;
    if( d->showTime )
        docSizeText = i18n("%1 min", d->doc->length().toString(false));
    else
        docSizeText = KIO::convertSize( d->doc->size() );

    QString overSizeText;
    if( d->cdSize.mode1Bytes() >= d->doc->size() )
        overSizeText = i18n("Available: %1 of %2",
                            d->showTime
                            ? i18n("%1 min", (cdSize - d->doc->length()).toString(false) )
                            : KIO::convertSize( (cdSize - d->doc->length()).mode1Bytes() ),
                            d->showTime
                            ? i18n("%1 min", cdSize.toString(false))
                            : KIO::convertSize( cdSize.mode1Bytes() ) );
    else
        overSizeText = i18n("Capacity exceeded by %1",
                            d->showTime
                            ? i18n("%1 min", (d->doc->length() - cdSize ).toString(false))
                            : KIO::convertSize( (long long)d->doc->size() - cdSize.mode1Bytes() ) );
    // ====================================================================================

    // calculate the medium size marker
    // ====================================================================================
    int mediumSizeMarkerPos = barRect.left() + (int)(one*cdSize.lba());
    QPoint mediumSizeMarkerFrom( mediumSizeMarkerPos, barRect.bottom() );
    QPoint mediumSizeMarkerTo( mediumSizeMarkerPos, barRect.top() + barRect.height()/2 );
    // ====================================================================================

    // we want to draw the docSizeText centered in the filled area
    // if there is not enough space we just align it left
    // ====================================================================================
    int docSizeTextPos = 0;
    int docSizeTextLength = fontMetrics().width(docSizeText);
    if( docSizeTextLength + 5 > crect.width() ) {
        docSizeTextPos = crect.left() + 5; // a little margin
    }
    else {
        docSizeTextPos = ( crect.width() - docSizeTextLength ) / 2;

        // make sure the text does not cross the medium size marker
        if( docSizeTextPos <= mediumSizeMarkerPos && mediumSizeMarkerPos <= docSizeTextPos + docSizeTextLength )
            docSizeTextPos = qMax( crect.left() + 5, mediumSizeMarkerPos - docSizeTextLength - 5 );
    }
    // ====================================================================================

    // calculate the over size text
    // ====================================================================================
    QFont overSizeFont(font());
    overSizeFont.setPointSize( qMax( 8, overSizeFont.pointSize()-4 ) );
    overSizeFont.setBold(false);

    QRect overSizeTextRect( barRect );
    int overSizeTextLength = QFontMetrics(overSizeFont).width(overSizeText);
    if( overSizeTextLength + 5 > overSizeTextRect.width() - (int)(one*cdSize.totalFrames()) ) {
        // we don't have enough space on the right, so we paint to the left of the line
        overSizeTextRect.setLeft( (int)(one*cdSize.totalFrames()) - overSizeTextLength - 5 );
    }
    else {
        overSizeTextRect.setLeft( mediumSizeMarkerPos + 5 );
    }

    // make sure the two text do not overlap (this does not cover all cases though)
    if( overSizeTextRect.left() < docSizeTextPos + docSizeTextLength )
        docSizeTextPos = qMax( crect.left() + 5, qMin( overSizeTextRect.left() - docSizeTextLength - 5, mediumSizeMarkerPos - docSizeTextLength - 5 ) );

    QRect docTextRect( barRect );
    docTextRect.setLeft( docSizeTextPos );

    // Draw the fill part
    p.setPen( fillPen );
    p.setClipRect( QStyle::visualRect( layoutDirection(), barRect, crect ) );
    p.drawLine( QStyle::visualPos( layoutDirection(), barRect, mediumSizeMarkerFrom ),
                QStyle::visualPos( layoutDirection(), barRect, mediumSizeMarkerTo ) );
    p.drawText( QStyle::visualRect( layoutDirection(), barRect, docTextRect ),
                QStyle::visualAlignment( layoutDirection(), Qt::AlignLeft | Qt::AlignVCenter ), docSizeText );
    p.setFont(overSizeFont);
    p.drawText( QStyle::visualRect( layoutDirection(), barRect, overSizeTextRect ),
                QStyle::visualAlignment( layoutDirection(), Qt::AlignLeft | Qt::AlignVCenter ), overSizeText );

    // Draw the remain part
    p.setPen( normalPen );
    p.setClipRect( QStyle::visualRect( layoutDirection(), barRect,
                                       QRect( crect.right(), barRect.top(), barRect.width()-crect.width(), barRect.height() ) ) );
    p.drawLine( QStyle::visualPos( layoutDirection(), barRect, mediumSizeMarkerFrom ),
                QStyle::visualPos( layoutDirection(), barRect, mediumSizeMarkerTo ) );
    p.setFont( font() );
    p.drawText( QStyle::visualRect( layoutDirection(), barRect, docTextRect ),
                QStyle::visualAlignment( layoutDirection(), Qt::AlignLeft | Qt::AlignVCenter ), docSizeText );
    p.setFont(overSizeFont);
    p.drawText( QStyle::visualRect( layoutDirection(), barRect, overSizeTextRect ),
                QStyle::visualAlignment( layoutDirection(), Qt::AlignLeft | Qt::AlignVCenter ), overSizeText );
    // ====================================================================================
}
Exemplo n.º 17
0
SequenceDialog::SequenceDialog(QWidget *parent, capture_file *cf, SequenceType type) :
    QDialog(parent),
    ui(new Ui::SequenceDialog),
    cap_file_(cf),
    num_items_(0),
    packet_num_(0),
    node_label_w_(20)
{
    ui->setupUi(this);
    QCustomPlot *sp = ui->sequencePlot;

    seq_diagram_ = new SequenceDiagram(sp->yAxis, sp->xAxis2, sp->yAxis2);
    sp->addPlottable(seq_diagram_);
    sp->axisRect()->setRangeDragAxes(sp->xAxis2, sp->yAxis);

    sp->xAxis->setVisible(false);
    sp->xAxis->setPadding(0);
    sp->xAxis->setLabelPadding(0);
    sp->xAxis->setTickLabelPadding(0);
    sp->xAxis2->setVisible(true);
    sp->yAxis2->setVisible(true);

    one_em_ = QFontMetrics(sp->yAxis->labelFont()).height();
    ui->horizontalScrollBar->setSingleStep(100 / one_em_);
    ui->verticalScrollBar->setSingleStep(100 / one_em_);

    sp->setInteractions(QCP::iRangeDrag);

    ui->gridLayout->setSpacing(0);
    connect(sp->yAxis, SIGNAL(rangeChanged(QCPRange)), sp->yAxis2, SLOT(setRange(QCPRange)));

    ctx_menu_.addAction(ui->actionReset);
    ctx_menu_.addSeparator();
    ctx_menu_.addAction(ui->actionMoveRight10);
    ctx_menu_.addAction(ui->actionMoveLeft10);
    ctx_menu_.addAction(ui->actionMoveUp10);
    ctx_menu_.addAction(ui->actionMoveDown10);
    ctx_menu_.addAction(ui->actionMoveRight1);
    ctx_menu_.addAction(ui->actionMoveLeft1);
    ctx_menu_.addAction(ui->actionMoveUp1);
    ctx_menu_.addAction(ui->actionMoveDown1);
    ctx_menu_.addSeparator();
    ctx_menu_.addAction(ui->actionGoToPacket);

    memset (&seq_analysis_, 0, sizeof(seq_analysis_));

    ui->showComboBox->blockSignals(true);
    ui->showComboBox->setCurrentIndex(0);
    ui->showComboBox->blockSignals(false);
    ui->addressComboBox->blockSignals(true);
    ui->addressComboBox->setCurrentIndex(0);
    ui->addressComboBox->blockSignals(false);

    QComboBox *fcb = ui->flowComboBox;
    fcb->addItem(ui->actionFlowAny->text(), SEQ_ANALYSIS_ANY);
    fcb->addItem(ui->actionFlowTcp->text(), SEQ_ANALYSIS_TCP);

    ui->flowComboBox->blockSignals(true);
    switch (type) {
    case any:
        seq_analysis_.type = SEQ_ANALYSIS_ANY;
        ui->flowComboBox->setCurrentIndex(SEQ_ANALYSIS_ANY);
        break;
    case tcp:
        seq_analysis_.type = SEQ_ANALYSIS_TCP;
        ui->flowComboBox->setCurrentIndex(SEQ_ANALYSIS_TCP);
        break;
    case voip:
        seq_analysis_.type = SEQ_ANALYSIS_VOIP;
        ui->flowComboBox->hide();
        ui->flowLabel->hide();
        break;
    }
    ui->flowComboBox->blockSignals(false);
    seq_analysis_.all_packets = TRUE;

    QPushButton *save_bt = ui->buttonBox->button(QDialogButtonBox::Save);
    save_bt->setText(tr("Save As..."));

    // XXX Use recent settings instead
    if (parent) {
        resize(parent->width(), parent->height() * 4 / 5);
    }

    connect(ui->horizontalScrollBar, SIGNAL(valueChanged(int)), this, SLOT(hScrollBarChanged(int)));
    connect(ui->verticalScrollBar, SIGNAL(valueChanged(int)), this, SLOT(vScrollBarChanged(int)));
    connect(sp->xAxis2, SIGNAL(rangeChanged(QCPRange)), this, SLOT(xAxisChanged(QCPRange)));
    connect(sp->yAxis, SIGNAL(rangeChanged(QCPRange)), this, SLOT(yAxisChanged(QCPRange)));
    connect(sp, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(diagramClicked(QMouseEvent*)));
    connect(sp, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMoved(QMouseEvent*)));
    connect(sp, SIGNAL(mouseRelease(QMouseEvent*)), this, SLOT(mouseReleased(QMouseEvent*)));
    connect(this, SIGNAL(goToPacket(int)), seq_diagram_, SLOT(setSelectedPacket(int)));

    disconnect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));

    fillDiagram();
}
Exemplo n.º 18
0
//! Initialized the syntax highlighter with default values.
void MetaModelicaHighlighter::initializeSettings()
{
  QFont font;
  font.setFamily(mpMetaModelicaEditorPage->getOptionsDialog()->getTextEditorPage()->getFontFamilyComboBox()->currentFont().family());
  font.setPointSizeF(mpMetaModelicaEditorPage->getOptionsDialog()->getTextEditorPage()->getFontSizeSpinBox()->value());
  mpPlainTextEdit->document()->setDefaultFont(font);
  mpPlainTextEdit->setTabStopWidth(mpMetaModelicaEditorPage->getOptionsDialog()->getTextEditorPage()->getTabSizeSpinBox()->value() * QFontMetrics(font).width(QLatin1Char(' ')));
  // set color highlighting
  mHighlightingRules.clear();
  HighlightingRule rule;
  mTextFormat.setForeground(mpMetaModelicaEditorPage->getColor("Text"));
  mKeywordFormat.setForeground(mpMetaModelicaEditorPage->getColor("Keyword"));
  mTypeFormat.setForeground(mpMetaModelicaEditorPage->getColor("Type"));
  mSingleLineCommentFormat.setForeground(mpMetaModelicaEditorPage->getColor("Comment"));
  mMultiLineCommentFormat.setForeground(mpMetaModelicaEditorPage->getColor("Comment"));
  mQuotationFormat.setForeground(mpMetaModelicaEditorPage->getColor("Quotes"));
  // Priority: keyword > func() > ident > number. Yes, the order matters :)
  mNumberFormat.setForeground(mpMetaModelicaEditorPage->getColor("Number"));
  rule.mPattern = QRegExp("[0-9][0-9]*([.][0-9]*)?([eE][+-]?[0-9]*)?");
  rule.mFormat = mNumberFormat;
  mHighlightingRules.append(rule);
  rule.mPattern = QRegExp("\\b[A-Za-z_][A-Za-z0-9_]*");
  rule.mFormat = mTextFormat;
  mHighlightingRules.append(rule);
  // keywords
  QStringList keywordPatterns;
  keywordPatterns << "\\balgorithm\\b"
                  << "\\band\\b"
                  << "\\bannotation\\b"
                  << "\\bassert\\b"
                  << "\\bblock\\b"
                  << "\\bbreak\\b"
                  << "\\bBoolean\\b"
                  << "\\bclass\\b"
                  << "\\bconnect\\b"
                  << "\\bconnector\\b"
                  << "\\bconstant\\b"
                  << "\\bconstrainedby\\b"
                  << "\\bder\\b"
                  << "\\bdiscrete\\b"
                  << "\\beach\\b"
                  << "\\belse\\b"
                  << "\\belseif\\b"
                  << "\\belsewhen\\b"
                  << "\\bencapsulated\\b"
                  << "\\bend\\b"
                  << "\\benumeration\\b"
                  << "\\bequation\\b"
                  << "\\bexpandable\\b"
                  << "\\bextends\\b"
                  << "\\bexternal\\b"
                  << "\\bfalse\\b"
                  << "\\bfinal\\b"
                  << "\\bflow\\b"
                  << "\\bfor\\b"
                  << "\\bfunction\\b"
                  << "\\bif\\b"
                  << "\\bimport\\b"
                  << "\\bimpure\\b"
                  << "\\bin\\b"
                  << "\\binitial\\b"
                  << "\\binner\\b"
                  << "\\binput\\b"
                  << "\\bloop\\b"
                  << "\\bmodel\\b"
                  << "\\bnot\\b"
                  << "\\boperator\\b"
                  << "\\bor\\b"
                  << "\\bouter\\b"
                  << "\\boutput\\b"
                  << "\\boptimization\\b"
                  << "\\bpackage\\b"
                  << "\\bparameter\\b"
                  << "\\bpartial\\b"
                  << "\\bprotected\\b"
                  << "\\bpublic\\b"
                  << "\\bpure\\b"
                  << "\\brecord\\b"
                  << "\\bredeclare\\b"
                  << "\\breplaceable\\b"
                  << "\\breturn\\b"
                  << "\\bstream\\b"
                  << "\\bthen\\b"
                  << "\\btrue\\b"
                  << "\\btype\\b"
                  << "\\bwhen\\b"
                  << "\\bwhile\\b"
                  << "\\bwithin\\b"
                  /* MetaModelica specific keywords */
                  << "\\bas\\b"
                  << "\\bcase\\b"
                  << "\\bcontinue\\b"
                  << "\\bequality\\b"
                  << "\\bfailure\\b"
                  << "\\bguard\\b"
                  << "\\blocal\\b"
                  << "\\bmatch\\b"
                  << "\\bmatchcontinue\\b"
                  << "\\buniontype\\b"
                  << "\\bsubtypeof\\b"
                  << "\\btry\\b"
                  << "\\bparfor\\b"
                  << "\\bparallel\\b"
                  << "\\bparlocal\\b"
                  << "\\bparglobal\\b"
                  << "\\bparkernel\\b"
                  << "\\bthreaded\\b";
  foreach (const QString &pattern, keywordPatterns) {
    rule.mPattern = QRegExp(pattern);
    rule.mFormat = mKeywordFormat;
    mHighlightingRules.append(rule);
  }
Exemplo n.º 19
0
bool SsfCreator::create(const QString& path, int width, int height, QImage& img)
{
    if (!QFile::exists(path))
        return false;

    KSsf ssf(path);
    if (!ssf.open(QIODevice::ReadOnly))
        return false;

    const KArchiveEntry* entry = ssf.directory()->entry("skin.ini");
    const KArchiveFile* skinini = static_cast<const KArchiveFile*>(entry);

    if (!skinini) {
        entry = ssf.directory()->entry("Skin.ini");
        skinini = static_cast<const KArchiveFile*>(entry);
        if (!skinini)
            return false;
    }

    QFont preEditFont;
    QFont candidateFont;
    QColor preEditColor;
    QColor labelColor;
    QColor candidateColor;

    int pt = 0, pb = 0, pl = 0, pr = 0;
    int zt = 0, zb = 0, zl = 0, zr = 0;

    QByteArray data = skinini->data();

    /// parse ini file content
    bool display = false;
    bool scheme_h1 = false;
    QPixmap skin;
    int hstm = 0;
    int sl = 0, sr = 0;
    int fontPixelSize = 12;
    QString font_ch, font_en;
    unsigned int color_ch, color_en;
    QHash<QString, OverlayPixmap> overlays;
    int opt = 0, opb = 0, opl = 0, opr = 0;
    QColor separatorColor = Qt::transparent;
    int sepl = 0, sepr = 0;

    QTextStream ss(data);
    QString line;
    QString key, value;
    do {
        line = ss.readLine();
        if (line.isEmpty())
            continue;

        if (line.at(0) == '[') {
            display = (line == "[Display]");
            scheme_h1 = (line == "[Scheme_H1]");
            continue;
        }

        if (!line.contains('='))
            continue;

        key = line.split('=').at(0);
        value = line.split('=').at(1);

        if (value.isEmpty())
            continue;

        if (display) {
            if (key == "font_size")
                fontPixelSize = value.trimmed().toInt();
            else if (key == "font_ch")
                font_ch = value;
            else if (key == "font_en")
                font_en = value;
            else if (key == "pinyin_color")
                color_en = value.toUInt(0, 0);
            else if (key == "zhongwen_color")
                color_ch = value.toUInt(0, 0);
        }
        else if (scheme_h1) {
            if (key == "pic") {
                const KArchiveEntry* e = ssf.directory()->entry(value);
                const KArchiveFile* pix = static_cast<const KArchiveFile*>(e);
                if (pix)
                    skin.loadFromData(pix->data());
            }
            else if (key == "layout_horizontal") {
                QStringList list = value.split(',');
                hstm = list.at(0).trimmed().toInt();
                sl = list.at(1).trimmed().toInt();
                sr = list.at(2).trimmed().toInt();
            }
            else if (key == "separator") {
                QStringList list = value.split(',');
                QString sep_color = list.at(0).trimmed();
                separatorColor = sep_color.leftJustified(8, '0').replace("0x", "#");
                sepl = list.at(1).trimmed().toInt();
                sepr = list.at(2).trimmed().toInt();
            }
            else if (key == "pinyin_marge") {
                QStringList list = value.split(',');
                pt = list.at(0).trimmed().toInt();
                pb = list.at(1).trimmed().toInt();
                pl = list.at(2).trimmed().toInt();
                pr = list.at(3).trimmed().toInt();
            }
            else if (key == "zhongwen_marge") {
                QStringList list = value.split(',');
                zt = list.at(0).trimmed().toInt();
                zb = list.at(1).trimmed().toInt();
                zl = list.at(2).trimmed().toInt();
                zr = list.at(3).trimmed().toInt();
            }
            else if (key.endsWith("_display")) {
                QString name = key.left(key.length() - 8);
                overlays.insert(name, OverlayPixmap());
            }
            else if (key.endsWith("_align")) {
                QString name = key.left(key.length() - 6);
                QStringList numbers = value.split(',');
                OverlayPixmap& op = overlays[ name ];
                op.mt = numbers.at(0).toInt();
                op.mb = numbers.at(1).toInt();
                op.ml = numbers.at(2).toInt();
                op.mr = numbers.at(3).toInt();
                op.alignVMode = numbers.at(4).toInt() + numbers.at(5).toInt();    /// FIXME: right or wrong?
                op.alignHMode = numbers.at(6).toInt() + numbers.at(7).toInt();    /// FIXME: right or wrong?
                op.alignArea = numbers.at(8).toInt();
                op.alignTarget = numbers.at(9).toInt();
            }
            else if (overlays.contains(key)) {
                const KArchiveEntry* e = ssf.directory()->entry(value);
                const KArchiveFile* pix = static_cast<const KArchiveFile*>(e);
                if (pix)
                    overlays[ key ].pixmap.loadFromData(pix->data());
            }
        }
    }
    while (!line.isNull());

    /// calculate overlay pixmap surrounding
    QHash<QString, OverlayPixmap>::ConstIterator it = overlays.constBegin();
    QHash<QString, OverlayPixmap>::ConstIterator end = overlays.constEnd();
    while (it != end) {
        const OverlayPixmap& op = it.value();
        switch (op.alignArea) {
            case 1:
                opl = qMax(opl, op.pixmap.width());
                opt = qMax(opt, op.pixmap.height());
                break;
            case 2:
                opt = qMax(opt, op.pixmap.height());
                break;
            case 3:
                opr = qMax(opr, op.pixmap.width());
                opt = qMax(opt, op.pixmap.height());
                break;
            case 4:
                opl = qMax(opl, op.pixmap.width());
                break;
            case 5:
                /// center pixmap, no addition
                break;
            case 6:
                opr = qMax(opr, op.pixmap.width());
                break;
            case 7:
                opl = qMax(opl, op.pixmap.width());
                opb = qMax(opb, op.pixmap.height());
                break;
            case 8:
                opb = qMax(opb, op.pixmap.height());
                break;
            case 9:
                opr = qMax(opr, op.pixmap.width());
                opb = qMax(opb, op.pixmap.height());
                break;
            default:
                /// never arrive here
                break;
        }
        ++it;
    }

    preEditFont.setFamily(font_en);
    preEditFont.setPixelSize(fontPixelSize);
    candidateFont.setFamily(font_ch);
    candidateFont.setPixelSize(fontPixelSize);

    /// swap from bgr to rgb
    preEditColor = QColor(qBlue(color_en), qGreen(color_en), qRed(color_en));
    candidateColor = QColor(qBlue(color_ch), qGreen(color_ch), qRed(color_ch));
    labelColor = candidateColor;

    int pinyinh = QFontMetrics(preEditFont).height();
    int zhongwenh = QFontMetrics(candidateFont).height();
    int pinyinw = QFontMetrics(preEditFont).width("ABC pinyin");
    int zhongwenw = QFontMetrics(candidateFont).width("1candidate");

    /// save target size
    int targetHeight = height;
    int targetWidth = width;

    height = qMax(pt + pinyinh + pb + zt + zhongwenh + zb + opt + opb, skin.height());
    width = qMax(pl + pinyinw + pr, zl + zhongwenw + zr);
    width = qMax(width + opl + opr, targetWidth);
    width = qMax(width, skin.width());

    QPixmap pixmap(width, height);
    pixmap.fill(Qt::transparent);

    QPainter p(&pixmap);

    /// left right
    p.drawPixmap(0, 0, sl, height, skin, 0, 0, sl, skin.height());
    p.drawPixmap(width - sr, 0, sr, height, skin, skin.width() - sr, 0, sr, skin.height());

    /// middle
    QPixmap middlepix = skin.copy(sl, 0, skin.width() - sl - sr, skin.height());
    if (hstm == 0)
        p.drawPixmap(sl, 0, middlepix.scaled(width - sl - sr, height));
    else
        p.drawTiledPixmap(sl, 0, width - sl - sr, height, middlepix.scaled(middlepix.width(), height));

    /// draw overlay pixmap
    it = overlays.constBegin();
    end = overlays.constEnd();
    while (it != end) {
        const OverlayPixmap& op = it.value();
        p.save();
        switch (op.alignArea) {
            case 1:
                p.translate(op.ml, op.mt);
                break;
            case 2:
                if (op.alignHMode == 0) {
                    p.translate((width + opl - opr - op.pixmap.width()) / 2, 0);
                    p.translate(op.ml / 2, op.mt);
                }
                else if (op.alignHMode == 1) {
                    p.translate(opl, 0);
                    p.translate(op.ml, op.mt);
                }
                else if (op.alignHMode == 2) {
                    p.translate(width - opr - op.pixmap.width(), 0);
                    p.translate(-op.mr, op.mt);
                }
                break;
            case 3:
                p.translate(width - opr, 0);
                p.translate(-op.mr, op.mt);
                break;
            case 4:
                if (op.alignVMode == 0) {
                    p.translate(0, (height - opb + opt - op.pixmap.height()) / 2);
                    p.translate(op.ml, op.mt / 2);
                }
                else if (op.alignVMode == 1) {
                    p.translate(0, opt);
                    p.translate(op.ml, op.mt);
                }
                else if (op.alignVMode == 2) {
                    p.translate(0, height - opb - op.pixmap.height());
                    p.translate(op.ml, -op.mb);
                }
                break;
            case 5:
                if (op.alignHMode == 0) {
                    p.translate((width + opl - opr - op.pixmap.width()) / 2, 0);
                    p.translate(op.ml / 2, 0);
                }
                else if (op.alignHMode == 1) {
                    p.translate(opl, 0);
                    p.translate(op.ml, 0);
                }
                else if (op.alignHMode == 2) {
                    p.translate(width - opr - op.pixmap.width(), 0);
                    p.translate(-op.mr, 0);
                }
                if (op.alignVMode == 0) {
                    p.translate(0, (height - opb + opt - op.pixmap.height()) / 2);
                    p.translate(0, op.mt / 2);
                }
                else if (op.alignVMode == 1) {
                    p.translate(0, opt);
                    p.translate(0, op.mt);
                }
                else if (op.alignVMode == 2) {
                    p.translate(0, height - opb - op.pixmap.height());
                    p.translate(0, -op.mb);
                }
                break;
            case 6:
                if (op.alignVMode == 0) {
                    p.translate(width - opr, (height - opb + opt - op.pixmap.height()) / 2);
                    p.translate(-op.mr, op.mt / 2);
                }
                else if (op.alignVMode == 1) {
                    p.translate(width - opr, opt);
                    p.translate(-op.mr, op.mt);
                }
                else if (op.alignVMode == 2) {
                    p.translate(width - opr, height - opb - op.pixmap.height());
                    p.translate(-op.mr, -op.mb);
                }
                break;
            case 7:
                p.translate(0, height - opb);
                p.translate(op.ml, -op.mb);
                break;
            case 8:
                if (op.alignHMode == 0) {
                    p.translate((width + opl - opr - op.pixmap.width()) / 2, height - opb);
                    p.translate(op.ml / 2, -op.mb);
                }
                else if (op.alignHMode == 1) {
                    p.translate(opl, height - opb);
                    p.translate(op.ml, -op.mb);
                }
                else if (op.alignHMode == 2) {
                    p.translate(width - opr - op.pixmap.width(), height - opb);
                    p.translate(-op.mr, -op.mb);
                }
                break;
            case 9:
                p.translate(width - opr, height - opb);
                p.translate(-op.mr, -op.mb);
                break;
            default:
                /// never arrive here
                break;
        }
        p.drawPixmap(0, 0, op.pixmap);
        p.restore();
        ++it;
    }

    if (separatorColor != Qt::transparent) {
        /// draw separator
        int sepy = opt + pt + pinyinh + pb;
        p.drawLine(opl + sepl, sepy, width - opr - sepr, sepy);
    }

    p.translate(opl, opt);
    int y = 0;

    /// draw preedit / aux text
    p.save();
    p.setFont(preEditFont);
    p.setPen(preEditColor);
    y += pt;
    p.drawText(pl, pt, width - pl - pr, pinyinh, Qt::AlignLeft, "ABC pinyin");
    int pixelsWide = QFontMetrics(preEditFont).width("ABC pinyin");
    p.drawLine(pl + pixelsWide, pt, pl + pixelsWide, pt + pinyinh);
    y += pinyinh + pb;
    p.restore();

    /// draw lookup table
    p.save();
    int x = zl;
    y += zt;
    int w = 0;
    p.setFont(candidateFont);
    /// draw label
    p.setPen(labelColor);
    w = p.fontMetrics().width("1");
    p.drawText(x, y, w, zhongwenh, Qt::AlignCenter, "1");
    x += w;
    /// draw candidate
    p.setPen(candidateColor);
    w = p.fontMetrics().width("candidate");
    p.drawText(x, y, w, zhongwenh, Qt::AlignCenter, "candidate");
    x += w;
    p.restore();

    p.end();

    if (targetWidth < width || targetHeight < height) {
        pixmap = pixmap.scaled(targetWidth, targetHeight, Qt::KeepAspectRatio);
    }

    img = pixmap.toImage();

    return true;
}
Exemplo n.º 20
0
BasepointPixmap OverlayTextLine::createPixmap(unsigned int maxwidth, unsigned int height, QColor col) {
	float twice_edge = 2.0f * fEdge;

	if (! height || ! maxwidth)
		return BasepointPixmap();

	if (qpp.isEmpty() || iCurWidth > static_cast<int>(maxwidth) || iCurHeight != static_cast<int>(height) || (static_cast<int>(maxwidth) > iCurWidth && bElided)) {
		QFont f = qfFont;
		QFontMetrics fm(f);

		// fit the font into a bounding box with padding
		float ps = static_cast<float>(f.pointSizeF());
		float f_ad = static_cast<float>(fm.ascent() + fm.descent()+1) / ps;

		float pointsize = static_cast<float>(height) / (f_ad + 2.0f*fEdgeFactor);

		if (fEdgeFactor * ps > 1.0f) {
			pointsize = static_cast<float>(height-2) / f_ad;
		}

		if (pointsize <= 0.0f) {
			return BasepointPixmap();
		}

		f.setPointSizeF(pointsize);
		setFont(f);
		fm = QFontMetrics(f);
		twice_edge = 2.0f * fEdge;

		if (!qpp.isEmpty()) {
			qpp = QPainterPath();
		}

		// calculate text metrics for eliding and scaling
		QRectF bb;
		qpp.addText(0.0f, 0.0f, f, qsText);
		bb = qpp.controlPointRect();

		qreal effective_ascent = -bb.top();
		qreal effective_descent = bb.bottom();
		float scale = 1.0f;
		bool keep_baseline = true;
		if (effective_descent > fDescent || effective_ascent > fAscent) {
			qreal scale_ascent = effective_ascent > 0.0f ? fAscent / effective_ascent : 1.0f;
			qreal scale_descent = effective_descent > 0.0f ? fDescent / effective_descent : 1.0f;
			scale = static_cast<float>(qMin(scale_ascent, scale_descent));

			if (scale < fBaseliningThreshold) {
				float text_height = static_cast<float>(bb.height()) + twice_edge;
				scale = static_cast<float>(height) / text_height;
				keep_baseline = false;
			}

			qWarning() << QString(QLatin1String("Text \"%1\" did not fit (+%2/-%3): (+%4/-%5). Scaling to %6.")).arg(qsText).arg(fAscent).arg(fDescent).arg(effective_ascent).arg(effective_descent).arg(scale);
		}

		// eliding by previously calculated width
		if ((bb.width()*scale) + twice_edge > maxwidth) {
			int eliding_width = iroundf((static_cast<float>(maxwidth) / scale) - twice_edge + 0.5f);
			QString str = fm.elidedText(qsText, Qt::ElideRight, eliding_width);

			// use ellipsis as shortest possible string
			if (str.trimmed().isEmpty()) {
				str = QString(QChar(0x2026));
			}

			qpp = QPainterPath();
			qpp.addText(0.0f, 0.0f, f, str);
			bb = qpp.controlPointRect();
			bElided = true;
		} else {
			bElided = false;
		}

		// translation to "pixmap space":
		QMatrix correction;
		//  * adjust left edge
		correction.translate(-bb.x() + fEdge, 0.0f);
		//  * scale overly high text (still on baseline)
		correction.scale(scale, scale);

		if (keep_baseline) {
			//  * translate down to baseline
			correction.translate(0.0f, (fAscent + fEdge) / scale);
		} else {
			//  * translate into bounding box
			correction.translate(0.0f, -bb.top() + fEdge);
		}

		qpp = correction.map(qpp);
		iCurWidth = iroundf(bb.width() * scale + 0.5f);
		iCurHeight = height;
	}

	QRectF qr = qpp.controlPointRect();

	return render(
	           iroundf(qr.width() + twice_edge + 0.5f),
	           iroundf(fAscent + fDescent + twice_edge + 0.5f),
	           col,
	           QPoint(0, iroundf(fAscent + fEdge + 0.5f))
	       );
}
Exemplo n.º 21
0
/*!
 * This function returns the height items in our list should have. This is
 * generally the larger of our icon size and our font size, plus the spacing
 * our items have around them.
 *
 * \return The height of a list item.
 */
int CSIconListWidget::getItemHeight() const
{
	return qMax(iconSize().height(), QFontMetrics(font()).lineSpacing()) +
		(spacing() * 2);
}
Exemplo n.º 22
0
void RCharacterWidget::updateFont(const QFont &font) {
    displayFont.setFamily(font.family());
    squareSize = qMax(24, QFontMetrics(displayFont).xHeight() * 3);
    adjustSize();
    update();
}
Exemplo n.º 23
0
void clsImprimirVehiculos::ImprimirFicha(const clsVehiculos *Vehi)
{
    printer = new QPrinter(QPrinter::PrinterResolution);
    printer->setPageSize(QPrinter::A4);

    QPrintDialog printDialog(printer);
    if (printDialog.exec())
    {
        printer->setPageMargins(20,20,15,20,QPrinter::Millimeter);

        QPainter painter(printer);
        painter.setRenderHint(QPainter::Antialiasing);
        QList<QStringList> pages;

        yLinea = 0;
        penInicial = painter.pen();
        brushInicial = painter.brush();
        fuenteInicial = painter.font();
        fuenteTitulo = painter.font();
        fuenteMedTitulo = painter.font();
        fuenteNegrita = painter.font();
        fuenteTitulo.setPointSize(20);
        fuenteNegrita.setBold(true);
        fuenteTitulo.setBold(true);
        fuenteMedTitulo.setBold(true);
        fuenteMedTitulo.setPointSize(15);
        fuenteNegrita.setPointSize(10);
        fuenteInicial.setPointSize(10);

        imagen = new QImage(Vehi->Imagen());
        imagen->scaledToHeight((maxAlt*65)/257,Qt::SmoothTransformation);

        QStringList listaEntradas;
        QString entrada;

        clsCentros Centro;
        Centro.Cargar(Vehi->Centro());

        entrada = "Vehi-|-" + Vehi->Matricula();
        entrada += "-|-" + Vehi->Marca();
        entrada += "-|-" + Vehi->Modelo();
        entrada += "-|-" + Centro.Nombre() + " - " + Centro.Ciudad();
        entrada += "-|-" + Vehi->FechaMatriculacion().toString(QObject::tr("dd/MM/yyyy"));
        entrada += "-|-" + Vehi->FechaITV().toString(QObject::tr("dd/MM/yyyy"));

        listaEntradas << entrada;

        for(int i = 0;i<Vehi->Movimientos().size();i++)
        {
            clsVehiculo_Movs Vehi_Mov(Vehi->Movimientos().at(i));
            Centro.Cargar(Vehi_Mov.Centro());

            entrada = "Mov-|-" + Vehi_Mov.FechaMovimiento().toString(QObject::tr("dd/MM/yyyy")) + "-|-" + Centro.Nombre() + " - " + Centro.Ciudad() + "-|-" + QString::number(Vehi_Mov.KmsFinales());

            listaEntradas << entrada;
        }

        maxAlt = painter.window().height();
        maxAnch = painter.window().width();
        Espacio = (maxAlt*3)/257;
        EspacioCorto = maxAlt/257;

        titulo = QObject::tr("Ficha de Vehículo");

        rectTitulo = QRect(0,0,maxAnch,(maxAlt*15)/257);
        rectFecha = QRect(0,0,maxAnch,(maxAlt*5)/257);
        rectPie = QRect(0,0,maxAnch,(maxAlt*5)/257);
        rectCabecera = QRect(0,0,maxAnch,QFontMetrics(painter.font()).height()+EspacioCorto);
        rectImagen = QRect(maxAnch - ((maxAnch*50)/175),Espacio + rectTitulo.height() + rectFecha.height(),(maxAnch*50)/175,(maxAlt*65)/257);

        painter.setFont(fuenteNegrita);

        AnchoCol1 = qMax(QFontMetrics(painter.font()).width(QObject::tr("Matrícula")),QFontMetrics(painter.font()).width(QObject::tr("Matriculación")))+EspacioCorto;

        AnchoCol2 = maxAnch - rectImagen.width() - Espacio - AnchoCol1 - EspacioCorto;

        rectfuenteNegrita = QRect(0,0,maxAnch,QFontMetrics(painter.font()).height()+EspacioCorto);

        painter.setFont(fuenteInicial);

        rectfuenteInicial = QRect(0,0,maxAnch,QFontMetrics(painter.font()).height()+EspacioCorto);

        maxAltDispo = maxAlt - (rectTitulo.height()+rectFecha.height()+rectPie.height() + Espacio);

        colorLinea = 0;

        DividirEnPaginasFV(&painter,&pages,listaEntradas);
        ImprimirPaginasFV(&painter,pages);
    }
}
Exemplo n.º 24
0
void RCharacterWidget::updateSize(const QString &fontSize) {
    displayFont.setPointSize(fontSize.toInt());
    squareSize = qMax(24, QFontMetrics(displayFont).xHeight() * 3);
    adjustSize();
    update();
}
Exemplo n.º 25
0
void clsImprimirVehiculos::ImprimirLineaFVM(QPainter *painter, const QString &cadena)
{
    QStringList campos = cadena.split("-|-");

    int AnchoObjeto = 0;

    if(colorLinea == 0)
        ImprimirCabeceraFVM(painter);

    QPen penInicial = painter->pen();

    painter->setFont(fuenteNegrita);

    int AnchoFMov = QFontMetrics(painter->font()).width(QObject::tr("Fecha Movimiento"));
    int AnchoKMFinales = QFontMetrics(painter->font()).width(QObject::tr("Kms Finales"));
    int AnchoCent = maxAnch - AnchoFMov - AnchoKMFinales - 2*Espacio;

    painter->setFont(fuenteInicial);

    if(colorLinea%2!=0)
    {
        painter->setPen(Qt::lightGray);
        painter->setBrush(Qt::lightGray);
        painter->drawRect(0,
                          yLinea,
                          maxAnch,
                          rectfuenteNegrita.height());
    }
    painter->setPen(penInicial);

    AnchoObjeto = 0;

    painter->drawText(AnchoObjeto,
                      yLinea,
                      AnchoFMov,
                      rectfuenteNegrita.height(),
                      Qt::AlignLeft|Qt::AlignVCenter,
                      campos[1]);

    AnchoObjeto += AnchoFMov+Espacio;

    painter->drawText(AnchoObjeto,
                      yLinea,
                      AnchoCent,
                      rectfuenteNegrita.height(),
                      Qt::AlignLeft|Qt::AlignVCenter|Qt::TextWordWrap,
                      campos[2]);

    AnchoObjeto += AnchoCent+Espacio;

    painter->drawText(AnchoObjeto,
                      yLinea,
                      AnchoKMFinales,
                      rectfuenteNegrita.height(),
                      Qt::AlignLeft|Qt::AlignVCenter|Qt::TextWordWrap,
                      campos[3]);

    colorLinea++;

    yLinea += rectfuenteNegrita.height();
}
Exemplo n.º 26
0
//! [3]
void Window::setupShapes()
{
    QPainterPath truck;
//! [3]
    truck.setFillRule(Qt::WindingFill);
    truck.moveTo(0.0, 87.0);
    truck.lineTo(0.0, 60.0);
    truck.lineTo(10.0, 60.0);
    truck.lineTo(35.0, 35.0);
    truck.lineTo(100.0, 35.0);
    truck.lineTo(100.0, 87.0);
    truck.lineTo(0.0, 87.0);
    truck.moveTo(17.0, 60.0);
    truck.lineTo(55.0, 60.0);
    truck.lineTo(55.0, 40.0);
    truck.lineTo(37.0, 40.0);
    truck.lineTo(17.0, 60.0);
    truck.addEllipse(17.0, 75.0, 25.0, 25.0);
    truck.addEllipse(63.0, 75.0, 25.0, 25.0);

//! [4]
    QPainterPath clock;
//! [4]
    clock.addEllipse(-50.0, -50.0, 100.0, 100.0);
    clock.addEllipse(-48.0, -48.0, 96.0, 96.0);
    clock.moveTo(0.0, 0.0);
    clock.lineTo(-2.0, -2.0);
    clock.lineTo(0.0, -42.0);
    clock.lineTo(2.0, -2.0);
    clock.lineTo(0.0, 0.0);
    clock.moveTo(0.0, 0.0);
    clock.lineTo(2.732, -0.732);
    clock.lineTo(24.495, 14.142);
    clock.lineTo(0.732, 2.732);
    clock.lineTo(0.0, 0.0);

//! [5]
    QPainterPath house;
//! [5]
    house.moveTo(-45.0, -20.0);
    house.lineTo(0.0, -45.0);
    house.lineTo(45.0, -20.0);
    house.lineTo(45.0, 45.0);
    house.lineTo(-45.0, 45.0);
    house.lineTo(-45.0, -20.0);
    house.addRect(15.0, 5.0, 20.0, 35.0);
    house.addRect(-35.0, -15.0, 25.0, 25.0);

//! [6]
    QPainterPath text;
//! [6]
    QFont font;
    font.setPixelSize(50);
    QRect fontBoundingRect = QFontMetrics(font).boundingRect(tr("Qt"));
    text.addText(-QPointF(fontBoundingRect.center()), font, tr("Qt"));

//! [7]
    shapes.append(clock);
    shapes.append(house);
    shapes.append(text);
    shapes.append(truck);

    connect(shapeComboBox, SIGNAL(activated(int)),
            this, SLOT(shapeSelected(int)));
}
Exemplo n.º 27
0
static void create_pixmaps()
{
    if(pixmaps_created)
        return;
    pixmaps_created = true;

    titleHeight = QFontMetrics(options()->font(true)).height();
    if (titleHeight < handleSize) titleHeight = handleSize;
    titleHeight &= ~1; // Make title height even
    if (titleHeight < 14) titleHeight = 14;

    btnWidth1 = titleHeight + 3;
    btnWidth2 = 3*titleHeight/2 + 6;

    // titlebar
    QPainter p;
    QPainter maskPainter;
    int i, x, y;
    titlePix = new QPixmap(33, 12);
    titlePix->fill( Qt::transparent );
    QBitmap mask(33, 12);
    mask.fill(Qt::color0);

    p.begin(titlePix);
    maskPainter.begin(&mask);
    maskPainter.setPen(Qt::color1);
    for(i=0, y=2; i < 3; ++i, y+=4){
        for(x=1; x <= 33; x+=3){
            p.setPen(options()->color(KDecoration::ColorTitleBar, true).light(150));
            p.drawPoint(x, y);
            maskPainter.drawPoint(x, y);
            p.setPen(options()->color(KDecoration::ColorTitleBar, true).dark(150));
            p.drawPoint(x+1, y+1);
            maskPainter.drawPoint(x+1, y+1);
        }
    }
    p.end();
    maskPainter.end();
    titlePix->setMask(mask);

    if(QPixmap::defaultDepth() > 8){
        aUpperGradient = new QPixmap(32, titleHeight+2);
        iUpperGradient = new QPixmap(32, titleHeight+2);
        QColor bgColor = options()->color(KDecoration::ColorTitleBar, true);
	gradientFill(aUpperGradient, bgColor.light(120), bgColor.dark(120));
        bgColor = options()->color(KDecoration::ColorTitleBar, false);
	gradientFill(iUpperGradient, bgColor.light(120), bgColor.dark(120));
    }
    // buttons (active/inactive, sunken/unsunken, 2 sizes each)
    QPalette g = options()->palette(KDecoration::ColorButtonBg, true);
    g.setCurrentColorGroup( QPalette::Active );
    QColor c = g.color( QPalette::Background );
    btnPix1 = new QPixmap(btnWidth1, titleHeight);
    btnDownPix1 = new QPixmap(btnWidth1, titleHeight);
    btnPix2 = new QPixmap(btnWidth2, titleHeight);
    btnDownPix2 = new QPixmap(btnWidth2, titleHeight);
    iBtnPix1 = new QPixmap(btnWidth1, titleHeight);
    iBtnDownPix1 = new QPixmap(btnWidth1, titleHeight);
    iBtnPix2 = new QPixmap(btnWidth2, titleHeight);
    iBtnDownPix2 = new QPixmap(btnWidth2, titleHeight);
    if(QPixmap::defaultDepth() > 8){
        gradientFill(btnPix1, c.light(120), c.dark(130), true);
        gradientFill(btnPix2, c.light(120), c.dark(130), true);
        gradientFill(btnDownPix1, c.light(120), c.dark(130), true);
        gradientFill(btnDownPix2, c.light(120), c.dark(130), true);
        g = options()->palette(KDecoration::ColorButtonBg, false);
        g.setCurrentColorGroup( QPalette::Active );
        c = g.color(QPalette::Background);
        gradientFill(iBtnPix1, c.light(120), c.dark(130), true);
        gradientFill(iBtnPix2, c.light(120), c.dark(130), true);
        gradientFill(iBtnDownPix1, c.light(120), c.dark(130), true);
        gradientFill(iBtnDownPix2, c.light(120), c.dark(130), true);
    }
    else{
        btnPix1->fill(c.rgb());
        btnDownPix1->fill(c.rgb());
        btnPix2->fill(c.rgb());
        btnDownPix2->fill(c.rgb());
        g = options()->palette(KDecoration::ColorButtonBg, false);
        g.setCurrentColorGroup( QPalette::Active );
        c = g.background().color();
        iBtnPix1->fill(c.rgb());
        iBtnDownPix1->fill(c.rgb());
        iBtnPix2->fill(c.rgb());
        iBtnDownPix2->fill(c.rgb());
    }
    g = options()->palette(KDecoration::ColorButtonBg, true);
    g.setCurrentColorGroup( QPalette::Active );
    c = g.background().color();
    drawButtonFrame(btnPix1, g, false);
    drawButtonFrame(btnDownPix1, g, true);
    drawButtonFrame(btnPix2, g, false);
    drawButtonFrame(btnDownPix2, g, true);
    g = options()->palette(KDecoration::ColorButtonBg, false);
    g.setCurrentColorGroup( QPalette::Active );
    c = g.background().color();
    drawButtonFrame(iBtnPix1, g, false);
    drawButtonFrame(iBtnDownPix1, g, true);
    drawButtonFrame(iBtnPix2, g, false);
    drawButtonFrame(iBtnDownPix2, g, true);

    if(qGray(options()->color(KDecoration::ColorButtonBg, true).rgb()) > 128)
        btnForeground = Qt::black;
    else
        btnForeground = Qt::white;
}
Exemplo n.º 28
0
void MyLcdDisplay::readStack() {
    bool stateOk = systemEngine->checkState();

    int visibleWidth = viewport()->size().width();

    if (!lcdPixmap) {
        lcdPixmap = new QPixmap(visibleWidth-3,pmHeight);
    }
    lcdPixmap->fill(Qt::transparent);

    if ( lcdPainter )
       delete lcdPainter;
    lcdPainter = new QPainter();

    lcdPainter->begin(lcdPixmap);
    lcdPainter->setPen(QApplication::palette().color(QPalette::Text));

    verticalOffset=0; // top margin
    int horizontalOffset = 10; // right margin
    if (!stateOk) {
        QRect r = QFontMetrics(QApplication::font()).boundingRect( 5, 5,
                visibleWidth-horizontalOffset, 80, 
                layoutDirection() == Qt::LeftToRight ? Qt::AlignRight : Qt::AlignLeft, 
                systemEngine->errorString);
        //the alignment below doesn't really matter. r already defines what is necessary
        lcdPainter->drawText( r, Qt::AlignRight, systemEngine->errorString );
        verticalOffset=25;
    } else {
        if (Qtopia::mousePreferred()) {
            QPixmap *tmp;
            if (systemEngine->dStack.isEmpty())
                return;
            int myoffset = 10;
            tmp = systemEngine->dStack.top()->draw();

            int drawPoint = qMax(visibleWidth - tmp->width(),0);
            int srcStart = qMax(tmp->width() - visibleWidth,0);

            lcdPainter->drawPixmap(drawPoint - myoffset,verticalOffset,*tmp,srcStart, 0, -1, -1);
            verticalOffset += tmp->height();
        }
        else {
            niStack = new QStack<QString*>();
            ndStack = new QStack<Data*>();
            while (!systemEngine->iStack.isEmpty())
                niStack->push(systemEngine->iStack.pop());
            while (!systemEngine->dStack.isEmpty())
                ndStack->push(systemEngine->dStack.pop());
            dataLeft = 1;
            while (!niStack->isEmpty() || !ndStack->isEmpty()) {
                horizontalOffset = 10;
                horizontalOffset = drawNextItem(horizontalOffset,true, visibleWidth);
            }

            delete niStack;
            delete ndStack;
        }
    }
    lcdPainter->end();

    QWidget *w = viewport();
    //w->resize(visibleWidth, verticalOffset);
    //w->update(0, 0, visibleWidth, verticalOffset);
    w->update();
}
Exemplo n.º 29
0
CpuPlot::CpuPlot(QWidget *parent):
    QwtPlot(parent),
    dataCount(0)
{
    setAutoReplot(false);

    plotLayout()->setAlignCanvasToScales(true);

    QwtLegend *legend = new QwtLegend;
    legend->setItemMode(QwtLegend::CheckableItem);
    insertLegend(legend, QwtPlot::RightLegend);

    setAxisTitle(QwtPlot::xBottom, " System Uptime [h:m:s]");
    setAxisScaleDraw(QwtPlot::xBottom,
                     new TimeScaleDraw(cpuStat.upTime()));
    setAxisScale(QwtPlot::xBottom, 0, HISTORY);
    setAxisLabelRotation(QwtPlot::xBottom, -50.0);
    setAxisLabelAlignment(QwtPlot::xBottom, Qt::AlignLeft | Qt::AlignBottom);

    /*
     In situations, when there is a label at the most right position of the
     scale, additional space is needed to display the overlapping part
     of the label would be taken by reducing the width of scale and canvas.
     To avoid this "jumping canvas" effect, we add a permanent margin.
     We don't need to do the same for the left border, because there
     is enough space for the overlapping label below the left scale.
     */

    QwtScaleWidget *scaleWidget = axisWidget(QwtPlot::xBottom);
    const int fmh = QFontMetrics(scaleWidget->font()).height();
    scaleWidget->setMinBorderDist(0, fmh / 2);

    setAxisTitle(QwtPlot::yLeft, "Cpu Usage [%]");
    setAxisScale(QwtPlot::yLeft, 0, 100);

    Background *bg = new Background();
    bg->attach(this);

    CpuPieMarker *pie = new CpuPieMarker();
    pie->attach(this);

    CpuCurve *curve;

    curve = new CpuCurve("System");
    curve->setColor(Qt::red);
    curve->attach(this);
    data[System].curve = curve;

    curve = new CpuCurve("User");
    curve->setColor(Qt::blue);
    curve->setZ(curve->z() - 1);
    curve->attach(this);
    data[User].curve = curve;

    curve = new CpuCurve("Total");
    curve->setColor(Qt::black);
    curve->setZ(curve->z() - 2);
    curve->attach(this);
    data[Total].curve = curve;

    curve = new CpuCurve("Idle");
    curve->setColor(Qt::darkCyan);
    curve->setZ(curve->z() - 3);
    curve->attach(this);
    data[Idle].curve = curve;

    showCurve(data[System].curve, true);
    showCurve(data[User].curve, true);
    showCurve(data[Total].curve, false);
    showCurve(data[Idle].curve, false);

    for ( int i = 0; i < HISTORY; i++ )
        timeData[HISTORY - 1 - i] = i;

    (void)startTimer(1000); // 1 second

    connect(this, SIGNAL(legendChecked(QwtPlotItem *, bool)),
            SLOT(showCurve(QwtPlotItem *, bool)));
}
soundKonverterView::soundKonverterView( Logger *_logger, Config *_config, CDManager *_cdManager, QWidget *parent )
    : QWidget( parent ),
      config( _config ),
      logger( _logger ),
      cdManager( _cdManager )
{
    setAcceptDrops( true );

    const int fontHeight = QFontMetrics(QApplication::font()).boundingRect("M").size().height();

    // the grid for all widgets in the main window
    QGridLayout* gridLayout = new QGridLayout( this );

    fileList = new FileList( logger, config, this );
    gridLayout->addWidget( fileList, 1, 0 );
    gridLayout->setRowStretch( 1, 1 );
    connect( fileList, SIGNAL(fileCountChanged(int)), this, SLOT(fileCountChanged(int)) );
    connect( fileList, SIGNAL(conversionStarted()), this, SLOT(conversionStarted()) );
    connect( fileList, SIGNAL(conversionStopped(bool)), this, SLOT(conversionStopped(bool)) );
    connect( fileList, SIGNAL(queueModeChanged(bool)), this, SLOT(queueModeChanged(bool)) );
    connect( fileList, SIGNAL(showLog(int)), this, SIGNAL(showLog(int)) );

    optionsLayer = new OptionsLayer( config, this );
    fileList->setOptionsLayer( optionsLayer );
    optionsLayer->hide();
    gridLayout->addWidget( optionsLayer, 1, 0 );
    connect( optionsLayer, SIGNAL(done(const KUrl::List&,ConversionOptions*,const QString&)), fileList, SLOT(addFiles(const KUrl::List&,ConversionOptions*,const QString&)) );
    connect( optionsLayer, SIGNAL(saveFileList()), fileList, SLOT(save()) );


    // add a horizontal box layout for the add combobutton to the grid
    QHBoxLayout *addBox = new QHBoxLayout();
    addBox->setContentsMargins( 1, 0, 1, 0 ); // extra margin - determined by experiments
    gridLayout->addLayout( addBox, 3, 0 );

    // create the combobutton for adding files to the file list
    cAdd = new ComboButton( this );
    QFont font = cAdd->font();
    //font.setWeight( QFont::DemiBold );
    font.setPointSize( font.pointSize() + 3 );
    cAdd->setFont( font );
    cAdd->insertItem( KIcon("audio-x-generic"), i18n("Add files...") );
    cAdd->insertItem( KIcon("folder"), i18n("Add folder...") );
    cAdd->insertItem( KIcon("media-optical-audio"), i18n("Add CD tracks...") );
    cAdd->insertItem( KIcon("network-workgroup"), i18n("Add url...") );
    cAdd->insertItem( KIcon("view-media-playlist"), i18n("Add playlist...") );
    cAdd->increaseHeight( 0.6*fontHeight );
    addBox->addWidget( cAdd, 0, Qt::AlignVCenter );
    connect( cAdd, SIGNAL(clicked(int)), this, SLOT(addClicked(int)) );
    cAdd->setFocus();

    addBox->addSpacing( fontHeight );

    startAction = new KAction( KIcon("system-run"), i18n("Start"), this );
    connect( startAction, SIGNAL(triggered()), fileList, SLOT(startConversion()) );

    pStart = new KPushButton( KIcon("system-run"), i18n("Start"), this );
    pStart->setFixedHeight( pStart->size().height() );
    pStart->setEnabled( false );
    startAction->setEnabled( false );
    addBox->addWidget( pStart, 0, Qt::AlignVCenter );
    connect( pStart, SIGNAL(clicked()), fileList, SLOT(startConversion()) );

    stopActionMenu = new KActionMenu( KIcon("process-stop"), i18n("Stop"), this );
    stopActionMenu->setDelayed( false );
    killAction = new KAction( KIcon("flag-red"), i18n("Stop immediatelly"), this );
    stopActionMenu->addAction( killAction );
    connect( killAction, SIGNAL(triggered()), fileList, SLOT(killConversion()) );
    stopAction = new KAction( KIcon("flag-yellow"), i18n("Stop after current conversions are completed"), this );
    stopActionMenu->addAction( stopAction );
    connect( stopAction, SIGNAL(triggered()), fileList, SLOT(stopConversion()) );
    continueAction = new KAction( KIcon("flag-green"), i18n("Continue after current conversions are completed"), this );
    stopActionMenu->addAction( continueAction );
    connect( continueAction, SIGNAL(triggered()), fileList, SLOT(continueConversion()) );
    queueModeChanged( true );

    pStop = new KPushButton( KIcon("process-stop"), i18n("Stop"), this );
    pStop->setFixedHeight( pStop->size().height() );
    pStop->hide();
    stopActionMenu->setEnabled( false );
    pStop->setMenu( stopActionMenu->menu() );
    addBox->addWidget( pStop, 0, Qt::AlignVCenter );

    addBox->addSpacing( fontHeight );

    progressIndicator = new ProgressIndicator( this, ProgressIndicator::Feature( ProgressIndicator::FeatureSpeed | ProgressIndicator::FeatureTime ) );
    addBox->addWidget( progressIndicator, 0, Qt::AlignVCenter );
    connect( progressIndicator, SIGNAL(progressChanged(const QString&)), this, SIGNAL(progressChanged(const QString&)) );
    connect( fileList, SIGNAL(timeChanged(float)), progressIndicator, SLOT(timeChanged(float)) );
    connect( fileList, SIGNAL(finished(bool)), progressIndicator, SLOT(finished(bool)) );

    Convert *convert = new Convert( config, fileList, logger, this );
    connect( fileList, SIGNAL(convertItem(FileListItem*)), convert, SLOT(add(FileListItem*)) );
    connect( fileList, SIGNAL(killItem(FileListItem*)), convert, SLOT(kill(FileListItem*)) );
    connect( fileList, SIGNAL(itemRemoved(FileListItem*)), convert, SLOT(itemRemoved(FileListItem*)) );
    connect( convert, SIGNAL(finished(FileListItem*,FileListItem::ReturnCode,bool)), fileList, SLOT(itemFinished(FileListItem*,FileListItem::ReturnCode,bool)) );
    connect( convert, SIGNAL(rippingFinished(const QString&)), fileList, SLOT(rippingFinished(const QString&)) );

    connect( convert, SIGNAL(finishedProcess(int,bool,bool)), logger, SLOT(processCompleted(int,bool,bool)) );

    connect( convert, SIGNAL(updateTime(float)), progressIndicator, SLOT(update(float)) );
    connect( convert, SIGNAL(timeFinished(float)), progressIndicator, SLOT(timeFinished(float)) );
}