void WriteSharedMemory::write( )
{
	
	QString text = read();

	QBuffer buffer;
	text = text + "C://project//projectFile" + QString::number(num) + ".txt;";
	

	buffer.open( QBuffer::ReadWrite );
	QDataStream out( &buffer );
	out << text;
	int size = buffer.size();

	if(sharedMem.size()<size)
	{
		qDebug() << "¹²ÏíÄÚ´æ¿Õ¼ä²»¹»£¡";
		return ;
	}
	num++;

	freeSystemSem.acquire();
	// Write into the shared memory
	sharedMem.lock();
	char *to = (char*)sharedMem.data();
	const char *from = buffer.data().data();
	memcpy( to, from, qMin( sharedMem.size(), size ) );
	sharedMem.unlock();
	usedSystemSem.release();


	ui.textEdit_2->append(text);
	qDebug() << "WriteSharedMemory:: Write:" << text;
}
Exemple #2
0
void Dialog::loadFromFile()
{
    if (sharedMemory.isAttached())
        detach();

    ui->label->setText(tr("选择一个图片文件!"));
    QString fileName = QFileDialog::getOpenFileName(0, QString(), QString(),
                                                    tr("Images (*.png *.jpg)"));
    QImage image;
    if (!image.load(fileName)) {
        ui->label->setText(tr("选择的文件不是图片,请选择图片文件!"));
        return;
    }
    ui->label->setPixmap(QPixmap::fromImage(image));

    // 将图片加载到共享内存
    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);
    QDataStream out(&buffer);
    out << image;
    int size = buffer.size();
    if (!sharedMemory.create(size)) {
        ui->label->setText(tr("无法创建共享内存段!"));
        return;
    }
    sharedMemory.lock();
    char *to = (char*)sharedMemory.data();
    const char *from = buffer.data().data();
    memcpy(to, from, qMin(sharedMemory.size(), size));
    sharedMemory.unlock();
}
Exemple #3
0
//! [1]
void Dialog::loadFromFile()
{
    if (sharedMemory.isAttached())
        detach();

    ui.label->setText(tr("Select an image file"));
    QString fileName = QFileDialog::getOpenFileName(0, QString(), QString(),
                                        tr("Images (*.png *.xpm *.jpg)"));
    QImage image;
    if (!image.load(fileName)) {
        ui.label->setText(tr("Selected file is not an image, please select another."));
        return;
    }
    ui.label->setPixmap(QPixmap::fromImage(image));
//! [1] //! [2]

    // load into shared memory
    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);
    QDataStream out(&buffer);
    out << image;
    int size = buffer.size();

    if (!sharedMemory.create(size)) {
        ui.label->setText(tr("Unable to create shared memory segment."));
        return;
    }
    sharedMemory.lock();
    char *to = (char*)sharedMemory.data();
    const char *from = buffer.data().data();
    memcpy(to, from, qMin(sharedMemory.size(), size));
    sharedMemory.unlock();
}
Exemple #4
0
void
CollectionScanner::ScanningState::writeFull()
{
    if( !isValid() )
        return;

    QBuffer buffer;
    QDataStream out(&buffer);

    m_sharedMemory->lock();
    buffer.open(QBuffer::WriteOnly);

    out << m_lastDirectory;
    out << m_directories;
    out << m_badFiles;
    m_lastFilePos = buffer.pos();
    out << m_lastFile;
    int size = buffer.size();

    if( size < m_sharedMemory->size() )
    {
        char *to = (char*)m_sharedMemory->data();
        const char *from = buffer.data().data();
        memcpy(to, from, size);
    }

    m_sharedMemory->unlock();
}
Exemple #5
0
void
CollectionScanner::ScanningState::setLastFile( const QString &file )
{
    if( file == m_lastFile )
        return;

    m_lastFile = file;

    if( !isValid() )
        return;

    QBuffer buffer;
    QDataStream out(&buffer);

    buffer.open(QBuffer::WriteOnly);

    out << m_lastFile;
    int size = buffer.size();

    if( size + m_lastFilePos < m_sharedMemory->size() )
    {
        char *to = (char*)m_sharedMemory->data();
        const char *from = buffer.data().data();
        memcpy(to + m_lastFilePos, from, size);
    }

    m_sharedMemory->unlock();
}
Exemple #6
0
void tst_QtWidgets::snapshot()
{
    QSKIP("This test doesn't do anything useful at the moment.", SkipAll);

    StyleWidget widget(0, Qt::X11BypassWindowManagerHint);
    widget.show();

    QPixmap pix = QPixmap::grabWidget(&widget);

    QVERIFY(!pix.isNull());

    QBuffer buf;
    pix.save(&buf, "PNG");
    QVERIFY(buf.size() > 0);

    QString filename = "qtwidgets_" + QHostInfo::localHostName() + "_" + QDateTime::currentDateTime().toString("yyyy.MM.dd_hh.mm.ss") + ".png";

    QFtp ftp;
    ftp.connectToHost("qt-test-server.qt-test-net");
    ftp.login("ftptest", "password");
    ftp.cd("qtest/pics");
    ftp.put(buf.data(), filename, QFtp::Binary);
    ftp.close();

    int i = 0;
    while (i < 100 && ftp.hasPendingCommands()) {
        QCoreApplication::instance()->processEvents();
        QTest::qWait(250);
        ++i;
    }
    QVERIFY2(ftp.error() == QFtp::NoError, ftp.errorString().toLocal8Bit().constData());
    QVERIFY(!ftp.hasPendingCommands());
}
Exemple #7
0
void tst_jpeg::jpegDecodingQtWebkitStyle()
{
    // QtWebkit currently calls size() to get the image size for layouting purposes.
    // Then when it is in the viewport (we assume that here) it actually gets decoded.
    QString testFile = QFINDTESTDATA("n900.jpeg");
    QVERIFY2(!testFile.isEmpty(), "cannot find test file n900.jpeg!");
    QFile inputJpeg(testFile);
    QVERIFY(inputJpeg.exists());
    inputJpeg.open(QIODevice::ReadOnly);
    QByteArray imageData = inputJpeg.readAll();
    QBuffer buffer;
    buffer.setData(imageData);
    buffer.open(QBuffer::ReadOnly);
    QCOMPARE(buffer.size(), qint64(19016));


    QBENCHMARK{
        for (int i = 0; i < 50; i++) {
            QImageReader reader(&buffer, "jpeg");
            QSize size = reader.size();
            QVERIFY(!size.isNull());
            QByteArray format = reader.format();
            QVERIFY(!format.isEmpty());
            QImage img = reader.read();
            QVERIFY(!img.isNull());
            buffer.reset();
        }
    }
}
bool MdlFileFormat::write(const chemkit::MoleculeFile *file, std::ostream &output)
{
    QBuffer buffer;
    buffer.open(QBuffer::WriteOnly);
    bool ok = write(file, &buffer);
    if(!ok){
        return false;
    }

    output.write(buffer.data().constData(), buffer.size());
    return true;
}
Exemple #9
0
QString OsmWriter::toString(const ConstOsmMapPtr& map)
{
  OsmWriter writer;
  // this will be deleted by the _fp auto_ptr
  QBuffer* buf = new QBuffer();
  writer._fp.reset(buf);
  if (!writer._fp->open(QIODevice::WriteOnly | QIODevice::Text))
  {
    throw InternalErrorException(QObject::tr("Error opening QBuffer for writing. Odd."));
  }
  writer.write(map);
  return QString::fromUtf8(buf->data(), buf->size());
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template<typename T> qint64
GetSize()
{
    QBuffer buffer;
    buffer.open(QIODevice::WriteOnly);

    QDataStream ds(&buffer);

    T obj;
    ds << obj;

    return buffer.size();
}
Exemple #11
0
// +-----------------------------------------------------------
bool f3::LogControl::setLogLevel(const QString &sAppName, const QtMsgType eLevel)
{
	// Try to lock the shared memory
	if(!m_pSharedMemory->lock())
		return false;

	// First Read the map from the shared memory
	QBuffer oBuffer;
	QDataStream oStream(&oBuffer);

	oBuffer.setData((char *) m_pSharedMemory->constData(), m_pSharedMemory->size());
	oBuffer.open(QBuffer::ReadOnly);

	QMap<QString, int> mApps;
	oStream >> mApps;

	// Then update the value in the map with the new log level (if needed)
	int iLevel = mApps[sAppName];
	int iNewLevel = ((int) eLevel) + 1;

	// And save the map data to the shared memory
	if(iLevel == 0 || iLevel != iNewLevel)
	{
		mApps[sAppName] = iNewLevel;

		QBuffer oNewBuffer;
		oNewBuffer.open(QBuffer::ReadWrite);
		QDataStream oNewStream(&oNewBuffer);

		oNewStream << mApps;

		int iSize = oNewBuffer.size();
		if(iSize < SHARED_MEMORY_SIZE)
		{
			char *sDataTo = (char *) m_pSharedMemory->data();
			const char *sDataFrom = oNewBuffer.data().data();
			memset(sDataTo, '\0', SHARED_MEMORY_SIZE);
			memcpy(sDataTo, sDataFrom, iSize);
		}
		else // Oops! Not enough space in the shared memory
		{
			// Unlock the shared memory before returning failure
			m_pSharedMemory->unlock();
			return false;
		}
	}

	// Unlock the shared memory before returning
	m_pSharedMemory->unlock();
	return true;
}
qint64 THttpSocket::write(const THttpHeader *header, QIODevice *body)
{
    T_TRACEFUNC("");

    if (body && !body->isOpen()) {
        if (!body->open(QIODevice::ReadOnly)) {
            tWarn("open failed");
            return -1;
        }
    }

    // Writes HTTP header
    QByteArray hdata = header->toByteArray();
    qint64 total = writeRawData(hdata.data(), hdata.size());
    if (total < 0) {
        return -1;
    }

    if (body) {
        QBuffer *buffer = qobject_cast<QBuffer *>(body);
        if (buffer) {
            if (writeRawData(buffer->data().data(), buffer->size()) != buffer->size()) {
                return -1;
            }
            total += buffer->size();
        } else {
            QByteArray buf(WRITE_BUFFER_LENGTH, 0);
            qint64 readLen = 0;
            while ((readLen = body->read(buf.data(), buf.size())) > 0) {
                if (writeRawData(buf.data(), readLen) != readLen) {
                    return -1;
                }
                total += readLen;
            }
        }
    }
    return total;
}
void QtBattleSounds::playCry(QBuffer &buffer) {
    qDebug() << "deleting old";
    const float volume = cry->volume();
    cry->deleteLater();

    qDebug() << "constructing new";
    cry = new QAudioOutput(readWavHeader(&buffer), this);
    cry->setBufferSize(buffer.size());
    cry->setVolume(volume);
    connect(cry, &QAudioOutput::stateChanged,
            this, &QtBattleSounds::cryStateChanged);
    qDebug() << "starting to play";
    cry->start(&buffer);
}
// called from the collection
bool KoImageDataPrivate::saveData(QIODevice &device)
{
    // if we have a temp file save that to the store. This is needed as to not loose data when
    // saving lossy formats. Also wrinting out gif is not supported by qt so saving temp file
    // also fixes the problem that gif images are empty after saving-
    if (temporaryFile) {
        if (!temporaryFile->open()) {
            kWarning(30006) << "Read file from temporary store failed";
            return false;
        }
        char buf[4096];
        while (true) {
            temporaryFile->waitForReadyRead(-1);
            qint64 bytes = temporaryFile->read(buf, sizeof(buf));
            if (bytes <= 0)
                break; // done!
            do {
                qint64 nWritten = device.write(buf, bytes);
                if (nWritten == -1) {
                    temporaryFile->close();
                    return false;
                }
                bytes -= nWritten;
            } while (bytes > 0);
        }
        temporaryFile->close();
        return true;
    }

    switch (dataStoreState) {
    case KoImageDataPrivate::StateEmpty:
        return false;
    case KoImageDataPrivate::StateNotLoaded:
        // we should not reach this state as above this will already be saved.
        Q_ASSERT(temporaryFile);
        return true;
    case KoImageDataPrivate::StateImageLoaded:
    case KoImageDataPrivate::StateImageOnly: {
        // save image
        QBuffer buffer;
        QImageWriter writer(&buffer, suffix.toLatin1());
        bool result = writer.write(image);
        device.write(buffer.data(), buffer.size());
        return result;
      }
    }
    return false;
}
Exemple #15
0
// +-----------------------------------------------------------
bool f3::LogControl::removeAppEntry(const QString &sAppName)
{
	// Try to lock the shared memory
	if(!m_pSharedMemory->lock())
		return false;

	// First Read the map from the shared memory
	QBuffer oBuffer;
	QDataStream oStream(&oBuffer);

	oBuffer.setData((char *) m_pSharedMemory->constData(), m_pSharedMemory->size());
	oBuffer.open(QBuffer::ReadOnly);

	QMap<QString, int> mApps;
	oStream >> mApps;

	// Then remove the entry in the map with the app name
	mApps.remove(sAppName);

	// Save the map data to the shared memory
	QBuffer oNewBuffer;
	oNewBuffer.open(QBuffer::ReadWrite);
	QDataStream oNewStream(&oNewBuffer);

	oNewStream << mApps;

	int iSize = oNewBuffer.size();
	if(iSize < SHARED_MEMORY_SIZE)
	{
		char *sDataTo = (char *) m_pSharedMemory->data();
		const char *sDataFrom = oNewBuffer.data().data();
		memset(sDataTo, '\0', SHARED_MEMORY_SIZE);
		memcpy(sDataTo, sDataFrom, iSize);
	}
	else // Oops! Not enough space in the shared memory
	{
		// Unlock the shared memory before returning failure
		m_pSharedMemory->unlock();
		return false;
	}

	// Unlock the shared memory before returning
	m_pSharedMemory->unlock();
	return true;
}
Exemple #16
0
void ContactGroupTest::testGroupListRoundTrip()
{
  // TODO should also test empty list

  ContactGroup::List list;

  ContactGroup group1( QLatin1String( "TestGroup1" ) );
  group1.append( ContactGroup::ContactReference( QLatin1String( "Xggdjetw" ) ) );
  group1.append( ContactGroup::Data( QLatin1String( "Tobias Koenig" ),
                                     QLatin1String( "*****@*****.**" ) ) );
  group1.append( ContactGroup::Data( QLatin1String( "Kevin Krammer" ),
                                     QLatin1String( "*****@*****.**" ) ) );

  list.append( group1 );

  ContactGroup group2( QLatin1String( "TestGroup2" ) );
  group2.append( ContactGroup::ContactReference( QLatin1String( "Xggdjetw" ) ) );
  group2.append( ContactGroup::Data( QLatin1String( "Tobias Koenig" ),
                                     QLatin1String( "*****@*****.**" ) ) );
  group2.append( ContactGroup::Data( QLatin1String( "Kevin Krammer" ),
                                     QLatin1String( "*****@*****.**" ) ) );

  list.append( group2 );

  QBuffer buffer;
  buffer.open( QIODevice::WriteOnly );

  QString errorMessage;
  bool result = ContactGroupTool::convertToXml( list, &buffer, &errorMessage );

  QVERIFY( result );
  QVERIFY( errorMessage.isEmpty() );
  buffer.close();
  QVERIFY( buffer.size() > 0 );

  buffer.open( QIODevice::ReadOnly );

  ContactGroup::List list2;
  result = ContactGroupTool::convertFromXml( &buffer, list2, &errorMessage );
  QVERIFY( result );
  QVERIFY( errorMessage.isEmpty() );
  QVERIFY( list2.size() == 2 );
  QCOMPARE( list2[0], group1 );
  QCOMPARE( list2[1], group2 );
}
Exemple #17
0
void
TestRun::test() {
    inputFilePath = KDESRCDIR "data/diagram.ppt";
    referenceDirPath = KDESRCDIR "data/diagram_odp/";
    const KoStore::Backend backend = KoStore::Tar;
    QBuffer buffer;
    convert(buffer, backend);
    qDebug() << buffer.isOpen();
    buffer.close();
    qDebug() << buffer.size();
    KoStore* input = KoStore::createStore(&buffer, KoStore::Read,
                                          KoOdf::mimeType(KoOdf::Presentation),
                                          backend);
    compareFiles(input, "content.xml");
    compareFiles(input, "styles.xml");
    compareFiles(input, "meta.xml");
    compareFiles(input, "settings.xml");
    compareFiles(input, "META-INF/manifest.xml");
}
Exemple #18
0
void KMimeTypeTest::testParseMagicFile()
{
    QFETCH(QString, testData);
    //kDebug() << QTest::currentDataTag();
    QFETCH(QString, expected);
    QBuffer testBuffer;
    testBuffer.setData(testData.toLatin1());
    QVERIFY(testBuffer.open(QIODevice::ReadOnly));
    const qint64 testBufferSize = testBuffer.size();
    QString found;
    QByteArray beginning;
    Q_FOREACH(const KMimeMagicRule& rule, m_rules) {
        if (rule.match(&testBuffer, testBufferSize, beginning)) {
            found = rule.mimetype();
            break;
        }
    }
    QCOMPARE(found, expected);
    testBuffer.close();
}
void tst_QRingBuffer::readPointerAtPositionWriteRead()
{
    //create some data
    QBuffer inData;
    inData.open(QIODevice::ReadWrite);
    inData.putChar(0x42);
    inData.putChar(0x23);
    inData.write("Qt rocks!");
    for (int i = 0; i < 5000; i++)
        inData.write(QString("Number %1").arg(i).toUtf8());
    inData.reset();
    QVERIFY(inData.size() > 0);

    //put the inData in the QRingBuffer
    QRingBuffer ringBuffer;
    qint64 remaining = inData.size();
    while (remaining > 0) {
        // write in chunks of 50 bytes
        // this ensures there will be multiple QByteArrays inside the QRingBuffer
        // since QRingBuffer is then only using individual arrays of around 4000 bytes
        qint64 thisWrite = qMin(remaining, qint64(50));
        char *pos = ringBuffer.reserve(thisWrite);
        inData.read(pos, thisWrite);
        remaining -= thisWrite;
    }
    // was data put into it?
    QVERIFY(ringBuffer.size() > 0);
    QCOMPARE(qint64(ringBuffer.size()), inData.size());

    //read from the QRingBuffer in loop, put back into another QBuffer
    QBuffer outData;
    outData.open(QIODevice::ReadWrite);
    remaining = ringBuffer.size();
    while (remaining > 0) {
        qint64 thisRead;
        // always try to read as much as possible
        const char *buf = ringBuffer.readPointerAtPosition(ringBuffer.size() - remaining, thisRead);
        outData.write(buf, thisRead);
        remaining -= thisRead;
    }
    outData.reset();

    QVERIFY(outData.size() > 0);

    // was the data read from the QRingBuffer the same as the one written into it?
    QCOMPARE(outData.size(), inData.size());
    QVERIFY(outData.buffer().startsWith(inData.buffer()));
}
Exemple #20
0
void Server::startServer()
{
    //detach the old one
    if (sharedMemory.isAttached())
        detach();

    //generate random numbers into dataList
    qsrand(time(NULL));
    QList<qreal> dataList;
    dataList.clear();
    double temp;
    for (int i = 0; i < 100; i++)
    {
        temp = qrand() % 80 - 40;
        dataList.append(temp);
    }

    //create SharedMemory
    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);
    QDataStream out(&buffer);
    out << dataList;
    int size = buffer.size();

    if (!sharedMemory.create(size)) {
        label->setText("Error: " + sharedMemory.errorString());
        return;
    }
    sharedMemory.lock();
    char *to = (char*)sharedMemory.data();
    const char *from = buffer.data().data();
    memcpy(to, from, qMin(sharedMemory.size(), size));
    sharedMemory.unlock();

    //counter, display info
    dataNum++;
    label->setText(QString("Sending No.%1 group of data.").arg(QString::number(dataNum)));
}
Exemple #21
0
// This is called from the worker thread, not main thread
bool SaveImageJob::run() {
    GFile* gfile = fm_path_to_gfile(path_);
    GFileOutputStream* fileStream = g_file_replace(gfile, NULL, false, G_FILE_CREATE_NONE, cancellable_, &error_);
    g_object_unref(gfile);

    if(fileStream) { // if the file stream is successfually opened
        const char* format = fm_path_get_basename(path_);
        format = strrchr(format, '.');
        if(format) // use filename extension as the image format
            ++format;

        QBuffer imageBuffer;
        image_.save(&imageBuffer, format); // save the image to buffer
        GOutputStream* outputStream = G_OUTPUT_STREAM(fileStream);
        g_output_stream_write_all(outputStream,
                                  imageBuffer.data().constData(),
                                  imageBuffer.size(),
                                  NULL,
                                  cancellable_,
                                  &error_);
        g_output_stream_close(outputStream, NULL, NULL);
    }
    return false;
}
Exemple #22
0
/** Constructor. Parses the command-line arguments, resets Rshare's
 * configuration (if requested), and sets up the GUI style and language
 * translation. */
Rshare::Rshare(QStringList args, int &argc, char **argv, const QString &dir)
: QApplication(argc, argv)
{
  mStartupTime = QDateTime::currentDateTime();
  localServer = NULL;

  //Initialize connection to LocalServer to know if other process runs.
  {
    QString serverName = QString(TARGET);

    if (!args.isEmpty()) {
      // load into shared memory
      QBuffer buffer;
      buffer.open(QBuffer::ReadWrite);
      QDataStream out(&buffer);
      out << args;
      int size = buffer.size();

      QSharedMemory newArgs;
      newArgs.setKey(serverName + "_newArgs");
      if (newArgs.isAttached()) newArgs.detach();

      if (!newArgs.create(size)) {
        std::cerr << "(EE) Rshare::Rshare Unable to create shared memory segment of size:"
                  << size << " error:" << newArgs.errorString().toStdString() << "." << std::endl;
#ifdef Q_OS_UNIX
        std::cerr << "Look with `ipcs -m` for nattch==0 segment. And remove it with `ipcrm -m 'shmid'`." << std::endl;
        //No need for windows, as it removes shared segment directly even when crash.
#endif
        newArgs.detach();
        ::exit(EXIT_FAILURE);
      }
      newArgs.lock();
      char *to = (char*)newArgs.data();
      const char *from = buffer.data().data();
      memcpy(to, from, qMin(newArgs.size(), size));
      newArgs.unlock();

      // Connect to the Local Server of the main process to notify it
      // that a new process had been started
      QLocalSocket localSocket;
      localSocket.connectToServer(QString(TARGET));

      std::cerr << "Rshare::Rshare waitForConnected to other instance." << std::endl;
      if( localSocket.waitForConnected(100) )
      {
        std::cerr << "Rshare::Rshare Connection etablished. Waiting for disconnection." << std::endl;
        localSocket.waitForDisconnected(1000);
        newArgs.detach();
        std::cerr << "Rshare::Rshare Arguments was sended." << std::endl
                  << " To disable it, in Options - General - Misc," << std::endl
                  << " uncheck \"Use Local Server to get new Arguments\"." << std::endl;
        ::exit(EXIT_SUCCESS); // Terminate the program using STDLib's exit function
      }
      newArgs.detach();
    }
    // No main process exists
    // Or started without arguments
    // So we start a Local Server to listen for connections from new process
    localServer= new QLocalServer();
    QObject::connect(localServer, SIGNAL(newConnection()), this, SLOT(slotConnectionEstablished()));
    updateLocalServer();
  }

#if QT_VERSION >= QT_VERSION_CHECK (5, 0, 0)
  qInstallMessageHandler(qt_msg_handler);
#else
  qInstallMsgHandler(qt_msg_handler);
#endif

#ifndef __APPLE__

  /* set default window icon */
  setWindowIcon(QIcon(":/icons/logo_128.png"));

#endif

  mBlink = true;
  QTimer *timer = new QTimer(this);
  timer->setInterval(500);
  connect(timer, SIGNAL(timeout()), this, SLOT(blinkTimer()));
  timer->start();

  timer = new QTimer(this);
  timer->setInterval(60000);
  connect(timer, SIGNAL(timeout()), this, SIGNAL(minuteTick()));
  timer->start();

  /* Read in all our command-line arguments. */
  parseArguments(args);

  /* Check if we're supposed to reset our config before proceeding. */
  if (_args.contains(ARG_RESET)) {
    Settings->reset();
  }
  
  /* Handle the -loglevel and -logfile options. */
  if (_args.contains(ARG_LOGFILE))
    _log.open(_args.value(ARG_LOGFILE));
  if (_args.contains(ARG_LOGLEVEL)) {
    _log.setLogLevel(Log::stringToLogLevel(
                      _args.value(ARG_LOGLEVEL)));
    if (!_args.contains(ARG_LOGFILE))
      _log.open(stdout);
  }
  if (!_args.contains(ARG_LOGLEVEL) && 
      !_args.contains(ARG_LOGFILE))
    _log.setLogLevel(Log::Off);

  /* config directory */
  useConfigDir = false;
  if (dir != "")
  {
  	setConfigDirectory(dir);
  }

  /** Initialize support for language translations. */
  //LanguageSupport::initialize();

  resetLanguageAndStyle();

  /* Switch off auto shutdown */
  setQuitOnLastWindowClosed ( false );

	/* Initialize GxsIdDetails */
	GxsIdDetails::initialize();
}
Exemple #23
0
// This is called from the worker thread, not main thread
bool LoadImageJob::run() {
  GFile* gfile = fm_path_to_gfile(path_);
  GFileInputStream* fileStream = g_file_read(gfile, cancellable_, &error_);
  g_object_unref(gfile);

  if(fileStream) { // if the file stream is successfually opened
    QBuffer imageBuffer;
    GInputStream* inputStream = G_INPUT_STREAM(fileStream);
    while(!g_cancellable_is_cancelled(cancellable_)) {
      char buffer[4096];
      gssize readSize = g_input_stream_read(inputStream,
                                            buffer, 4096,
                                            cancellable_, &error_);
      if(readSize == -1 || readSize == 0) // error or EOF
        break;
      // append the bytes read to the image buffer
        imageBuffer.buffer().append(buffer, readSize);
    }
    g_input_stream_close(inputStream, NULL, NULL);

    // FIXME: maybe it's a better idea to implement a GInputStream based QIODevice.
    if(!error_ && !g_cancellable_is_cancelled(cancellable_)) { // load the image from buffer if there are no errors
      image_ = QImage::fromData(imageBuffer.buffer());

      if(!image_.isNull()) { // if the image is loaded correctly
        // check if this file is a jpeg file
        // FIXME: can we use FmFileInfo instead if it's available?
        const char* basename = fm_path_get_basename(path_);
        char* mime_type = g_content_type_guess(basename, NULL, 0, NULL);
        if(mime_type && strcmp(mime_type, "image/jpeg") == 0) { // this is a jpeg file
          // use libexif to extract additional info embedded in jpeg files
          ExifLoader *exif_loader = exif_loader_new();
          // write image data to exif loader
          int ret = exif_loader_write(exif_loader, (unsigned char*)imageBuffer.data().constData(), (unsigned int)imageBuffer.size());
          ExifData *exif_data = exif_loader_get_data(exif_loader);
          exif_loader_unref(exif_loader);
          if(exif_data) {
            /* reference for EXIF orientation tag:
            * http://www.impulseadventure.com/photo/exif-orientation.html */
            ExifEntry* orient_ent = exif_data_get_entry(exif_data, EXIF_TAG_ORIENTATION);
            if(orient_ent) { /* orientation flag found in EXIF */
              gushort orient;
              ExifByteOrder bo = exif_data_get_byte_order(exif_data);
              /* bo == EXIF_BYTE_ORDER_INTEL ; */
              orient = exif_get_short (orient_ent->data, bo);
              qreal rotate_degrees = 0.0;
              switch(orient) {
                case 1: /* no rotation */
                  break;
                case 8:
                  rotate_degrees = 270.0;
                  break;
                case 3:
                  rotate_degrees = 180.0;
                  break;
                case 6:
                  rotate_degrees = 90.0;
                  break;
              }
              // rotate the image according to EXIF orientation tag
              if(rotate_degrees != 0.0) {
                QTransform transform;
                transform.rotate(rotate_degrees);
                image_ = image_.transformed(transform, Qt::SmoothTransformation);
              }
              // TODO: handle other EXIF tags as well
            }
            exif_data_unref(exif_data);
          }
        }
        g_free(mime_type);
      }
    }
  }
  return false;
}
Exemple #24
0
void WordsGraphicsHandler::parseOfficeArtContainers()
{
    debugMsDoc;

    if (!m_fib.lcbDggInfo) return;

    POLE::Stream& stream = m_document->poleTableStream();
    if (stream.fail()) {
        debugMsDoc << "Table stream not provided, no access to OfficeArt file records!";
        return;
    }

    QByteArray array;
    QBuffer buffer;
    array.resize(m_fib.lcbDggInfo);
    stream.seek(m_fib.fcDggInfo);
    unsigned long n = stream.read((unsigned char*) array.data(), m_fib.lcbDggInfo);
    if (n != m_fib.lcbDggInfo) {
        errorMsDoc << "Error while reading from " << stream.fullName().data() << "stream";
        return;
    }

    buffer.setData(array);
    buffer.open(QIODevice::ReadOnly);
    LEInputStream in(&buffer);

    //parse OfficeArfDggContainer from msdoc
    try {
        parseOfficeArtDggContainer(in, m_officeArtDggContainer);
    }
    catch (const IOException& e) {
        debugMsDoc << "Caught IOException while parsing OfficeArtDggContainer.";
        debugMsDoc << e.msg;
        return;
    }
    catch (...) {
        debugMsDoc << "Caught UNKNOWN exception while parsing OfficeArtDggContainer.";
        return;
    }
#ifdef DEBUG_GHANDLER
    debugMsDoc << "OfficeArtDggContainer [ OK ]" ;
#endif

    // parse drawingsVariable from msdoc
    // 0 - next OfficeArtDgContainer belongs to Main document;
    // 1 - next OfficeArtDgContainer belongs to Header Document
    unsigned char drawingsVariable = 0;
    try {
        drawingsVariable = in.readuint8();
    }
    catch (const IOException& e) {
        debugMsDoc << "Caught IOException while parsing DrawingsVariable.";
        debugMsDoc << e.msg;
        return;
    }
    catch (...) {
        debugMsDoc << "Caught UNKNOWN exception while parsing DrawingsVariable.";
        return;
    }

    //parse OfficeArfDgContainer from msdoc
    OfficeArtDgContainer *pDgContainer = 0;
    try {
        pDgContainer = new OfficeArtDgContainer();
        if (drawingsVariable == 0) {
            m_pOfficeArtBodyDgContainer = pDgContainer;
        } else {
            m_pOfficeArtHeaderDgContainer = pDgContainer;
        }
        parseOfficeArtDgContainer(in, *pDgContainer);
    }
    catch (const IOException& e) {
        debugMsDoc << "Caught IOException while parsing OfficeArtDgContainer.";
        debugMsDoc << e.msg;
        return;
    }
    catch (...) {
        debugMsDoc << "Caught UNKNOWN exception while parsing OfficeArtDgContainer.";
        return;
    }
#ifdef DEBUG_GHANDLER
    debugMsDoc << "OfficeArtDgContainer (" << (drawingsVariable ? "Headers" : "Body") << ") [ OK ]";
#endif

    // parse drawingsVariable from msdoc
    // 0 - next OfficeArtDgContainer belongs to Main Document
    // 1 - next OfficeArtDgContainer belongs to Header Document
    try {
        drawingsVariable = in.readuint8();
    }
    catch (const IOException& e) {
        debugMsDoc << "Caught IOException while parsing the 2nd DrawingsVariable.";
        debugMsDoc << e.msg;
        return;
    }
    catch (...) {
        debugMsDoc << "Caught UNKNOWN exception while parsing the 2nd DrawingsVariable.";
        return;
    }

    //parse OfficeArfDgContainer from msdoc
    pDgContainer = 0;
    try {
        pDgContainer = new OfficeArtDgContainer();
        if (drawingsVariable == 0) {
            if (m_pOfficeArtBodyDgContainer != 0){
                delete m_pOfficeArtBodyDgContainer;
            }
            m_pOfficeArtBodyDgContainer = pDgContainer;
        } else {
            if (m_pOfficeArtHeaderDgContainer != 0) {
                delete m_pOfficeArtHeaderDgContainer;
            }
            m_pOfficeArtHeaderDgContainer = pDgContainer;
        }
        parseOfficeArtDgContainer(in, *pDgContainer);
    }
    catch (const IOException& e) {
        debugMsDoc << "Caught IOException while parsing the 2nd OfficeArtDgContainer.";
        debugMsDoc << e.msg;
        return;
    }
    catch (...) {
        debugMsDoc << "Caught UNKNOWN exception while parsing the 2nd OfficeArtDgContainer.";
        return;
    }

#ifdef DEBUG_GHANDLER
    debugMsDoc << "OfficeArtDgContainer (" << (drawingsVariable ? "Headers" : "Body") << ") [ OK ]";
#endif

    quint32 r = buffer.size() - in.getPosition();
    if (r > 0) {
        errorMsDoc << "Error:" << r << "bytes left to parse from the OfficeArtContent!";
    }
}