예제 #1
0
int
main (int argc, char **argv)
{
	char	src[MAX_PATH+1], ext[MAX_PATH+1];
	QString	dst;
	int	i, w = 0;

	if (argc < 2) usage (argv[0]);

	memset (src, 0, sizeof (src));
	memset (ext, 0, sizeof (ext));

	snprintf (src, sizeof (src) - 1, "%s", argv[1]);
	i = strlen (src) - 1;
	while ((i >= 0) && (src[i] != '.')) i--;
	if (i<0) usage (argv[0]);

	src[i] = '\0'; i++;
	snprintf (ext, sizeof (ext) - 1, "%s", &(src[i]));

	if (strncmp (ext, "xpm", 4) == 0) {
		dst.sprintf ("new_%s.xpm", src);
	} else {
		dst.sprintf ("%s.xpm", src);
	}

	if (argc > 2) { w = atoi (argv[2]); }

	QApplication App (argc, argv);
	QPixmap srcpm (src, ext);

	if (w) srcpm = srcpm.scaledToWidth (w, Qt::FastTransformation);

	srcpm.save (dst, "xpm");

	return (0);
}
예제 #2
0
void MainWindow::on_captureIntro_pushButton_clicked()
{
    QString fileName;
    QPixmap pixmap;
    QPixmap pix;
    //this->width ()
    //pix = pixmap.grabWidget (this,680,130,300,540); // 獲取當前窗口  (0 , 0, -1, -1)

    //获取抓取的横纵坐标
    //int grapX= year_lineEdit->geometry ().x ();
    //int grapY = year_lineEdit->geometry ().y ();

    //使用grabWidget 获取截图 gridLayout_2
    pix = pixmap.grabWidget (this->explain_textEdit, 0 ,0, this->explain_textEdit->width (), this->explain_textEdit->height () );

    if (pix.isNull())
    {
        QMessageBox::information(this, "error", "grab Screen failed!", QMessageBox::Ok);
    }
    else
    {
        QString path = QFileDialog::getExistingDirectory(this, tr("Open Directory"),"/home",QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

        if(path!="")
        {
            fileName = path+"/说明截图.png";
            if (!pix.save(fileName, "PNG"))
            {
                QMessageBox::information(this, "right", "保存失败!", QMessageBox::Ok);
            }
            else
            {
                QMessageBox::information(this, "Grab", "保存成功!", QMessageBox::Ok);
            }
        }
    }
}
예제 #3
0
void Application::uploadProfilePhoto(const QImage &tosend, const PeerId &peerId) {
	PreparedPhotoThumbs photoThumbs;
	QVector<MTPPhotoSize> photoSizes;

	QPixmap thumb = QPixmap::fromImage(tosend.scaled(160, 160, Qt::KeepAspectRatio, Qt::SmoothTransformation));
	photoThumbs.insert('a', thumb);
	photoSizes.push_back(MTP_photoSize(MTP_string("a"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0)));

	QPixmap medium = QPixmap::fromImage(tosend.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation));
	photoThumbs.insert('b', medium);
	photoSizes.push_back(MTP_photoSize(MTP_string("b"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0)));

	QPixmap full = QPixmap::fromImage(tosend);
	photoThumbs.insert('c', full);
	photoSizes.push_back(MTP_photoSize(MTP_string("c"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)));

	QByteArray jpeg;
	QBuffer jpegBuffer(&jpeg);
	full.save(&jpegBuffer, "JPG", 87);

	PhotoId id = MTP::nonce<PhotoId>();

	MTPPhoto photo(MTP_photo(MTP_long(id), MTP_long(0), MTP_int(MTP::authedId()), MTP_int(unixtime()), MTP_string(""), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes)));

	QString file, filename;
	int32 filesize = 0;
	QByteArray data;

	ReadyLocalMedia ready(ToPreparePhoto, file, filename, filesize, data, id, id, peerId, photo, photoThumbs, MTP_documentEmpty(MTP_long(0)), jpeg, false);

	connect(App::uploader(), SIGNAL(photoReady(MsgId, const MTPInputFile &)), App::app(), SLOT(photoUpdated(MsgId, const MTPInputFile &)), Qt::UniqueConnection);

	MsgId newId = clientMsgId();
	App::app()->regPhotoUpdate(peerId, newId);
	App::uploader()->uploadMedia(newId, ready);
}
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++;
}
예제 #5
0
  /**
   * This method allows the user to save the plot as a png,
   * jpg, or tif image file.
   */
  void ScatterPlotWindow::savePlot() {
    QPixmap pixmap;
    QString output =
    QFileDialog::getSaveFileName((QWidget *)parent(),
                                 "Choose output file",
                                 "./",
                                 QString("Images (*.png *.jpg *.tif)"));
    if (output.isEmpty()) return;
     //Make sure the filename is valid
    if (!output.isEmpty()) {
      if(!output.endsWith(".png") && !output.endsWith(".jpg") && !output.endsWith(".tif")) {
        output = output + ".png";
      }
    }

    QString format = QFileInfo(output).suffix();
    pixmap = QPixmap::grabWidget(p_plot);

    std::string formatString = format.toStdString();
    if (!pixmap.save(output,formatString.c_str())) {
      QMessageBox::information((QWidget *)parent(),"Error","Unable to save "+ output);
      return;
    }
  }
예제 #6
0
파일: guibehind.cpp 프로젝트: shuge/dukto
void GuiBehind::sendScreenStage2() {

    // Screenshot
    QPixmap screen = QPixmap::grabWindow(QApplication::desktop()->winId());

    // Restore window
    mView->setWindowState(Qt::WindowActive);

    // Salvataggio screenshot in file
    QTemporaryFile tempFile;
    tempFile.setAutoRemove(false);
    tempFile.open();
    mScreenTempPath = tempFile.fileName();
    tempFile.close();
    screen.save(mScreenTempPath, "JPG", 95);

    // Prepare file transfer
    QString ip;
    qint16 port;
    if (!prepareStartTransfer(&ip, &port)) return;

    // Start screen transfer
    mDuktoProtocol.sendScreen(ip, port, mScreenTempPath);
}
예제 #7
0
void IconManager::addIconFromRes(int catId, const QString &iconName, const QString & resName)
{
//    QIcon _icon(resName);
    
    QPixmap pix = QIcon(resName).pixmap(48, 48);
    int lastPos = resName.lastIndexOf("/");
    QString fileName = resName.mid(lastPos + 1);
    QByteArray bytes;
    QBuffer buffer(&bytes);
    buffer.open(QIODevice::WriteOnly);
    //bytes << icon;
    //buffer << (buffer, icon);
    pix.save(&buffer, "PNG");
    QString sql = "INSERT INTO Icons (catId, name, fileName, iconData) VALUES (?, ?, ?, ?)";
    QSqlQuery *q = new QSqlQuery(db);
    q->prepare(sql);
    q->addBindValue(catId);
    q->addBindValue(iconName);
    q->addBindValue(fileName);
    q->addBindValue(bytes);
    q->exec();
    delete q;
    
}
예제 #8
0
	void CustomWebView::NavigateHome ()
	{
		QFile file (":/resources/html/home.html");
		file.open (QIODevice::ReadOnly);
		QString data = file.readAll ();
		data.replace ("{pagetitle}",
				tr ("Welcome to LeechCraft!"));
		data.replace ("{title}",
				tr ("Welcome to LeechCraft!"));
		data.replace ("{body}",
				tr ("Welcome to LeechCraft, the integrated internet-client.<br />"
					"More info is available on the <a href='http://leechcraft.org'>"
					"project's site</a>."));

		QBuffer iconBuffer;
		iconBuffer.open (QIODevice::ReadWrite);
		QPixmap pixmap (":/resources/images/poshuku.svg");
		pixmap.save (&iconBuffer, "PNG");

		data.replace ("{img}",
				QByteArray ("data:image/png;base64,") + iconBuffer.buffer ().toBase64 ());

		setHtml (data);
	}
예제 #9
0
void SpeedDial::thumbnailCreated(const QPixmap &image)
{
    PageThumbnailer* thumbnailer = qobject_cast<PageThumbnailer*>(sender());
    if (!thumbnailer) {
        return;
    }

    QString url = thumbnailer->url().toString();
    QString fileName = m_thumbnailsDir + QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md4).toHex() + ".png";

    if (image.isNull()) {
        fileName = "qrc:/html/broken-page.png";
    }
    else {
        if (!image.save(fileName)) {
            qWarning() << "SpeedDial::thumbnailCreated Cannot save thumbnail to " << fileName;
        }

        fileName = QUrl::fromLocalFile(fileName).toString();
    }

    m_regenerateScript = true;

    for (int i = 0; i < m_webFrames.count(); i++) {
        QWebFrame* frame = m_webFrames.at(i).data();
        if (!frame) {
            m_webFrames.removeAt(i);
            i--;
            continue;
        }

        frame->evaluateJavaScript(QString("setImageToUrl('%1', '%2');").arg(url, fileName));
    }

    thumbnailer->deleteLater();
}
예제 #10
0
void Scene::sceneMain()
{
    qDebug() << "now in sceneMain";
    Chessboard* floor = new Chessboard(200, Color(255, 0, 0),
                                    Point(0, SHEIGHT, 0),
                                    Vector(-1, 0, 0), Vector(0, 0, 1),
                                    this,
                                    Color(0, 255, 0),
                                    0.0, 0.7, 0.05, 20, 0, 1);
    Chessboard* background = new Chessboard(200, Color(255, 255, 0),
                                  Point(0, 0, SDEPTH),
                                  Vector(1, 0, 0), Vector(0, 1, 0),
                                  this,
                                  Color(128, 128, 255),
                                  0.0, 0.7, 0.05, 20, 0, 1);
    models.append(floor);
    models.append(background);
    Plane* mirror = new Plane(Point(0.2 * SWIDTH, 0, 0),
                              Vector(0.2, 0, 1), Vector(0, -1, 0),
                              this,
                              Color(255, 255, 255),
                              1, 0, 0, 0, 0, 0);
    //models.append(mirror);
    Ball* b2 = new Ball(200,
                        Point(2 * SWIDTH / 3,  2 * SHEIGHT / 3, SDEPTH / 3),
                        this,
                        Color(255, 224, 0),
                        0.95, 0.01, 0.01, 50, 0, 1.5);
    Ball* b3 = new Ball(300,
                        Point(SWIDTH / 2,  SHEIGHT / 2, SDEPTH * 0.3),
                        this,
                        Color(128, 128, 128),
                        0, 0, 0.1, 50, 0.9, 1.1);
    //models.append(b2);
    //models.append(b3);
    for(int i = 12; i < 13; i ++)
    {
        Ball* b1 = new Ball(200,
                            Point(SWIDTH * 0.55, SHEIGHT * 0.45, SDEPTH * (i / 20.0) ),
                            this, Color(255, 255, 255),
                            0.4, 0.2, 0.2, 50, 0, 1.5);
        //models.append(b1);
        for(int j = 0; j <10 ; j ++)
        {
            for(int k = 0; k < 10; k ++)
            {
                for(int l = 0; l < 10; l ++)
                {
                    Ball *b = new Ball(100, Point(SWIDTH * 0.1 * (j + 0.5), SHEIGHT * 0.1 * (k + 0.5), SDEPTH * 0.1 * (l + 0.5)),
                                       this, Color(255 * 0.1 * (j + 0.5), 255 * 0.1 * (k + 0.5), 255 * 0.1 * (l + 0.5)),
                        0, 0, 0.1, 50, 0.9, 1.1);
                    models.append(b);
                }
            }
        }
        QTime time;
        time.start();
        qDebug() << "Now rendering " << i;
        render();
        int diff = time.elapsed();
        qDebug() << "Render finished in" << diff / 1000.0 << "seconds.";

        QPixmap pixmap = QPixmap::fromImage(*image);
        QString str = "Ball_" + QString::number(i) + ".png";
        pixmap.save(str);
        addPixmap(pixmap);
        models.pop_back();
        if(b1 != NULL)
        {
            delete b1;
            b1 = NULL;
        }
    }
    qDebug() << "Finished!";
}
예제 #11
0
SettingsWidget::SettingsWidget(int page, const QString &moduleName, QWidget *videoEq) :
	videoEq(videoEq), videoEqOriginalParent(videoEq->parentWidget()),
	wasShow(false),
	moduleIndex(0)
{
	setWindowFlags(Qt::Window);
	setWindowTitle(tr("Settings"));
	setAttribute(Qt::WA_DeleteOnClose);

	Settings &QMPSettings = QMPlay2Core.getSettings();

	tabW = new QTabWidget;

	QPushButton *applyB = new QPushButton;
	applyB->setText(tr("Apply"));
	connect(applyB, SIGNAL(clicked()), this, SLOT(apply()));

	QPushButton *closeB = new QPushButton;
	closeB->setText(tr("Close"));
	closeB->setShortcut(QKeySequence("Escape"));
	connect(closeB, SIGNAL(clicked()), this, SLOT(close()));

	QGridLayout *layout = new QGridLayout(this);
	layout->addWidget(tabW, 0, 0, 1, 3);
	layout->addWidget(applyB, 1, 1, 1, 1);
	layout->addWidget(closeB, 1, 2, 1, 1);
	layout->setMargin(2);

	/* Page 1 */
	{
		QWidget *page1Widget = new QWidget;
		page1 = new Ui::GeneralSettings;
		page1->setupUi(page1Widget);

		appendColon(page1->langL);
		appendColon(page1->styleL);
		appendColon(page1->encodingL);
		appendColon(page1->audioLangL);
		appendColon(page1->subsLangL);
		appendColon(page1->screenshotL);
		appendColon(page1->profileL);

		tabW->addTab(page1Widget, tr("General settings"));

		int idx;

		page1->langBox->addItem("English", "en");
		page1->langBox->setCurrentIndex(0);
		const QStringList langs = QMPlay2Core.getLanguages();
		for (int i = 0; i < langs.count(); i++)
		{
			page1->langBox->addItem(QMPlay2Core.getLongFromShortLanguage(langs[i]), langs[i]);
			if (QMPlay2Core.getLanguage() == langs[i])
				page1->langBox->setCurrentIndex(i + 1);
		}

		page1->styleBox->addItems(QStyleFactory::keys());
		idx = page1->styleBox->findText(QApplication::style()->objectName(), Qt::MatchFixedString);
		if (idx > -1 && idx < page1->styleBox->count())
			page1->styleBox->setCurrentIndex(idx);
		connect(page1->styleBox, SIGNAL(currentIndexChanged(int)), this, SLOT(chStyle()));

		QStringList encodings;
		for (const QByteArray &item : QTextCodec::availableCodecs())
			encodings += QTextCodec::codecForName(item)->name();
		encodings.removeDuplicates();
		page1->encodingB->addItems(encodings);
		idx = page1->encodingB->findText(QMPSettings.getByteArray("FallbackSubtitlesEncoding"));
		if (idx > -1)
			page1->encodingB->setCurrentIndex(idx);

		const QString audioLang = QMPSettings.getString("AudioLanguage");
		const QString subsLang = QMPSettings.getString("SubtitlesLanguage");
		page1->audioLangB->addItem(tr("Default or first stream"));
		page1->subsLangB->addItem(tr("Default or first stream"));
		for (const QString &lang : QMPlay2Core.getLanguagesMap())
		{
			page1->audioLangB->addItem(lang);
			page1->subsLangB->addItem(lang);
			if (lang == audioLang)
				page1->audioLangB->setCurrentIndex(page1->audioLangB->count() - 1);
			if (lang == subsLang)
				page1->subsLangB->setCurrentIndex(page1->subsLangB->count() - 1);
		}
		{
			const QString currentProfile = QSettings(QMPlay2Core.getSettingsDir() + "Profile.ini", QSettings::IniFormat).value("Profile").toString();
			page1->profileB->addItem(tr("Default"));
			for (const QString &profile : QDir(QMPlay2Core.getSettingsDir() + "Profiles/").entryList(QDir::Dirs | QDir::NoDotAndDotDot))
			{
				page1->profileB->addItem(profile);
				if (profile == currentProfile)
					page1->profileB->setCurrentIndex(page1->profileB->count() - 1);
			}
			connect(page1->profileB, SIGNAL(currentIndexChanged(int)), this, SLOT(profileListIndexChanged(int)));

			page1->profileRemoveB->setIcon(QMPlay2Core.getIconFromTheme("list-remove"));
			page1->profileRemoveB->setEnabled(page1->profileB->currentIndex() != 0);
			connect(page1->profileRemoveB, SIGNAL(clicked()), this, SLOT(removeProfile()));
		}

		page1->screenshotE->setText(QMPSettings.getString("screenshotPth"));
		page1->screenshotFormatB->setCurrentIndex(page1->screenshotFormatB->findText(QMPSettings.getString("screenshotFormat")));
		page1->screenshotB->setIcon(QMPlay2Core.getIconFromTheme("folder-open"));
		connect(page1->screenshotB, SIGNAL(clicked()), this, SLOT(chooseScreenshotDir()));

		connect(page1->setAppearanceB, SIGNAL(clicked()), this, SLOT(setAppearance()));
		connect(page1->setKeyBindingsB, SIGNAL(clicked()), this, SLOT(setKeyBindings()));

#ifdef ICONS_FROM_THEME
		page1->iconsFromTheme->setChecked(QMPSettings.getBool("IconsFromTheme"));
#else
		delete page1->iconsFromTheme;
		page1->iconsFromTheme = nullptr;
#endif

		page1->showCoversGB->setChecked(QMPSettings.getBool("ShowCovers"));
		page1->blurCoversB->setChecked(QMPSettings.getBool("BlurCovers"));
		page1->showDirCoversB->setChecked(QMPSettings.getBool("ShowDirCovers"));

		page1->autoOpenVideoWindowB->setChecked(QMPSettings.getBool("AutoOpenVideoWindow"));
		page1->autoRestoreMainWindowOnVideoB->setChecked(QMPSettings.getBool("AutoRestoreMainWindowOnVideo"));

		page1->autoUpdatesB->setChecked(QMPSettings.getBool("AutoUpdates"));
#ifndef UPDATER
		page1->autoUpdatesB->setText(tr("Automatically check for updates"));
#endif

		if (Notifies::hasBoth())
			page1->trayNotifiesDefault->setChecked(QMPSettings.getBool("TrayNotifiesDefault"));
		else
		{
			delete page1->trayNotifiesDefault;
			page1->trayNotifiesDefault = nullptr;
		}

		page1->autoDelNonGroupEntries->setChecked(QMPSettings.getBool("AutoDelNonGroupEntries"));

		page1->tabsNorths->setChecked(QMPSettings.getBool("MainWidget/TabPositionNorth"));

#ifdef QMPLAY2_ALLOW_ONLY_ONE_INSTANCE
		page1->allowOnlyOneInstance->setChecked(QMPSettings.getBool("AllowOnlyOneInstance"));
#else
		delete page1->allowOnlyOneInstance;
		page1->allowOnlyOneInstance = nullptr;
#endif

		page1->hideArtistMetadata->setChecked(QMPSettings.getBool("HideArtistMetadata"));
		page1->displayOnlyFileName->setChecked(QMPSettings.getBool("DisplayOnlyFileName"));
		page1->restoreRepeatMode->setChecked(QMPSettings.getBool("RestoreRepeatMode"));
		page1->stillImages->setChecked(QMPSettings.getBool("StillImages"));

		page1->proxyB->setChecked(QMPSettings.getBool("Proxy/Use"));
		page1->proxyHostE->setText(QMPSettings.getString("Proxy/Host"));
		page1->proxyPortB->setValue(QMPSettings.getInt("Proxy/Port"));
		page1->proxyLoginB->setChecked(QMPSettings.getBool("Proxy/Login"));
		page1->proxyUserE->setText(QMPSettings.getString("Proxy/User"));
		page1->proxyPasswordE->setText(QByteArray::fromBase64(QMPSettings.getByteArray("Proxy/Password")));

		const QIcon viewRefresh = QMPlay2Core.getIconFromTheme("view-refresh");
		page1->clearCoversCache->setIcon(viewRefresh);
		connect(page1->clearCoversCache, SIGNAL(clicked()), this, SLOT(clearCoversCache()));
		page1->removeYtDlB->setIcon(QMPlay2Core.getIconFromTheme("list-remove"));
		connect(page1->removeYtDlB, SIGNAL(clicked()), this, SLOT(removeYouTubeDl()));
		page1->resetSettingsB->setIcon(viewRefresh);
		connect(page1->resetSettingsB, SIGNAL(clicked()), this, SLOT(resetSettings()));
	}

	/* Page 2 */
	{
		QWidget *page2Widget = new QWidget;
		page2 = new Ui::PlaybackSettings;
		page2->setupUi(page2Widget);

		appendColon(page2->shortSeekL);
		appendColon(page2->longSeekL);
		appendColon(page2->bufferLocalL);
		appendColon(page2->bufferNetworkL);
		appendColon(page2->backwardBufferNetworkL);
		appendColon(page2->playIfBufferedL);
		appendColon(page2->maxVolL);
		appendColon(page2->forceSamplerate);
		appendColon(page2->forceChannels);

		page2->shortSeekB->setSuffix(" " + page2->shortSeekB->suffix());
		page2->longSeekB->setSuffix(" " + page2->longSeekB->suffix());
		page2->playIfBufferedB->setSuffix(" " + page2->playIfBufferedB->suffix());
		page2->replayGainPreamp->setPrefix(page2->replayGainPreamp->prefix() + ": ");

		tabW->addTab(page2Widget, tr("Playback settings"));

		page2->shortSeekB->setValue(QMPSettings.getInt("ShortSeek"));
		page2->longSeekB->setValue(QMPSettings.getInt("LongSeek"));
		page2->bufferLocalB->setValue(QMPSettings.getInt("AVBufferLocal"));
		page2->bufferNetworkB->setValue(QMPSettings.getInt("AVBufferNetwork"));
		page2->backwardBufferNetworkB->setCurrentIndex(QMPSettings.getUInt("BackwardBuffer"));
		page2->playIfBufferedB->setValue(QMPSettings.getDouble("PlayIfBuffered"));
		page2->maxVolB->setValue(QMPSettings.getInt("MaxVol"));

		page2->forceSamplerate->setChecked(QMPSettings.getBool("ForceSamplerate"));
		page2->samplerateB->setValue(QMPSettings.getInt("Samplerate"));
		connect(page2->forceSamplerate, SIGNAL(toggled(bool)), page2->samplerateB, SLOT(setEnabled(bool)));
		page2->samplerateB->setEnabled(page2->forceSamplerate->isChecked());

		page2->forceChannels->setChecked(QMPSettings.getBool("ForceChannels"));
		page2->channelsB->setValue(QMPSettings.getInt("Channels"));
		connect(page2->forceChannels, SIGNAL(toggled(bool)), page2->channelsB, SLOT(setEnabled(bool)));
		page2->channelsB->setEnabled(page2->forceChannels->isChecked());

		page2->replayGain->setChecked(QMPSettings.getBool("ReplayGain/Enabled"));
		page2->replayGainAlbum->setChecked(QMPSettings.getBool("ReplayGain/Album"));
		page2->replayGainPreventClipping->setChecked(QMPSettings.getBool("ReplayGain/PreventClipping"));
		page2->replayGainPreamp->setValue(QMPSettings.getDouble("ReplayGain/Preamp"));

		page2->wheelActionB->setChecked(QMPSettings.getBool("WheelAction"));
		page2->wheelSeekB->setChecked(QMPSettings.getBool("WheelSeek"));
		page2->wheelVolumeB->setChecked(QMPSettings.getBool("WheelVolume"));

		page2->storeARatioAndZoomB->setChecked(QMPSettings.getBool("StoreARatioAndZoom"));
		connect(page2->storeARatioAndZoomB, &QCheckBox::toggled, this, [this](bool checked) {
			if (checked)
			{
				page2->keepZoom->setChecked(true);
				page2->keepARatio->setChecked(true);
			}
		});

		page2->keepZoom->setChecked(QMPSettings.getBool("KeepZoom"));
		connect(page2->keepZoom, &QCheckBox::toggled, this, [this](bool checked) {
			if (!checked && !page2->keepARatio->isChecked())
			{
				page2->storeARatioAndZoomB->setChecked(false);
			}
		});

		page2->keepARatio->setChecked(QMPSettings.getBool("KeepARatio"));
		connect(page2->keepARatio, &QCheckBox::toggled, this, [this](bool checked) {
			if (!checked && !page2->keepZoom->isChecked())
			{
				page2->storeARatioAndZoomB->setChecked(false);
			}
		});

		page2->showBufferedTimeOnSlider->setChecked(QMPSettings.getBool("ShowBufferedTimeOnSlider"));
		page2->savePos->setChecked(QMPSettings.getBool("SavePos"));
		page2->keepSubtitlesDelay->setChecked(QMPSettings.getBool("KeepSubtitlesDelay"));
		page2->keepSubtitlesScale->setChecked(QMPSettings.getBool("KeepSubtitlesScale"));
		page2->keepVideoDelay->setChecked(QMPSettings.getBool("KeepVideoDelay"));
		page2->keepSpeed->setChecked(QMPSettings.getBool("KeepSpeed"));
		page2->syncVtoA->setChecked(QMPSettings.getBool("SyncVtoA"));
		page2->silence->setChecked(QMPSettings.getBool("Silence"));
		page2->restoreVideoEq->setChecked(QMPSettings.getBool("RestoreVideoEqualizer"));
		page2->ignorePlaybackError->setChecked(QMPSettings.getBool("IgnorePlaybackError"));
		page2->leftMouseTogglePlay->setCheckState((Qt::CheckState)qBound(0, QMPSettings.getInt("LeftMouseTogglePlay"), 2));

		page2->accurateSeekB->setCheckState((Qt::CheckState)QMPSettings.getInt("AccurateSeek"));
		page2->accurateSeekB->setToolTip(tr("Slower, but more accurate seeking.\nPartially checked doesn't affect seeking on slider."));

		page2->unpauseWhenSeekingB->setChecked(QMPSettings.getBool("UnpauseWhenSeeking"));

		const QString modulesListTitle[3] = {
			tr("Video output priority"),
			tr("Audio output priority"),
			tr("Decoders priority")
		};
		for (int m = 0; m < 3; ++m)
		{
			QGroupBox *groupB = new QGroupBox(modulesListTitle[m]);
			Ui::ModulesList *ml = new Ui::ModulesList;
			ml->setupUi(groupB);
			connect(ml->list, SIGNAL(itemDoubleClicked (QListWidgetItem *)), this, SLOT(openModuleSettings(QListWidgetItem *)));
			connect(ml->moveUp, SIGNAL(clicked()), this, SLOT(moveModule()));
			connect(ml->moveDown, SIGNAL(clicked()), this, SLOT(moveModule()));
			ml->moveUp->setProperty("idx", m);
			ml->moveDown->setProperty("idx", m);
			page2->modulesListLayout->addWidget(groupB);
			page2ModulesList[m] = ml;
		}
	}

	/* Page 3 */
	{
		page3 = new Page3;
		tabW->addTab(page3, tr("Modules"));

		page3->listW = new QListWidget;
		page3->listW->setIconSize({32, 32});
		page3->listW->setMinimumSize(200, 0);
		page3->listW->setMaximumSize(200, 16777215);
		for (Module *module : QMPlay2Core.getPluginsInstance())
		{
			QListWidgetItem *tWI = new QListWidgetItem(module->name());
			tWI->setData(Qt::UserRole, qVariantFromValue((void *)module));
			QString toolTip = "<html>" + tr("Contains") + ":";
			for (const Module::Info &mod : module->getModulesInfo(true))
			{
				const QPixmap moduleIcon = Functions::getPixmapFromIcon(mod.icon, QSize(22, 22), this);
				toolTip += "<p>&nbsp;&nbsp;&nbsp;&nbsp;";
				bool hasIcon = false;
				if (!moduleIcon.isNull())
				{
					QBuffer buffer;
					if (buffer.open(QBuffer::WriteOnly) && moduleIcon.save(&buffer, "PNG"))
					{
						toolTip += "<img width='22' height='22' src='data:image/png;base64, " + buffer.data().toBase64() + "'/> ";
						hasIcon = true;
					}
				}
				if (!hasIcon)
					toolTip += "- ";
				toolTip += mod.name + "</p>";
			}
			toolTip += "</html>";
			tWI->setToolTip(toolTip);
			tWI->setIcon(QMPlay2GUI.getIcon(module->icon()));
			page3->listW->addItem(tWI);
			if (page == 2 && !moduleName.isEmpty() && module->name() == moduleName)
				moduleIndex = page3->listW->count() - 1;
		}

		page3->scrollA = new QScrollArea;
		page3->scrollA->setWidgetResizable(true);
		page3->scrollA->setFrameShape(QFrame::NoFrame);

		QHBoxLayout *layout = new QHBoxLayout(page3);
		layout->setMargin(0);
		layout->setSpacing(1);
		layout->addWidget(page3->listW);
		layout->addWidget(page3->scrollA);
		connect(page3->listW, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(chModule(QListWidgetItem *)));
	}

	/* Page 4 */
	{
		page4 = new Page4;
		tabW->addTab(page4, tr("Subtitles"));

		page4->colorsAndBordersB = new QCheckBox(tr("Colors and borders"));
		page4->colorsAndBordersB->setChecked(QMPSettings.getBool("ApplyToASS/ColorsAndBorders"));

		page4->marginsAndAlignmentB = new QCheckBox(tr("Margins and alignment"));
		page4->marginsAndAlignmentB->setChecked(QMPSettings.getBool("ApplyToASS/MarginsAndAlignment"));

		page4->fontsB = new QCheckBox(tr("Fonts and spacing"));
		page4->fontsB->setChecked(QMPSettings.getBool("ApplyToASS/FontsAndSpacing"));

		page4->overridePlayResB = new QCheckBox(tr("Use the same size"));
		page4->overridePlayResB->setChecked(QMPSettings.getBool("ApplyToASS/OverridePlayRes"));

		page4->toAssGB = new QGroupBox(tr("Apply for ASS/SSA subtitles"));
		page4->toAssGB->setCheckable(true);
		page4->toAssGB->setChecked(QMPSettings.getBool("ApplyToASS/ApplyToASS"));

		QGridLayout *page4ToAssLayout = new QGridLayout(page4->toAssGB);
		page4ToAssLayout->addWidget(page4->colorsAndBordersB, 0, 0, 1, 1);
		page4ToAssLayout->addWidget(page4->marginsAndAlignmentB, 1, 0, 1, 1);
		page4ToAssLayout->addWidget(page4->fontsB, 0, 1, 1, 1);
		page4ToAssLayout->addWidget(page4->overridePlayResB, 1, 1, 1, 1);

		page4->addWidget(page4->toAssGB);
	}

	/* Page 5 */
	{
		page5 = new Page5;
		tabW->addTab(page5, tr("OSD"));

		page5->enabledB = new QCheckBox(tr("OSD enabled"));
		page5->enabledB->setChecked(QMPSettings.getBool("OSD/Enabled"));
		page5->addWidget(page5->enabledB);
	}

	/* Page 6 */
	{
		page6 = new Page6;
		tabW->addTab(page6, tr("Video filters"));

		QWidget *widget = new QWidget;

		QGridLayout *layout = new QGridLayout(widget);
		layout->setMargin(0);

		page6->deintSettingsW = new DeintSettingsW;
		layout->addWidget(page6->deintSettingsW, 0, 0, 1, 2);

		page6->videoEqContainer = new QGroupBox(videoEq->objectName());
		layout->addWidget(page6->videoEqContainer, 1, 0, 2, 1);

		page6->otherVFiltersW = new OtherVFiltersW(false);
		if (!page6->otherVFiltersW->count())
		{
			delete page6->otherVFiltersW;
			page6->otherVFiltersW = nullptr;
		}
		else
		{
			QGroupBox *otherVFiltersContainer = new QGroupBox(tr("Software video filters"));
			QGridLayout *otherVFiltersLayout = new QGridLayout(otherVFiltersContainer);
			otherVFiltersLayout->addWidget(page6->otherVFiltersW);
			connect(page6->otherVFiltersW, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(openModuleSettings(QListWidgetItem *)));
			layout->addWidget(otherVFiltersContainer, 1, 1, 1, 1);
		}

		OtherVFiltersW *otherHWVFiltersW = new OtherVFiltersW(true);
		if (!otherHWVFiltersW->count())
			delete otherHWVFiltersW;
		else
		{
			QGroupBox *otherHWVFiltersContainer = new QGroupBox(tr("Hardware accelerated video outputs"));
			QGridLayout *otherHWVFiltersLayout = new QGridLayout(otherHWVFiltersContainer);
			otherHWVFiltersLayout->addWidget(otherHWVFiltersW);
			connect(otherHWVFiltersW, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(openModuleSettings(QListWidgetItem *)));
			layout->addWidget(otherHWVFiltersContainer, 2, 1, 1, 1);
		}

		page6->setWidget(widget);
	}

	connect(tabW, SIGNAL(currentChanged(int)), this, SLOT(tabCh(int)));
	tabW->setCurrentIndex(page);

	show();
}
예제 #12
0
void TupCanvas::wakeUpLibrary()
{
    QString graphicPath = QFileDialog::getOpenFileName (this, tr("Import a SVG file..."), QDir::homePath(),
                                                    tr("Vectorial") + " (*.svg *.png *.jpg *.jpeg *.gif)");
    if (graphicPath.isEmpty())
        return;

    QFile f(graphicPath);
    QFileInfo fileInfo(f);

    if (graphicPath.toLower().endsWith(".svg")) {
        QString tag = fileInfo.fileName();

        if (f.open(QIODevice::ReadOnly)) {
            QByteArray data = f.readAll();
            f.close();
            // int projectWidth = k->size.width();
            // int projectHeight = k->size.height();

            TupProjectRequest request = TupRequestBuilder::createLibraryRequest(TupProjectRequest::Add, tag,
                                        TupLibraryObject::Svg, TupProject::FRAMES_EDITION, data, QString(),
                                        k->scene->currentSceneIndex(), k->scene->currentLayerIndex(), k->scene->currentFrameIndex());
            emit requestTriggered(&request);
        }
    } else {
        QString symName = fileInfo.fileName();

        if (f.open(QIODevice::ReadOnly)) {
            QByteArray data = f.readAll();
            f.close();

            QPixmap *pixmap = new QPixmap(graphicPath);
            int picWidth = pixmap->width();
            int picHeight = pixmap->height();
            int projectWidth = k->size.width(); 
            int projectHeight = k->size.height();

            if (picWidth > projectWidth || picHeight > projectHeight) {
                QDesktopWidget desktop;
                QMessageBox msgBox;
                msgBox.setWindowTitle(tr("Information"));
                msgBox.setIcon(QMessageBox::Question);
                msgBox.setText(tr("Image is bigger than workspace."));
                msgBox.setInformativeText(tr("Do you want to resize it?"));
                msgBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
                msgBox.setDefaultButton(QMessageBox::Ok);
                msgBox.show();
                msgBox.move((int) (desktop.screenGeometry().width() - msgBox.width())/2,
                            (int) (desktop.screenGeometry().height() - msgBox.height())/2);

                int answer = msgBox.exec();

                if (answer == QMessageBox::Yes) {
                    pixmap = new QPixmap();
                    QString extension = fileInfo.suffix().toUpper();
                    QByteArray ba = extension.toAscii();
                    const char* ext = ba.data();
                    if (pixmap->loadFromData(data, ext)) {
                        QPixmap newpix;
                        if (picWidth > projectWidth)
                            newpix = QPixmap(pixmap->scaledToWidth(projectWidth, Qt::SmoothTransformation));
                        else
                            newpix = QPixmap(pixmap->scaledToHeight(projectHeight, Qt::SmoothTransformation));
                        QBuffer buffer(&data);
                        buffer.open(QIODevice::WriteOnly);
                        newpix.save(&buffer, ext);
                    }
                }
           }

           QString tag = symName;

           TupProjectRequest request = TupRequestBuilder::createLibraryRequest(TupProjectRequest::Add, tag,
                                                                               TupLibraryObject::Image, TupProject::FRAMES_EDITION, data, QString(),
                                                                               k->scene->currentSceneIndex(), k->scene->currentLayerIndex(), k->scene->currentFrameIndex());
           emit requestTriggered(&request);

           data.clear();
        }
    }
}
예제 #13
0
// Remote controlling
void MainWindow::remoteAction(QString cmd) {

	if(variables->verbose)
		LOG << CURDATE << "remoteAction(): " << cmd.toStdString() << NL;

	if(cmd == "open") {

		if(variables->verbose)
			LOG << CURDATE << "remoteAction(): Open file" << NL;
		if(!this->isVisible()) {
			// Get screenshots
			for(int i = 0; i < QGuiApplication::screens().count(); ++i) {
				QScreen *screen = QGuiApplication::screens().at(i);
				QRect r = screen->geometry();
				QPixmap pix = screen->grabWindow(0,r.x(),r.y(),r.width(),r.height());
				pix.save(QDir::tempPath() + QString("/photoqt_screenshot_%1.jpg").arg(i));
			}
			updateWindowGeometry();
			this->raise();
			this->requestActivate();
		}

		QMetaObject::invokeMethod(object, "openFile");

	} else if(cmd == "nothumbs") {

		if(variables->verbose)
			LOG << CURDATE << "remoteAction(): Disable thumbnails" << NL;
		settingsPermanent->thumbnailDisable = true;
		settingsPermanent->thumbnailDisableChanged(settingsPermanent->thumbnailDisable);

	} else if(cmd == "thumbs") {

		if(variables->verbose)
			LOG << CURDATE << "remoteAction(): Enable thumbnails" << NL;
		settingsPermanent->thumbnailDisable = true;
		settingsPermanent->thumbnailDisableChanged(settingsPermanent->thumbnailDisable);

	} else if(cmd == "hide" || (cmd == "toggle" && this->isVisible())) {

		if(variables->verbose)
			LOG << CURDATE << "remoteAction(): Hiding" << NL;
		if(settingsPermanent->trayicon != 1) {
			settingsPermanent->trayicon = 1;
			settingsPermanent->trayiconChanged(settingsPermanent->trayicon);
		}
		QMetaObject::invokeMethod(object, "hideOpenFile");
		this->hide();

	} else if(cmd.startsWith("show") || (cmd == "toggle" && !this->isVisible())) {

		if(variables->verbose)
			LOG << CURDATE << "remoteAction(): Showing" << NL;

		// The same code can be found at the end of main.cpp
		if(!this->isVisible()) {
			// Get screenshots
			for(int i = 0; i < QGuiApplication::screens().count(); ++i) {
				QScreen *screen = QGuiApplication::screens().at(i);
				QRect r = screen->geometry();
				QPixmap pix = screen->grabWindow(0,r.x(),r.y(),r.width(),r.height());
				pix.save(QDir::tempPath() + QString("/photoqt_screenshot_%1.jpg").arg(i));
			}
			updateWindowGeometry();
		}
		this->raise();
		this->requestActivate();

		if(variables->currentDir == "" && cmd != "show_noopen")
			QMetaObject::invokeMethod(object, "openFile");

	} else if(cmd.startsWith("::file::")) {

		if(variables->verbose)
			LOG << CURDATE << "remoteAction(): Opening passed-on file" << NL;
		QMetaObject::invokeMethod(object, "hideOpenFile");
		handleOpenFileEvent(cmd.remove(0,8));

	}


}
예제 #14
0
파일: core.cpp 프로젝트: Pik-9/qTox
/**
 * @brief Initializes the core, must be called before anything else
 */
void Core::start()
{
    bool isNewProfile = profile.isNewProfile();
    if (isNewProfile)
    {
        qDebug() << "Creating a new profile";
        makeTox(QByteArray());
        setStatusMessage(tr("Toxing on qTox"));
        setUsername(profile.getName());
    }
    else
    {
        qDebug() << "Loading user profile";
        QByteArray savedata = profile.loadToxSave();
        if (savedata.isEmpty())
        {
            emit failedToStart();
            return;
        }
        makeTox(savedata);
    }

    qsrand(time(nullptr));

    if (!tox)
    {
        ready = true;
        GUI::setEnabled(true);
        return;
    }

    // set GUI with user and statusmsg
    QString name = getUsername();
    if (!name.isEmpty())
        emit usernameSet(name);

    QString msg = getStatusMessage();
    if (!msg.isEmpty())
        emit statusMessageSet(msg);

    QString id = getSelfId().toString();
    if (!id.isEmpty())
        emit idSet(id);

    // TODO: This is a backwards compatibility check,
    // once most people have been upgraded away from the old HistoryKeeper, remove this
    if (Nexus::getProfile()->isEncrypted())
        checkEncryptedHistory();

    loadFriends();

    tox_callback_friend_request(tox, onFriendRequest, this);
    tox_callback_friend_message(tox, onFriendMessage, this);
    tox_callback_friend_name(tox, onFriendNameChange, this);
    tox_callback_friend_typing(tox, onFriendTypingChange, this);
    tox_callback_friend_status_message(tox, onStatusMessageChanged, this);
    tox_callback_friend_status(tox, onUserStatusChanged, this);
    tox_callback_friend_connection_status(tox, onConnectionStatusChanged, this);
    tox_callback_friend_read_receipt(tox, onReadReceiptCallback, this);
    tox_callback_group_invite(tox, onGroupInvite, this);
    tox_callback_group_message(tox, onGroupMessage, this);
    tox_callback_group_namelist_change(tox, onGroupNamelistChange, this);
    tox_callback_group_title(tox, onGroupTitleChange, this);
    tox_callback_group_action(tox, onGroupAction, this);
    tox_callback_file_chunk_request(tox, CoreFile::onFileDataCallback, this);
    tox_callback_file_recv(tox, CoreFile::onFileReceiveCallback, this);
    tox_callback_file_recv_chunk(tox, CoreFile::onFileRecvChunkCallback, this);
    tox_callback_file_recv_control(tox, CoreFile::onFileControlCallback, this);

    QPixmap pic = profile.loadAvatar();
    if (!pic.isNull() && !pic.size().isEmpty())
    {
        QByteArray data;
        QBuffer buffer(&data);
        buffer.open(QIODevice::WriteOnly);
        pic.save(&buffer, "PNG");
        buffer.close();
        setAvatar(data);
    }
    else
    {
        qDebug() << "Self avatar not found, will broadcast empty avatar to friends";
        setAvatar({});
    }

    ready = true;

    // If we created a new profile earlier,
    // now that we're ready save it and ONLY THEN broadcast the new ID.
    // This is useful for e.g. the profileForm that searches for saves.
    if (isNewProfile)
    {
        profile.saveToxSave();
        emit idSet(getSelfId().toString());
    }

    if (isReady())
        GUI::setEnabled(true);

    process(); // starts its own timer
    av->start();
}
예제 #15
0
파일: dataio.cpp 프로젝트: pqpqpqpqpq/Graph
/*!
	\brief Save QPixmap to .jpg file
	\param	pixmap		QPixmap object which holds the pixmap
	\param	fileName	The file name of the pixmap file
*/
void DataIO::savePixmap(QPixmap &pixmap, const QString &fileName)
{
	pixmap.save(fileName);
}
예제 #16
0
QPixmap MediaBrowser::iconForImage(const QString & file, const QSize & size)
{
	QPixmap cache;
	QDir path(QString("%1/%2").arg(AppSettings::cachePath()).arg(CACHE_DIR));
	if(!path.exists())
		QDir(AppSettings::cachePath()).mkdir(CACHE_DIR);

	QString cacheFile = QString("%1/%2/%3-%4x%5")
				.arg(AppSettings::cachePath())
				.arg(CACHE_DIR)
				.arg(MD5::md5sum(file))
				.arg(size.width())
				.arg(size.height());


	//QPixmap orig(file);
	//orig = orig.scaled(size,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
	//orig.detach();

	//return orig;

	bool cacheFileModified = !QFile(cacheFile).exists() || QFileInfo(file).lastModified() >= QFileInfo(cacheFile).lastModified();
	//qDebug() << "MediaBrowser::iconForImage: file:"<<file<<", size:"<<size<<", cacheFile: "<<cacheFile<<", cacheModified:"<<cacheFileModified;
	
	if(!QPixmapCache::find(cacheFile,cache) || cacheFileModified)
	{
		if(QFile(cacheFile).exists() && !cacheFileModified)
		{
			cache.load(cacheFile);
			QPixmapCache::insert(cacheFile,cache);
// 			qDebug() << "MediaBrowser::iconForImage: file:"<<file<<", size:"<<size<<": hit DISK (loaded scaled from disk cache)";
		}
		else
		{
			bool gotThumb = false;
			try
			{
				Exiv2::Image::AutoPtr exiv = Exiv2::ImageFactory::open(file.toStdString()); 
				if(exiv.get() != 0)
				{
					exiv->readMetadata();
					Exiv2::ExifData& exifData = exiv->exifData();
					if (exifData.empty()) 
					{
// 						qDebug() << file << ": No Exif data found in the file";
					}
					Exiv2::ExifThumb exifThumb(exifData);
					std::string thumbExt = exifThumb.extension();
					if (thumbExt.empty()) 
					{
// 						qDebug() << file << ": Image does not contain an Exif thumbnail";
					}
					else
					{
						Exiv2::DataBuf buf = exifThumb.copy();
						if (buf.size_ != 0) 
						{
							qDebug() << file << ": Attempting to load thumnail (" << exifThumb.mimeType() << ", "
								<< buf.size_ << " Bytes)";
							
							QPixmap thumb;
							if(!thumb.loadFromData(buf.pData_, buf.size_))
							{
								qDebug() << file << "QPixmap::fromData() failed";
							}
							else
							{
								QString rotateSensor = exifData["Exif.Image.Orientation"].toString().c_str();
								int rotationFlag = rotateSensor.toInt(); 
								int rotateDegrees = rotationFlag == 1 ||
										rotationFlag == 2 ? 0 :
										rotationFlag == 7 ||
										rotationFlag == 8 ? -90 :
										rotationFlag == 3 ||
										rotationFlag == 4 ? -180 :
										rotationFlag == 5 ||
										rotationFlag == 6 ? -270 :
										0;
								QTransform t = QTransform().rotate(rotateDegrees);
								thumb = thumb.transformed(t);
										
								cache = thumb.scaled(size,Qt::KeepAspectRatio,Qt::SmoothTransformation);
								
								if(abs(rotateDegrees) == 90 || abs(rotateDegrees) == 270)
								{
									QPixmap centeredCache(size);
									centeredCache.fill(Qt::transparent);
									int pos = size.width() /2 - cache.width() / 2;
									QPainter painter(&centeredCache);
									painter.drawPixmap(pos,0,cache);
									cache = centeredCache;
									qDebug() << file << " * Centered rotated pixmap in frame";
								}
								
								cache.save(cacheFile,"PNG");
								//qDebug() << "MediaBrowser::iconForImage: file:"<<file<<", image file: caching to:"<<cacheFile<<" for "<<file;
								QPixmapCache::insert(cacheFile,cache);
								
								gotThumb = true;
								
// 								qDebug() << file << ": Succesfully loaded Exiv thumnail and scaled to size, wrote to: "<<cacheFile;
							}
						}
					}
				}
			}
			catch (Exiv2::AnyError& e) 
			{
				//std::cout << "Caught Exiv2 exception '" << e << "'\n";
				//return -1;
				gotThumb = false;
			}
			
			if(!gotThumb)
			{
				QPixmap orig(file);
				if(orig.isNull())
				{
					cache = QPixmap();
					QPixmapCache::insert(cacheFile,cache);
					qDebug() << "MediaBrowser::iconForImage: file:"<<file<<", size:"<<size<<": load INVALID (Can't load original)";
				}
				else
				{
					cache = orig.scaled(size,Qt::KeepAspectRatio,Qt::SmoothTransformation);
					cache.save(cacheFile,"PNG");
					////qDebug() << "MyQFileIconProvider::icon(): image file: caching to:"<<cacheFile<<" for "<<file;
					QPixmapCache::insert(cacheFile,cache);
// 					qDebug() << "MediaBrowser::iconForImage: file:"<<file<<", size:"<<size<<": load GOOD (loaded original and scaled)";
					//QApplication::processEvents();
				}
			}
		}
	}
	else
	{
		//qDebug() << "MediaBrowser::iconForImage: file:"<<file<<", size:"<<size<<": hit RAM (scaled image already in ram)";
	}

	//qDebug() << "MediaBrowser::data: iconForImage: file:"<<file<<", cacheKey:"<<cache.cacheKey();

	return cache;
}
예제 #17
0
void LocalImageLoaderPrivate::prepareImages() {
	QString file, filename, mime;
    int32 filesize = 0;
	QImage img;
	QByteArray data;
	PeerId peer;
    uint64 id, jpeg_id = 0;
	ToPrepareMediaType type;
	{
		QMutexLocker lock(loader->toPrepareMutex());
		ToPrepareMedias &list(loader->toPrepareMedias());
		if (list.isEmpty()) return;

		file = list.front().file;
		img = list.front().img;
		data = list.front().data;
		peer = list.front().peer;
		id = list.front().id;
		type = list.front().type;
	}

	if (img.isNull()) {
		if (!file.isEmpty()) {
			QFileInfo info(file);
			if (type == ToPrepareAuto) {
				QString lower(file.toLower());
				const QStringList &photoExtensions(cPhotoExtensions());
				for (QStringList::const_iterator i = photoExtensions.cbegin(), e = photoExtensions.cend(); i != e; ++i) {
					if (lower.lastIndexOf(*i) == lower.size() - i->size()) {
						if (info.size() < MaxUploadPhotoSize) {
							type = ToPreparePhoto;
							break;
						}
					}
				}
				if (type == ToPrepareAuto && info.size() < MaxUploadDocumentSize) {
					type = ToPrepareDocument;
				}
			}
			if (type != ToPrepareAuto && info.size() < MaxUploadPhotoSize) {
				img = App::readImage(file);
			}
			if (type == ToPrepareDocument) {
				mime = QMimeDatabase().mimeTypeForFile(info).name();
			}
			filename = info.fileName();
			filesize = info.size();
		} else if (!data.isEmpty()) {
			img = App::readImage(data);
			if (type == ToPrepareAuto) {
				if (!img.isNull() && data.size() < MaxUploadPhotoSize) {
					type = ToPreparePhoto;
				} else if (data.size() < MaxUploadDocumentSize) {
					type = ToPrepareDocument;
				} else {
					img = QImage();
				}
			}
			QMimeType mimeType = QMimeDatabase().mimeTypeForData(data);
			if (type == ToPrepareDocument) {
				mime = mimeType.name();
			}
			filename = qsl("Document");
			QStringList patterns = mimeType.globPatterns();
			if (!patterns.isEmpty()) {
				filename = patterns.front().replace('*', filename);
			}
			filesize = data.size();
		}
	} else {
		if (type == ToPrepareDocument) {
			filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true);
			QMimeType mimeType = QMimeDatabase().mimeTypeForName("image/png");
			data = QByteArray();
			{
				QBuffer b(&data);
				img.save(&b, "PNG");
			}
			filesize = data.size();
		} else {
			type = ToPreparePhoto; // only photo from QImage
			filename = qsl("Untitled.jpg");
			filesize = 0;
		}
	}

	if ((img.isNull() && (type != ToPrepareDocument || !filesize)) || type == ToPrepareAuto || (img.isNull() && file.isEmpty() && data.isEmpty())) { // if could not decide what type
		{
			QMutexLocker lock(loader->toPrepareMutex());
			ToPrepareMedias &list(loader->toPrepareMedias());
			list.pop_front();
		}

		QTimer::singleShot(1, this, SLOT(prepareImages()));

		emit imageFailed(id);
	} else {
		PreparedPhotoThumbs photoThumbs;
		QVector<MTPPhotoSize> photoSizes;

		MTPPhotoSize thumb(MTP_photoSizeEmpty(MTP_string("")));
		MTPPhoto photo(MTP_photoEmpty(MTP_long(0)));
		MTPDocument document(MTP_documentEmpty(MTP_long(0)));

		QByteArray jpeg;
		if (type == ToPreparePhoto) {
			int32 w = img.width(), h = img.height();

			QPixmap thumb = (w > 100 || h > 100) ? QPixmap::fromImage(img.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img);
			photoThumbs.insert('s', thumb);
			photoSizes.push_back(MTP_photoSize(MTP_string("s"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0)));

			QPixmap medium = (w > 320 || h > 320) ? QPixmap::fromImage(img.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img);
			photoThumbs.insert('m', medium);
			photoSizes.push_back(MTP_photoSize(MTP_string("m"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0)));

			QPixmap full = (w > 800 || h > 800) ? QPixmap::fromImage(img.scaled(800, 800, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img);
			photoThumbs.insert('x', full);
			photoSizes.push_back(MTP_photoSize(MTP_string("x"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)));

			{
				QBuffer jpegBuffer(&jpeg);
				full.save(&jpegBuffer, "JPG", 87);
			}
			if (!filesize) filesize = jpeg.size();
		
			photo = MTP_photo(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_string(""), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes));

			jpeg_id = id;
		} else if ((type == ToPrepareVideo || type == ToPrepareDocument) && !img.isNull()) {
			int32 w = img.width(), h = img.height();

			QPixmap full = (w > 90 || h > 90) ? QPixmap::fromImage(img.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img);

			{
				QBuffer jpegBuffer(&jpeg);
				full.save(&jpegBuffer, "JPG", 87);
			}

			photoThumbs.insert('0', full);
			thumb = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0));

			jpeg_id = MTP::nonce<uint64>();
		}

		if (type == ToPrepareDocument) {
			document = MTP_document(MTP_long(id), MTP_long(0), MTP_int(MTP::authedId()), MTP_int(unixtime()), MTP_string(filename), MTP_string(mime), MTP_int(filesize), thumb, MTP_int(MTP::maindc()));
		}

		{
			QMutexLocker lock(loader->readyMutex());
			loader->readyList().push_back(ReadyLocalMedia(type, file, filename, filesize, data, id, jpeg_id, peer, photo, photoThumbs, document, jpeg));
		}

		{
			QMutexLocker lock(loader->toPrepareMutex());
			ToPrepareMedias &list(loader->toPrepareMedias());
			list.pop_front();
		}

		QTimer::singleShot(1, this, SLOT(prepareImages()));

		emit imageReady();
	}
}
예제 #18
0
void ModelExportHelper::exportToPNG(ObjectsScene *scene, const QString &filename, float zoom, bool show_grid, bool show_delim)
{
	if(!scene)
		throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__);

	try
	{
		QPixmap pix;
		QRectF ret=scene->itemsBoundingRect();
		bool shw_grd, shw_dlm, align_objs;
		QGraphicsView viewp(scene);
		QRect retv;
		QPolygon pol;

		//Clear the object scene selection to avoid drawing the selectoin rectangle of the objects
		scene->clearSelection();

		//Make a backup of the current scene options
		ObjectsScene::getGridOptions(shw_grd, align_objs, shw_dlm);

		//Sets the options passed by the user
		ObjectsScene::setGridOptions(show_grid, false, show_delim);

		//Updates the scene to apply the change on grid and delimiter
		scene->update();

		//Configures the viewport alignment to top-left coordinates.
		viewp.setAlignment(Qt::AlignLeft | Qt::AlignTop);

		//Apply the zoom factor on the viewport
		viewp.resetTransform();
		viewp.centerOn(0,0);
		viewp.scale(zoom, zoom);

		//Convert the objects bounding rect to viewport coordinates to correctly draw them onto pixmap
		pol=viewp.mapFromScene(ret);

		//Configure the viewport area to be copied
		retv.setTopLeft(pol.at(0));
		retv.setTopRight(pol.at(1));
		retv.setBottomRight(pol.at(2));
		retv.setBottomLeft(pol.at(3));

		//Creates the output pixmap
		pix=QPixmap(retv.size());
		pix.fill();
		QPainter p(&pix);

		//Setting optimizations on the painter
		p.setRenderHint(QPainter::Antialiasing, true);
		p.setRenderHint(QPainter::TextAntialiasing, true);
		p.setRenderHint(QPainter::SmoothPixmapTransform, true);

		emit s_progressUpdated(50, trUtf8("Rendering objects onto the output pixmap..."), BASE_OBJECT);

		//Render the entire viewport onto the pixmap
		viewp.render(&p, QRectF(QPointF(0,0), pix.size()), retv);

		//Restore the scene options
		ObjectsScene::setGridOptions(shw_grd, align_objs, shw_dlm);

		//Updates the scene to apply the restoration of grid and delimiter statuses
		scene->update();

		//If the pixmap is not saved raises an error
		if(!pix.save(filename))
			throw Exception(Exception::getErrorMessage(ERR_FILE_NOT_WRITTEN).arg(Utf8String::create(filename)),
											ERR_FILE_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__);

		emit s_exportFinished();
	}
	catch(Exception &e)
	{
		throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
	}
}
예제 #19
0
void ChartPlot::exportChart(std::string file, string extension)
{
	QPixmap pixmap = grab();
	pixmap.save(file.c_str(), extension.c_str());
}
예제 #20
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());

}
예제 #21
0
파일: cmdmisc.cpp 프로젝트: gyuris/scribus
// This function is fairly complex because it can either save its output to a
// file, or return it as a Python string.
PyObject *scribus_renderfont(PyObject* /*self*/, PyObject* args, PyObject* kw)
{
	char *Name = const_cast<char*>("");
	char *FileName = const_cast<char*>("");
	char *Sample = const_cast<char*>("");
	char *format = NULL;
	int Size;
	bool ret = false;
	char *kwargs[] = {const_cast<char*>("fontname"),
					  const_cast<char*>("filename"),
					  const_cast<char*>("sample"),
					  const_cast<char*>("size"),
					  const_cast<char*>("format"),
					  NULL};
	if (!PyArg_ParseTupleAndKeywords(args, kw, "esesesi|es", kwargs,
				"utf-8", &Name, "utf-8", &FileName, "utf-8", &Sample, &Size, "ascii", &format))
		return NULL;
	if (!PrefsManager::instance()->appPrefs.fontPrefs.AvailFonts.contains(QString::fromUtf8(Name)))
	{
		PyErr_SetString(NotFoundError, QObject::tr("Font not found.","python error").toLocal8Bit().constData());
		return NULL;
	}
	QString ts = QString::fromUtf8(Sample);
	if (ts.isEmpty())
	{
		PyErr_SetString(PyExc_ValueError, QObject::tr("Cannot render an empty sample.","python error").toLocal8Bit().constData());
		return NULL;
	}
	if (!format)
		// User specified no format, so use the historical default of PPM format.
		format =  const_cast<char*>("PPM");
	QPixmap pm = FontSample(PrefsManager::instance()->appPrefs.fontPrefs.AvailFonts[QString::fromUtf8(Name)], Size, ts, Qt::white);
	// If the user specified an empty filename, return the image data as
	// a string. Otherwise, save it to disk.
	if (QString::fromUtf8(FileName).isEmpty())
	{
		QByteArray buffer_string = "";
		QBuffer buffer(&buffer_string);
		buffer.open(QIODevice::WriteOnly);
		bool ret = pm.save(&buffer, format);
		if (!ret)
		{
			PyErr_SetString(ScribusException, QObject::tr("Unable to save pixmap","scripter error").toLocal8Bit().constData());
			return NULL;
		}
		int bufferSize = buffer.size();
		buffer.close();
		// Now make a Python string from the data we generated
		PyObject* stringPython = PyString_FromStringAndSize(buffer_string,bufferSize);
		// Return even if the result is NULL (error) since an exception will have been
		// set in that case.
		return stringPython;
	}
	else
	// Save the pixmap to a file, since the filename is non-empty
	{
		ret = pm.save(QString::fromUtf8(FileName), format);
		if (!ret)
		{
			PyErr_SetString(PyExc_Exception, QObject::tr("Unable to save pixmap","scripter error").toLocal8Bit().constData());
			return NULL;
		}
		// For historical reasons, we need to return true on success.
//		Py_INCREF(Py_True);
//		return Py_True;
//		Py_RETURN_TRUE;
		return PyBool_FromLong(static_cast<long>(true));
	}
}
예제 #22
0
	bool packageThemes(
			const QString &szPackagePath,
			const QString &szPackageName,
			const QString &szPackageVersion,
			const QString &szPackageDescription,
			const QString &szPackageAuthor,
			const QString &szPackageImagePath,
			KviPointerList<KviThemeInfo> &lThemeInfoList,
			QString &szError
		)
	{
		if(szPackagePath.isEmpty())
		{
			szError = __tr2qs_ctx("Invalid empty package path","theme");
			return false;
		}

		if(szPackageName.isEmpty())
		{
			szError = __tr2qs_ctx("Invalid empty package name","theme");
			return false;
		}

		QPixmap out;

		if(!szPackageImagePath.isEmpty())
		{
			QImage pix(szPackageImagePath);
			if(pix.isNull())
			{
				szError = __tr2qs_ctx("Failed to load the selected image: please fix it","theme");
				return false;
			}

			if((pix.width() > 300) || (pix.height() > 225))
				out = out.fromImage(pix.scaled(300,225,Qt::KeepAspectRatio));
			else
				out=out.fromImage(pix);
		}

		KviPackageWriter f;

		f.addInfoField("PackageType","ThemePack");
		f.addInfoField("ThemePackVersion",KVI_CURRENT_THEME_ENGINE_VERSION);
		f.addInfoField("Name",szPackageName);
		f.addInfoField("Version",szPackageVersion.isEmpty() ? "1.0.0" : szPackageVersion);
		f.addInfoField("Author",szPackageAuthor);
		f.addInfoField("Description",szPackageDescription);
		// this is the equivalent to an empty date.toString() call, but it's needed
		// to ensure qt4 will use the default() locale and not the system() one
		f.addInfoField("Date",QDateTime::currentDateTime().toString(Qt::ISODate));
		f.addInfoField("Application","KVIrc " KVI_VERSION "." KVI_SOURCES_DATE);

		if(!out.isNull())
		{
			QByteArray * pba = new QByteArray();
			QBuffer buffer(pba,0);
			buffer.open(QIODevice::WriteOnly);
			out.save(&buffer,"PNG");
			buffer.close();
			f.addInfoField("Image",pba); // cool :) [no disk access needed]
		}

		QString szTmp;

		szTmp.setNum(lThemeInfoList.count());
		f.addInfoField("ThemeCount",szTmp);

		int iIdx = 0;
		for(KviThemeInfo * pInfo = lThemeInfoList.first();pInfo;pInfo = lThemeInfoList.next())
		{
			if(pInfo->name().isEmpty())
			{
				szError = __tr2qs_ctx("Invalid theme name","theme");
				return false;
			}
			if(pInfo->version().isEmpty())
			{
				szError = __tr2qs_ctx("Invalid theme version","theme");
				return false;
			}

			QString szSubdir = pInfo->name() + QString("-") + pInfo->version();
			szSubdir.replace(QRegExp("[^a-zA-Z0-9_\\-.][^a-zA-Z0-9_\\-.]*"),"_");

			szTmp = QString("Theme%1Name").arg(iIdx);
			f.addInfoField(szTmp,pInfo->name());
			szTmp = QString("Theme%1Version").arg(iIdx);
			f.addInfoField(szTmp,pInfo->version());
			szTmp = QString("Theme%1Description").arg(iIdx);
			f.addInfoField(szTmp,pInfo->description());
			szTmp = QString("Theme%1Date").arg(iIdx);
			f.addInfoField(szTmp,pInfo->date());
			szTmp = QString("Theme%1Subdirectory").arg(iIdx);
			f.addInfoField(szTmp,szSubdir);
			szTmp = QString("Theme%1Author").arg(iIdx);
			f.addInfoField(szTmp,pInfo->author());
			szTmp = QString("Theme%1Application").arg(iIdx);
			f.addInfoField(szTmp,pInfo->application());
			szTmp = QString("Theme%1ThemeEngineVersion").arg(iIdx);
			f.addInfoField(szTmp,pInfo->themeEngineVersion());
			QPixmap pixScreenshot = pInfo->smallScreenshot();
			if(!pixScreenshot.isNull())
			{
				szTmp = QString("Theme%1Screenshot").arg(iIdx);
				QByteArray * pba = new QByteArray();

				QBuffer bufferz(pba,0);
				bufferz.open(QIODevice::WriteOnly);
				pixScreenshot.save(&bufferz,"PNG");
				bufferz.close();
				f.addInfoField(szTmp,pba);
			}

			if(!f.addDirectory(pInfo->directory(),szSubdir))
			{
				szError = __tr2qs_ctx("Packaging failed","theme");
				szError += ": ";
				szError += f.lastError();
				return false;
			}

			iIdx++;
		}

		if(!f.pack(szPackagePath))
		{
			szError = __tr2qs_ctx("Packaging failed","theme");
			szError += ": ";
			szError += f.lastError();
			return false;
		}

		return true;
	}
예제 #23
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);
    }
}
예제 #24
0
void ObserverTextScreen::saveAsImage(std::string file, std::string extension)
{
      QPixmap pixmap = textEdit->grab();
      pixmap.save(file.c_str(), extension.c_str());
}
예제 #25
0
/// @todo chart problem at midnight.
void StatisticsDialog::generatePageFromQStringList ( QStringList values, const QString & subTitle )
{
	KColorScheme colorScheme ( QPalette::Active, KColorScheme::View );
	generalHTMLPart->begin();
	generalHTMLPart->write ( QString ( "<html><head><style>.bar { margin:0px;} "
	                                   "body"
	                                   "{"
	                                   "font-size:11px"
	                                   "}"
	                                   ".chart"								// Style for the charts
	                                   "{ height:100px;"
	                                   "border-left:1px solid #999;"
	                                   "border-bottom:1px solid #999;"
	                                   "vertical-align:bottom;"
	                                   "}"
	                                   ".statgroup"							// Style for groups of similar statistics
	                                   "{ margin-bottom:10px;"
	                                   "background-color:white;"
	                                   "border-left: 5px solid #369;"
	                                   "border-top: 1px dashed #999;"
	                                   "border-bottom: 1px dashed #999;"
	                                   "margin-left: 10px;"
	                                   "margin-right: 5px;"
	                                   "padding:3px 3px 3px 10px;}"
	                                   "</style></head><body>" +
	                                   i18n ( "<h1>Statistics for %1</h1>", m_contact->metaContact()->displayName() ) +
	                                   "<h3>%1</h3><hr>" ).arg ( subTitle ) );

	generalHTMLPart->write ( i18n ( "<div class=\"statgroup\"><b><a href=\"main:generalinfo\" title=\"General summary view\">General</a></b><br>"
	                                "<span title=\"Select the day or month for which you want to view statistics\"><b>Days: </b>"
	                                "<a href=\"dayofweek:1\">Monday</a>&nbsp;"
	                                "<a href=\"dayofweek:2\">Tuesday</a>&nbsp;"
	                                "<a href=\"dayofweek:3\">Wednesday</a>&nbsp;"
	                                "<a href=\"dayofweek:4\">Thursday</a>&nbsp;"
	                                "<a href=\"dayofweek:5\">Friday</a>&nbsp;"
	                                "<a href=\"dayofweek:6\">Saturday</a>&nbsp;"
	                                "<a href=\"dayofweek:7\">Sunday</a><br>"
	                                "<b>Months: </b>"
	                                "<a href=\"monthofyear:1\">January</a>&nbsp;"
	                                "<a href=\"monthofyear:2\">February</a>&nbsp;"
	                                "<a href=\"monthofyear:3\">March</a>&nbsp;"
	                                "<a href=\"monthofyear:4\">April</a>&nbsp;"
	                                "<a href=\"monthofyear:5\">May</a>&nbsp;"
	                                "<a href=\"monthofyear:6\">June</a>&nbsp;"
	                                "<a href=\"monthofyear:7\">July</a>&nbsp;"
	                                "<a href=\"monthofyear:8\">August</a>&nbsp;"
	                                "<a href=\"monthofyear:9\">September</a>&nbsp;"
	                                "<a href=\"monthofyear:10\">October</a>&nbsp;"
	                                "<a href=\"monthofyear:11\">November</a>&nbsp;"
	                                "<a href=\"monthofyear:12\">December</a>&nbsp;"
	                                "</span></div><br>" ) );

//	dialogUi->listView->addColumn(i18n("Status"));
//	dialogUi->listView->addColumn(i18n("Start Date"));
//	dialogUi->listView->addColumn(i18n("End Date"));
//	dialogUi->listView->addColumn(i18n("Start Date"));
//	dialogUi->listView->addColumn(i18n("End Date"));

	QString todayString;
	todayString.append ( i18n ( "<div class=\"statgroup\" title=\"Contact status history for today\"><h2>Today</h2><table width=\"100%\"><tr><td>Status</td><td>From</td><td>To</td></tr>" ) );

	bool today;

	int totalTime = 0; // this is in seconds
	int totalAwayTime = 0; // this is in seconds
	int totalOnlineTime = 0; // this is in seconds
	int totalOfflineTime = 0; // idem

	int hours[24]; // in seconds, too
	int iMaxHours = 0;
	int hoursOnline[24]; // this is in seconds
	int iMaxHoursOnline = 0;
	int hoursAway[24]; // this is in seconds
	int iMaxHoursAway = 0;
	int hoursOffline[24]; // this is in seconds. Hours where we are sure contact is offline
	int iMaxHoursOffline = 0;

	for ( uint i=0; i<24; i++ )
	{
		hours[i] = 0;
		hoursOnline[i] = 0;
		hoursAway[i] = 0;
		hoursOffline[i] = 0;
	}

	for ( int i=0; i<values.count(); i+=3 /* because SELECT 3 columns */ )
	{
		/* 	Here we try to interpret one database entry...
			What's important here, is to not count two times the same hour for instance
			This is why there are some if in all this stuff ;-)
		*/


		// it is the STARTDATE from the database
		QDateTime dateTime1;
		dateTime1.setTime_t ( values[i+1].toInt() );
		// it is the ENDDATE from the database
		QDateTime dateTime2;
		dateTime2.setTime_t ( values[i+2].toInt() );

		if ( dateTime1.date() == QDate::currentDate() || dateTime2.date() == QDate::currentDate() )
			today = true;
		else today = false;

		totalTime += dateTime1.secsTo ( dateTime2 );

		if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Online )
			totalOnlineTime += dateTime1.secsTo ( dateTime2 );
		else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Away )
			totalAwayTime += dateTime1.secsTo ( dateTime2 );
		else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Busy )
			totalAwayTime += dateTime1.secsTo ( dateTime2 );
		else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Offline )
			totalOfflineTime += dateTime1.secsTo ( dateTime2 );


		/*
		 * To build the chart/hours
		 */

		// Number of hours between dateTime1 and dateTime2
		int nbHours = ( int ) ( dateTime1.secsTo ( dateTime2 ) /3600.0 );

		uint tempHour =
		    dateTime1.time().hour() == dateTime2.time().hour()
		    ? dateTime1.secsTo ( dateTime2 ) // (*)
		    : 3600 - dateTime1.time().minute() *60 - dateTime1.time().second();
		hours[dateTime1.time().hour() ] += tempHour;

		if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Online )
			hoursOnline[dateTime1.time().hour() ] += tempHour;
		else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Away )
			hoursAway[dateTime1.time().hour() ] += tempHour;
		else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Busy )
			hoursAway[dateTime1.time().hour() ] += tempHour;
		else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Offline )
			hoursOffline[dateTime1.time().hour() ] += tempHour;

		for ( int j= dateTime1.time().hour() +1; j < dateTime1.time().hour() + nbHours - 1; j++ )
		{
			hours[j%24] += 3600;
			if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Online )
				hoursOnline[j%24] += 3600;
			else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Away )
				hoursAway[j%24] += 3600;
			else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Busy )
				hoursAway[j%24] += 3600;
			else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Offline )
				hoursOffline[j%24] += 3600;
		}


		if ( dateTime1.time().hour() != dateTime2.time().hour() )
			// We don't want to count this if the hour from dateTime2 is the same than the one from dateTime1
			// since it as already been taken in account in the (*) instruction
		{
			tempHour = dateTime2.time().minute() *60 +dateTime2.time().second();
			hours[dateTime2.time().hour() ] += tempHour;

			if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Online )
				hoursOnline[dateTime2.time().hour() ] += tempHour;
			else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Away )
				hoursAway[dateTime2.time().hour() ] += tempHour;
			else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Busy )
				hoursAway[dateTime2.time().hour() ] += tempHour;
			else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Offline )
				hoursOffline[dateTime2.time().hour() ] += tempHour;


		}

		if ( today )
		{
			QString status;
			if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Online )
				status = i18n ( "Online" );
			else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Away )
				status = i18n ( "Away" );
			else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Busy )
				status = i18n ( "Busy" );
			else if ( Kopete::OnlineStatus::statusStringToType ( values[i] ) == Kopete::OnlineStatus::Offline )
				status = i18n ( "Offline" );

			todayString.append ( QString ( "<tr><td>%2</td><td>%3</td><td>%4</td></tr>" ).arg ( status, dateTime1.time().toString(), dateTime2.time().toString() ) );
		}

		// We add a listview item to the log list
		// QDateTime listViewDT1, listViewDT2;
		// listViewDT1.setTime_t(values[i+1].toInt());
		// listViewDT2.setTime_t(values[i+2].toInt());
		// new K3ListViewItem(dialogUi->listView, values[i], values[i+1], values[i+2], listViewDT1.toString(), listViewDT2.toString());
	}


	todayString.append ( "</table></div>" );

	// Get the max from the hours*
	for ( uint i=1; i<24; i++ )
	{
		if ( hours[iMaxHours] < hours[i] )
			iMaxHours = i;
		if ( hoursOnline[iMaxHoursOnline] < hoursOnline[i] )
			iMaxHoursOnline = i;
		if ( hoursOffline[iMaxHoursOffline] < hoursOffline[i] )
			iMaxHoursOffline = i;
		if ( hoursAway[iMaxHoursAway] < hoursAway[i] )
			iMaxHoursAway = i;
	}

	//

	/*
	 * Here we really generate the page
	 */
	// Some "total times"
	generalHTMLPart->write ( i18n ( "<div class=\"statgroup\">" ) );
	generalHTMLPart->write ( i18n ( "<b title=\"The total time %1 was visible\">"
	                                "Total visible time :</b> %2<br>", m_contact->metaContact()->displayName(), stringFromSeconds ( totalOnlineTime + totalAwayTime ) ) );
	generalHTMLPart->write ( i18n ( "<b title=\"The total time %1 was online\">"
	                                "Total online time :</b> %2<br>", m_contact->metaContact()->displayName(), stringFromSeconds ( totalOnlineTime ) ) );
	generalHTMLPart->write ( i18n ( "<b title=\"The total time %1 was away\">Total busy time :</b> %2<br>", m_contact->metaContact()->displayName(), stringFromSeconds ( totalAwayTime ) ) );
	generalHTMLPart->write ( i18n ( "<b title=\"The total time %1 was offline\">Total offline time :</b> %2", m_contact->metaContact()->displayName(), stringFromSeconds ( totalOfflineTime ) ) );
	generalHTMLPart->write ( QString ( "</div>" ) );

	if ( subTitle == i18n ( "General information" ) )
		/*
		 * General stats that should not be shown on "day" or "month" pages
		 */
	{
		generalHTMLPart->write ( QString ( "<div class=\"statgroup\">" ) );
		generalHTMLPart->write ( i18np ( "<b>Average message length:</b> %1 character<br>",
						"<b>Average message length:</b> %1 characters<br>", m_contact->messageLength() ) );
		generalHTMLPart->write ( i18np ( "<b>Time between two messages:</b> %1 second",
						 "<b>Time between two messages:</b> %1 seconds", m_contact->timeBetweenTwoMessages() ) );
		generalHTMLPart->write ( QString ( "</div>" ) );

		generalHTMLPart->write ( QString ( "<div class=\"statgroup\">" ) );
		generalHTMLPart->write ( i18n ( "<b title=\"The last time you talked with %1\">Last talk :</b> %2<br>", m_contact->metaContact()->displayName(), KGlobal::locale()->formatDateTime ( m_contact->lastTalk() ) ) );
		generalHTMLPart->write ( i18n ( "<b title=\"The last time %1 was online or away\">Last time present :</b> %2", m_contact->metaContact()->displayName(), KGlobal::locale()->formatDateTime ( m_contact->lastPresent() ) ) );
		generalHTMLPart->write ( QString ( "</div>" ) );

		//generalHTMLPart->write(QString("<div class=\"statgroup\">"));
		//generalHTMLPart->write(i18n("<b title=\"%1 uses to set his status online at these hours (EXPERIMENTAL)\">Main online events :</b><br>").arg(m_contact->metaContact()->displayName()));
		//QValueList<QTime> mainEvents = m_contact->mainEvents(Kopete::OnlineStatus::Online);
		//for (uint i=0; i<mainEvents.count(); i++)
		//generalHTMLPart->write(QString("%1<br>").arg(mainEvents[i].toString()));
		//generalHTMLPart->write(QString("</div>"));

		generalHTMLPart->write ( "<div title=\"" +i18n ( "Current status" ) + "\" class=\"statgroup\">" );
		generalHTMLPart->write ( i18n ( "Is <b>%1</b> since <b>%2</b>",
		                                Kopete::OnlineStatus ( m_contact->oldStatus() ).description(),
		                                KGlobal::locale()->formatDateTime ( m_contact->oldStatusDateTime() ) ) );
		generalHTMLPart->write ( QString ( "</div>" ) );
	}

	/*
	 * Chart which shows the hours where plugin has seen this contact online
	 */
	generalHTMLPart->write ( QString ( "<div class=\"statgroup\">" ) );
	generalHTMLPart->write ( QString ( "<table width=\"100%\"><tr><td colspan=\"3\">" )
	                         + i18nc ( "TRANSLATOR: please reverse 'left' and 'right' as appropriate for your language",
	                                   "When was this contact visible?<br />All charts are in 24 blocks, "
	                                   "one per hour, encompassing one day. %1 is on the left, "
	                                   "and %2 is on the right.", KGlobal::locale()->formatTime ( QTime ( 0, 0 ) ),
	                                   KGlobal::locale()->formatTime ( QTime ( 23, 59 ) ) )
	                         + QString ( "</td></tr>" ) );
	generalHTMLPart->write ( QString ( "<tr><td height=\"200\" valign=\"bottom\" colspan=\"3\" class=\"chart\">" ) );

	QString chartString;
	QByteArray colorPath;
	QPixmap pixmap ( 1, 1 );
	pixmap.fill ( Qt::black );
	// Generate base64 picture.
	QByteArray tempArray;
	QBuffer tempBuffer ( &tempArray );
	tempBuffer.open ( QIODevice::WriteOnly );
	if ( pixmap.save ( &tempBuffer, "PNG" ) )
		colorPath = tempArray.toBase64();
	for ( uint i=0; i<24; i++ )
	{

		int hrWidth = qRound ( ( double ) ( hoursOnline[i] + hoursAway[i] ) / ( double ) hours[iMaxHours]*100. );
		chartString += QString ( "<img class=\"margin:0px;\"  height=\"" )
		               + ( totalTime ? QString::number ( hrWidth ) : QString::number ( 0 ) )
		               + QString ( "\" src=\"data:image/png;base64," )
		               +colorPath
		               +"\" width=\"4%\" title=\""
		               +i18n ( "Between %1 and %2, %3 was visible for %4% of the hour.",
		                       KGlobal::locale()->formatTime ( QTime ( i, 0 ) ),
		                       KGlobal::locale()->formatTime ( QTime ( ( i+1 ) % 24, 0 ) ),
		                       m_contact->metaContact()->displayName(), hrWidth )
		               + QString ( "\">" );
	}
	generalHTMLPart->write ( chartString );
	generalHTMLPart->write ( QString ( "</td></tr>" ) );



	generalHTMLPart->write ( QString ( "<tr><td>" )
	                         +i18n ( "Online time" )
	                         +QString ( "</td><td>" )
	                         +i18n ( "Away time" )
	                         +QString ( "</td><td>" )
	                         +i18n ( "Offline time" )
	                         +QString ( "</td></tr><td valign=\"bottom\" width=\"33%\" class=\"chart\">" ) );


	generalHTMLPart->write ( generateHTMLChart ( hoursOnline, hoursAway, hoursOffline, i18n ( "online" ),
	                         m_onlineColor ) );
	generalHTMLPart->write ( QString ( "</td><td valign=\"bottom\" width=\"33%\" class=\"chart\">" ) );
	generalHTMLPart->write ( generateHTMLChart ( hoursAway, hoursOnline, hoursOffline, i18n ( "away" ),
	                         m_awayColor ) );
	generalHTMLPart->write ( QString ( "</td><td valign=\"bottom\" width=\"33%\" class=\"chart\">" ) );
	generalHTMLPart->write ( generateHTMLChart ( hoursOffline, hoursAway, hoursOnline, i18n ( "offline" ),
	                         m_offlineColor ) );
	generalHTMLPart->write ( QString ( "</td></tr></table></div>" ) );

	if ( subTitle == i18n ( "General information" ) )
		/* On main page, show the different status of the contact today
		 */
	{
		generalHTMLPart->write ( QString ( todayString ) );
	}
	generalHTMLPart->write ( QString ( "</body></html>" ) );

	generalHTMLPart->end();

}
예제 #26
0
showAnCalChrRes::showAnCalChrRes(customRect *rect, QImage* origEditImg, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::showAnCalChrRes)
{
    ui->setupUi(this);

    //internOrigEditImg = origEditImg;

    //Get rectangle
    //..
    globalRect = rect;
    qreal rx1,ry1,rx2,ry2;
    //rect->rect().getRect(&rx1,&ry1,&rw,&rh);
    rect->rect().getCoords(&rx1,&ry1,&rx2,&ry2);    
    globalCalStruct.x1 = (int)rx1;
    globalCalStruct.y1 = (int)ry1;
    globalCalStruct.x2 = (int)rx2;
    globalCalStruct.y2 = (int)ry2;

    globalCalStruct.canvasW = rect->parameters.W;
    globalCalStruct.canvasH = rect->parameters.H;


    //Prepare variables
    //..
    int w, h, W, H;
    //QPixmap tmpPix(_PATH_DISPLAY_IMAGE);
    QPixmap tmpPix = QPixmap::fromImage(*origEditImg);
    W = tmpPix.width();
    H = tmpPix.height();
    w = rect->parameters.canvas->width();
    h = rect->parameters.canvas->height();
    //qDebug() << "Canvas w: " << w;
    //qDebug() << "Canvas h: " << h;
    //qDebug() << "x1: " << globalCalStruct.x1;
    //qDebug() << "y1: " << globalCalStruct.y1;
    //qDebug() << "x2: " << globalCalStruct.x2;
    //qDebug() << "y2: " << globalCalStruct.y2;
    //Extrapolate dimensions
    globalCalStruct.X1 = round( ((float)W/(float)w)*(float)globalCalStruct.x1 );
    globalCalStruct.Y1 = round( ((float)H/(float)h)*(float)globalCalStruct.y1 );
    globalCalStruct.X2 = round( ((float)W/(float)w)*(float)globalCalStruct.x2 );
    globalCalStruct.Y2 = round( ((float)H/(float)h)*(float)globalCalStruct.y2 );
    globalCalStruct.lenW = abs(globalCalStruct.X2-globalCalStruct.X1);
    globalCalStruct.lenH = abs(globalCalStruct.Y2-globalCalStruct.Y1);
    globalCalStruct.origImgW = W;
    globalCalStruct.origImgH = H;

    //qDebug() << "p1: " << globalCalStruct.x1 << ", " << globalCalStruct.y1;
    //qDebug() << "p2: " << globalCalStruct.x2 << ", " << globalCalStruct.y2;
    //qDebug() << "P1: " << globalCalStruct.X1 << ", " << globalCalStruct.Y1;
    //qDebug() << "P2: " << globalCalStruct.X2 << ", " << globalCalStruct.Y2;
    //qDebug() << "lenW: " << globalCalStruct.lenW;
    //qDebug() << "lenH: " << globalCalStruct.lenH;

    //Crop & show image
    //..
    //qDeleteAll(canvasSpec->scene()->items());
    int tmpOffset = 10;
    QPixmap cropped = tmpPix.copy( QRect( globalCalStruct.X1, globalCalStruct.Y1, globalCalStruct.lenW, globalCalStruct.lenH ) );
    cropped.save("./tmpImages/tmpCropped.ppm");
    QGraphicsScene *scene = new QGraphicsScene(0,0,cropped.width(),cropped.height());
    ui->canvasCroped->setBackgroundBrush(cropped);
    ui->canvasCroped->setCacheMode(QGraphicsView::CacheNone);
    ui->canvasCroped->setScene( scene );
    ui->canvasCroped->resize(cropped.width(),cropped.height());
    float toolBarW = ui->frame->width();
    int newW = (cropped.width()>toolBarW)?cropped.width():toolBarW;
    this->resize(QSize(newW+(tmpOffset*2),cropped.height()+(tmpOffset*2)+ui->frame->height()));
    int framex = round((float)(this->width()-ui->frame->width())/2.0);
    int framey = ui->canvasCroped->height()+tmpOffset;
    ui->frame->move(QPoint(framex,framey));
    int canvasx = round((float)(this->width()-ui->canvasCroped->width())/2.0);
    ui->canvasCroped->move(QPoint(canvasx,0));
    ui->canvasCroped->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
    ui->canvasCroped->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );

    //Update lines
    //..
    globalRedLine   = new customLine(QPoint(0,0),QPoint(0,0),QPen(Qt::red));
    globalGreenLine = new customLine(QPoint(0,0),QPoint(0,0),QPen(Qt::green));
    globalBlueLine  = new customLine(QPoint(0,0),QPoint(0,0),QPen(Qt::blue));
    drawSensitivities();

}
예제 #27
0
void ScreenGrabber :: saveFrame(const QPixmap& pixmap)
{
  pixmap.save(m_dir.absoluteFilePath(QString("frame%1.png").arg(m_frame_count, 4, 10, QChar('0'))));
  ++m_frame_count;
}
예제 #28
0
void LocalImageLoaderPrivate::prepareImages() {
	QString file, filename, mime, stickerMime = qsl("image/webp");
    int32 filesize = 0;
	QImage img;
	QByteArray data;
	PeerId peer;
    uint64 id, thumbId = 0;
	int32 duration = 0;
	QString thumbExt = "jpg";
	ToPrepareMediaType type;
	bool animated = false;
	bool ctrlShiftEnter = false;
	MsgId replyTo = 0;
	{
		QMutexLocker lock(loader->toPrepareMutex());
		ToPrepareMedias &list(loader->toPrepareMedias());
		if (list.isEmpty()) return;

		file = list.front().file;
		img = list.front().img;
		data = list.front().data;
		peer = list.front().peer;
		id = list.front().id;
		type = list.front().type;
		duration = list.front().duration;
		ctrlShiftEnter = list.front().ctrlShiftEnter;
		replyTo = list.front().replyTo;
	}

	if (img.isNull()) {
		if (!file.isEmpty()) {
			QFileInfo info(file);
			if (type == ToPrepareAuto) {
				QString lower(file.toLower());
				const QStringList &photoExtensions(cPhotoExtensions());
				for (QStringList::const_iterator i = photoExtensions.cbegin(), e = photoExtensions.cend(); i != e; ++i) {
					if (lower.lastIndexOf(*i) == lower.size() - i->size()) {
						if (info.size() < MaxUploadPhotoSize) {
							type = ToPreparePhoto;
							break;
						}
					}
				}
				if (type == ToPrepareAuto && info.size() < MaxUploadDocumentSize) {
					type = ToPrepareDocument;
				}
			}
			if (type == ToPrepareDocument) {
				mime = mimeTypeForFile(info).name();
			}
			if (type != ToPrepareAuto && info.size() < MaxUploadPhotoSize) {
				bool opaque = (mime != stickerMime);
				img = App::readImage(file, 0, opaque, &animated);
			}
			filename = info.fileName();
			filesize = info.size();
		} else if (!data.isEmpty()) {
			if (type != ToPrepareAudio) {
				img = App::readImage(data, 0, true, &animated);
				if (type == ToPrepareAuto) {
					if (!img.isNull() && data.size() < MaxUploadPhotoSize) {
						type = ToPreparePhoto;
					} else if (data.size() < MaxUploadDocumentSize) {
						type = ToPrepareDocument;
					} else {
						img = QImage();
					}
				}
			}
			MimeType mimeType = mimeTypeForData(data);
			if (type == ToPrepareDocument || type == ToPrepareAudio) {
				mime = mimeType.name();
			}
			if (mime == "image/jpeg") {
				filename = filedialogDefaultName(qsl("image"), qsl(".jpg"), QString(), true);
			} else if (type == ToPrepareAudio) {
				filename = filedialogDefaultName(qsl("audio"), qsl(".ogg"), QString(), true);
				mime = "audio/ogg";
			} else {
				QString ext;
				QStringList patterns = mimeType.globPatterns();
				if (!patterns.isEmpty()) {
					ext = patterns.front().replace('*', QString());
				}
				filename = filedialogDefaultName((type == ToPrepareAudio) ? qsl("audio") : qsl("doc"), ext, QString(), true);
			}
			filesize = data.size();
		}
	} else {
		if (type == ToPrepareDocument) {
			filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true);
			mime = mimeTypeForName("image/png").name();
			data = QByteArray();
			{
				QBuffer b(&data);
				img.save(&b, "PNG");
			}
			filesize = data.size();
		} else {
			if (img.hasAlphaChannel()) {
				QImage solid(img.width(), img.height(), QImage::Format_ARGB32_Premultiplied);
				solid.fill(st::white->c);
				{
					QPainter(&solid).drawImage(0, 0, img);
				}
				img = solid;
			}
			type = ToPreparePhoto;
			filename = qsl("Untitled.jpg");
			filesize = 0;
		}
	}

	if ((img.isNull() && ((type != ToPrepareDocument && type != ToPrepareAudio) || !filesize)) || type == ToPrepareAuto || (img.isNull() && file.isEmpty() && data.isEmpty())) { // if could not decide what type
		{
			QMutexLocker lock(loader->toPrepareMutex());
			ToPrepareMedias &list(loader->toPrepareMedias());
			list.pop_front();
		}

		QTimer::singleShot(1, this, SLOT(prepareImages()));

		emit imageFailed(id);
	} else {
		PreparedPhotoThumbs photoThumbs;
		QVector<MTPPhotoSize> photoSizes;

		QVector<MTPDocumentAttribute> attributes(1, MTP_documentAttributeFilename(MTP_string(filename)));

		MTPPhotoSize thumb(MTP_photoSizeEmpty(MTP_string("")));
		MTPPhoto photo(MTP_photoEmpty(MTP_long(0)));
		MTPDocument document(MTP_documentEmpty(MTP_long(0)));
		MTPAudio audio(MTP_audioEmpty(MTP_long(0)));

		QByteArray jpeg;
		if (type == ToPreparePhoto) {
			int32 w = img.width(), h = img.height();

			QPixmap thumb = (w > 100 || h > 100) ? QPixmap::fromImage(img.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img);
			photoThumbs.insert('s', thumb);
			photoSizes.push_back(MTP_photoSize(MTP_string("s"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0)));

			QPixmap medium = (w > 320 || h > 320) ? QPixmap::fromImage(img.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img);
			photoThumbs.insert('m', medium);
			photoSizes.push_back(MTP_photoSize(MTP_string("m"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0)));

			QPixmap full = (w > 1280 || h > 1280) ? QPixmap::fromImage(img.scaled(1280, 1280, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img);
			photoThumbs.insert('y', full);
			photoSizes.push_back(MTP_photoSize(MTP_string("y"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)));

			{
				QBuffer jpegBuffer(&jpeg);
				full.save(&jpegBuffer, "JPG", 77);
			}
			if (!filesize) filesize = jpeg.size();
		
			photo = MTP_photo(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes));

			thumbId = id;
		} else if ((type == ToPrepareVideo || type == ToPrepareDocument) && !img.isNull()) {
			int32 w = img.width(), h = img.height();
			QByteArray thumbFormat = "JPG";
			int32 thumbQuality = 87;
			if (animated) {
				attributes.push_back(MTP_documentAttributeAnimated());
			} else if (mime == stickerMime && w > 0 && h > 0 && w <= StickerMaxSize && h <= StickerMaxSize && filesize < StickerInMemory) {
				attributes.push_back(MTP_documentAttributeSticker(MTP_string(""), MTP_inputStickerSetEmpty()));
				thumbFormat = "webp";
				thumbExt = qsl("webp");
			}
			attributes.push_back(MTP_documentAttributeImageSize(MTP_int(w), MTP_int(h)));
			if (w < 20 * h && h < 20 * w) {
				QPixmap full = (w > 90 || h > 90) ? QPixmap::fromImage(img.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img, Qt::ColorOnly);

				{
					QBuffer jpegBuffer(&jpeg);
					full.save(&jpegBuffer, thumbFormat, thumbQuality);
				}

				photoThumbs.insert('0', full);
				thumb = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0));

				thumbId = MTP::nonce<uint64>();
			}
		}

		if (type == ToPrepareDocument) {
			document = MTP_document(MTP_long(id), MTP_long(0), MTP_int(unixtime()), MTP_string(mime), MTP_int(filesize), thumb, MTP_int(MTP::maindc()), MTP_vector<MTPDocumentAttribute>(attributes));
		} else if (type == ToPrepareAudio) {
			audio = MTP_audio(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_int(duration), MTP_string(mime), MTP_int(filesize), MTP_int(MTP::maindc()));
		}

		{
			QMutexLocker lock(loader->readyMutex());
			loader->readyList().push_back(ReadyLocalMedia(type, file, filename, filesize, data, id, thumbId, thumbExt, peer, photo, audio, photoThumbs, document, jpeg, ctrlShiftEnter, replyTo));
		}

		{
			QMutexLocker lock(loader->toPrepareMutex());
			ToPrepareMedias &list(loader->toPrepareMedias());
			list.pop_front();
		}

		QTimer::singleShot(1, this, SLOT(prepareImages()));

		emit imageReady();
	}
}
예제 #29
0
QPixmap* ImageBackground::NewImage(Qt::AlignmentFlag alignment, int width, int height)
{
	QPixmap* image = new QPixmap(width, height);
	image->fill(Qt::transparent);

	QPainter painter(image);
	QColor color = colorBackground;
	if(transparency == true) color.setAlpha(alpha);

	switch (alignment){
	case Qt::AlignTop:{
			QRect rect(0, 0 , width, height - offset);

			// Fondo de la franja.
			painter.fillRect(rect, QBrush(color));

			// Linea blanca.
			painter.fillRect(rect.left(), rect.bottom() - 4, rect.width(), 4, QBrush(colorLine));

			// Puntitos.
			QLinearGradient gradient(rect.topLeft(), rect.topRight());
			gradient.setColorAt(0.5, QColor(colorDots.red(), colorDots.green(), colorDots.blue(), 0));
			gradient.setColorAt(1.0, QColor(colorDots.red(), colorDots.green(), colorDots.blue(), 100));
			painter.fillPath(drawDots(rect), gradient);

			// Logotipo ubuntu.
			painter.drawPixmap(15, rect.top() + 10, pixmapLogoUbuntu);

			// Logotipo círculo.
			painter.drawPixmap(width - 20 - pixmapLogoCircle.width(), rect.bottom() - pixmapLogoCircle.height() + offset, pixmapLogoCircle);
			break;
		}
	case Qt::AlignLeft:{
			QRect rect(0, 0 , width - offset, height);

			// Fondo de la franja.
			painter.fillRect(rect, QBrush(color));

			// Linea blanca.
			painter.fillRect(rect.right() - 4, rect.top(), 4, rect.height(), QBrush(colorLine));

			// Puntitos.
			QLinearGradient gradient(rect.topLeft(), rect.bottomLeft());
			gradient.setColorAt(0.5, QColor(colorDots.red(), colorDots.green(), colorDots.blue(), 0));
			gradient.setColorAt(1.0, QColor(colorDots.red(), colorDots.green(), colorDots.blue(), 100));
			painter.fillPath(drawDots(rect), gradient);

			// Logotipo ubuntu.
			painter.drawPixmap(15, rect.top() + 10, pixmapLogoUbuntu);

			// Logotipo círculo.
			painter.drawPixmap(rect.right() - pixmapLogoCircle.width() + offset, rect.bottom() - 20 - pixmapLogoCircle.height(), pixmapLogoCircle);
			break;
		}
	case Qt::AlignRight:{
			QRect rect(offset, 0 , width - offset, height);

			// Fondo de la franja.
			painter.fillRect(rect, QBrush(color));

			// Linea blanca.
			painter.fillRect(rect.left(), rect.top(), 4, rect.height(), QBrush(colorLine));

			// Puntitos.
			QLinearGradient gradient(rect.topRight(), rect.bottomRight());
			gradient.setColorAt(0.5, QColor(colorDots.red(), colorDots.green(), colorDots.blue(), 0));
			gradient.setColorAt(1.0, QColor(colorDots.red(), colorDots.green(), colorDots.blue(), 100));
			painter.fillPath(drawDots(rect), gradient);

			// Logotipo ubuntu.
			painter.drawPixmap(15 + offset, rect.top() + 10, pixmapLogoUbuntu);

			// Logotipo círculo.
			painter.drawPixmap(rect.left() - offset, rect.bottom() - 20 - pixmapLogoCircle.height(), pixmapLogoCircle);
			break;
		}
	default:{ // Qt::AlignBottom
			QRect rect(0, offset, width, height - offset);

			// Fondo de la franja.
			painter.fillRect(rect, QBrush(color));

			// Linea blanca.
			painter.fillRect(rect.left(), rect.top(), rect.width(), 4, QBrush(colorLine));

			// Puntitos.
			QLinearGradient gradient(rect.bottomLeft(), rect.bottomRight());
			gradient.setColorAt(0.5, QColor(colorDots.red(), colorDots.green(), colorDots.blue(), 0));
			gradient.setColorAt(1.0, QColor(colorDots.red(), colorDots.green(), colorDots.blue(), 100));
			painter.fillPath(drawDots(rect), gradient);

			// Logotipo ubuntu.
			painter.drawPixmap(15, 10 + offset, pixmapLogoUbuntu);

			// Logotipo círculo.
			painter.drawPixmap(rect.width() - 20 - pixmapLogoCircle.width(), 0, pixmapLogoCircle);
			break;
		}
	}

	// Creamos la ruta.
	QDir dir;
	dir.mkpath(QDir::homePath() + "/.ConkyWizardTheme/pix/");

	// Guardamos la imagen.
	image->save(QDir::homePath() + "/.ConkyWizardTheme/pix/background.png", "PNG");
	return image;
}
예제 #30
-1
void JsExtender::savePicture()
{
	if ( !QFile::exists( m_tempFile ) )
	{
		jsCall( "handleError", "savePicFailed" );
		return;
	}
	QString pFile = QDesktopServices::storageLocation( QDesktopServices::PicturesLocation );
	if ( m_mainWindow->eidCard() )
		pFile += QString( "%1%2.jpg" ).arg( QDir::separator() ).arg( m_mainWindow->eidCard()->getId() );
	QString file = QFileDialog::getSaveFileName( m_mainWindow, tr( "Save picture" ), pFile, tr( "JPEG (*.jpg *.jpeg);;PNG (*.png);;TIFF (*.tif *.tiff);;24-bit Bitmap (*.bmp)" ) );
	if( file.isEmpty() )
		return;
	QString ext = QFileInfo( file ).suffix();
	if( ext != "png" && ext != "jpg" && ext != "jpeg" && ext != "tiff" && ext != "bmp" )
		file.append( ".jpg" );
	QPixmap pix;
	if ( !pix.load( m_tempFile + "_big.jpg" ) )
	{
		jsCall( "handleError", "savePicFailed" );
		return;
	}
	pix.save( file );
}