Example #1
0
void TopBar::resizeEvent(QGraphicsSceneResizeEvent* /*event*/)
{
    //Check orientation
    QString topbarName;
    QSize mainViewSize = m_mainView->size();
    int rotationAngle = static_cast<MainView*>(m_mainView)->rotationAngle();
    if(rotationAngle == 90 || rotationAngle == 270 ) {
       int wd = mainViewSize.width();
       int ht = mainViewSize.height();
       mainViewSize.setWidth(ht);
       mainViewSize.setHeight(wd);
    }
    bool m_orientationChanged = false;
    if(mainViewSize.height() >= mainViewSize.width()) {
        if(m_orientation == TopBar::Landscape)
            m_orientationChanged = true;
        m_orientation = TopBar::Portrait;
        topbarName = "topbar.svg";
    }
    else {
        if(m_orientation == TopBar::Portrait)
            m_orientationChanged = true;
        m_orientation = TopBar::Landscape;
        topbarName = "topbar_horisontal.svg";
    }

    //Calculate new size, resize by height, don't make it wider than the screen
    QHash<QString, QSize>sizes = (Theme::p()->theme() == Theme::Blue) ?
        m_sizesBlue : m_sizesLime;

    //Get current size for topbarpixmap
    QSize currentSize = !m_topBarPixmap.isNull() && !m_orientationChanged ?
            m_topBarPixmap.size() : sizes[topbarName];
    QSize newSize = !m_orientationChanged ? QSize(currentSize) : sizes[topbarName];

    //Scale according to aspect ratio
    newSize.scale(size().toSize(), Qt::KeepAspectRatio);

    //fix width to window widht if previous scaling produced too narrow image
    if(newSize.width() < size().width()) {
        newSize.scale(size().toSize(), Qt::KeepAspectRatioByExpanding);
    }

    //Calculate scaling factor for rest of the graphics scaling
    qreal scaleFactor = (newSize.width() *1.0) / (currentSize.width() * 1.0);

    //Scale graphics, if the scalefactor applies
    //This is really heavy since the SVG graphics are read again from the resource
    if(scaleFactor != 1 || m_topBarPixmap.isNull() )  {
        m_topBarPixmap = Theme::p()->pixmap(topbarName, newSize );
        m_topBarUserIcon = Theme::p()->pixmap("user_default_icon.svg",
                !m_topBarUserIcon.isNull() && !m_orientationChanged ? m_topBarUserIcon.size()* scaleFactor : sizes["user_default_icon.svg"] * scaleFactor);

        m_topBarUserStatus = Theme::p()->pixmap("user_status_online.svg",
                !m_topBarUserStatus.isNull() && !m_orientationChanged ? m_topBarUserStatus.size() * scaleFactor : sizes["user_status_online.svg"] * scaleFactor);

        m_topBarStatusBarLeft = Theme::p()->pixmap("status_field_left.svg",
                !m_topBarStatusBarLeft.isNull() && !m_orientationChanged ? m_topBarStatusBarLeft.size()* scaleFactor : sizes["status_field_left.svg"] * scaleFactor);

        m_topBarStatusBarRight = Theme::p()->pixmap("status_field_right.svg",
                !m_topBarStatusBarRight.isNull() && !m_orientationChanged ? m_topBarStatusBarRight.size()* scaleFactor : sizes["status_field_right.svg"] * scaleFactor);

        m_topBarStatusBarMiddle = Theme::p()->pixmap("status_field_middle.svg",
                !m_topBarStatusBarMiddle.isNull() && !m_orientationChanged ? m_topBarStatusBarMiddle.size() * scaleFactor : QSize(185, sizes["status_field_middle.svg"].height()) * scaleFactor);

        //Update the sizeHint to match the size of the scaled m_topBarPixmap
        updateGeometry();

        //Point Update - Positions relative to the Top Bar "Backgroud" size.
        //TODO: consider some layout instead of calculating relative locations
        QSize topBarPixmapSize = m_topBarPixmap.size();
        QSize topBarUserIconSize = m_topBarUserIcon.size();
        QSize topBarUserStatusSize = m_topBarUserStatus.size();
        QSize topBarStatusBarLeftSize = m_topBarStatusBarLeft.size();
        QSize topBarStatusBarMiddleSize = m_topBarStatusBarMiddle.size();

        //Location for Title text 5% width, 35% height of the background pixmap
        m_topBarTitlePoint = QPoint(topBarPixmapSize.width()* 0.05,
                topBarPixmapSize.height() * 0.35);

        //User Icon location
        //Placing 70% of the width and 10% of the height of the top bar background
        m_topBarUserIconPoint = QPoint((topBarPixmapSize.width() * 0.7), (topBarPixmapSize.height() * 0.1));

        //If Blue theme is in use - position user status icon on the right side of the user icon
        if(!m_isLimeTheme) {
            //Place the status icon on top of the right edge of the user icon, lower it by 35% of the height of the user icon
            m_topBarUserStatusPoint = QPoint( ( (m_topBarUserIconPoint.x()+topBarUserIconSize.width() ) -
                    ( topBarUserStatusSize.width()/2 )),
                (m_topBarUserIconPoint.y() + (topBarUserIconSize.height() * 0.35 )));
        }
        //If Lime theme is in use - position user status icon on the left side of the user icon
        else {
            //Place the status icon on top of the left side of the user icon, lower it by 50% of the height of the user icon
            //and move left by 5% of the icon
            m_topBarUserStatusPoint = QPoint(  m_topBarUserIconPoint.x() + ( topBarUserIconSize.width() * 0.05),
                        (m_topBarUserIconPoint.y() + (topBarUserIconSize.height() * 0.5 )));
        }

        //Status bar
        //Placing the left side of the status bar  5% of the width, 50% of the height of the top bar background
        //Set the text baseline 80% of the height of the status bar
        m_topBarStatusBarLeftPoint = QPoint( (topBarPixmapSize.width()* 0.05),
                                                        (topBarPixmapSize.height() * 0.5));
        m_topBarStatusBarMiddlePoint = QPoint( (m_topBarStatusBarLeftPoint.x() + topBarStatusBarLeftSize.width()),
                                                            (m_topBarStatusBarLeftPoint.y()));
        m_topBarStatusBarRightPoint = QPoint( (m_topBarStatusBarMiddlePoint.x() + topBarStatusBarMiddleSize.width()),
                                                        (m_topBarStatusBarMiddlePoint.y() ) );
        m_topBarStatusBarTextPoint = QPoint(m_topBarStatusBarMiddlePoint.x(),
                                                        m_topBarStatusBarMiddlePoint.y() + (topBarStatusBarMiddleSize.height()*0.8) );
    } //if scalefactor
}
Example #2
0
void QtResourceViewPrivate::createResources(const QString &path)
{
    QDir dir(path);
    QStringList files = m_pathToContents.value(path);
    QStringListIterator it(files);
    while (it.hasNext()) {
        QString file = it.next();
        QString filePath = dir.absoluteFilePath(file);
        QFileInfo fi(filePath);
        if (fi.isFile()) {
            QListWidgetItem *item = new QListWidgetItem(fi.fileName(), m_listWidget);
            const QPixmap pix = QPixmap(filePath);
            if (pix.isNull()) {
                item->setToolTip(filePath);
            } else {
                item->setIcon(QIcon(makeThumbnail(pix)));
                const QSize size = pix.size();
                item->setToolTip(QtResourceView::tr("Size: %1 x %2\n%3").arg(size.width()).arg(size.height()).arg(filePath));
            }
            item->setFlags(item->flags() | Qt::ItemIsDragEnabled);
            item->setData(Qt::UserRole, filePath);
            m_itemToResource[item] = filePath;
            m_resourceToItem[filePath] = item;
        }
    }
}
Example #3
0
QString PrettySize(const QSize& size) {
  return QString::number(size.width()) + "x" + QString::number(size.height());
}
Example #4
0
//-----------------------------------------------------------------------------
void ctkAxesWidget::paintEvent(QPaintEvent *)
{
  Q_D(ctkAxesWidget);

  // init
  QPainter painter(this);
  
  //painter.setRenderHint(QPainter::Antialiasing);
  
  QPoint center = QPoint(this->width(), this->height())  / 2;
  int length = qMin(this->width(), this->height());
  int diameter = length / goldenRatio;
  int radius = diameter / 2;

  QStringList axesLabels;
  
  QList<QPoint> positions = d->extremities(center, radius);
  
  
  QFontMetrics fm = this->fontMetrics();
  QSize letterSize = fm.size(Qt::TextShowMnemonic, "X") + QSize(1,1);
  QSize halfLetterSize = letterSize / 2;
  int blankSize = (length - diameter) / 2;
  QSize betweenLetterSpace = QSize(blankSize - letterSize.width(), blankSize - letterSize.height()) / 2;
  QList<QRect>  labelRects = d->labelRects(positions, betweenLetterSpace);
  
  for (int i = 0; i < 6; ++i)
    {
    //QRect rect(positions[i] + QPoint(cos(d->AxesAngles[i]) * (betweenLetterSpace.width()+halfLetterSize.width()),
    //                                 -sin(d->AxesAngles[i]) * (betweenLetterSpace.height()+halfLetterSize.height()))
    //                                - QPoint(halfLetterSize.width(), halfLetterSize.height()), letterSize);
    QRect rect = labelRects[i];
    //if (d->HighlightAxes)
      {
      QFont font = painter.font();
      font.setBold(d->HighlightAxis == (i + 1));
      painter.setFont(font);
      }
    painter.drawText(rect, Qt::AlignCenter, d->AxesLabels[i]);
    } 
  
  // Drawing the lines
  for (int i = 0; i < 6; ++i)
    {
    //if (d->HighlightAxes)
      {
      QPen pen;
      if (d->HighlightAxis == (i + 1)) // axes start at 1
        {
        pen.setWidth(3);
        //pen.setColor(QColor(64, 64, 72)); // Payne's grey
        pen.setColor(this->palette().color(QPalette::Highlight));
        }
      painter.setPen(pen);
      }
    painter.drawLine(center, positions[i]);
    }
  
  QSize sphereRadius((blankSize / 2) / 1.6180339887,
                     (blankSize / 2) / 1.6180339887);
  // Draw the center sphere
  QRadialGradient rg(QPointF(0.3333, 0.3333),0.7);
  rg.setCoordinateMode(QGradient::ObjectBoundingMode);
  if (//d->HighlightAxes &&
      d->HighlightAxis == ctkAxesWidget::None)
    {
    rg.setColorAt(0., this->palette().color(QPalette::Highlight));
    }
  else
    {
    rg.setColorAt(0., this->palette().color(QPalette::Light));
    }
  rg.setColorAt(1., QColor(64, 64, 72));
  painter.setBrush(QBrush(rg));
  painter.setPen(QPen(Qt::NoPen));
  painter.drawEllipse(QPointF(center), sphereRadius.width(), sphereRadius.height());
}
OpenDialog::OpenDialog(
   QWidget* pParent, const QString& n1, const QString& n2, const QString& n3,
   bool bMerge, const QString& outputName, const char* slotConfigure, OptionDialog* pOptions )
: QDialog( pParent )
{
   setObjectName("OpenDialog");
   setModal(true);
   m_pOptions = pOptions;

   QVBoxLayout* v = new QVBoxLayout( this );
   v->setMargin(5);
   QGridLayout* h = new QGridLayout();
   v->addLayout(h);
   h->setSpacing( 5 );
   h->setColumnStretch( 1, 10 );

   QLabel* label  = new QLabel( i18n("A (Base):"), this );

   m_pLineA = new QComboBox();
   m_pLineA->setEditable(true);
   m_pLineA->insertItems( 0, m_pOptions->m_recentAFiles );
   m_pLineA->setEditText( KUrl(n1).prettyUrl() );
   m_pLineA->setMinimumWidth( 200 );
   QPushButton * button = new QPushButton( i18n("File..."), this );
   connect( button, SIGNAL(clicked()), this, SLOT( selectFileA() ) );
   QPushButton * button2 = new QPushButton( i18n("Dir..."), this );
   connect( button2, SIGNAL(clicked()), this, SLOT( selectDirA() ) );
   connect( m_pLineA, SIGNAL(editTextChanged(const QString&)), this, SLOT(inputFilenameChanged() ) );

   h->addWidget( label,    0, 0 );
   h->addWidget( m_pLineA,  0, 1 );
   h->addWidget( button,   0, 2 );
   h->addWidget( button2,  0, 3 );

   label    = new QLabel( "B:", this );
   m_pLineB  = new QComboBox();
   m_pLineB->setEditable(true);
   m_pLineB->insertItems( 0, m_pOptions->m_recentBFiles );
   m_pLineB->setEditText( KUrl(n2).prettyUrl() );
   m_pLineB->setMinimumWidth( 200 );
   button   = new QPushButton( i18n("File..."), this );
   connect( button, SIGNAL(clicked()), this, SLOT( selectFileB() ) );
   button2   = new QPushButton( i18n("Dir..."), this );
   connect( button2, SIGNAL(clicked()), this, SLOT( selectDirB() ) );
   connect( m_pLineB, SIGNAL(editTextChanged(const QString&)), this, SLOT(inputFilenameChanged() ) );

   h->addWidget( label,     1, 0 );
   h->addWidget( m_pLineB,  1, 1 );
   h->addWidget( button,    1, 2 );
   h->addWidget( button2,   1, 3 );

   label  = new QLabel( i18n("C (Optional):"), this );
   m_pLineC= new QComboBox();
   m_pLineC->setEditable(true);
   m_pLineC->insertItems( 0, m_pOptions->m_recentCFiles );
   m_pLineC->setEditText( KUrl(n3).prettyUrl() );
   m_pLineC->setMinimumWidth( 200 );
   button = new QPushButton( i18n("File..."), this );
   connect( button, SIGNAL(clicked()), this, SLOT( selectFileC() ) );
   button2   = new QPushButton( i18n("Dir..."), this );
   connect( button2, SIGNAL(clicked()), this, SLOT( selectDirC() ) );
   connect( m_pLineC, SIGNAL(editTextChanged(const QString&)), this, SLOT(inputFilenameChanged() ) );

   h->addWidget( label,     2, 0 );
   h->addWidget( m_pLineC,   2, 1 );
   h->addWidget( button,    2, 2 );
   h->addWidget( button2,   2, 3 );

   m_pMerge = new QCheckBox( i18n("Merge"), this );
   h->addWidget( m_pMerge, 3, 0 );

   QHBoxLayout* hl = new QHBoxLayout();
   h->addLayout( hl, 3, 1 );
   hl->addStretch(2);
   button = new QPushButton(i18n("Swap/Copy Names ..."), this);
   //button->setToggleButton(false);
   hl->addWidget( button );

   QMenu* m = new QMenu(this);
   m->addAction( i18n("Swap %1<->%2", QString("A"),QString("B") ));
   m->addAction( i18n("Swap %1<->%2",QString("B"),QString("C") ));
   m->addAction( i18n("Swap %1<->%2",QString("C"),QString("A") ));
   m->addAction( i18n("Copy %1->Output",QString("A")  ));
   m->addAction( i18n("Copy %1->Output",QString("B")  ));
   m->addAction( i18n("Copy %1->Output",QString("C")  ));
   m->addAction( i18n("Swap %1<->Output",QString("A") ));
   m->addAction( i18n("Swap %1<->Output",QString("B") ));
   m->addAction( i18n("Swap %1<->Output",QString("C") ));
   connect( m, SIGNAL(triggered(QAction*)), this, SLOT(slotSwapCopyNames(QAction*)));
   button->setMenu(m);


   hl->addStretch(2);

   label  = new QLabel( i18n("Output (optional):"), this );
   m_pLineOut = new QComboBox();
   m_pLineOut->setEditable(true);
   m_pLineOut->insertItems( 0, m_pOptions->m_recentOutputFiles );
   m_pLineOut->setEditText( KUrl(outputName).prettyUrl() );
   m_pLineOut->setMinimumWidth( 200 );
   button = new QPushButton( i18n("File..."), this );
   connect( button, SIGNAL(clicked()), this, SLOT( selectOutputName() ) );
   button2   = new QPushButton( i18n("Dir..."), this );
   connect( button2, SIGNAL(clicked()), this, SLOT( selectOutputDir() ) );
   connect( m_pMerge, SIGNAL(stateChanged(int)), this, SLOT(internalSlot(int)) );
   connect( this, SIGNAL(internalSignal(bool)), m_pLineOut, SLOT(setEnabled(bool)) );
   connect( this, SIGNAL(internalSignal(bool)), button, SLOT(setEnabled(bool)) );
   connect( this, SIGNAL(internalSignal(bool)), button2, SLOT(setEnabled(bool)) );

   m_pMerge->setChecked( !bMerge );
   m_pMerge->setChecked( bMerge );
//   m_pLineOutput->setEnabled( bMerge );

//   button->setEnabled( bMerge );

   h->addWidget( label,          4, 0 );
   h->addWidget( m_pLineOut,      4, 1 );
   h->addWidget( button,         4, 2 );
   h->addWidget( button2,        4, 3 );

   h->addItem(new QSpacerItem(200, 0), 0, 1);

   QHBoxLayout* l = new QHBoxLayout();
   v->addLayout( l );
   l->setSpacing(5);

   button = new QPushButton( i18n("Configure..."), this );
   connect( button, SIGNAL(clicked()), pParent, slotConfigure );
   l->addWidget( button, 1 );

   l->addStretch(1);

   button = new QPushButton( i18n("&OK"), this );
   button->setDefault( true );
   connect( button, SIGNAL(clicked()), this, SLOT( accept() ) );
   l->addWidget( button, 1 );

   button = new QPushButton( i18n("&Cancel"), this );
   connect( button, SIGNAL(clicked()), this, SLOT( reject() ) );
   l->addWidget( button,1 );

   QSize sh = sizeHint();
   setFixedHeight( sh.height() );
   m_bInputFileNameChanged = false;

#ifdef KREPLACEMENTS_H
   m_pLineA->lineEdit()->installEventFilter( this );
   m_pLineB->lineEdit()->installEventFilter( this );
   m_pLineC->lineEdit()->installEventFilter( this );
   m_pLineOut->lineEdit()->installEventFilter( this );
#endif
}
Example #6
0
int main(int argc, char **argv)
{
    //! [0]
    QApplication app(argc, argv);
    Q3DSurface *graph = new Q3DSurface();
    QWidget *container = QWidget::createWindowContainer(graph);
    //! [0]

    if (!graph->hasContext()) {
        QMessageBox msgBox;
        msgBox.setText("Couldn't initialize the OpenGL context.");
        msgBox.exec();
        return -1;
    }

    QSize screenSize = graph->screen()->size();
    container->setMinimumSize(QSize(screenSize.width() / 2, screenSize.height() / 1.6));
    container->setMaximumSize(screenSize);
    container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    container->setFocusPolicy(Qt::StrongFocus);

    //! [1]
    QWidget *widget = new QWidget;
    QHBoxLayout *hLayout = new QHBoxLayout(widget);
    QVBoxLayout *vLayout = new QVBoxLayout();
    hLayout->addWidget(container, 1);
    hLayout->addLayout(vLayout);
    vLayout->setAlignment(Qt::AlignTop);
    //! [1]

    widget->setWindowTitle(QStringLiteral("Surface example"));

    QGroupBox *modelGroupBox = new QGroupBox(QStringLiteral("Model"));

    QRadioButton *sqrtSinModelRB = new QRadioButton(widget);
    sqrtSinModelRB->setText(QStringLiteral("Sqrt && Sin"));
    sqrtSinModelRB->setChecked(false);

    QRadioButton *heightMapModelRB = new QRadioButton(widget);
    heightMapModelRB->setText(QStringLiteral("Height Map"));
    heightMapModelRB->setChecked(false);

    QVBoxLayout *modelVBox = new QVBoxLayout;
    modelVBox->addWidget(sqrtSinModelRB);
    modelVBox->addWidget(heightMapModelRB);
    modelGroupBox->setLayout(modelVBox);

    QGroupBox *selectionGroupBox = new QGroupBox(QStringLiteral("Selection Mode"));

    QRadioButton *modeNoneRB = new QRadioButton(widget);
    modeNoneRB->setText(QStringLiteral("No selection"));
    modeNoneRB->setChecked(false);

    QRadioButton *modeItemRB = new QRadioButton(widget);
    modeItemRB->setText(QStringLiteral("Item"));
    modeItemRB->setChecked(false);

    QRadioButton *modeSliceRowRB = new QRadioButton(widget);
    modeSliceRowRB->setText(QStringLiteral("Row Slice"));
    modeSliceRowRB->setChecked(false);

    QRadioButton *modeSliceColumnRB = new QRadioButton(widget);
    modeSliceColumnRB->setText(QStringLiteral("Column Slice"));
    modeSliceColumnRB->setChecked(false);

    QVBoxLayout *selectionVBox = new QVBoxLayout;
    selectionVBox->addWidget(modeNoneRB);
    selectionVBox->addWidget(modeItemRB);
    selectionVBox->addWidget(modeSliceRowRB);
    selectionVBox->addWidget(modeSliceColumnRB);
    selectionGroupBox->setLayout(selectionVBox);

    QSlider *axisMinSliderX = new QSlider(Qt::Horizontal, widget);
    axisMinSliderX->setMinimum(0);
    axisMinSliderX->setTickInterval(1);
    axisMinSliderX->setEnabled(true);
    QSlider *axisMaxSliderX = new QSlider(Qt::Horizontal, widget);
    axisMaxSliderX->setMinimum(1);
    axisMaxSliderX->setTickInterval(1);
    axisMaxSliderX->setEnabled(true);
    QSlider *axisMinSliderZ = new QSlider(Qt::Horizontal, widget);
    axisMinSliderZ->setMinimum(0);
    axisMinSliderZ->setTickInterval(1);
    axisMinSliderZ->setEnabled(true);
    QSlider *axisMaxSliderZ = new QSlider(Qt::Horizontal, widget);
    axisMaxSliderZ->setMinimum(1);
    axisMaxSliderZ->setTickInterval(1);
    axisMaxSliderZ->setEnabled(true);

    QComboBox *themeList = new QComboBox(widget);
    themeList->addItem(QStringLiteral("Qt"));
    themeList->addItem(QStringLiteral("Primary Colors"));
    themeList->addItem(QStringLiteral("Digia"));
    themeList->addItem(QStringLiteral("Stone Moss"));
    themeList->addItem(QStringLiteral("Army Blue"));
    themeList->addItem(QStringLiteral("Retro"));
    themeList->addItem(QStringLiteral("Ebony"));
    themeList->addItem(QStringLiteral("Isabelle"));

    QGroupBox *colorGroupBox = new QGroupBox(QStringLiteral("Custom gradient"));

    QLinearGradient grBtoY(0, 0, 1, 100);
    grBtoY.setColorAt(1.0, Qt::black);
    grBtoY.setColorAt(0.67, Qt::blue);
    grBtoY.setColorAt(0.33, Qt::red);
    grBtoY.setColorAt(0.0, Qt::yellow);
    QPixmap pm(24, 100);
    QPainter pmp(&pm);
    pmp.setBrush(QBrush(grBtoY));
    pmp.setPen(Qt::NoPen);
    pmp.drawRect(0, 0, 24, 100);
    QPushButton *gradientBtoYPB = new QPushButton(widget);
    gradientBtoYPB->setIcon(QIcon(pm));
    gradientBtoYPB->setIconSize(QSize(24, 100));

    QLinearGradient grGtoR(0, 0, 1, 100);
    grGtoR.setColorAt(1.0, Qt::darkGreen);
    grGtoR.setColorAt(0.5, Qt::yellow);
    grGtoR.setColorAt(0.2, Qt::red);
    grGtoR.setColorAt(0.0, Qt::darkRed);
    pmp.setBrush(QBrush(grGtoR));
    pmp.drawRect(0, 0, 24, 100);
    QPushButton *gradientGtoRPB = new QPushButton(widget);
    gradientGtoRPB->setIcon(QIcon(pm));
    gradientGtoRPB->setIconSize(QSize(24, 100));

    QHBoxLayout *colorHBox = new QHBoxLayout;
    colorHBox->addWidget(gradientBtoYPB);
    colorHBox->addWidget(gradientGtoRPB);
    colorGroupBox->setLayout(colorHBox);

    vLayout->addWidget(modelGroupBox);
    vLayout->addWidget(selectionGroupBox);
    vLayout->addWidget(new QLabel(QStringLiteral("Column range")));
    vLayout->addWidget(axisMinSliderX);
    vLayout->addWidget(axisMaxSliderX);
    vLayout->addWidget(new QLabel(QStringLiteral("Row range")));
    vLayout->addWidget(axisMinSliderZ);
    vLayout->addWidget(axisMaxSliderZ);
    vLayout->addWidget(new QLabel(QStringLiteral("Theme")));
    vLayout->addWidget(themeList);
    vLayout->addWidget(colorGroupBox);

    widget->show();

    SurfaceGraph *modifier = new SurfaceGraph(graph);

    QObject::connect(heightMapModelRB, &QRadioButton::toggled,
                     modifier, &SurfaceGraph::enableHeightMapModel);
    QObject::connect(sqrtSinModelRB, &QRadioButton::toggled,
                     modifier, &SurfaceGraph::enableSqrtSinModel);
    QObject::connect(modeNoneRB, &QRadioButton::toggled,
                     modifier, &SurfaceGraph::toggleModeNone);
    QObject::connect(modeItemRB,  &QRadioButton::toggled,
                     modifier, &SurfaceGraph::toggleModeItem);
    QObject::connect(modeSliceRowRB,  &QRadioButton::toggled,
                     modifier, &SurfaceGraph::toggleModeSliceRow);
    QObject::connect(modeSliceColumnRB,  &QRadioButton::toggled,
                     modifier, &SurfaceGraph::toggleModeSliceColumn);
    QObject::connect(axisMinSliderX, &QSlider::valueChanged,
                     modifier, &SurfaceGraph::adjustXMin);
    QObject::connect(axisMaxSliderX, &QSlider::valueChanged,
                     modifier, &SurfaceGraph::adjustXMax);
    QObject::connect(axisMinSliderZ, &QSlider::valueChanged,
                     modifier, &SurfaceGraph::adjustZMin);
    QObject::connect(axisMaxSliderZ, &QSlider::valueChanged,
                     modifier, &SurfaceGraph::adjustZMax);
    QObject::connect(themeList, SIGNAL(currentIndexChanged(int)),
                     modifier, SLOT(changeTheme(int)));
    QObject::connect(gradientBtoYPB, &QPushButton::pressed,
                     modifier, &SurfaceGraph::setBlackToYellowGradient);
    QObject::connect(gradientGtoRPB, &QPushButton::pressed,
                     modifier, &SurfaceGraph::setGreenToRedGradient);

    modifier->setAxisMinSliderX(axisMinSliderX);
    modifier->setAxisMaxSliderX(axisMaxSliderX);
    modifier->setAxisMinSliderZ(axisMinSliderZ);
    modifier->setAxisMaxSliderZ(axisMaxSliderZ);

    sqrtSinModelRB->setChecked(true);
    modeItemRB->setChecked(true);
    themeList->setCurrentIndex(2);

    return app.exec();
}
Example #7
0
QJsonDocument variantMapToJsonDocument(const QSettings::SettingsMap& map) {
    QJsonObject object;
    for (auto it = map.cbegin(); it != map.cend(); ++it) {
        auto& key = it.key();
        auto& variant = it.value();
        auto variantType = variant.type();

        // Switch some types so they are readable/modifiable in the json file
        if (variantType == QVariant(1.0f).type()) { // float
            variantType = QVariant::Double;
        }
        if (variantType == QVariant((quint16)0).type()) { // uint16
            variantType = QVariant::UInt;
        }
        if (variantType == QVariant::Url) { // QUrl
            variantType = QVariant::String;
        }

        switch (variantType) {
            case QVariant::Hash: {
                qCritical() << "Unsupported variant type" << variant.typeName() << ";" << key << variant;
                Q_ASSERT(false);
                break;
            }

            case QVariant::Invalid:
                object.insert(key, QJsonValue());
                break;
            case QVariant::LongLong:
            case QVariant::ULongLong:
            case QVariant::Int:
            case QVariant::UInt:
            case QVariant::Bool:
            case QVariant::Double:
            case QVariant::Map:
            case QVariant::List:
                object.insert(key, QJsonValue::fromVariant(variant));
                break;

            case QVariant::String: {
                QString result = variant.toString();
                if (result.startsWith(QLatin1Char('@'))) {
                    result.prepend(QLatin1Char('@'));
                }
                object.insert(key, result);
                break;
            }

            case QVariant::ByteArray: {
                QByteArray a = variant.toByteArray();
                QString result = QLatin1String("@ByteArray(");
                result += QString::fromLatin1(a.constData(), a.size());
                result += QLatin1Char(')');
                object.insert(key, result);
                break;
            }
            case QVariant::Rect: {
                QRect r = qvariant_cast<QRect>(variant);
                QString result = QLatin1String("@Rect(");
                result += QString::number(r.x());
                result += QLatin1Char(' ');
                result += QString::number(r.y());
                result += QLatin1Char(' ');
                result += QString::number(r.width());
                result += QLatin1Char(' ');
                result += QString::number(r.height());
                result += QLatin1Char(')');
                object.insert(key, result);
                break;
            }
            case QVariant::Size: {
                QSize s = qvariant_cast<QSize>(variant);
                QString result = QLatin1String("@Size(");
                result += QString::number(s.width());
                result += QLatin1Char(' ');
                result += QString::number(s.height());
                result += QLatin1Char(')');
                object.insert(key, result);
                break;
            }
            case QVariant::Point: {
                QPoint p = qvariant_cast<QPoint>(variant);
                QString result = QLatin1String("@Point(");
                result += QString::number(p.x());
                result += QLatin1Char(' ');
                result += QString::number(p.y());
                result += QLatin1Char(')');
                object.insert(key, result);
                break;
            }

            default: {
                QByteArray array;
                {
                    QDataStream stream(&array, QIODevice::WriteOnly);
                    stream.setVersion(QDataStream::Qt_4_0);
                    stream << variant;
                }

                QString result = QLatin1String("@Variant(");
                result += QString::fromLatin1(array.constData(), array.size());
                result += QLatin1Char(')');
                object.insert(key, result);
                break;
            }
        }
    }

    return QJsonDocument(object);
}
Example #8
0
static void read_image_scaled(QImage *outImage, png_structp png_ptr, png_infop info_ptr,
                              QPngHandlerPrivate::AllocatedMemoryPointers &amp, QSize scaledSize)
{

    png_uint_32 width;
    png_uint_32 height;
    int bit_depth;
    int color_type;
    png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
    uchar *data = outImage->bits();
    int bpl = outImage->bytesPerLine();

    if (scaledSize.isEmpty() || !width || !height)
        return;

    const quint32 iysz = height;
    const quint32 ixsz = width;
    const quint32 oysz = scaledSize.height();
    const quint32 oxsz = scaledSize.width();
    const quint32 ibw = 4*width;
    amp.accRow = new quint32[ibw];
    memset(amp.accRow, 0, ibw*sizeof(quint32));
    amp.inRow = new png_byte[ibw];
    memset(amp.inRow, 0, ibw*sizeof(png_byte));
    amp.outRow = new uchar[ibw];
    memset(amp.outRow, 0, ibw*sizeof(uchar));
    qint32 rval = 0;
    for (quint32 oy=0; oy<oysz; oy++) {
        // Store the rest of the previous input row, if any
        for (quint32 i=0; i < ibw; i++)
            amp.accRow[i] = rval*amp.inRow[i];
        // Accumulate the next input rows
        for (rval = iysz-rval; rval > 0; rval-=oysz) {
            png_read_row(png_ptr, amp.inRow, NULL);
            quint32 fact = qMin(oysz, quint32(rval));
            for (quint32 i=0; i < ibw; i++)
                amp.accRow[i] += fact*amp.inRow[i];
        }
        rval *= -1;

        // We have a full output row, store it
        for (quint32 i=0; i < ibw; i++)
            amp.outRow[i] = uchar(amp.accRow[i]/iysz);

        quint32 a[4] = {0, 0, 0, 0};
        qint32 cval = oxsz;
        quint32 ix = 0;
        for (quint32 ox=0; ox<oxsz; ox++) {
            for (quint32 i=0; i < 4; i++)
                a[i] = cval * amp.outRow[ix+i];
            for (cval = ixsz - cval; cval > 0; cval-=oxsz) {
                ix += 4;
                if (ix >= ibw)
                    break;            // Safety belt, should not happen
                quint32 fact = qMin(oxsz, quint32(cval));
                for (quint32 i=0; i < 4; i++)
                    a[i] += fact * amp.outRow[ix+i];
            }
            cval *= -1;
            for (quint32 i=0; i < 4; i++)
                data[(4*ox)+i] = uchar(a[i]/ixsz);
        }
        data += bpl;
    }
    amp.deallocate();

    outImage->setDotsPerMeterX((png_get_x_pixels_per_meter(png_ptr,info_ptr)*oxsz)/ixsz);
    outImage->setDotsPerMeterY((png_get_y_pixels_per_meter(png_ptr,info_ptr)*oysz)/iysz);
}
Example #9
0
RCDrawRobot::RCDrawRobot(const QPointF &center, QSize size, QWidget *parent) : RCDraw(QRect(center.x()-(size.width()/2.), center.y()-(size.height()/2.), size.width(), size.height()), parent)
{
	init();
}
VpnWizard::VpnWizard(QWidget * parent)
    : FramelessWizard(parent)
{
    addPage(new CStartPage);
    addPage(new GeneralPage);
    addPage(new RemotePage);
    addPage(new CertPage);
    addPage(new AdvPage);
    addPage(new CEndPage);

    
    //this->button(QWizard::WizardButton::BackButton)->setIcon(QIcon(":/data/images/back_small.png"));
    //this->button(QWizard::WizardButton::NextButton)->setIcon(QIcon(":/data/images/next_small.png"));
    

    auto geom = this->geometry();
    geom.setHeight(460);
    geom.setWidth(501);

	QSize size = geom.size();
	//
	int h = size.height();
	int w = size.width();
	//

	size.setHeight(qFloor(h * windowsDpiScale()));
	size.setWidth(qFloor(w * windowsDpiScale()));

	setFixedWidth(size.width());
	setFixedHeight(size.height());

	//
    resize(size);
    
    QPixmap pixmap(":/data/images/banner_wiz.png");
    pixmap = pixmap.scaledToWidth(size.width(), Qt::TransformationMode::SmoothTransformation);
    setPixmap(QWizard::BannerPixmap, pixmap);
    //page(0)->setContentsMargins(0, 20, 0, 0);
    //page(1)->setContentsMargins(0, 20, 0, 0);
    //page(2)->setContentsMargins(0, 20, 0, 0);
    //page(3)->setContentsMargins(0, 20, 0, 0);
    //page(4)->setContentsMargins(0, 20, 0, 0);
    setWindowIcon(QIcon(":/data/images/logo.png"));
    setWindowTitle(QObject::tr("Create a new SSL VPN connection"));
    setWindowFlags(Qt::WindowCloseButtonHint);
    setModal(true);
    this->setWindowFlags(Qt::WindowCloseButtonHint | Qt::FramelessWindowHint);
    DWORD style = GetWindowLong((HWND)winId(), GWL_STYLE);
    SetWindowLong((HWND)winId(), GWL_STYLE, style);
    setWizardStyle(ModernStyle);
    


    //this->button(QWizard::WizardButton::NextButton)->setLayoutDirection(Qt::RightToLeft);
    this->setButtonText(QWizard::WizardButton::NextButton, QObject::tr("Next"));
    this->setButtonText(QWizard::WizardButton::BackButton, QObject::tr("Back"));
    this->setButtonText(QWizard::WizardButton::CancelButton, QObject::tr("Cancel"));
    this->setButtonText(QWizard::WizardButton::FinishButton, QObject::tr("Finish"));

    setStyleSheet("QPushButton:hover {background-color: rgb(195, 195, 195);}\nQPushButton {;text-align:center;	\npadding-left: 3px;\n	padding-top: 3px;   padding-right: 3px;\n	padding-bottom: 3px;}");

    this->setupFrameless();
}
Example #11
0
static
void setup_qt(QImage& image, png_structp png_ptr, png_infop info_ptr, QSize scaledSize, bool *doScaledRead, float screen_gamma=0.0)
{
    if (screen_gamma != 0.0 && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA)) {
        double file_gamma;
        png_get_gAMA(png_ptr, info_ptr, &file_gamma);
        png_set_gamma(png_ptr, screen_gamma, file_gamma);
    }

    png_uint_32 width;
    png_uint_32 height;
    int bit_depth;
    int color_type;
    png_bytep trans_alpha = 0;
    png_color_16p trans_color_p = 0;
    int num_trans;
    png_colorp palette = 0;
    int num_palette;
    int interlace_method;
    png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_method, 0, 0);
    png_set_interlace_handling(png_ptr);

    if (color_type == PNG_COLOR_TYPE_GRAY) {
        // Black & White or 8-bit grayscale
        if (bit_depth == 1 && png_get_channels(png_ptr, info_ptr) == 1) {
            png_set_invert_mono(png_ptr);
            png_read_update_info(png_ptr, info_ptr);
            if (image.size() != QSize(width, height) || image.format() != QImage::Format_Mono) {
                image = QImage(width, height, QImage::Format_Mono);
                if (image.isNull())
                    return;
            }
            image.setColorCount(2);
            image.setColor(1, qRgb(0,0,0));
            image.setColor(0, qRgb(255,255,255));
        } else if (bit_depth == 16 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
            png_set_expand(png_ptr);
            png_set_strip_16(png_ptr);
            png_set_gray_to_rgb(png_ptr);
            if (image.size() != QSize(width, height) || image.format() != QImage::Format_ARGB32) {
                image = QImage(width, height, QImage::Format_ARGB32);
                if (image.isNull())
                    return;
            }
            if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
                png_set_swap_alpha(png_ptr);

            png_read_update_info(png_ptr, info_ptr);
        } else {
            if (bit_depth == 16)
                png_set_strip_16(png_ptr);
            else if (bit_depth < 8)
                png_set_packing(png_ptr);
            int ncols = bit_depth < 8 ? 1 << bit_depth : 256;
            png_read_update_info(png_ptr, info_ptr);
            if (image.size() != QSize(width, height) || image.format() != QImage::Format_Indexed8) {
                image = QImage(width, height, QImage::Format_Indexed8);
                if (image.isNull())
                    return;
            }
            image.setColorCount(ncols);
            for (int i=0; i<ncols; i++) {
                int c = i*255/(ncols-1);
                image.setColor(i, qRgba(c,c,c,0xff));
            }
            if (png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, &trans_color_p) && trans_color_p) {
                const int g = trans_color_p->gray;
                if (g < ncols) {
                    image.setColor(g, 0);
                }
            }
        }
    } else if (color_type == PNG_COLOR_TYPE_PALETTE
               && png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette)
               && num_palette <= 256)
    {
        // 1-bit and 8-bit color
        if (bit_depth != 1)
            png_set_packing(png_ptr);
        png_read_update_info(png_ptr, info_ptr);
        png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
        QImage::Format format = bit_depth == 1 ? QImage::Format_Mono : QImage::Format_Indexed8;
        if (image.size() != QSize(width, height) || image.format() != format) {
            image = QImage(width, height, format);
            if (image.isNull())
                return;
        }
        png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
        image.setColorCount(num_palette);
        int i = 0;
        if (png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, &trans_color_p) && trans_alpha) {
            while (i < num_trans) {
                image.setColor(i, qRgba(
                    palette[i].red,
                    palette[i].green,
                    palette[i].blue,
                    trans_alpha[i]
                   )
               );
                i++;
            }
        }
        while (i < num_palette) {
            image.setColor(i, qRgba(
                palette[i].red,
                palette[i].green,
                palette[i].blue,
                0xff
               )
           );
            i++;
        }
    } else {
        // 32-bit
        if (bit_depth == 16)
            png_set_strip_16(png_ptr);

        png_set_expand(png_ptr);

        if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
            png_set_gray_to_rgb(png_ptr);

        QImage::Format format = QImage::Format_ARGB32;
        // Only add filler if no alpha, or we can get 5 channel data.
        if (!(color_type & PNG_COLOR_MASK_ALPHA)
            && !png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
            png_set_filler(png_ptr, 0xff, QSysInfo::ByteOrder == QSysInfo::BigEndian ?
                           PNG_FILLER_BEFORE : PNG_FILLER_AFTER);
            // We want 4 bytes, but it isn't an alpha channel
            format = QImage::Format_RGB32;
        }
        QSize outSize(width,height);
        if (!scaledSize.isEmpty() && quint32(scaledSize.width()) <= width &&
            quint32(scaledSize.height()) <= height && interlace_method == PNG_INTERLACE_NONE) {
            // Do inline downscaling
            outSize = scaledSize;
            if (doScaledRead)
                *doScaledRead = true;
        }
        if (image.size() != outSize || image.format() != format) {
            image = QImage(outSize, format);
            if (image.isNull())
                return;
        }

        if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
            png_set_swap_alpha(png_ptr);

        png_read_update_info(png_ptr, info_ptr);
    }

    // Qt==ARGB==Big(ARGB)==Little(BGRA)
    if (QSysInfo::ByteOrder == QSysInfo::LittleEndian) {
        png_set_bgr(png_ptr);
    }
}
Example #12
0
void PanelKMenu::setMaximumSize(const QSize & s)
{
    KPanelMenu::setMaximumSize(s.width() + sidePixmap.width(), s.height());
}
Example #13
0
//! [1]
static QPointF posForLocation(int column, int row, const QSize &size)
{
    return QPointF(column * 150, row * 150)
        - QPointF((size.width() - 1) * 75, (size.height() - 1) * 75);
}
Example #14
0
//! [0]
static QRectF boundsFromSize(const QSize &size)
{
    return QRectF((-size.width() / 2.0) * 150, (-size.height() / 2.0) * 150,
                  size.width() * 150, size.height() * 150);
}
Example #15
0
static inline int pmKey(const QSize &size, QIcon::Mode mode, QIcon::State state)
{
    return ((((((size.width()<<11)|size.height())<<11)|mode)<<4)|state);
}
Example #16
0
void UIGraphicsButton::paint(QPainter *pPainter, const QStyleOptionGraphicsItem* /* pOption */, QWidget* /* pWidget = 0 */)
{
    /* Prepare variables: */
    int iMargin = data(GraphicsButton_Margin).toInt();
    QIcon icon = data(GraphicsButton_Icon).value<QIcon>();
    QSize iconSize = data(GraphicsButton_IconSize).toSize();

    /* Which type button has: */
    switch (m_buttonType)
    {
        case UIGraphicsButtonType_Iconified:
        {
            /* Just draw the pixmap: */
            pPainter->drawPixmap(QRect(QPoint(iMargin, iMargin), iconSize), icon.pixmap(iconSize));
            break;
        }
        case UIGraphicsButtonType_DirectArrow:
        {
            /* Prepare variables: */
            QPalette pal = palette();
            QColor buttonColor = pal.color(m_fParentSelected ? QPalette::HighlightedText : QPalette::Mid);
#ifdef Q_WS_MAC
            /* Mac is using only light standard highlight colors, keeping highlight-text color always black.
             * User can choose a darker (non-standard) highlight color but it will be his visibility problem.
             * I think using highlight-text color (black) for arrow-buttons is too ugly,
             * so the corresponding color will be received from the highlight color: */
            if (m_fParentSelected)
                buttonColor = pal.color(QPalette::Highlight).darker(150);
#endif /* Q_WS_MAC */

            /* Setup: */
            pPainter->setRenderHint(QPainter::Antialiasing);
            QPen pen = pPainter->pen();
            pen.setColor(buttonColor);
            pen.setWidth(2);
            pen.setCapStyle(Qt::RoundCap);

            /* Draw path: */
            QPainterPath circlePath;
            circlePath.moveTo(iMargin, iMargin);
            circlePath.lineTo(iMargin + iconSize.width() / 2, iMargin);
            circlePath.arcTo(QRectF(circlePath.currentPosition(), iconSize).translated(-iconSize.width() / 2, 0), 90, -180);
            circlePath.lineTo(iMargin, iMargin + iconSize.height());
            circlePath.closeSubpath();
            pPainter->strokePath(circlePath, pen);

            /* Draw triangle: */
            QPainterPath linePath;
            linePath.moveTo(iMargin + 5, iMargin + 5);
            linePath.lineTo(iMargin + iconSize.height() - 5, iMargin + iconSize.width() / 2);
            linePath.lineTo(iMargin + 5, iMargin + iconSize.width() - 5);
            pPainter->strokePath(linePath, pen);
            break;
        }
        case UIGraphicsButtonType_RoundArrow:
        {
            /* Prepare variables: */
            QPalette pal = palette();
            QColor buttonColor = pal.color(m_fParentSelected ? QPalette::HighlightedText : QPalette::Mid);
#ifdef Q_WS_MAC
            /* Mac is using only light standard highlight colors, keeping highlight-text color always black.
             * User can choose a darker (non-standard) highlight color but it will be his visibility problem.
             * I think using highlight-text color (black) for arrow-buttons is too ugly,
             * so the corresponding color will be received from the highlight color: */
            if (m_fParentSelected)
                buttonColor = pal.color(QPalette::Highlight).darker(150);
#endif /* Q_WS_MAC */

            /* Setup: */
            pPainter->setRenderHint(QPainter::Antialiasing);
            QPen pen = pPainter->pen();
            pen.setColor(buttonColor);
            pen.setWidth(2);
            pen.setCapStyle(Qt::RoundCap);

            /* Draw circle: */
            QPainterPath circlePath;
            circlePath.moveTo(iMargin, iMargin);
            circlePath.addEllipse(QRectF(circlePath.currentPosition(), iconSize));
            pPainter->strokePath(circlePath, pen);

            /* Draw triangle: */
            QPainterPath linePath;
            linePath.moveTo(iMargin + 5, iMargin + 5);
            linePath.lineTo(iMargin + iconSize.height() - 5, iMargin + iconSize.width() / 2);
            linePath.lineTo(iMargin + 5, iMargin + iconSize.width() - 5);
            pPainter->strokePath(linePath, pen);
            break;
        }
    }
}
Example #17
0
void StelDialog::setVisible(bool v)
{
	if (v)
	{
		QSize screenSize = StelMainView::getInstance().size();
		if (dialog)
		{
			dialog->show();
			StelMainView::getInstance().scene()->setActiveWindow(proxy);
			// If the main window has been resized, it is possible the dialog
			// will be off screen.  Check for this and move it to a visible
			// position if necessary
			QPointF newPos = proxy->pos();
			if (newPos.x()>=screenSize.width())
				newPos.setX(screenSize.width() - dialog->size().width());
			if (newPos.y()>=screenSize.height())
				newPos.setY(screenSize.height() - dialog->size().height());
			if (newPos != dialog->pos())
				proxy->setPos(newPos);

			proxy->setFocus();
			return;
		}

		QGraphicsWidget* parent = qobject_cast<QGraphicsWidget*>(this->parent());
		dialog = new QDialog(NULL);
		// dialog->setParent(parent);
		StelGui* gui = dynamic_cast<StelGui*>(StelApp::getInstance().getGui());
		Q_ASSERT(gui);
		//dialog->setAttribute(Qt::WA_OpaquePaintEvent, true);
		connect(dialog, SIGNAL(rejected()), this, SLOT(close()));
		createDialogContent();
		dialog->setStyleSheet(gui->getStelStyle().qtStyleSheet);

		proxy = new CustomProxy(parent, Qt::Tool);
		proxy->setWidget(dialog);
		QSizeF size = proxy->size();

		// centre with dialog according to current window size.
		int newX = (int)((screenSize.width() - size.width())/2);
		int newY = (int)((screenSize.height() - size.height())/2);
		// Make sure that the window's title bar is accessible
		if (newY <-0)
			newY = 0;
		proxy->setPos(newX, newY);
		proxy->setWindowFrameMargins(2,0,2,2);
		// (this also changes the bounding rectangle size)

		// The caching is buggy on all plateforms with Qt 4.5.2
		proxy->setCacheMode(QGraphicsItem::ItemCoordinateCache);

		proxy->setZValue(100);
		StelMainView::getInstance().scene()->setActiveWindow(proxy);
		proxy->setFocus();
	}
	else
	{
		dialog->hide();
		emit visibleChanged(false);
		//proxy->clearFocus();
		StelMainView::getInstance().focusSky();
	}
}
void Window::resizeD3D(const QSize &size)
{
    qDebug("resize %d %d", size.width(), size.height());
}
Example #19
0
void Slider::resizeEvent(QResizeEvent *e)
{

	d_resized = TRUE;
	QSize s = e->size();
	int sliderWidth = d_thumbWidth + 2 * d_bwTrough;

	// reposition slider
	if (d_orient == Qt::Horizontal)
	{
		switch (d_scalePos)
		{
			case Top:

				d_sliderRect.setRect(this->rect().x() + d_xMargin,
						this->rect().y() + s.height() - 1
						- d_yMargin - sliderWidth,
						s.width() - 2 * d_xMargin,
						sliderWidth);
				d_scale.setGeometry(d_sliderRect.x() + d_bwTrough + d_thumbHalf,
						d_sliderRect.y() - d_scaleDist,
						d_sliderRect.width() - d_thumbLength - 2 * d_bwTrough,
						ScaleDraw::Top);

				break;

			case Bottom:

				d_sliderRect.setRect(this->rect().x() + d_xMargin,
						this->rect().y() + d_yMargin,
						s.width() - 2 * d_xMargin,
						sliderWidth);
				d_scale.setGeometry(d_sliderRect.x() + d_bwTrough + d_thumbHalf,
						d_sliderRect.y() + d_sliderRect.height() + d_scaleDist,
						d_sliderRect.width() - d_thumbLength - 2 * d_bwTrough,
						ScaleDraw::Bottom);

				break;

			default:
				d_sliderRect.setRect(this->rect().x(), this->rect().x(),
						s.width(), s.height());
				break;
		}
	}
	else
	{
		switch (d_scalePos)
		{
			case Left:
				d_sliderRect.setRect(this->rect().x() + s.width()
						- sliderWidth - 1 - d_xMargin,
						this->rect().y() + d_yMargin,
						sliderWidth,
						s.height() - 2 * d_yMargin);
				d_scale.setGeometry(d_sliderRect.x() - d_scaleDist,
						d_sliderRect.y() + d_thumbHalf + d_bwTrough,
						s.height() - d_thumbLength - 2 * d_bwTrough,
						ScaleDraw::Left);

				break;
			case Right:
				d_sliderRect.setRect(this->rect().x() + d_xMargin,
						this->rect().y() + d_yMargin,
						sliderWidth,
						s.height() - 2 * d_yMargin);
				d_scale.setGeometry(this->rect().x() + d_sliderRect.width()
						+ d_scaleDist,
						d_sliderRect.y() + d_thumbHalf + d_bwTrough,
						s.height() - d_thumbLength - 2 * d_bwTrough,
						ScaleDraw::Right);
				break;
			default:
				d_sliderRect.setRect(this->rect().x(), this->rect().x(),
						s.width(), s.height());
				break;
		}
	}

}
Example #20
0
//===========
// PUBLIC SLOTS
//===========
void LPanel::UpdatePanel(){
  //Create/Update the panel as designated in the Settings file
  settings->sync(); //make sure to catch external settings changes
  //First set the geometry of the panel and send the EWMH message to reserve that space
  if(DEBUG){ qDebug() << "Update Panel"; }
  hidden = settings->value(PPREFIX+"hidepanel",false).toBool(); //default to true for the moment
  QString loc = settings->value(PPREFIX+"location","").toString().toLower();
  if(loc.isEmpty() && defaultpanel){ loc="top"; }
  if(loc=="top" || loc=="bottom"){ 
    horizontal=true; 
    layout->setAlignment(Qt::AlignLeft); 
    layout->setDirection(QBoxLayout::LeftToRight);
  }else{
    horizontal=false;
    layout->setAlignment(Qt::AlignTop);
    layout->setDirection(QBoxLayout::TopToBottom);
  }
  int ht = settings->value(PPREFIX+"height", 30).toInt(); //this is technically the distance into the screen from the edge
  int hidesize = qRound(ht*0.01); //use 1% of the panel size
  if(hidesize<2){ hidesize=2; } //minimum of 2 pixels (need space for the mouse to go over it)
  if(hidden){ viswidth = hidesize; }
  else{ viswidth = ht; }
  if(DEBUG){ qDebug() << "Hidden Panel size:" << hidesize << "pixels"; }
  //qDebug() << " - set Geometry";
  int xwid = screen->screenGeometry(screennum).width();
  int xhi = screen->screenGeometry(screennum).height();
  int xloc = screen->screenGeometry(screennum).x();
  double panelPercent = settings->value(PPREFIX+"lengthPercent",100).toInt();
  if(panelPercent<1 || panelPercent>100){ panelPercent = 100; }
  panelPercent = panelPercent/100.0;
  QString panelPinLoc = settings->value(PPREFIX+"pinLocation","center").toString().toLower(); //[left/right/center] possible values (assume center otherwise)
  //xloc=xoffset;
  if(loc=="top"){ //top of screen
    QSize sz = QSize(xwid*panelPercent, ht);
    if(panelPinLoc=="left"){} // no change to xloc
    else if(panelPinLoc=="right"){ xloc = xloc+xwid-sz.width(); }
    else{ xloc = xloc+((xwid-sz.width())/2) ; } //centered
    this->setMinimumSize(sz);
    this->setMaximumSize(sz);
    this->setGeometry(xloc,0,sz.width(), sz.height());
    if(!hidden){ LX11::ReservePanelLocation(this->winId(), xloc, 0, this->width(), ht, "top"); }
    else{ 
      LX11::ReservePanelLocation(this->winId(), xloc, 0, this->width(), hidesize, "top");
      hidepoint = QPoint(xloc, hidesize-ht);
      showpoint = QPoint(xloc, 0);
      this->move(hidepoint); //Could bleed over onto the screen above
    }
  }else if(loc=="bottom"){ //bottom of screen
    QSize sz = QSize(xwid*panelPercent, ht);
    if(panelPinLoc=="left"){} // no change to xloc
    else if(panelPinLoc=="right"){ xloc = xloc+xwid-sz.width(); }
    else{ xloc = xloc+((xwid-sz.width())/2) ; } //centered
    this->setMinimumSize(sz);
    this->setMaximumSize(sz);
    this->setGeometry(xloc,xhi-ht,sz.width(), ht );
    if(!hidden){ LX11::ReservePanelLocation(this->winId(), xloc, xhi-ht, this->width(), ht, "bottom"); }
    else{ 
      LX11::ReservePanelLocation(this->winId(), xloc, xhi-hidesize, this->width(), hidesize, "bottom"); 
      hidepoint = QPoint(xloc, xhi-hidesize);
      showpoint = QPoint(xloc, xhi-ht);
      this->move(hidepoint); //Could bleed over onto the screen below
    }
  }else if(loc=="left"){ //left side of screen
    QSize sz = QSize(ht, xhi*panelPercent);
    int yloc = 0;
    if(panelPinLoc=="left"){} //this is actually the top (left of center in length dimension)
    else if(panelPinLoc=="right"){ yloc = yloc+xhi-sz.height(); }
    else{ yloc = yloc+((xhi-sz.height())/2) ; } //centered
    this->setMinimumSize(sz);
    this->setMaximumSize(sz);
    this->setGeometry(xloc,yloc, ht, sz.height());
    if(!hidden){ LX11::ReservePanelLocation(this->winId(), xloc, yloc, ht, sz.height(), "left"); }
    else{ 
      LX11::ReservePanelLocation(this->winId(), xloc, yloc, hidesize, sz.height(), "left"); 
      hidepoint = QPoint(xloc-ht+hidesize, yloc);
      showpoint = QPoint(xloc, yloc);
      this->move(hidepoint); //Could bleed over onto the screen left
    }
  }else{ //right side of screen
    QSize sz = QSize(ht, xhi*panelPercent);
    int yloc = 0;
    if(panelPinLoc=="left"){} //this is actually the top (left of center in length dimension)
    else if(panelPinLoc=="right"){ yloc = yloc+xhi-sz.height(); }
    else{ yloc = yloc+((xhi-sz.height())/2) ; } //centered
    this->setMinimumSize(sz);
    this->setMaximumSize(sz);
    this->setGeometry(xloc+xwid-ht,yloc,ht, sz.height());
    if(!hidden){ LX11::ReservePanelLocation(this->winId(), xloc+xwid-ht, yloc, ht, sz.height(), "right"); }  
    else{ 
      LX11::ReservePanelLocation(this->winId(), xloc+xwid-hidesize, yloc, hidesize, sz.height(), "right"); 
      hidepoint = QPoint(xloc+xwid-hidesize, yloc);
      showpoint = QPoint(xloc+xwid-ht, yloc);
      this->move(hidepoint); //Could bleed over onto the screen right
    }
  }
  //With QT5, we need to make sure to reset window properties on occasion
  //LSession::handle()->XCB->SetAsSticky(this->winId()); 
  //LX11::SetAsPanel(this->winId());
  //First test/update all the window attributes as necessary
  //if(!this->testAttribute(Qt::WA_X11DoNotAcceptFocus)){ this->setAttribute(Qt::WA_X11DoNotAcceptFocus); }
  //if(!this->testAttribute(Qt::WA_X11NetWmWindowTypeDock)){ this->setAttribute(Qt::WA_X11NetWmWindowTypeDock); }
  //if(!this->testAttribute(Qt::WA_AlwaysShowToolTips)){ this->setAttribute(Qt::WA_AlwaysShowToolTips); }
  
  //Now update the appearance of the toolbar
  if(settings->value(PPREFIX+"customcolor", false).toBool()){
    QString color = settings->value(PPREFIX+"color", "rgba(255,255,255,160)").toString();
    QString style = "QWidget#LuminaPanelColor{ background: %1; border-radius: 3px; border: 1px solid %1; }";
    style = style.arg(color);
    panelArea->setStyleSheet(style);
  }else{ 
    panelArea->setStyleSheet(""); //clear it and use the one from the theme
  }
  
  //Then go through the plugins and create them as necessary
  QStringList plugins = settings->value(PPREFIX+"pluginlist", QStringList()).toStringList();
  if(defaultpanel && plugins.isEmpty()){
    plugins << "userbutton" << "taskmanager" << "spacer" << "systemtray" << "clock" << "systemdashboard";
  }
  if(DEBUG){ qDebug() << " - Initialize Plugins: " << plugins; }
  for(int i=0; i<plugins.length(); i++){
    //Ensure this plugin has a unique ID (NOTE: this numbering does not persist between sessions)
    if(!plugins[i].contains("---")){
      int num=1;
      while( plugins.contains(plugins[i]+"---"+QString::number(screennum)+"."+QString::number(this->number())+"."+QString::number(num)) ){
        num++;
      }
      
      plugins[i] = plugins[i]+"---"+QString::number(screennum)+"."+QString::number(this->number())+"."+QString::number(num);
      //qDebug() << "Adjust Plugin ID:" << plugins[i];
    }
    //See if this plugin is already there or in a different spot
    bool found = false;
    for(int p=0; p<PLUGINS.length(); p++){
      if(PLUGINS[p]->type()==plugins[i]){
        found = true; //already exists
	//Make sure the plugin layout has the correct orientation
	if(horizontal){PLUGINS[p]->layout()->setDirection(QBoxLayout::LeftToRight); }
	else{ PLUGINS[p]->layout()->setDirection(QBoxLayout::TopToBottom); }
	QTimer::singleShot(0,PLUGINS[p], SLOT( OrientationChange() ) );
	//Now check the location of the plugin in the panel
	if(p!=i){ //wrong place in the panel
	  layout->takeAt(p); //remove the item from the current location
	  layout->insertWidget(i, PLUGINS[p]); //add the item into the correct location
	  PLUGINS.move(p,i); //move the identifier in the list to match
	}
	break;
      }
    }
    if(!found){
      //New Plugin
      if(DEBUG){ qDebug() << " -- New Plugin:" << plugins[i] << i; }
      LPPlugin *plug = NewPP::createPlugin(plugins[i], panelArea, horizontal);
      if(plug != 0){ 
        PLUGINS.insert(i, plug);
        layout->insertWidget(i, PLUGINS[i]);
      }else{
        //invalid plugin type
	plugins.removeAt(i); //remove this invalid plugin from the list
	i--; //make sure we don't miss the next item with the re-order
      }
    }
    LSession::processEvents();
  }
  //Now remove any extra plugins from the end
  //qDebug() << "plugins:" << plugins;
  //qDebug() << "PLUGINS length:" << PLUGINS.length();
  for(int i=0; i<PLUGINS.length(); i++){
    if(plugins.contains(PLUGINS[i]->type())){ continue; } //good plugin - skip it
    if(DEBUG){ qDebug() << " -- Remove Plugin: " << PLUGINS[i]->type(); }
    //If this is the system tray - stop it first
    if( PLUGINS[i]->type().startsWith("systemtray---") ){
      static_cast<LSysTray*>(PLUGINS[i])->stop();
    }
    layout->takeAt(i); //remove from the layout
    delete PLUGINS.takeAt(i); //delete the actual widget
    LSession::processEvents();
    i--; //need to back up one space to not miss another plugin
  }
  this->update();
  this->show(); //make sure the panel is visible now
  if(hidden){ this->move(hidepoint); }
  //Now go through and send the orientation update signal to each plugin
  for(int i=0; i<PLUGINS.length(); i++){
    QTimer::singleShot(0,PLUGINS[i], SLOT(OrientationChange()));
  }
  LSession::processEvents();
}
Example #21
0
QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) {
    QOpenGLFramebufferObject* primaryFBO = Application::getInstance()->getTextureCache()->getPrimaryFramebufferObject();
    primaryFBO->release();
    glBindTexture(GL_TEXTURE_2D, primaryFBO->texture());

    glPushMatrix();
    glLoadIdentity();
    
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    
    glDisable(GL_BLEND);
    glDisable(GL_DEPTH_TEST);
    glDepthMask(GL_FALSE);
    
    QOpenGLFramebufferObject* destFBO = toTexture ?
        Application::getInstance()->getTextureCache()->getSecondaryFramebufferObject() : NULL;
    if (_isEmpty && _renderMode != DIFFUSE_ADD_MODE) {
        // copy the primary to the screen
        if (QOpenGLFramebufferObject::hasOpenGLFramebufferBlit()) {
            QOpenGLFramebufferObject::blitFramebuffer(destFBO, primaryFBO);
                
        } else {
            maybeBind(destFBO);
            glEnable(GL_TEXTURE_2D);
            glDisable(GL_LIGHTING);
            glColor3f(1.0f, 1.0f, 1.0f);
            renderFullscreenQuad();    
            glDisable(GL_TEXTURE_2D);
            glEnable(GL_LIGHTING);
            maybeRelease(destFBO);
        }
    } else if (_renderMode == ADD_MODE) {
        maybeBind(destFBO);
        _addProgram->bind();
        renderFullscreenQuad();
        _addProgram->release();
        maybeRelease(destFBO);
    
    } else if (_renderMode == DIFFUSE_ADD_MODE) {
        // diffuse into the secondary/tertiary (alternating between frames)
        QOpenGLFramebufferObject* oldDiffusedFBO =
            Application::getInstance()->getTextureCache()->getSecondaryFramebufferObject();
        QOpenGLFramebufferObject* newDiffusedFBO =
            Application::getInstance()->getTextureCache()->getTertiaryFramebufferObject();
        if (_isOddFrame) {
            qSwap(oldDiffusedFBO, newDiffusedFBO);
        }
        newDiffusedFBO->bind();
        
        if (_isFirstFrame) {
            glClear(GL_COLOR_BUFFER_BIT);    
            
        } else {
            glActiveTexture(GL_TEXTURE1);
            glBindTexture(GL_TEXTURE_2D, oldDiffusedFBO->texture());
            
            _diffuseProgram->bind();
            QSize size = Application::getInstance()->getGLWidget()->size();
            _diffuseProgram->setUniformValue(_diffusionScaleLocation, 1.0f / size.width(), 1.0f / size.height());
        
            renderFullscreenQuad();
        
            _diffuseProgram->release();
        }
        
        newDiffusedFBO->release();
        
        // add diffused texture to the primary
        glBindTexture(GL_TEXTURE_2D, newDiffusedFBO->texture());
        
        if (toTexture) {
            destFBO = oldDiffusedFBO;
        }
        maybeBind(destFBO);
        _addSeparateProgram->bind();      
        renderFullscreenQuad();
        _addSeparateProgram->release();
        maybeRelease(destFBO);
        
        glBindTexture(GL_TEXTURE_2D, 0);
        glActiveTexture(GL_TEXTURE0);
        
    } else { // _renderMode == BLUR_ADD_MODE || _renderMode == BLUR_PERSIST_ADD_MODE
        // render the primary to the secondary with the horizontal blur
        QOpenGLFramebufferObject* secondaryFBO =
            Application::getInstance()->getTextureCache()->getSecondaryFramebufferObject();
        secondaryFBO->bind();
     
        _horizontalBlurProgram->bind();
        renderFullscreenQuad();
        _horizontalBlurProgram->release();
     
        secondaryFBO->release();
        
        if (_renderMode == BLUR_ADD_MODE) {
            // render the secondary to the screen with the vertical blur
            glActiveTexture(GL_TEXTURE1);
            glBindTexture(GL_TEXTURE_2D, secondaryFBO->texture());
            
            if (toTexture) {
                destFBO = Application::getInstance()->getTextureCache()->getTertiaryFramebufferObject();
            }
            maybeBind(destFBO);
            _verticalBlurAddProgram->bind();      
            renderFullscreenQuad();
            _verticalBlurAddProgram->release();
            maybeRelease(destFBO);
            
        } else { // _renderMode == BLUR_PERSIST_ADD_MODE
            // render the secondary to the tertiary with vertical blur and persistence
            QOpenGLFramebufferObject* tertiaryFBO =
                Application::getInstance()->getTextureCache()->getTertiaryFramebufferObject();
            tertiaryFBO->bind();
            
            glEnable(GL_BLEND);
            glBlendFunc(GL_ONE_MINUS_CONSTANT_ALPHA, GL_CONSTANT_ALPHA);
            const float PERSISTENCE_SMOOTHING = 0.9f;
            glBlendColor(0.0f, 0.0f, 0.0f, _isFirstFrame ? 0.0f : PERSISTENCE_SMOOTHING);
            
            glBindTexture(GL_TEXTURE_2D, secondaryFBO->texture());
            
            _verticalBlurProgram->bind();      
            renderFullscreenQuad();
            _verticalBlurProgram->release();
        
            glBlendColor(0.0f, 0.0f, 0.0f, 0.0f);
            glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_CONSTANT_ALPHA, GL_ONE);
            glDisable(GL_BLEND);
        
            // now add the tertiary to the primary buffer
            tertiaryFBO->release();
            
            glBindTexture(GL_TEXTURE_2D, primaryFBO->texture());
            
            glActiveTexture(GL_TEXTURE1);
            glBindTexture(GL_TEXTURE_2D, tertiaryFBO->texture());
            
            maybeBind(destFBO);
            _addSeparateProgram->bind();      
            renderFullscreenQuad();
            _addSeparateProgram->release();
            maybeRelease(destFBO);
        }
        
        glBindTexture(GL_TEXTURE_2D, 0);
        glActiveTexture(GL_TEXTURE0);
    }
    
    glPopMatrix();
    
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
       
    glEnable(GL_BLEND);
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);
    glBindTexture(GL_TEXTURE_2D, 0);
    
    _isFirstFrame = false;
    
    return destFBO;
}
void KisCubismFilter::cubism(KisPaintDeviceSP src,
                             const QPoint& srcTopLeft,
                             KisPaintDeviceSP dst,
                             const QPoint& dstTopLeft,
                             const QSize& size,
                             quint32 tileSize,
                             quint32 tileSaturation) const
{
    Q_ASSERT(src);
    Q_ASSERT(dst);

    //fill the destination image with the background color (black for now)
    KisRectIteratorPixel dstIt = dst->createRectIterator(dstTopLeft.x(), dstTopLeft.y(), size.width(), size.height());
    qint32 depth = src->colorSpace()->colorChannelCount();
    while (! dstIt.isDone()) {
        for (qint32 i = 0; i < depth; i++) {
            dstIt.rawData()[i] = 0;
        }
        ++dstIt;
    }

    //compute number of rows and columns
    qint32 cols = (size.width() + tileSize - 1) / tileSize;
    qint32 rows = (size.height() + tileSize - 1) / tileSize;
    qint32 numTiles = (rows + 1) * (cols + 1);

//         setProgressTotalSteps(numTiles);
//         setProgressStage(i18n("Applying cubism filter..."),0);

    qint32* randomIndices = new qint32[numTiles];
    for (qint32 i = 0; i < numTiles; i++) {
        randomIndices[i] = i;
    }
    randomizeIndices(numTiles, randomIndices);

    qint32 count = 0;
    qint32 i, j, ix, iy;
    double x, y, width, height, theta;
    KisPolygon *poly = new KisPolygon();
    qint32 pixelSize = src->pixelSize();
    const quint8 *srcPixel /*= new quint8[ pixelSize ]*/;
    quint8 *dstPixel = 0;
    KisRandomAccessor srcAccessor = src->createRandomAccessor(0, 0);
    while (count < numTiles) {
        i = randomIndices[count] / (cols + 1);
        j = randomIndices[count] % (cols + 1);
        x = j * tileSize + (tileSize / 4.0) - randomDoubleNumber(0, tileSize / 2.0) + dstTopLeft.x();
        y = i * tileSize + (tileSize / 4.0) - randomDoubleNumber(0, tileSize / 2.0) + dstTopLeft.y();
        width = (tileSize + randomDoubleNumber(0, tileSize / 4.0) - tileSize / 8.0) * tileSaturation;
        height = (tileSize + randomDoubleNumber(0, tileSize / 4.0) - tileSize / 8.0) * tileSaturation;
        theta = randomDoubleNumber(0, 2 * M_PI);
        poly->clear();
        poly->addPoint(-width / 2.0, -height / 2.0);
        poly->addPoint(width / 2.0, -height / 2.0);
        poly->addPoint(width / 2.0, height / 2.0);
        poly->addPoint(-width / 2.0, height / 2.0);
        poly->rotate(theta);
        poly->translate(x, y);
        //  bounds check on x, y
        ix = (qint32) CLAMP(x, dstTopLeft.x(), dstTopLeft.x() + size.width() - 1);
        iy = (qint32) CLAMP(y, dstTopLeft.y(), dstTopLeft.y() + size.height() - 1);

        //read the pixel at ix, iy
        srcAccessor.moveTo(ix, iy);
        srcPixel = srcAccessor.rawData();
        if (srcPixel[pixelSize - 1]) {
            fillPolyColor(src, srcTopLeft, dst, dstTopLeft, size, poly, srcPixel, dstPixel);
        }
        count++;
//                 if ((count % 5) == 0) setProgress(count);
    }

}
Example #23
0
void QToolButtonPrivate::popupTimerDone()
{
    Q_Q(QToolButton);
    popupTimer.stop();
    if (!menuButtonDown && !down)
        return;

    menuButtonDown = true;
    QPointer<QMenu> actualMenu;
    bool mustDeleteActualMenu = false;
    if(menuAction) {
        actualMenu = menuAction->menu();
    } else if (defaultAction && defaultAction->menu()) {
        actualMenu = defaultAction->menu();
    } else {
        actualMenu = new QMenu(q);
        mustDeleteActualMenu = true;
        for(int i = 0; i < actions.size(); i++)
            actualMenu->addAction(actions.at(i));
    }
    repeat = q->autoRepeat();
    q->setAutoRepeat(false);
    bool horizontal = true;
#if !defined(QT_NO_TOOLBAR)
    QToolBar *tb = qobject_cast<QToolBar*>(parent);
    if (tb && tb->orientation() == Qt::Vertical)
        horizontal = false;
#endif
    QPoint p;
    QRect screen = QApplication::desktop()->availableGeometry(q);
    QSize sh = ((QToolButton*)(QMenu*)actualMenu)->receivers(SIGNAL(aboutToShow()))? QSize() : actualMenu->sizeHint();
    QRect rect = q->rect();
    if (horizontal) {
        if (q->isRightToLeft()) {
            if (q->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height()) {
                p = q->mapToGlobal(rect.bottomRight());
            } else {
                p = q->mapToGlobal(rect.topRight() - QPoint(0, sh.height()));
            }
            p.rx() -= sh.width();
        } else {
            if (q->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height()) {
                p = q->mapToGlobal(rect.bottomLeft());
            } else {
                p = q->mapToGlobal(rect.topLeft() - QPoint(0, sh.height()));
            }
        }
    } else {
        if (q->isRightToLeft()) {
            if (q->mapToGlobal(QPoint(rect.left(), 0)).x() - sh.width() <= screen.x()) {
                p = q->mapToGlobal(rect.topRight());
            } else {
                p = q->mapToGlobal(rect.topLeft());
                p.rx() -= sh.width();
            }
        } else {
            if (q->mapToGlobal(QPoint(rect.right(), 0)).x() + sh.width() <= screen.right()) {
                p = q->mapToGlobal(rect.topRight());
            } else {
                p = q->mapToGlobal(rect.topLeft() - QPoint(sh.width(), 0));
            }
        }
    }
    p.rx() = qMax(screen.left(), qMin(p.x(), screen.right() - sh.width()));
    p.ry() += 1;
    QPointer<QToolButton> that = q;
    actualMenu->setNoReplayFor(q);
    if (!mustDeleteActualMenu) //only if action are not in this widget
        QObject::connect(actualMenu, SIGNAL(triggered(QAction*)), q, SLOT(_q_menuTriggered(QAction*)));
    QObject::connect(actualMenu, SIGNAL(aboutToHide()), q, SLOT(_q_updateButtonDown()));
    actualMenu->d_func()->causedPopup.widget = q;
    actualMenu->d_func()->causedPopup.action = defaultAction;
    actionsCopy = q->actions(); //(the list of action may be modified in slots)
    actualMenu->exec(p);

    if (!that)
        return;

    QObject::disconnect(actualMenu, SIGNAL(aboutToHide()), q, SLOT(_q_updateButtonDown()));
    if (mustDeleteActualMenu)
        delete actualMenu;
    else
        QObject::disconnect(actualMenu, SIGNAL(triggered(QAction*)), q, SLOT(_q_menuTriggered(QAction*)));

    actionsCopy.clear();

    if (repeat)
        q->setAutoRepeat(true);
}
void KisCubismFilter::process(KisConstProcessingInformation srcInfo,
                              KisProcessingInformation dstInfo,
                              const QSize& size,
                              const KisFilterConfiguration* configuration,
                              KoUpdater* progressUpdater
                             ) const
{
    Q_UNUSED(progressUpdater);

    const KisPaintDeviceSP src = srcInfo.paintDevice();
    KisPaintDeviceSP dst = dstInfo.paintDevice();
    QPoint dstTopLeft = dstInfo.topLeft();
    QPoint srcTopLeft = srcInfo.topLeft();
    Q_ASSERT(src);
    Q_ASSERT(dst);
    Q_ASSERT(configuration);

    //read the filter configuration values from the KisFilterConfiguration object
    quint32 tileSize = configuration->getInt("tileSize", 1);
    quint32 tileSaturation = configuration->getInt("tileSaturation");

    if (srcInfo.selection()) {

        KisPaintDeviceSP dev = new KisPaintDevice(src->colorSpace());

        cubism(src, srcTopLeft, dev, dstTopLeft, size, tileSize, tileSaturation);

        KisPainter gc(dst);
        gc.setSelection(srcInfo.selection());
        gc.bitBlt(dstTopLeft.x(), dstTopLeft.y(), dev, dstTopLeft.x(), dstTopLeft.y(), size.width(), size.height());
        gc.end();
    } else {
        cubism(src, srcTopLeft, dst, dstTopLeft, size, tileSize, tileSaturation);
    }
}
Example #25
0
void autofix(QString originalFileName, int numFiles, QSize size)
{
    std::cout << "Autofixing " << numFiles << size.width() << "x" << size.height()
              << " thumbnails of " << originalFileName.toLocal8Bit().constData() << "\n";

    QEventLoop loop;
    QTime time;

    Quill::setTemporaryFilePath(QDir::homePath() + Strings::testsTempDir);
    Quill::setPreviewSize(0, size);

    QString fileName[numFiles];
    QuillFile *quillFile[numFiles];

    for (int i=0; i<numFiles; i++) {
        {   // Needed for the life of the QTemporaryFile
            QTemporaryFile file;
            file.setFileTemplate(QDir::homePath() + Strings::testsTempFilePattern);
            file.open();
            fileName[i] = file.fileName();
            file.close();
        }
        QFile::remove(fileName[i]);
        QFile::copy(originalFileName, fileName[i]);
    }

    time.start();

    for (int i=0; i<numFiles; i++) {
        quillFile[i] = new QuillFile(fileName[i], Strings::jpegMimeType);
        QObject::connect(quillFile[i], SIGNAL(imageAvailable(const QuillImageList)),
                         &loop, SLOT(quit()));
    }

    int initTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        quillFile[i]->setDisplayLevel(0);

    int displayLevelTime = time.elapsed();

    do
        loop.exec();
    while (Quill::isCalculationInProgress());

    int prepareTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        if (quillFile[i]->image(0).isNull()) {
            std::cout<<"Error: not all images are loaded!\n";
            return;
        }

    time.restart();

    for (int i=0; i<numFiles; i++) {
        QuillImageFilter *filter =
            QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_AutoLevels);
        quillFile[i]->runFilter(filter);
    }

    do
        loop.exec();
    while (Quill::isCalculationInProgress());

    int finalTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        if (quillFile[i]->image(0).isNull()) {
            std::cout<<"Error: not all images are edited!\n";
            return;
        }

    std::cout << "Initialize " << numFiles << " QuillFiles: "
             << initTime << "ms" << "\n";

    std::cout << "Set display levels of " << numFiles << " QuillFiles: "
             << displayLevelTime - initTime << "ms" << "\n";

    std::cout << "Total prepare " << numFiles << " QuillFiles: "
             << prepareTime << "ms" << "\n";

    std::cout << "Use case edit response for " << numFiles << " QuillFiles: "
             << finalTime << "ms" << "\n";

    for (int i=0; i<numFiles; i++) {
        delete quillFile[i];
        QFile::remove(fileName[i]);
    }
}
Example #26
0
inline
bool operator<(QSize const& lhs, QSize const& rhs)
{
    return (lhs.width() + lhs.height()) > (rhs.width() + rhs.height()); // yes, inverse
}
Example #27
0
void LogScene::getTaskItem(const QModelIndex &index) {
    Task* task = _model->task(index);

    Calendar* calendar = task->project()->projectDefaultCalendar();
    int hoursInDay = calendar->endHour().hour() - calendar->startHour().hour();
    std::vector<TaskLog*>* logs =task->logs();
    double startHour = 0;//calendar->startHour().hour();
    double endHour = 24;//calendar->endHour().hour() + 1;
    double minuteSize = (double)24*BLOCKSIZE / (double)((endHour - startHour) * 60);
    int red = 0;
    for (std::vector<TaskLog*>::iterator iter = logs->begin(); iter != logs->end(); iter++) {
        TaskLog* log = *iter;

        QSize size = sizeHint(index);

        int bordermargin = (size.height() * .4) / 2;

        int daysToStart = _startDate.daysTo(*log->start);
        double x1 = (double)daysToStart * (double)_dayWidth;
        DTime logStartTime = log->start->time();
        double y1 = (double)(logStartTime.totalMinutes() - (startHour*60)) * minuteSize;

        double x2 = (daysToStart + 1) * (double)_dayWidth;
        DTime logEndTime = log->end->time();
        if (log->end->getDay() != log->start->getDay()) {
            logEndTime = DTime(23, 59, 59);
        }
        double y2 = (double)(logEndTime.totalMinutes() - (startHour*60)) * minuteSize;

        QBrush b(task->taskColor());//QImage(":/img/task_bar.png"));//(QPixmap(":/img/task_bar.png"));
        red += 20;
        QColor penColor((task->taskColor().red() < 100) ? 0: (task->taskColor().red() - 100),
                        (task->taskColor().green() < 100) ? 0: (task->taskColor().green() - 100),
                        (task->taskColor().blue() < 100) ? 0: (task->taskColor().blue() - 100));
        QPen pen(penColor);
        if (log->activeLog) {
            pen.setWidth(3);
        }

        QGraphicsItem* item = this->addRect(x1, y1, (x2 - x1), (y2 - y1), pen, b);
        item->setZValue(1);
        if ((y2 - y1) > 20) {
            QFont f("Arial", 8);
            f.setWeight(QFont::Light);
            QBrush brush(penColor);

            std::string description = *task->shortDescription();
            int textY = y1 + 5;
            while (description.length() > 0) {
                std::string label;
                if (description.length() > 15) {
                    label = description.substr(0, 15);
                    description = description.substr(15);
                    if ((label.at(label.length() - 1) != ' ') &&
                        (description.at(0) != ' ')) {
                        int pos;
                        if ((pos = label.rfind(' ')) != std::string::npos) {
                            description = label.substr(pos) + description;
                            label = label.substr(0, pos);
                        }
                    }
                } else {
                    label = description;
                    description = "";
                }
                label = label.erase(label.find_last_not_of(" \n\r\t")+1);
                description = description.erase(description.find_last_not_of(" \n\r\t")+1);
                if ((textY + 20) < y2) {
                    QGraphicsSimpleTextItem* text = this->addSimpleText(tr(label.c_str()));
                    text->setPos(x1 + 10, textY);
                    //text->rotate(90);
                    text->setVisible(true);
                    text->setBrush(brush);
                    text->setFont(f);
                    text->setZValue(2);
                    textY += 15;
                } else {
                    break;
                }
            }
        }
        _currentY += sizeHint(index).height();
    }
    delete(logs);
}
Example #28
0
 QString pmcKey(const QSize &size, QIcon::Mode mode, QIcon::State state)
     { return QLatin1String("$qt_svgicon_")
              + QString::number(serialNum, 16).append(QLatin1Char('_'))
              + QString::number((((((size.width()<<11)|size.height())<<11)|mode)<<4)|state, 16); }
Example #29
0
bool ViewAreaImpl::viewTabMouseMoveEvent(ViewPane* pane, QMouseEvent* event)
{
    if(!isViewDragging){
        if(event->buttons() & Qt::LeftButton){
            if((event->pos() - tabDragStartPosition).manhattanLength() > QApplication::startDragDistance()){
                if(!pane->tabBar()->geometry().contains(event->pos())){
                    if(draggedView = pane->currentView()){
                        isViewDragging = true;
                        dragSrcPane = pane;

                        QWidget* toplevel = pane;
                        while(toplevel->parentWidget()){
                            toplevel = toplevel->parentWidget();
                        }
                        QSize s = toplevel->frameGeometry().size();
                        draggedViewWindowSize.setWidth(draggedView->width() + s.width() - toplevel->width());
                        draggedViewWindowSize.setHeight(draggedView->height() + s.height() - toplevel->height());
                        
                        QApplication::setOverrideCursor(Qt::ClosedHandCursor);
                    }
                }
            }
        }
    } else {
        ViewArea* prevViewArea = dragDestViewArea;
        dragDestViewArea = 0;
        dragDestPane = 0;

        // find a window other than the rubber band
        QPoint p = event->globalPos();
        QWidget* window = 0;
        for(int i=0; i < 3; ++i){
            window = QApplication::topLevelAt(p);
            if(window && !dynamic_cast<QRubberBand*>(window)){
                break;
            }
            p += QPoint(-1, -1);
        }
        if(window){
            dragDestViewArea = dynamic_cast<ViewArea*>(window);
            if(!dragDestViewArea){
                if(MainWindow* mainWindow = dynamic_cast<MainWindow*>(window)){
                    ViewArea* viewArea = mainWindow->viewArea();
                    if(viewArea->rect().contains(viewArea->mapFromGlobal(event->globalPos()))){
                        dragDestViewArea = viewArea;
                    }
                }
            }
        }
        if(dragDestViewArea){
            QWidget* pointed = dragDestViewArea->childAt(dragDestViewArea->mapFromGlobal(event->globalPos()));
            while(pointed){
                dragDestPane = dynamic_cast<ViewPane*>(pointed);
                if(dragDestPane){
                    dragView(event);
                    break;
                }
                pointed = pointed->parentWidget();
            }
        } else {
            dragViewOutside(event->globalPos());
        }
        if(prevViewArea != dragDestViewArea){
            if(prevViewArea){
                prevViewArea->impl->rubberBand->hide();
            } else {
                rubberBand->hide();
            }
        }
    }
    return false;
}
Example #30
0
void TopBar::themeChange()
{
    m_titleFont = Theme::p()->font(Theme::TitleBar);
    m_statusFont = Theme::p()->font(Theme::StatusBar);

    //Calculate the scaling factor
    QHash<QString, QSize>sizes = (Theme::p()->theme() == Theme::Blue) ?
        m_sizesBlue : m_sizesLime;

    QString topbarString= m_orientation == TopBar::Portrait ?
            "topbar.svg" : "topbar_horisontal.svg";

    QSize topBarSize = sizes[topbarString];
    QSize newSize = QSize(topBarSize);

    //Scale according to aspect ratio
    newSize.scale(size().toSize(), Qt::KeepAspectRatio);

    //fix width to window widht if previous scaling produced too narrow image
    if(newSize.width() < size().width()) {
        newSize.scale(size().toSize(), Qt::KeepAspectRatioByExpanding);
    }

    //Calculate scaling factor for rest of the graphics scaling
    qreal scaleFactor = (newSize.width() *1.0) / (topBarSize.width() * 1.0);

    //Background
    m_topBarPixmap = Theme::p()->pixmap(topbarString, sizes[topbarString] * scaleFactor);

    //User Icon
    m_topBarUserIcon = Theme::p()->pixmap("user_default_icon.svg", sizes["user_default_icon.svg"] * scaleFactor);

    //User Status
    m_topBarUserStatus = Theme::p()->pixmap("user_status_online.svg", sizes["user_status_online.svg"] * scaleFactor);

    //Status Bar
    m_topBarStatusBarLeft = Theme::p()->pixmap("status_field_left.svg", sizes["status_field_left.svg"] * scaleFactor);
    m_topBarStatusBarRight = Theme::p()->pixmap("status_field_right.svg", sizes["status_field_right.svg"] * scaleFactor);
    m_topBarStatusBarMiddle = Theme::p()->pixmap("status_field_middle.svg",
            QSize(185, sizes["status_field_middle.svg"].height())* scaleFactor);

    //Update Drawing points for Top Bar elements, points are relative to the top bar background size
    QSize topBarPixmapSize = m_topBarPixmap.size();
    QSize topBarUserIconSize = m_topBarUserIcon.size();
    QSize topBarUserStatusSize = m_topBarUserStatus.size();
    QSize topBarStatusBarLeftSize = m_topBarStatusBarLeft.size();
    QSize topBarStatusBarMiddleSize = m_topBarStatusBarMiddle.size();

    //Theme Check
    (Theme::p()->theme() == Theme::Lime) ? m_isLimeTheme = true : m_isLimeTheme = false;

    //User Icon location
    //Placing 70% of the width and 10% of the height of the top bar background
    m_topBarUserIconPoint = QPoint((0.7*topBarPixmapSize.width()), (0.1*topBarPixmapSize.height()));

    //If Blue theme is in use - position user status icon on the right side of the user icon
    if(!m_isLimeTheme) {
        //Place the status icon on top of the right edge of the user icon, lower it by 35% of the height of the user icon
        m_topBarUserStatusPoint = QPoint( ( (m_topBarUserIconPoint.x()+topBarUserIconSize.width() ) - ( topBarUserStatusSize.width()/2 )),
            (m_topBarUserIconPoint.y() + (topBarUserIconSize.height() * 0.35 )));
    }
    //If Lime theme is in use - position user status icon on the left side of the user icon
    else {
        //Place the status icon on top of the left side of the user icon, lower it by 50% of the height of the user icon
        //and move left by 5% of the icon
        m_topBarUserStatusPoint = QPoint(  m_topBarUserIconPoint.x() + ( topBarUserIconSize.width() * 0.05),
                    (m_topBarUserIconPoint.y() + (topBarUserIconSize.height() * 0.5 )));
    }

    //Status bar
    //Placing the left side of the status bar  5% of the width, 50% of the height of the top bar background
    //Set the text baseline 80% of the height of the status bar
    m_topBarStatusBarLeftPoint = QPoint( (topBarPixmapSize.width()* 0.05),
                                                    (topBarPixmapSize.height() * 0.5));
    m_topBarStatusBarMiddlePoint = QPoint( (m_topBarStatusBarLeftPoint.x() + topBarStatusBarLeftSize.width()),
                                                        (m_topBarStatusBarLeftPoint.y()));
    m_topBarStatusBarRightPoint = QPoint( (m_topBarStatusBarMiddlePoint.x() + topBarStatusBarMiddleSize.width()),
                                                    (m_topBarStatusBarMiddlePoint.y() ) );
    m_topBarStatusBarTextPoint = QPoint(m_topBarStatusBarMiddlePoint.x(),
                                                    m_topBarStatusBarMiddlePoint.y() + (topBarStatusBarMiddleSize.height()*0.8) );

    update();
}