void ContactInfoDialog::Private::addStateRow(const QString& description, Tp::Contact::PresenceState state)
{
    QLabel *descriptionLabel = new QLabel(description, q);

    QIcon icon;
    switch (state) {
        case Tp::Contact::PresenceStateYes:
            icon = QIcon::fromTheme(QStringLiteral("task-complete"));
            break;
        case Tp::Contact::PresenceStateNo:
            icon = QIcon::fromTheme(QStringLiteral("task-reject"));
            break;
        case Tp::Contact::PresenceStateAsk:
        default:
            icon = QIcon::fromTheme(QStringLiteral("task-attempt"));
            break;
    }

    QLabel *stateLabel = new QLabel(q);
    stateLabel->setPixmap(icon.pixmap(16));

    stateLayout->addRow(descriptionLabel, stateLabel);
}
PersonPresentationWidget::PersonPresentationWidget(const QString &name, const QIcon &avatar, QWidget *parent)
    : QWidget(parent)
{
    setLayout(new QHBoxLayout(this));

    m_email = new QLabel(this);
    m_phone = new QLabel(this);
    m_name = new QLabel(this);
    m_pixmap = new QLabel(this);

    m_selected = new QCheckBox(this);
    m_selected->setChecked(true);

    m_name->setText(name);

    // Scaling the pixmap size to the name font
    int pixmapHeight = m_name->fontMetrics().height()*3;
    QSize pixSize(pixmapHeight,pixmapHeight);

    m_pixmap->setPixmap( avatar.pixmap(pixSize)
                .scaled(pixSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    draw() ;
}
FilterLineEdit::FilterLineEdit(QWidget *parent) :
    FancyLineEdit(parent),
    m_lastFilterText(text())
{
    // KDE has custom icons for this. Notice that icon namings are counter intuitive
    // If these icons are not avaiable we use the freedesktop standard name before
    // falling back to a bundled resource
    QIcon icon = QIcon::fromTheme(layoutDirection() == Qt::LeftToRight ?
                                  QLatin1String("edit-clear-locationbar-rtl") :
                                  QLatin1String("edit-clear-locationbar-ltr"),
                                  QIcon::fromTheme(QLatin1String("edit-clear"), QIcon(QLatin1String(":/fatrat/editclear.png"))));

    QPixmap pixmap = icon.pixmap(16);
    setButtonPixmap(Right, pixmap);
    setButtonVisible(Right, true);
#if QT_VERSION >= 0x040700
    setPlaceholderText(tr("Filter"));
#endif
    setButtonToolTip(Right, tr("Clear text"));
    setAutoHideButton(Right, true);
    connect(this, SIGNAL(rightButtonClicked()), this, SLOT(clear()));
    connect(this, SIGNAL(textChanged(QString)), this, SLOT(slotTextChanged()));
}
    void DiscoveryDiagnosticDialog::connectionResult(bool suc, qint64 mstimeExecute, const QString& resultText, std::vector<ServerDiscoveryInfoSPtr> infos)
    {
        glassWidget_->stop();

        executeTimeLabel_->setText(timeTemplate.arg(mstimeExecute));
        listWidget_->setEnabled(suc);
        listWidget_->clear();
        if(suc){
            QIcon icon = GuiFactory::instance().successIcon();
            const QPixmap pm = icon.pixmap(stateIconSize);
            iconLabel_->setPixmap(pm);

            for(int i = 0; i < infos.size(); ++i){
                ServerDiscoveryInfoSPtr inf = infos[i];
                common::net::hostAndPort host = inf->host();
                IConnectionSettingsBaseSPtr con(IConnectionSettingsRemote::createFromType(inf->connectionType(), inf->name(), host));
                ConnectionListWidgetItemEx* item = new ConnectionListWidgetItemEx(con, inf->type());
                item->setDisabled(inf->self() || cluster_->findSettingsByHost(host));
                listWidget_->addTopLevelItem(item);
            }
        }
        statusLabel_->setText(connectionStatusTemplate.arg(resultText));
    }
void UIGInformationElement::setIcon(const QIcon &icon)
{
    /* Cache icon: */
    if (icon.isNull())
    {
        /* No icon provided: */
        m_pixmapSize = QSize();
        m_pixmap = QPixmap();
    }
    else
    {
        /* Determine default the icon size: */
        const QStyle *pStyle = QApplication::style();
        const int iIconMetric = pStyle->pixelMetric(QStyle::PM_SmallIconSize);
        m_pixmapSize = QSize(iIconMetric, iIconMetric);
        /* Acquire the icon of the corresponding size: */
        m_pixmap = icon.pixmap(m_pixmapSize);
    }

    /* Update linked values: */
    updateMinimumHeaderWidth();
    updateMinimumHeaderHeight();
}
Beispiel #6
0
ConfigureDialog::ConfigureDialog() 
	: QDialog(NULL)
	, m_nUpdates(0)
	, m_parentItem(NULL)
{
    setupUi(this);
    setWindowIcon(Icon("configure"));
    setButtonsPict(this);
    setTitle();
    lstBox->header()->hide();
    QIcon iconSet = Icon("webpress");
    if (!iconSet.pixmap(QSize(16,16), QIcon::Normal).isNull())
        btnUpdate->setIcon(iconSet);
    btnUpdate->hide();
    lstBox->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    fill(0);
    connect(buttonApply, SIGNAL(clicked()), this, SLOT(apply()));
    connect(btnUpdate, SIGNAL(clicked()), this, SLOT(updateInfo()));
    connect(lstBox, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)),
            this, SLOT(itemSelected(QTreeWidgetItem*, QTreeWidgetItem*)));
    lstBox->setCurrentItem(lstBox->topLevelItem(0));
    itemSelected(lstBox->topLevelItem(0), 0);
}
Beispiel #7
0
    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {
        if (!index.isValid()) {
            return QSize(0, 0);
        }

        const QString text = index.model()->data(index, Qt::DisplayRole).toString();
        const QIcon icon = index.model()->data(index, Qt::DecorationRole).value<QIcon>();
        const QPixmap pixmap = icon.pixmap(iconSize, iconSize);

        QFontMetrics fm = option.fontMetrics;
        int gap = fm.height();
        int wp = pixmap.width();
        int hp = pixmap.height();

        if (hp == 0) {
            /**
            * No pixmap loaded yet, we'll use the default icon size in this case.
            */
            hp = iconSize;
            wp = iconSize;
        }

        QTextLayout iconTextLayout(text, option.font);
        int wt = layoutText(&iconTextLayout, qMax(3 * wp, 8 * fm.height()));
        int ht = iconTextLayout.boundingRect().height();

        int width, height;
        if (text.isEmpty()) {
            height = hp;
        } else {
            height = hp + ht + 10;

        }

        width = qMax(wt, wp) + gap;
        return QSize(width, height);
    }
void QExtMouse3DLinuxInputDevice::setWidget(QWidget *widget)
{
    QExtMouse3DDevice::setWidget(widget);
    if (isOpen && !widget) {
        // Close the device - we don't need it any more.
        delete notifier;
        ::close(fd);
        notifier = 0;
        fd = -1;
        isOpen = false;
    } else if (!isOpen && widget) {
        // Attempt to open the device.
        int fd = ::open(devName.toLatin1().constData(), O_RDONLY | O_NONBLOCK, 0);
        if (fd >= 0) {
            isOpen = true;
            initDevice(fd);
        }
    }
    if (lcdScreen) {
        lcdScreen->setActive(widget != 0);
        if (widget) {
            QWidget *window = widget->window();
            QString title = window->windowIconText();
            if (title.isEmpty())
                title = window->windowTitle();
            lcdScreen->setTitle(title);
            QIcon icon = window->windowIcon();
            if (icon.isNull())
                lcdScreen->setImage(QImage());
            else
                lcdScreen->setImage(icon.pixmap(128, 128).toImage());
            lcdScreen->update();
        } else {
            lcdScreen->setTitle(QString());
        }
    }
}
Beispiel #9
0
QPixmap IconProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
{
//qDebug() << id << requestedSize;
    // absolute path: just load the image
    if (id.startsWith('/')) {
        QPixmap ret(id);
        if (ret.width() > requestedSize.width() || ret.height() > requestedSize.height())
            ret = ret.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        if (size)
            *size = ret.size();
        return ret;
    }
    // main strategy: QIcon usually knows how to find it
    QIcon icon = QIcon::fromTheme(id);
//    QIcon icon = XdgIcon::fromTheme(id, XdgIcon::defaultApplicationIcon()); // often not working well
    // fall back to /usr/share/pixmaps if nothing found yet
    if (icon.isNull()) {
        QStringList p = UsrSharePixmaps.entryList({id + "*"}, QDir::Files);
        if (!p.isEmpty()) {
            QPixmap ret(UsrSharePixmaps.filePath(p.first()));
            if (ret.width() > requestedSize.width() || ret.height() > requestedSize.height())
                ret = ret.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            if (size)
                *size = ret.size();
            return ret;
        }
    }
    // default app icon if all else fails
    if (icon.isNull()) {
        qWarning() << "failed to find icon" << id;
        icon = QIcon::fromTheme(XdgIcon::defaultApplicationIconName());
    }
    QPixmap ret = icon.pixmap(requestedSize);
    if (size)
        *size = ret.size();
    return ret;
}
Beispiel #10
0
MinecraftProcess *LegacyInstance::prepareForLaunch(AuthSessionPtr account)
{
	MinecraftProcess *proc = new MinecraftProcess(this);

	QIcon icon = MMC->icons()->getIcon(iconKey());
	auto pixmap = icon.pixmap(128, 128);
	pixmap.save(PathCombine(minecraftRoot(), "icon.png"), "PNG");

	// create the launch script
	QString launchScript;
	{
		// window size
		QString windowParams;
		if (settings().get("LaunchMaximized").toBool())
			windowParams = "max";
		else
			windowParams = QString("%1x%2")
							   .arg(settings().get("MinecraftWinWidth").toInt())
							   .arg(settings().get("MinecraftWinHeight").toInt());

		QString lwjgl = QDir(MMC->settings()->get("LWJGLDir").toString() + "/" + lwjglVersion())
							.absolutePath();
		launchScript += "userName " + account->player_name + "\n";
		launchScript += "sessionId " + account->session + "\n";
		launchScript += "windowTitle " + windowTitle() + "\n";
		launchScript += "windowParams " + windowParams + "\n";
		launchScript += "lwjgl " + lwjgl + "\n";
		launchScript += "launcher legacy\n";
	}
	proc->setLaunchScript(launchScript);

	// set the process work path
	proc->setWorkdir(minecraftRoot());

	return proc;
}
Beispiel #11
0
void ToolTipItem::addToolTip(const QString &toolTip, const QIcon &icon, const QPixmap *pixmap)
{
	QGraphicsPixmapItem *iconItem = 0, *pixmapItem = 0;
	double yValue = title->boundingRect().height() + SPACING;
	Q_FOREACH (ToolTip t, toolTips) {
		yValue += t.second->boundingRect().height();
	}
	if (!icon.isNull()) {
		iconItem = new QGraphicsPixmapItem(icon.pixmap(ICON_SMALL, ICON_SMALL), this);
		iconItem->setPos(SPACING, yValue);
	} else {
		if (pixmap && !pixmap->isNull()) {
			pixmapItem = new QGraphicsPixmapItem(*pixmap, this);
			pixmapItem->setPos(SPACING, yValue);
		}
	}

	QGraphicsSimpleTextItem *textItem = new QGraphicsSimpleTextItem(toolTip, this);
	textItem->setPos(SPACING + ICON_SMALL + SPACING, yValue);
	textItem->setBrush(QBrush(Qt::white));
	textItem->setFlag(ItemIgnoresTransformations);
	toolTips.push_back(qMakePair(iconItem, textItem));
	expand();
}
Beispiel #12
0
void RoutingLayerPrivate::renderPlacemarks( GeoPainter *painter )
{
    m_placemarks.clear();
    painter->setPen( QColor( Qt::black ) );
    for ( int i = 0; i < m_placemarkModel->rowCount(); ++i ) {
        QModelIndex index = m_placemarkModel->index( i, 0 );
        QVariant data = index.data( MarblePlacemarkModel::CoordinateRole );
        if ( index.isValid() && !data.isNull() ) {
            GeoDataCoordinates pos = qVariantValue<GeoDataCoordinates>( data );

            QPixmap pixmap = qVariantValue<QPixmap>( index.data( Qt::DecorationRole ) );
            if ( !pixmap.isNull() && m_selectionModel->isSelected( index ) ) {
                QIcon selected = QIcon( pixmap );
                QPixmap result = selected.pixmap( m_pixmapSize, QIcon::Selected, QIcon::On );
                painter->drawPixmap( pos, result );
            } else {
                painter->drawPixmap( pos, pixmap );
            }

            QRegion region = painter->regionFromRect( pos, m_targetPixmap.width(), m_targetPixmap.height() );
            m_placemarks.push_back( ModelRegion( index, region ) );
        }
    }
}
void QTableModelWordMLWriter::writeDecoration(QXmlStreamWriter & stream, const QVariant & decoration)
{
	QIcon icon = qvariant_cast<QIcon>(decoration);
	QPixmap pixmap;
	if (icon.isNull()){
		pixmap = qvariant_cast<QPixmap>(decoration);
		if (pixmap.isNull()){
			return;
		}
	} else {
		pixmap = icon.pixmap(16, 16);
	}
	QByteArray bytes;
	QBuffer buffer(&bytes);
	buffer.open(QIODevice::WriteOnly);
	pixmap.save(&buffer, "PNG"); // writes pixmap into bytes in PNG format
	stream.writeStartElement("w:pict");
	// export image data
	stream.writeStartElement("w:binData");
	stream.writeAttribute("w:name", QString("wordml://%1.png").arg(m_imageId, 8, 10, QLatin1Char('0')));
	stream.writeAttribute("xml:space", "preserve");
	stream.writeCharacters(bytes.toBase64());
	stream.writeEndElement();
	//
	stream.writeStartElement("v:shape");
	stream.writeAttribute("style", QString("width:%1px;height:%2px").arg(pixmap.size().width()).arg(pixmap.size().height()));
	stream.writeEmptyElement("v:imageData");
	stream.writeAttribute("src", QString("wordml://%1.png").arg(m_imageId, 8, 10, QLatin1Char('0')));

	// end tag <w:shape>
	stream.writeEndElement();
	// end tag <w:pict>
	stream.writeEndElement();

	m_imageId++;
}
    ConnectionDiagnosticDialog::ConnectionDiagnosticDialog(QWidget* parent, IConnectionSettingsBaseSPtr connection)
        : QDialog(parent)
    {
        using namespace translations;

        setWindowTitle(trConnectionDiagnostic);
        setWindowIcon(GuiFactory::instance().icon(connection->connectionType()));
        setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); // Remove help button (?)

        QVBoxLayout* mainLayout = new QVBoxLayout;

        executeTimeLabel_ = new QLabel;
        executeTimeLabel_->setText(connectionStatusTemplate.arg("execute..."));
        mainLayout->addWidget(executeTimeLabel_);

        statusLabel_ = new QLabel(timeTemplate.arg("calculate..."));
        iconLabel_ = new QLabel;
        QIcon icon = GuiFactory::instance().failIcon();
        const QPixmap pm = icon.pixmap(stateIconSize);
        iconLabel_->setPixmap(pm);

        mainLayout->addWidget(statusLabel_);
        mainLayout->addWidget(iconLabel_, 1, Qt::AlignCenter);

        QDialogButtonBox* buttonBox = new QDialogButtonBox;
        buttonBox->setOrientation(Qt::Horizontal);
        buttonBox->setStandardButtons(QDialogButtonBox::Ok);
        VERIFY(connect(buttonBox, &QDialogButtonBox::accepted, this, &ConnectionDiagnosticDialog::accept));

        mainLayout->addWidget(buttonBox);
        setFixedSize(QSize(fix_width, fix_height));
        setLayout(mainLayout);

        glassWidget_ = new fasto::qt::gui::GlassWidget(GuiFactory::instance().pathToLoadingGif(), trTryToConnect, 0.5, QColor(111, 111, 100), this);
        testConnection(connection);
    }
Beispiel #15
0
QPixmap  ActionRepositoryMimeData::actionDragPixmap(const QAction *action)
{

    // Try to find a suitable pixmap. Grab either widget or icon.
    const QIcon icon = action->icon();
    if (!icon.isNull())
        return icon.pixmap(QSize(22, 22));

    foreach (QWidget *w, action->associatedWidgets())
        if (QToolButton *tb = qobject_cast<QToolButton *>(w))
            return QPixmap::grabWidget(tb);

    // Create a QToolButton
    QToolButton *tb = new QToolButton;
    tb->setText(action->text());
    tb->setToolButtonStyle(Qt::ToolButtonTextOnly);
#ifdef Q_WS_WIN // Force alien off to make adjustSize() take the system minimumsize into account.
    tb->createWinId();
#endif
    tb->adjustSize();
    const QPixmap rc = QPixmap::grabWidget(tb);
    tb->deleteLater();
    return rc;
}
QSize DPageListViewDelegate::sizeHint( const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
  if ( !index.isValid() )
    return QSize( 0, 0 );

  const QString text = index.model()->data( index, Qt::DisplayRole ).toString();
  const QIcon icon = index.model()->data( index, Qt::DecorationRole ).value<QIcon>();
  const QPixmap pixmap = icon.pixmap( 32, 32 );

  QFontMetrics fm = option.fontMetrics;
  int ht = fm.boundingRect( 0, 0, 0, 0, Qt::AlignCenter, text ).height();
  int wt = fm.boundingRect( 0, 0, 0, 0, Qt::AlignCenter, text ).width() + 10;
  int wp = pixmap.width() + 10;

  int width, height;
  if ( text.isEmpty() )
    height = pixmap.height();
  else
    height = pixmap.height() + ht + 10;

  width = qMax( wt, wp );

  return QSize( width, height );
}
Beispiel #17
0
void StatusNotifierItem::refreshIcons()
{
#if QT_VERSION >= 0x050000
    if (!_iconThemePath.isEmpty()) {
        QDir baseDir{_iconThemePath + "/hicolor"};
        baseDir.removeRecursively();
        for (auto &&trayState : { State::Active, State::Passive, State::NeedsAttention }) {
            auto iconName = SystemTray::iconName(trayState);
            QIcon icon = icon::get(iconName);
            if (!icon.isNull()) {
                for (auto &&size : icon.availableSizes()) {
                    auto pixDir = QString{"%1/%2x%3/status"}.arg(baseDir.absolutePath()).arg(size.width()).arg(size.height());
                    QDir{}.mkpath(pixDir);
                    if (!icon.pixmap(size).save(pixDir + "/" + iconName + ".png")) {
                        qWarning() << "Could not save tray icon" << iconName << "for size" << size;
                    }
                }
            }
            else {
                // No theme icon found; use fallback from resources
                auto iconDir = QString{"%1/24x24/status"}.arg(baseDir.absolutePath());
                QDir{}.mkpath(iconDir);
                if (!QFile::copy(QString{":/icons/hicolor/24x24/status/%1.svg"}.arg(iconName),
                                 QString{"%1/%2.svg"}.arg(iconDir, iconName))) {
                    qWarning() << "Could not access fallback tray icon" << iconName;
                    continue;
                }
            }
        }
    }
#endif
    if (_statusNotifierItemDBus) {
        emit _statusNotifierItemDBus->NewIcon();
        emit _statusNotifierItemDBus->NewAttentionIcon();
    }
}
void WidgetDiskItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    QStyleOptionViewItemV4 opt = *qstyleoption_cast<const QStyleOptionViewItemV4*>(&option);

    bool selected = opt.state & QStyle::State_Selected;

    QStyle* style  = (opt.widget != NULL ? opt.widget->style() : QApplication::style());
    QString text   = index.data(Qt::DisplayRole).toString();
    QIcon   icon   = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
    QPixmap pixmap = icon.pixmap(opt.decorationSize, (selected == true ? QIcon::Selected : QIcon::Normal));

    int alignment = 0;
    switch (opt.decorationPosition) {
        case QStyleOptionViewItem::Left:
            alignment |= Qt::AlignLeft | Qt::AlignVCenter;
            break;
        case QStyleOptionViewItem::Right:
            alignment |= Qt::AlignRight | Qt::AlignVCenter;
            break;
        case QStyleOptionViewItem::Top:
            alignment |= Qt::AlignTop | Qt::AlignHCenter;
            break;
        case QStyleOptionViewItem::Bottom:
            alignment |= Qt::AlignBottom | Qt::AlignHCenter;
            break;
    }

    QRect icon_rect = style->itemPixmapRect(opt.rect.adjusted(adjust_dx, adjust_dy, -adjust_dx, -adjust_dy), alignment, pixmap);
    style->drawItemPixmap(painter, icon_rect, opt.decorationAlignment, pixmap);

    QRect free_rect;
    switch (opt.decorationPosition) {
        case QStyleOptionViewItem::Left:
            free_rect = opt.rect.adjusted(icon_rect.width() + adjust_dx * 3, adjust_dy, -adjust_dx, -adjust_dy);
            break;
        case QStyleOptionViewItem::Right:
            free_rect = opt.rect.adjusted(adjust_dx, adjust_dy, -icon_rect.width() - adjust_dx * 3, -adjust_dy);
            break;
        case QStyleOptionViewItem::Top:
            free_rect = opt.rect.adjusted(adjust_dx, icon_rect.height() + adjust_dy * 3, -adjust_dx, -adjust_dy);
            break;
        case QStyleOptionViewItem::Bottom:
            free_rect = opt.rect.adjusted(adjust_dx, adjust_dy, -adjust_dx, -icon_rect.height() - adjust_dy * 3);
            break;
    }

    if (selected == true) {
        int dr = qMax(adjust_dx, adjust_dy);

        QRect text_rect = style->itemTextRect(opt.fontMetrics, free_rect, alignment, true, text);
        QRect high_rect = text_rect.adjusted(-dr, -dr, dr, dr);

        painter->save();

        painter->setRenderHint(QPainter::Antialiasing);

        painter->setPen(opt.palette.highlight().color());
        painter->setBrush(opt.palette.highlight());
        painter->drawRoundedRect(high_rect, dr, dr);

        painter->restore();
    }

    style->drawItemText(painter, free_rect, alignment, option.palette, true, text, (selected == true ? QPalette::HighlightedText : QPalette::WindowText));
}
Beispiel #19
0
/* -----------------------------------------------------------------\
|  Method: paint
|  Begin:  22.03.2011 / 12:20
|  Author: Jo2003
|  Description: paint custom view item
|
|  Parameters: painter, view item, model index
|
|  Returns: --
\----------------------------------------------------------------- */
void QChanListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
   // paint any selection / hover effect ...
   QStyledItemDelegate::paint(painter, option, index);
   painter->save();

   /////////////////////////////////////////////////////////////////////////////
   int     iPos     = qvariant_cast<int>(index.data(channellist::posRole));
   int     iCid     = qvariant_cast<int>(index.data(channellist::cidRole));
   uint    uiStart  = qvariant_cast<uint>(index.data(channellist::startRole));
   uint    uiEnd    = qvariant_cast<uint>(index.data(channellist::endRole));
   QIcon   icon     = qvariant_cast<QIcon>(index.data(channellist::iconRole));
#ifdef _TASTE_CHITRAM_TV
   // maybe we should think about to use these values for all brandings ...
   QSize   iconsize = icon.actualSize(QSize(42, 42));
#else
   QSize   iconsize = icon.actualSize(option.decorationSize);
#endif // _TASTE_CHITRAM_TV
   QString sChan    = qvariant_cast<QString>(index.data(channellist::nameRole));
   QString sProg    = qvariant_cast<QString>(index.data(channellist::progRole));
   QString sColor   = qvariant_cast<QString>(index.data(channellist::bgcolorRole));
   QString fromTo   = QString("%1 - %2")
                      .arg(QDateTime::fromTime_t(uiStart).toString("h:mm"))
                      .arg(QDateTime::fromTime_t(uiEnd).toString("h:mm"));
   /////////////////////////////////////////////////////////////////////////////

   // colorize background if this is a channel group ...
   if ((iCid == -1) && (sColor != "")
      && !(option.state & (QStyle::State_Selected | QStyle::State_MouseOver)))
   {
      // channel group ...
      painter->fillRect(option.rect, QColor(sColor));
   }

   // draw icon ...
   int   x = option.rect.x() + 2;
   int   y = option.rect.y() + ((option.rect.height() - iconsize.height()) / 2);
   QRect iconRect(x, y, iconsize.width(), iconsize.height());
   painter->drawPixmap(iconRect, icon.pixmap(iconsize));

   x = iconRect.right() + 4;
   int rightWidth = option.rect.right() - x - 2;

   // font stuff for channel line ...
   QFont chanFont = option.font;
   chanFont.setPointSize(chanFont.pointSize() + 1);
   chanFont.setBold(true);
   QFontMetrics fmChan(chanFont);

   // check if additional info is available ...
   if ((sProg == "") || !uiStart || !uiEnd)
   {
      // draw simple item only ...

      // channel line ...
      y = option.rect.y() + ((option.rect.height() - fmChan.height()) / 2);
      QRect chanRect(x, y, rightWidth, fmChan.height());

      painter->setFont(chanFont);
      painter->drawText(chanRect, Qt::TextSingleLine, sChan);
   }
   else
   {
      // draw advanced item ...
      QRect bounting;
      QFont progFont = option.font;
      progFont.setPointSize(progFont.pointSize() - 1);
      progFont.setWeight(progFont.weight() - 2);
      QFontMetrics fmProg(progFont);

      // channel line ...
      y = option.rect.y() + 2;
      QRect chanRect(x, y, rightWidth, fmChan.height());

      CSmallHelpers::cutProgString(sChan, fmChan, rightWidth);
      painter->setFont(chanFont);
      painter->drawText(chanRect, Qt::TextSingleLine, sChan, &bounting);

      // program line ...
      y = bounting.bottom();
      QRect progRect(x, y, rightWidth, fmProg.height());

      CSmallHelpers::cutProgString(sProg, fmProg, rightWidth);
      painter->setFont(progFont);
      painter->drawText(progRect, Qt::TextSingleLine, sProg.section('\n', 0, 0), &bounting);

      // from ... to line ...
      y = bounting.bottom();
      QRect timesRect(x, y, rightWidth, fmProg.height());
      painter->drawText(timesRect, Qt::TextSingleLine, fromTo, &bounting);

      // progress bar ...
      y = bounting.bottom() + 2;
      QRect progressRect(x, y, rightWidth, 5);
      iPos = (iPos > (int)(uiEnd - uiStart)) ? (int)(uiEnd - uiStart) : iPos;

#ifndef Q_OS_MAC
      QStyleOptionProgressBar progressBar;
      progressBar.rect        = progressRect;
      progressBar.minimum     = 0;
      progressBar.maximum     = (int)(uiEnd - uiStart);
      progressBar.progress    = iPos;
      progressBar.textVisible = false;

      QApplication::style()->drawControl(QStyle::CE_ProgressBar,
                                         &progressBar, painter);
#else
      // Drawing the progress bar on mac doesn't look nice
      // because the height can't be shrinked as needed.
      // So we try to draw our own progress bar here ...

      // make sure background is white ...
      painter->fillRect(progressRect, QColor("white"));

      // prepare pen for border line ...
      QPen pen(Qt::SolidLine);
      pen.setColor(QColor("silver"));
      pen.setWidth(1);
      painter->setPen(pen);

      // draw outline ...
      painter->drawRect(progressRect);

      // compute size of inner rect (take care of border) ...
      x = progressRect.width()  - pen.width();
      y = progressRect.height() - pen.width();
      x = (uiEnd - uiStart) ? ((x * iPos) / (int)(uiEnd - uiStart)) : 0; ///< avoid division with 0 !!!

      // inner rectangle (progess) ...
      QRect macRect(progressRect.x() + pen.width(), progressRect.y() + pen.width(), x, y);

      // paint progress ...
      painter->fillRect(macRect, QColor("#036"));
#endif // Q_OS_MAC

   }

   painter->restore();
}
Beispiel #20
0
void TorManager::reportTorCheckResults(int page)
{
    QString statusbar;
    QNetworkProxy proxy = BrowserApplication::instance()->networkAccessManager()->currentProxy();

    QFile file(QLatin1String(":/torcheck.html"));
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "WebPage::handleUnsupportedContent" << "Unable to open torcheck.html";
        return;
    }
    QString tororaIssues;
    QString issuesfile;
#if defined(TORORA)
    issuesfile = QLatin1String(":/TORORA_ISSUES");
#else
    issuesfile = QLatin1String(":/ARORA_ISSUES");
#endif
    QFile issues(issuesfile);
    QString title, headline, bulletone, bullettwo, bulletthree, bulletfour, img;
    switch (page) {
      case TOR_CHECK:
        if (m_checkTorSilently)
            return;
        title = tr("Checking Tor..");
        headline = tr("Checking Tor..");
        bulletone = tr("Torora is checking https://check.torproject.org.");
        bullettwo = tr("Once Torora is sure you can browse anonymously, browsing will be enabled.");
        bulletthree = tr("This check may take a few seconds, so please be patient.");
        img = QLatin1String(":graphics/tor-checking.png");
        statusbar = QLatin1String("Checking Tor...");
        break;
      case USING_TOR:
        /*FIXME: Pseudorandom intervals may not be enough to prevent an attacker guessing who
                is testing */
        #define TOR_CHECK_PERIOD (60 * 1000 * ((qrand() % 10) + 1))
        m_timer->start(TOR_CHECK_PERIOD);
//        qDebug() << "TOR_CHECK_PERIOD " << TOR_CHECK_PERIOD << endl;

        if (m_checkTorSilently)
            return;
        if (!issues.open(QIODevice::ReadOnly)) {
            qWarning() << "WebPage::handleUnsupportedContent" << "Unable to open " << issuesfile;
            return;
        }
        tororaIssues = QString(QLatin1String(issues.readAll()));
        title = tr("Torora Ready For Use..");
        headline = tr("Tor is Working Properly. You Can Browse Anonymously.");
        bulletone = tr("You can confirm this yourself by visiting <a href='https://check.torproject.org'>https://check.torproject.org</a>");
        bullettwo = tr("The bookmark toolbar contains some well known hidden services you can check out.");
        bulletthree = tr("You can check Tor at any time by pressing F12 or clicking <b>Tools->Check Tor.</b>");
        img = QLatin1String(":graphics/tor-on.png");
        statusbar = QLatin1String("Tor Check Successful");
       break;
      default:
        setBrowsingEnabled(false);
        /* Stop the periodic tor checks until we're back up */
        m_timer->stop();
        title = tr("Check Your Tor Installation");
        if (!m_torIsRunning) {
            headline = tr("Tor Is Not Running On Your Computer!");
            bulletone = tr("Check that you have installed Tor.");
            bullettwo = tr("Check that you have started Tor.");
        } else if (page == NOT_USING_TOR) {
            headline = tr("Torora May Be By-Passing Tor!");
            bulletone = tr("Testing at https://check.torproject.org indicated that you are not using Tor.");
            bullettwo = tr("Your set-up seems OK, Tor is running and seem to be correctly configured.");
            bulletfour = tr("<li>Click 'Change Identity' in Vidalia or TorK and try again. The exit node used for the test may not be listed with the checking service yet.</li>");
        } else {
            headline = tr("The Tor Check Website May Be Down!");
            bulletone = tr("Check that https://check.torproject.org is available using another browser.");
            bullettwo = tr("There may be a temporary issue with the website.");
            bulletfour = tr("<li>Click 'Change Identity' in Vidalia or TorK and try again. The exit node used for the test may not be listed with the checking service yet.</li>");
        }
        bulletthree = tr("Press F12 or <b>Tools->Check Tor</b> to test Tor again.");
        img = QLatin1String(":graphics/tor-off.png");
        statusbar = QLatin1String("Tor Check Failed");

        tororaIssues = QString(QLatin1String("<table align='center'><tr><td></td> <td>"
                                                      "<object type=\"application/x-qt-plugin\" classid=\"QPushButton\" "
                                                      "name=\"TryAgainButton\" height=25 width=110></object>\n"
                                                      "<script>\n"
                                                      "document.TryAgainButton.text = 'Try Again';\n"
                                                      "</script>\n"
                                                      "</td>  <td></td></tr></table>\n"));
        /* Create a new circuit for the next test, just in case we used an exit that isn't listed yet */
        if (torcontrol)
            torcontrol->newIdentity();
        setBrowsingEnabled(false);
        break;
    }
    QString html = QString(QLatin1String(file.readAll()))
                        .arg(title)
                        .arg(QString())
                        .arg(headline)
                        .arg(bulletone)
                        .arg(bullettwo)
                        .arg(bulletthree)
                        .arg(bulletfour)
                        .arg(tororaIssues);

    QBuffer imageBuffer;
    imageBuffer.open(QBuffer::ReadWrite);
    QIcon icon = QIcon(img);
    QPixmap pixmap = icon.pixmap(QSize(32, 32));
    if (pixmap.save(&imageBuffer, "PNG")) {
        html.replace(QLatin1String("IMAGE_BINARY_DATA_HERE"),
                     QString(QLatin1String(imageBuffer.buffer().toBase64())));
    }

    if (page == USING_TOR) {
        imageBuffer.open(QBuffer::ReadWrite);
        icon = QIcon(QLatin1String(":graphics/info.png"));
        pixmap = icon.pixmap(QSize(32, 32));
        if (pixmap.save(&imageBuffer, "PNG")) {
            html.replace(QLatin1String("INFO_IMAGE_HERE"),
                        QString(QLatin1String(imageBuffer.buffer().toBase64())));
        }

        imageBuffer.open(QBuffer::ReadWrite);
        icon = QIcon(QLatin1String(":graphics/important.png"));
        pixmap = icon.pixmap(QSize(32, 32));
        if (pixmap.save(&imageBuffer, "PNG")) {
            html.replace(QLatin1String("WARNING_IMAGE_HERE"),
                        QString(QLatin1String(imageBuffer.buffer().toBase64())));
        }

        imageBuffer.open(QBuffer::ReadWrite);
        icon = QIcon(QLatin1String(":graphics/help.png"));
        pixmap = icon.pixmap(QSize(32, 32));
        if (pixmap.save(&imageBuffer, "PNG")) {
            html.replace(QLatin1String("QUESTION_IMAGE_HERE"),
                        QString(QLatin1String(imageBuffer.buffer().toBase64())));
        }
    }
    BrowserApplication::instance()->mainWindow()->currentTab()->page()->mainFrame()->setHtml(html, QUrl());

    if (!m_checkTorSilently && page == USING_TOR)
        connectToTor();

    if (!m_checkTorSilently) {
        m_statusbar=statusbar;
        QTimer::singleShot(1000, this, SLOT(displayStatusResult()));
        if (page != TOR_CHECK)
            BrowserApplication::instance()->mainWindow()->setStatusBarMessagesEnabled(true);
    }
}
Beispiel #21
0
void TorManager::passwordHelp()
{
    QString proceedButton = QString(QLatin1String("<object type=\"application/x-qt-plugin\" classid=\"QPushButton\" name=\"DoneButton\" height=25 width=110></object>\n"
                            "<script>\n"
                            "document.DoneButton.text = 'Done';\n"
                            "</script>\n"));

    QFile file(QLatin1String(":/passwordhelp.html"));
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "WebPage::handleUnsupportedContent" << "Unable to open torcheck.html";
        return;
    }
    QString tororaIssues;
    QString title, headline, intro, bullettwo, bulletthree, bulletfour, bulletfive, img;
    headline = tr("To Use Torora You Need To Set Tor's Password.");
    intro = tr("1. Right click the 'green onion' at the bottom right of your screen and choose 'Settings'.");
    bullettwo = tr("2. Select 'Advanced' in the 'Settings' dialog.");
    bulletthree = tr("3. Clear the 'Randomly Generate' check-box.");
    bulletfour = tr("4. Type in a password of your choosing and click 'OK'.");
    bulletfive = tr("5. Click 'Done' below and enter this password when Torora requests it.");
    img = QLatin1String(":graphics/vidalia-password.png");

    QString html = QString(QLatin1String(file.readAll()))
                        .arg(title)
                        .arg(QString())
                        .arg(headline)
                        .arg(intro)
                        .arg(bullettwo)
                        .arg(bulletthree)
                        .arg(bulletfour)
                        .arg(bulletfive)
                        .arg(proceedButton);

    QBuffer imageBuffer;
    imageBuffer.open(QBuffer::ReadWrite);
    QIcon icon = QIcon(QLatin1String(":graphics/vidalia-systray.png"));
    QPixmap pixmap = icon.pixmap(QSize(183, 137));
    if (pixmap.save(&imageBuffer, "PNG")) {
        html.replace(QLatin1String("HELP_ONE_DATA_HERE"),
                     QString(QLatin1String(imageBuffer.buffer().toBase64())));
    }

    imageBuffer.open(QBuffer::ReadWrite);
    icon = QIcon(QLatin1String(":graphics/vidalia-advanced.png"));
    pixmap = icon.pixmap(QSize(118, 97));
    if (pixmap.save(&imageBuffer, "PNG")) {
        html.replace(QLatin1String("HELP_TWO_DATA_HERE"),
                     QString(QLatin1String(imageBuffer.buffer().toBase64())));
    }

    imageBuffer.open(QBuffer::ReadWrite);
    icon = QIcon(QLatin1String(":graphics/vidalia-random.png"));
    pixmap = icon.pixmap(QSize(149, 71));
    if (pixmap.save(&imageBuffer, "PNG")) {
        html.replace(QLatin1String("HELP_THREE_DATA_HERE"),
                     QString(QLatin1String(imageBuffer.buffer().toBase64())));
    }

    imageBuffer.open(QBuffer::ReadWrite);
    icon = QIcon(QLatin1String(":graphics/vidalia-pass.png"));
    pixmap = icon.pixmap(QSize(166, 78));
    if (pixmap.save(&imageBuffer, "PNG")) {
        html.replace(QLatin1String("HELP_FOUR_DATA_HERE"),
                     QString(QLatin1String(imageBuffer.buffer().toBase64())));
    }

    imageBuffer.open(QBuffer::ReadWrite);
    icon = QIcon(QLatin1String(":graphics/help.png"));
    pixmap = icon.pixmap(QSize(32, 32));
    if (pixmap.save(&imageBuffer, "PNG")) {
        html.replace(QLatin1String("INFO_BINARY_DATA_HERE"),
                    QString(QLatin1String(imageBuffer.buffer().toBase64())));
    }

    BrowserApplication::instance()->mainWindow()->currentTab()->page()->mainFrame()->setHtml(html, QUrl());

}
MigrateDialog::MigrateDialog(QWidget *parent,
                             const QString arg1,
                             const QString arg2,
                             const QString arg3,
                             const QStringList list) :
    QDialog(parent), domainName(arg1), hostName(arg2),
    connType(arg3), connList(list)
{
    setWindowTitle(QString("Migrate '%1'").arg(domainName));
    commonLayout = new QVBoxLayout();
    Name = new QLineEdit(this);
    Name->setText(domainName);
    Name->setPlaceholderText("Enter new VM name");
    commonLayout->addWidget(Name);
    host = new QLabel(QString("Original Host / Connection Type : %1 / %2")
                      .arg(hostName).arg(connType.toUpper()), this);
    commonLayout->addWidget(host);
    newHost = new QLabel("Destination Host / Connection :", this);
    commonLayout->addWidget(newHost);
    connectList = new QComboBox(this);
    connList.prepend("Set Host/URI manually");
    connectList->addItems(connList);
    commonLayout->addWidget(connectList);

    connLayout = new QGridLayout();
    uriLabel = new QLabel("Destination\nHost/URI", this);
    uri = new QLineEdit(this);
    help = new QLabel(this);
    QIcon icon = QIcon::fromTheme("dialog-warning");
    if ( icon.isNull() ) {
        help->setText("Help:");
    } else {
        help->setPixmap(icon.pixmap(this->fontInfo().pixelSize()));
    };
    helpText = new QTextBrowser(this);
    connLayout->addWidget(uriLabel, 0, 0, Qt::AlignRight);
    connLayout->addWidget(uri, 0, 2);
    connLayout->addWidget(help, 1, 0, Qt::AlignRight|Qt::AlignTop);
    connLayout->addWidget(helpText, 1, 2);
    connectivity = new QWidget(this);
    connectivity->setLayout(connLayout);

    useAdvanced = new QCheckBox("Advanced", this);
    useAdvanced->setChecked(false);
    commonLayout->addWidget(useAdvanced);
    //commonLayout->addWidget(connectivity);
    commonLayout->insertStretch(-1);

    advanced = new QWidget(this);
    advanced->setEnabled(false);
    advLayout = new QGridLayout();
    nativeMigration = new QRadioButton("Native migration data\nover hypervisor transport\n(encrypt if HV support it)", this);
    nativeMigration->setChecked(true);
    nativeMigration->setLayoutDirection(Qt::RightToLeft);
    tunnelMigration = new QRadioButton("Tunnel migration data\nover libvirtd connection\n(encrypt always)", this);
    tunnelMigration->setLayoutDirection(Qt::LeftToRight);
    p2pMigration = new QLabel("Use peer2peer", this);
    maxDownTimeLabel = new QLabel("Maximum tolerable downtime\nfor live migration (ms)", this);
    maxDownTimeLabel->setEnabled( connType.toLower()!="lxc" );
    p2pCheck = new QCheckBox(this);
    p2pCheck->setChecked(p2p);
    maxDownCheck = new QCheckBox(this);
    maxDownCheck->setChecked(false);
    maxDownCheck->setEnabled( connType.toLower()!="lxc" );
    maxDownTime = new QSpinBox(this);
    maxDownTime->setEnabled(false);
    maxDownTime->setValue(30);
    bandWdthLabel = new QLabel("BandWidth (MiB/s)", this);
    bandWdthCheck = new QCheckBox(this);
    bandWdthCheck->setChecked(false);
    bandwidth = new QSpinBox(this);
    bandwidth->setEnabled(false);
    liveMigration = new QCheckBox("Live migration", this);
    liveMigration->setLayoutDirection(Qt::RightToLeft);
    persistDestMigration = new QCheckBox("Persist the VM\non the destination", this);
    persistDestMigration->setLayoutDirection(Qt::LeftToRight);
    undefineSourceMigration = new QCheckBox("Undefine the VM\non the source", this);
    undefineSourceMigration->setLayoutDirection(Qt::RightToLeft);
    pausedMigration = new QCheckBox("Leave\nthe domain suspended\non the remote side", this);
    pausedMigration->setLayoutDirection(Qt::LeftToRight);
    fullNonSharedDiskMigration = new QCheckBox("Migration with\nnon-shared storage\nwith full disk copy", this);
    fullNonSharedDiskMigration->setLayoutDirection(Qt::RightToLeft);
    incNonSharedDiskMigration = new QCheckBox("Migration with\nnon-shared storage\nwith incremental copy", this);
    incNonSharedDiskMigration->setLayoutDirection(Qt::LeftToRight);
    unsafeMigration = new QCheckBox("Force migration even\nif it is considered unsafe", this);
    unsafeMigration->setLayoutDirection(Qt::RightToLeft);
    offlineMigration = new QCheckBox("Migrate offline", this);
    offlineMigration->setLayoutDirection(Qt::LeftToRight);
    compressedMigration = new QCheckBox("Compress data\nduring migration", this);
    compressedMigration->setLayoutDirection(Qt::RightToLeft);
    abortOnMigration = new QCheckBox("Abort migration\non I/O errors happened\nduring migration", this);
    abortOnMigration->setLayoutDirection(Qt::LeftToRight);
    advLayout->addWidget(nativeMigration, 0, 0);
    advLayout->addWidget(tunnelMigration, 0, 2);
    advLayout->addWidget(p2pMigration, 1, 0, Qt::AlignRight);
    advLayout->addWidget(p2pCheck, 1, 1, Qt::AlignBottom|Qt::AlignCenter);
    advLayout->addWidget(maxDownTimeLabel, 2, 0, Qt::AlignRight);
    advLayout->addWidget(maxDownCheck, 2, 1, Qt::AlignBottom|Qt::AlignCenter);
    advLayout->addWidget(maxDownTime, 2, 2, Qt::AlignBottom);
    advLayout->addWidget(bandWdthLabel, 3, 0, Qt::AlignRight);
    advLayout->addWidget(bandWdthCheck, 3, 1, Qt::AlignBottom|Qt::AlignCenter);
    advLayout->addWidget(bandwidth, 3, 2, Qt::AlignBottom);
    advLayout->addWidget(liveMigration, 4, 0);
    advLayout->addWidget(persistDestMigration, 4, 2);
    advLayout->addWidget(undefineSourceMigration, 5, 0);
    advLayout->addWidget(pausedMigration, 5, 2);
    advLayout->addWidget(fullNonSharedDiskMigration, 6, 0);
    advLayout->addWidget(incNonSharedDiskMigration, 6, 2);
    advLayout->addWidget(unsafeMigration, 7, 0);
    advLayout->addWidget(offlineMigration, 7, 2);
    advLayout->addWidget(compressedMigration, 8, 0);
    advLayout->addWidget(abortOnMigration, 8, 2);
    advanced->setLayout(advLayout);
    flags = new QScrollArea(this);
    flags->setWidget(advanced);
    splitter = new QSplitter(this);
    splitter->setOrientation(Qt::Vertical);
    splitter->addWidget(connectivity);
    splitter->addWidget(flags);
    commonLayout->addWidget(splitter);

    helpLinkLabel = new QLabel("<a href='http://libvirt.org/migration.html'>About Migration</a>", this);
    helpLinkLabel->setOpenExternalLinks(true);
    ok = new QPushButton("Migrate", this);
    ok->setIcon(QIcon::fromTheme("migrate"));
    cancel = new QPushButton("Cancel", this);
    cancel->setIcon(QIcon::fromTheme("dialog-cancel"));
    buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(helpLinkLabel);
    buttonLayout->addWidget(cancel);
    buttonLayout->addWidget(ok);
    buttons = new QWidget(this);
    buttons->setLayout(buttonLayout);
    commonLayout->addWidget(buttons);
    setLayout(commonLayout);
    connect(useAdvanced, SIGNAL(toggled(bool)), this, SLOT(advancedVisibility(bool)));
    connect(ok, SIGNAL(clicked()), this, SLOT(migrateClicked()));
    connect(cancel, SIGNAL(clicked()), this, SLOT(cancelClicked()));
    connect(connectList, SIGNAL(currentIndexChanged(int)), this, SLOT(connectChanged(int)));
    connect(bandWdthCheck, SIGNAL(toggled(bool)), this, SLOT(bandWdthVisibility(bool)));
    connect(maxDownCheck, SIGNAL(toggled(bool)), this, SLOT(maxDownTimeVisibility(bool)));
    connect(nativeMigration, SIGNAL(clicked()), this, SLOT(migrTransportChanged()));
    connect(tunnelMigration, SIGNAL(clicked()), this, SLOT(migrTransportChanged()));
    connect(p2pCheck, SIGNAL(clicked(bool)), this, SLOT(p2pChanged(bool)));
    connect(fullNonSharedDiskMigration, SIGNAL(clicked()), this, SLOT(migrDiskRegimeChanged()));
    connect(incNonSharedDiskMigration, SIGNAL(clicked()), this, SLOT(migrDiskRegimeChanged()));
    migrTransportChanged(connectList->currentIndex()==0);
    restoreGeometry(settings.value("MigrationDialogGeometry").toByteArray());
}
Beispiel #23
0
void LineEdit::setIcon(const QIcon& icon)
{
	icon_ = icon.pixmap(16, 16);
	updateLayout();
	update();
}
void SearchResultItemDelegate::paint(QPainter *painter,
                                     const QStyleOptionViewItem &option,
                                     const QModelIndex &index) const {
    const SearchResultListModel *model = static_cast<const SearchResultListModel*>(index.model());
    QBrush backBrush;
    bool selected = false;
    FileSearchResult file = getSearchResult(index);

    if (option.state & (QStyle::State_HasFocus | QStyle::State_Selected)) {
        backBrush = QColor(kFileItemBackgroundColorHighlighted);
        selected = true;
    } else {
        backBrush = QColor(kFileItemBackgroundColor);
    }

    //
    // draw item's background
    //
    painter->save();
    painter->fillRect(option.rect, backBrush);
    painter->restore();

    QIcon icon = model->data(index, Qt::DecorationRole).value<QIcon>();
    // get the device pixel radio from current painter device
    int scale_factor = 1;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    scale_factor = painter->device()->devicePixelRatio();
#endif // QT5
    QPixmap pixmap(icon.pixmap(QSize(kFileIconWidth, kFileIconHeight) * scale_factor));
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    if (pixmap.size() != QSize(kFileIconWidth, kFileIconHeight))
        pixmap.setDevicePixelRatio(scale_factor);
#endif // QT5

    //
    // paint file icon
    //
    QPoint file_icon_pos(kMarginLeft + kPadding, kMarginTop + kPadding);
    file_icon_pos += option.rect.topLeft();
    painter->save();
    painter->drawPixmap(file_icon_pos, pixmap);
    painter->restore();

    // Calculate the file column by the delta of mainwindow's width
    QString title = file.name;

    const int file_name_width = kFileNameWidth
      + seafApplet->mainWindow()->width() - seafApplet->mainWindow()->minimumWidth();
    painter->save();
    QPoint file_name_pos = file_icon_pos + QPoint(kFileIconWidth + kMarginBetweenFileIconAndName, -kPadding);
    QRect file_name_rect(file_name_pos, QSize(file_name_width, kFileNameHeight));
    painter->setPen(QColor(selected ? kFileNameColorHighlighted : kFileNameColor));
    painter->setFont(changeFontSize(painter->font(), kFileNameFontSize));

    painter->drawText(file_name_rect,
                      Qt::AlignLeft | Qt::AlignTop,
                      fitTextToWidth(title, option.font, file_name_width),
                      &file_name_rect);
    painter->restore();

    //
    // Paint repo_name
    //
    int count_of_splash = file.fullpath.endsWith("/") ? 2 : 1;
    QString subtitle = file.fullpath.mid(1, file.fullpath.size() - count_of_splash - file.name.size());
    if (!subtitle.isEmpty())
        subtitle = file.repo_name + "/" + subtitle.left(subtitle.size() - 1);
    else
        subtitle = file.repo_name;

    painter->save();
    QPoint file_desc_pos = file_name_rect.bottomLeft() + QPoint(0, kPadding / 2);
    QRect file_desc_rect(file_desc_pos, QSize(file_name_width, kSubtitleHeight));
    painter->setFont(changeFontSize(painter->font(), kSubtitleFontSize));
    painter->setPen(QColor(selected ? kSubtitleColorHighlighted : kSubtitleColor));
    painter->drawText(file_desc_rect,
                      Qt::AlignLeft | Qt::AlignTop,
                      fitTextToWidth(subtitle, option.font, file_name_width),
                      &file_desc_rect);
    painter->restore();

    //
    // Paint file description
    //
    QString size, mtime;

    size = readableFileSize(file.size);
    mtime = translateCommitTime(file.last_modified);

    QString extra_title = size + "  " + mtime;

    painter->save();
    QPoint file_extra_pos = file_desc_rect.bottomLeft() + QPoint(0, kPadding / 2 + 2);
    QRect file_extra_rect(file_extra_pos, QSize(file_name_width, kSubtitleHeight));
    painter->setFont(changeFontSize(painter->font(), kSubtitleFontSize));
    painter->setPen(QColor(selected ? kSubtitleColorHighlighted : kSubtitleColor));
    painter->drawText(file_extra_rect,
                      Qt::AlignLeft | Qt::AlignTop,
                      fitTextToWidth(extra_title, option.font, file_name_width),
                      &file_extra_rect);
    painter->restore();

    //
    // Draw the bottom border lines
    //
    painter->save();
    painter->setPen(QPen(QColor(kItemBottomBorderColor), 1, Qt::SolidLine));
    painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight());
    painter->restore();
}
Beispiel #25
0
void FolderViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                               const QModelIndex &index) const
{
  QStyledItemDelegate::paint(painter,option,index);

  painter->save();

  QFont aliasFont    = QApplication::font();
  QFont subFont = QApplication::font();
  QFont errorFont = subFont;

  //font.setPixelSize(font.weight()+);
  aliasFont.setBold(true);
  aliasFont.setPointSize( subFont.pointSize()+2 );

  QFontMetrics subFm( subFont );
  QFontMetrics aliasFm( aliasFont );
  int margin = aliasFm.height()/2;

  QIcon folderIcon = qvariant_cast<QIcon>(index.data(FolderIconRole));
  QIcon statusIcon = qvariant_cast<QIcon>(index.data(FolderStatusIcon));
  QString aliasText = qvariant_cast<QString>(index.data(FolderAliasRole));
  QString pathText = qvariant_cast<QString>(index.data(FolderPathRole));
  QString remotePath = qvariant_cast<QString>(index.data(FolderSecondPathRole));
  QString errorText  = qvariant_cast<QString>(index.data(FolderErrorMsg));

  // QString statusText = qvariant_cast<QString>(index.data(FolderStatus));
  bool syncEnabled = index.data(FolderSyncEnabled).toBool();
  // QString syncStatus = syncEnabled? tr( "Enabled" ) : tr( "Disabled" );

  QSize iconsize(48, 48); //  = icon.actualSize(option.decorationSize);

  QRect aliasRect = option.rect;
  QRect iconRect = option.rect;

  iconRect.setLeft( margin );
  iconRect.setWidth( 48 );
  iconRect.setTop( iconRect.top() + margin ); // (iconRect.height()-iconsize.height())/2);

  QRect statusRect = iconRect;
  statusRect.setLeft( option.rect.right() - margin - 48 );
  statusRect.setRight( option.rect.right() - margin );

  aliasRect.setLeft(iconRect.right()+margin);

  aliasRect.setTop(aliasRect.top() + aliasFm.height()/2 );
  aliasRect.setBottom(aliasRect.top()+subFm.height());

  // local directory box
  QRect localPathRect = aliasRect;
  localPathRect.setTop(aliasRect.bottom() + margin / 3);
  localPathRect.setBottom(localPathRect.top()+subFm.height());

  // remote directory box
  QRect remotePathRect = localPathRect;
  remotePathRect.setTop( localPathRect.bottom() + subFm.height()/2 );
  remotePathRect.setBottom( remotePathRect.top() + subFm.height());

  iconRect.setBottom(remotePathRect.bottom());

  //painter->drawPixmap(QPoint(iconRect.right()/2,iconRect.top()/2),icon.pixmap(iconsize.width(),iconsize.height()));
  if( syncEnabled ) {
      painter->drawPixmap(QPoint(iconRect.left(),iconRect.top()), folderIcon.pixmap(iconsize.width(),iconsize.height()));
  } else {
      painter->drawPixmap(QPoint(iconRect.left(),iconRect.top()), folderIcon.pixmap(iconsize.width(),iconsize.height(), QIcon::Disabled ));
  }

  painter->drawPixmap(QPoint(statusRect.left(), statusRect.top()), statusIcon.pixmap(48,48));

  painter->setFont(aliasFont);
  painter->drawText(aliasRect, aliasText);

  painter->setFont(subFont);
  painter->drawText(localPathRect.left(),localPathRect.top()+17, pathText);
  painter->drawText(remotePathRect, tr("Remote path: %1").arg(remotePath));

  // paint an error overlay if there is an error string
  if( !errorText.isEmpty() ) {
      QRect errorRect = localPathRect;
      errorRect.setLeft( iconRect.left());
      errorRect.setTop( iconRect.bottom()+subFm.height()/2 );
      errorRect.setHeight(subFm.height()+margin);
      errorRect.setRight( statusRect.right() );

      painter->setBrush( QColor(0xbb, 0x4d, 0x4d) );
      painter->setPen( QColor(0xaa, 0xaa, 0xaa));
      painter->drawRoundedRect( errorRect, 4, 4 );

      QIcon warnIcon(":/mirall/resources/warning-16");
      painter->drawPixmap( QPoint(errorRect.left()+2, errorRect.top()+2), warnIcon.pixmap(QSize(16,16)));

      painter->setPen( Qt::white );
      painter->setFont(errorFont);
      QRect errorTextRect = errorRect;
      errorTextRect.setLeft( errorTextRect.left()+margin/2 +16);
      errorTextRect.setTop( errorTextRect.top()+margin/2 );

      int linebreak = errorText.indexOf(QLatin1String("<br"));
      QString eText = errorText;
      if(linebreak) {
          eText = errorText.left(linebreak);
      }
      painter->drawText(errorTextRect, eText);
  }

  // painter->drawText(lastSyncRect, tr("Last Sync: %1").arg( statusText ));
  // painter->drawText(statusRect, tr("Sync Status: %1").arg( syncStatus ));
  painter->restore();

}
Beispiel #26
0
// Draws a cached pixmap with shadow
void StyleHelper::drawIconWithShadow(const QIcon &icon, const QRect &rect,
                                     QPainter *p, QIcon::Mode iconMode, int radius, const QColor &color, const QPoint &offset)
{
    QPixmap cache;
    QString pixmapName = QString("icon %0 %1 %2").arg(icon.cacheKey()).arg(iconMode).arg(rect.height());

    if (!QPixmapCache::find(pixmapName, cache)) {
        QPixmap px = icon.pixmap(rect.size());
        cache = QPixmap(px.size() + QSize(radius * 2, radius * 2));
        cache.fill(Qt::transparent);

        QPainter cachePainter(&cache);
        if (iconMode == QIcon::Disabled) {
            QImage im = px.toImage().convertToFormat(QImage::Format_ARGB32);
            for (int y=0; y<im.height(); ++y) {
                QRgb *scanLine = (QRgb*)im.scanLine(y);
                for (int x=0; x<im.width(); ++x) {
                    QRgb pixel = *scanLine;
                    char intensity = qGray(pixel);
                    *scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel));
                    ++scanLine;
                }
            }
            px = QPixmap::fromImage(im);
        }

        // Draw shadow
        QImage tmp(px.size() + QSize(radius * 2, radius * 2 + 1), QImage::Format_ARGB32_Premultiplied);
        tmp.fill(Qt::transparent);

        QPainter tmpPainter(&tmp);
        tmpPainter.setCompositionMode(QPainter::CompositionMode_Source);
        tmpPainter.drawPixmap(QPoint(radius, radius), px);
        tmpPainter.end();

        // blur the alpha channel
        QImage blurred(tmp.size(), QImage::Format_ARGB32_Premultiplied);
        blurred.fill(Qt::transparent);
        QPainter blurPainter(&blurred);
        qt_blurImage(&blurPainter, tmp, radius, false, true);
        blurPainter.end();

        tmp = blurred;

        // blacken the image...
        tmpPainter.begin(&tmp);
        tmpPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
        tmpPainter.fillRect(tmp.rect(), color);
        tmpPainter.end();

        tmpPainter.begin(&tmp);
        tmpPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
        tmpPainter.fillRect(tmp.rect(), color);
        tmpPainter.end();

        // draw the blurred drop shadow...
        cachePainter.drawImage(QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp);

        // Draw the actual pixmap...
        cachePainter.drawPixmap(QPoint(radius, radius) + offset, px);
        QPixmapCache::insert(pixmapName, cache);
    }

    QRect targetRect = cache.rect();
    targetRect.moveCenter(rect.center());
    p->drawPixmap(targetRect.topLeft() - offset, cache);
}
Beispiel #27
0
void SearchResultTreeItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    static const int iconSize = 16;

    painter->save();

    QStyleOptionViewItemV3 opt = setOptions(index, option);
    painter->setFont(opt.font);

    QItemDelegate::drawBackground(painter, opt, index);

    // ---- do the layout
    QRect checkRect;
    QRect pixmapRect;
    QRect textRect;

    // check mark
    bool checkable = (index.model()->flags(index) & Qt::ItemIsUserCheckable);
    Qt::CheckState checkState = Qt::Unchecked;
    if (checkable) {
        QVariant checkStateData = index.data(Qt::CheckStateRole);
        checkState = static_cast<Qt::CheckState>(checkStateData.toInt());
        checkRect = check(opt, opt.rect, checkStateData);
    }

    // icon
    QIcon icon = index.model()->data(index, ItemDataRoles::ResultIconRole).value<QIcon>();
    if (!icon.isNull()) {
        pixmapRect = QRect(0, 0, iconSize, iconSize);
    }

    // text
    textRect = opt.rect.adjusted(0, 0, checkRect.width() + pixmapRect.width(), 0);

    // do layout
    doLayout(opt, &checkRect, &pixmapRect, &textRect, false);

    // ---- draw the items
    // icon
    if (!icon.isNull())
        QItemDelegate::drawDecoration(painter, opt, pixmapRect, icon.pixmap(iconSize));

    // line numbers
    int lineNumberAreaWidth = drawLineNumber(painter, opt, textRect, index);
    textRect.adjust(lineNumberAreaWidth, 0, 0, 0);

    // selected text
    QString displayString = index.model()->data(index, Qt::DisplayRole).toString();
    drawMarker(painter, index, displayString, textRect);

    // show number of subresults in displayString
    if (index.model()->hasChildren(index)) {
        displayString += QString::fromLatin1(" (")
                         + QString::number(index.model()->rowCount(index))
                         + QLatin1Char(')');
    }

    // text and focus/selection
    QItemDelegate::drawDisplay(painter, opt, textRect, displayString);
    QItemDelegate::drawFocus(painter, opt, opt.rect);

    // check mark
    if (checkable)
        QItemDelegate::drawCheck(painter, opt, checkRect, checkState);

    painter->restore();
}
Beispiel #28
0
RenameDialog::RenameDialog(FmFileInfo* src, FmFileInfo* dest, QWidget* parent, Qt::WindowFlags f):
  QDialog(parent, f),
  action_(ActionIgnore),
  applyToAll_(false) {

  ui = new Ui::RenameDialog();
  ui->setupUi(this);

  FmPath* path = fm_file_info_get_path(dest);
  FmIcon* srcIcon = fm_file_info_get_icon(src);
  FmIcon* destIcon = fm_file_info_get_icon(dest);

  // show info for the source file
  QIcon icon = IconTheme::icon(srcIcon);
  QSize iconSize(fm_config->big_icon_size, fm_config->big_icon_size);
  QPixmap pixmap = icon.pixmap(iconSize);
  ui->srcIcon->setPixmap(pixmap);

  QString infoStr;
  const char* disp_size = fm_file_info_get_disp_size(src);
  if(disp_size) {
    infoStr = QString(tr("Type: %1\nSize: %2\nModified: %3"))
                .arg(QString::fromUtf8(fm_file_info_get_desc(src)))
                .arg(QString::fromUtf8(disp_size))
                .arg(QString::fromUtf8(fm_file_info_get_disp_mtime(src)));
  }
  else {
    infoStr = QString(tr("Type: %1\nModified: %2"))
                .arg(QString::fromUtf8(fm_file_info_get_desc(src)))
                .arg(QString::fromUtf8(fm_file_info_get_disp_mtime(src)));
  }
  ui->srcInfo->setText(infoStr);

  // show info for the dest file
  icon = IconTheme::icon(destIcon);
  pixmap = icon.pixmap(iconSize);
  ui->destIcon->setPixmap(pixmap);

  disp_size = fm_file_info_get_disp_size(dest);
  if(disp_size) {
    infoStr = QString(tr("Type: %1\nSize: %2\nModified: %3"))
                .arg(QString::fromUtf8(fm_file_info_get_desc(dest)))
                .arg(QString::fromUtf8(disp_size))
                .arg(QString::fromUtf8(fm_file_info_get_disp_mtime(dest)));
  }
  else {
    infoStr = QString(tr("Type: %1\nModified: %3"))
                .arg(QString::fromUtf8(fm_file_info_get_desc(src)))
                .arg(QString::fromUtf8(fm_file_info_get_disp_mtime(src)));
  }
  ui->destInfo->setText(infoStr);

  char* basename = fm_path_display_basename(path);
  ui->fileName->setText(QString::fromUtf8(basename));
  oldName_ = basename;
  g_free(basename);
  connect(ui->fileName, SIGNAL(textChanged(QString)), SLOT(onFileNameChanged(QString)));

  // add "Rename" button
  QAbstractButton* button = ui->buttonBox->button(QDialogButtonBox::Ok);
  button->setText(tr("&Overwrite"));
  // FIXME: there seems to be no way to place the Rename button next to the overwrite one.
  renameButton_ = ui->buttonBox->addButton(tr("&Rename"), QDialogButtonBox::ActionRole);
  connect(renameButton_, SIGNAL(clicked(bool)), SLOT(onRenameClicked()));
  renameButton_->setEnabled(false); // disabled by default

  button = ui->buttonBox->button(QDialogButtonBox::Ignore);
  connect(button, SIGNAL(clicked(bool)), SLOT(onIgnoreClicked()));
}
void EditSearchEngine::setIcon(const QIcon &icon)
{
    ui->icon->setPixmap(icon.pixmap(16, 16));
}
Beispiel #30
0
void TabIcon::setIcon(const QIcon &icon)
{
    m_sitePixmap = icon.pixmap(16);
    update();
}