QByteArray QHelpDBReader::fileData(const QString &virtualFolder,
                                   const QString &filePath) const
{
    QByteArray ba;
    if (virtualFolder.isEmpty() || filePath.isEmpty() || !m_query)
        return ba;

    namespaceName();
    m_query->prepare(QLatin1String("SELECT a.Data FROM FileDataTable a, FileNameTable b, FolderTable c, "
        "NamespaceTable d WHERE a.Id=b.FileId AND (b.Name=? OR b.Name=?) AND b.FolderId=c.Id "
        "AND c.Name=? AND c.NamespaceId=d.Id AND d.Name=?"));
    m_query->bindValue(0, filePath);
    m_query->bindValue(1, QString(QLatin1String("./") + filePath));
    m_query->bindValue(2, virtualFolder);
    m_query->bindValue(3, m_namespace);
    m_query->exec();
    if (m_query->next() && m_query->isValid())
        ba = qUncompress(m_query->value(0).toByteArray());
    return ba;
}
示例#2
0
WebPage::WebPage(QObject *parent) : QWebPage(parent) {
  QResource javascript(":/capybara.js");
  if (javascript.isCompressed()) {
    QByteArray uncompressedBytes(qUncompress(javascript.data(), javascript.size()));
    m_capybaraJavascript = QString(uncompressedBytes);
  } else {
    char * javascriptString =  new char[javascript.size() + 1];
    strcpy(javascriptString, (const char *)javascript.data());
    javascriptString[javascript.size()] = 0;
    m_capybaraJavascript = javascriptString;
  }
  m_loading = false;

  this->setNetworkAccessManager(new NetworkAccessManager());

  connect(this, SIGNAL(loadStarted()), this, SLOT(loadStarted()));
  connect(this, SIGNAL(loadFinished(bool)), this, SLOT(loadFinished(bool)));
  connect(this, SIGNAL(frameCreated(QWebFrame *)),
          this, SLOT(frameCreated(QWebFrame *)));
}
示例#3
0
文件: drawmapwidget.cpp 项目: CaF2/hw
void DrawMapWidget::load(const QString & fileName)
{
    if(m_scene)
    {
        QFile f(fileName);

        if(!f.open(QIODevice::ReadOnly))
        {
            QMessageBox errorMsg(this);
            errorMsg.setIcon(QMessageBox::Warning);
            errorMsg.setWindowTitle(QMessageBox::tr("File error"));
            errorMsg.setText(QMessageBox::tr("Cannot open '%1' for reading").arg(fileName));
            errorMsg.setWindowModality(Qt::WindowModal);
            errorMsg.exec();
        }
        else
            m_scene->decode(qUncompress(QByteArray::fromBase64(f.readAll())));
            //m_scene->decode(f.readAll());
    }
}
示例#4
0
文件: DataFile.cpp 项目: AHudon/lmms
void DataFile::loadData( const QByteArray & _data, const QString & _sourceFile )
{
	QString errorMsg;
	int line = -1, col = -1;
	if( !setContent( _data, &errorMsg, &line, &col ) )
	{
		// parsing failed? then try to uncompress data
		QByteArray uncompressed = qUncompress( _data );
		if( !uncompressed.isEmpty() )
		{
			if( setContent( uncompressed, &errorMsg, &line, &col ) )
			{
				line = col = -1;
			}
		}
		if( line >= 0 && col >= 0 )
		{
			qWarning() << "at line" << line << "column" << errorMsg;
			QMessageBox::critical( NULL,
				SongEditor::tr( "Error in file" ),
				SongEditor::tr( "The file %1 seems to contain "
						"errors and therefore can't be "
						"loaded." ).
							arg( _sourceFile ) );
			return;
		}
	}

	QDomElement root = documentElement();
	m_type = type( root.attribute( "type" ) );
	m_head = root.elementsByTagName( "head" ).item( 0 ).toElement();

	if( root.hasAttribute( "creatorversion" ) &&
		root.attribute( "creatorversion" ) != LMMS_VERSION )
	{
		upgrade();
	}

	m_content = root.elementsByTagName( typeName( m_type ) ).
							item( 0 ).toElement();
}
void WebKitBrowserExtension::restoreState(QDataStream &stream)
{
    KUrl u;
    QByteArray historyData;
    qint32 xOfs = -1, yOfs = -1, historyItemIndex = -1;
    stream >> u >> xOfs >> yOfs >> historyItemIndex >> historyData;

    QWebHistory* history = (view() ? view()->page()->history() : 0);
    if (history) {
        bool success = false;
        if (history->count() == 0) {   // Handle restoration: crash recovery, tab close undo, session restore
            if (!historyData.isEmpty()) {
                historyData = qUncompress(historyData); // uncompress the history data...
                QBuffer buffer (&historyData);
                if (buffer.open(QIODevice::ReadOnly)) {
                    QDataStream stream (&buffer);
                    view()->page()->setProperty("HistoryNavigationLocked", true);
                    stream >> *history;
                    QWebHistoryItem currentItem (history->currentItem());
                    if (currentItem.isValid()) {
                        if (currentItem.userData().isNull() && (xOfs != -1 || yOfs != -1)) {
                            const QPoint scrollPos (xOfs, yOfs);
                            currentItem.setUserData(scrollPos);
                        }
                        // NOTE 1: The following Konqueror specific workaround is necessary
                        // because Konqueror only preserves information for the last visited
                        // page. However, we save the entire history content in saveState and
                        // and hence need to elimiate all but the current item here.
                        // NOTE 2: This condition only applies when Konqueror is restored from
                        // abnormal termination ; a crash and/or a session restoration.
                        if (QCoreApplication::applicationName() == QLatin1String("konqueror")) {
                            history->clear();
                        }
                        //kDebug() << "Restoring URL:" << currentItem.url();
                        m_part->setProperty("NoEmitOpenUrlNotification", true);
                        history->goToItem(currentItem);
                    }
                }
            }
            success = (history->count() > 0);
        } else {        // Handle navigation: back and forward button navigation.
示例#6
0
void QSvgIconEnginePrivate::loadDataForModeAndState(QSvgRenderer *renderer, QIcon::Mode mode, QIcon::State state)
{
    QByteArray buf;
    if (svgBuffers) {
        buf = svgBuffers->value(hashKey(mode, state));
        if (buf.isEmpty())
            buf = svgBuffers->value(hashKey(QIcon::Normal, QIcon::Off));
    }
    if (!buf.isEmpty()) {
#ifndef QT_NO_COMPRESS
        buf = qUncompress(buf);
#endif
        renderer->load(buf);
    } else {
        QString svgFile = svgFiles.value(hashKey(mode, state));
        if (svgFile.isEmpty())
            svgFile = svgFiles.value(hashKey(QIcon::Normal, QIcon::Off));
        if (!svgFile.isEmpty())
            renderer->load(svgFile);
    }
}
示例#7
0
static QByteArray unzipXPM(QString data, ulong& length)
{
#ifndef QT_NO_COMPRESS
    const int lengthOffset = 4;
    QByteArray ba(lengthOffset, ' ');

    // qUncompress() expects the first 4 bytes to be the expected length of the
    // uncompressed data
    ba[0] = (length & 0xff000000) >> 24;
    ba[1] = (length & 0x00ff0000) >> 16;
    ba[2] = (length & 0x0000ff00) >> 8;
    ba[3] = (length & 0x000000ff);
    ba.append(transformImageData(data));
    QByteArray baunzip = qUncompress(ba);
    return baunzip;
#else
    Q_UNUSED(data);
    Q_UNUSED(length);
    return QByteArray();
#endif
}
示例#8
0
			Sync::Payloads_t DeltaStorage::Get (const Sync::ChainID_t& chainId)
			{
				DeltasRequested (chainId);

				QMap<int, Sync::Payload> tmpPayloads;

				QDir dir = GetDir (chainId);

				Q_FOREACH (const QString& filename, dir.entryList (QDir::Files | QDir::NoDotAndDotDot))
				{
					bool ok = true;
					int num = filename.toInt (&ok);
					if (!ok)
						continue;

					QFile file (dir.absoluteFilePath (filename));
					if (!file.open (QIODevice::ReadOnly))
					{
						qWarning () << Q_FUNC_INFO
								<< "unable to open"
								<< file.fileName ()
								<< "for reading:"
								<< file.errorString ();
						throw std::runtime_error ("Unable to open file for reading.");
					}

					QByteArray data = file.readAll ();
					Sync::Payload payload = Sync::Deserialize (qUncompress (data));
					tmpPayloads [num] = payload;
				}

				QList<Sync::Payload> result;
				QList<int> keys = tmpPayloads.keys ();
				std::sort (keys.begin (), keys.end ());
				Q_FOREACH (int key, keys)
					result << tmpPayloads [key];

				return result;
			}
示例#9
0
void deserializeData(QDataStream *stream, QVariantMap *data)
{
    try {
        qint32 length;

        *stream >> length;
        if ( stream->status() != QDataStream::Ok )
            return;

        if (length == -2) {
            deserializeDataV2(stream, data);
            return;
        }

        if (length < 0) {
            stream->setStatus(QDataStream::ReadCorruptData);
            return;
        }

        // Deprecated format.
        // TODO: Data should be saved again in new format.
        QString mime;
        QByteArray tmpBytes;
        for (qint32 i = 0; i < length && stream->status() == QDataStream::Ok; ++i) {
            *stream >> mime >> tmpBytes;
            if( !tmpBytes.isEmpty() ) {
                tmpBytes = qUncompress(tmpBytes);
                if ( tmpBytes.isEmpty() ) {
                    stream->setStatus(QDataStream::ReadCorruptData);
                    break;
                }
            }
            data->insert(mime, tmpBytes);
        }
    } catch (const std::exception &e) {
        log( QObject::tr("Data deserialization failed: %1").arg(e.what()), LogError );
        stream->setStatus(QDataStream::ReadCorruptData);
    }
}
示例#10
0
//////////////////////////////////////////////////////////////////////
// name Get Functions
//////////////////////////////////////////////////////////////////////
// Load the binary rep
GLC_3DRep GLC_BSRep::loadRep()
{
	GLC_3DRep loadedRep;

	if (open(QIODevice::ReadOnly))
	{
		if (headerIsOk())
		{
			timeStampOk(QDateTime());
			GLC_BoundingBox boundingBox;
			m_DataStream >> boundingBox;
			bool useCompression;
			m_DataStream >> useCompression;
			if (useCompression)
			{
				QByteArray CompresseBuffer;
				m_DataStream >> CompresseBuffer;
				QByteArray uncompressedBuffer= qUncompress(CompresseBuffer);
				uncompressedBuffer.squeeze();
				CompresseBuffer.clear();
				CompresseBuffer.squeeze();
				QDataStream bufferStream(uncompressedBuffer);
				bufferStream >> loadedRep;
			}
			else
			{
				m_DataStream >> loadedRep;
			}
			loadedRep.setFileName(m_FileInfo.filePath());

			if (!close())
			{
				QString message(QString("GLC_BSRep::loadRep An error occur when loading file ") + m_FileInfo.fileName());
				GLC_FileFormatException fileFormatException(message, m_FileInfo.fileName(), GLC_FileFormatException::WrongFileFormat);
				throw(fileFormatException);
			}
		}
		else
		{
示例#11
0
QByteArray Compression::uncompress(quint32 unpacked_len, QByteArray bytes, Compression::CompressionType compressionType)
{
    if (unpacked_len > 30000) return QByteArray();
    if (bytes.size() < 1) return QByteArray();


    switch(compressionType) {
    case Uncompressed:
        return bytes;
    case RLE:
    {
        char *dst = new char[unpacked_len];
        decode_packbits(bytes.constData(), dst, bytes.length(), unpacked_len);
        QByteArray ba(dst, unpacked_len);
        delete[] dst;
        return ba;
     }
    case ZIP:
    case ZIPWithPrediction:
    {
        // prepend the expected length of the pixels in big-endian
        // format to the byte array as qUncompress expects...

        QByteArray b;
        QBuffer buf(&b);
        quint32 val = ntohl(unpacked_len);
        buf.write((char*)&val, 4);
        b.append(bytes);

        // and let's hope that this is sufficient...
        return qUncompress(b);
    }
    default:
        qFatal("Cannot uncompress layer data: invalid compression type");
    }


    return QByteArray();
}
bool xml_sax_handler_read_devices::handle_file()
{
	if (!file.open(QFile::ReadOnly)) 
		{
        QMessageBox::warning(w_main, "Error", QObject::tr("Cannot read file %1:\n%2.").arg(file.fileName()).arg(file.errorString()));
        return FALSE;
		}

	in.setDevice(&file);
	in.setCodec("UTF-8");	//Attenzione: UTF-8 usa 8bit per carattere ma riesce a scrivere tutto l'unicode usando sequenze multibyte quando necessario
	
	//Il file è stato compresso per cui lo carico tutto in memoria per scompattarlo
	datablock_compressed.clear();
	datablock_compressed.append(in.readAll());
	//I dati compressi con ZLib iniziano sempre con 4 numeri che indicano la dimensione di memoria seguiti da 120 e -100 
	if ((datablock_compressed.at(4) != 120) || (datablock_compressed.at(5) != -100))	
                return FALSE;
        datablock = qUncompress(datablock_compressed);
        datablock_compressed.clear();

	return TRUE;
}
示例#13
0
void HWMapContainer::loadDrawing()
{
    QString fileName = QFileDialog::getOpenFileName(NULL, tr("Load drawn map"), ".", tr("Drawn Maps") + " (*.hwmap);;" + tr("All files") + " (*)");

    if(fileName.isEmpty()) return;

    QFile f(fileName);

    if(!f.open(QIODevice::ReadOnly))
    {
        QMessageBox errorMsg(parentWidget());
        errorMsg.setIcon(QMessageBox::Warning);
        errorMsg.setWindowTitle(QMessageBox::tr("File error"));
        errorMsg.setText(QMessageBox::tr("Cannot open '%1' for reading").arg(fileName));
        errorMsg.setWindowModality(Qt::WindowModal);
        errorMsg.exec();
    }
    else
    {
        drawMapScene.decode(qUncompress(QByteArray::fromBase64(f.readAll())));
        mapDrawingFinished();
    }
}
示例#14
0
文件: treemodel.cpp 项目: jhj/aqp-qt5
bool TreeModel::dropMimeData(const QMimeData *mimeData,
        Qt::DropAction action, int row, int column,
        const QModelIndex &parent)
{
    if (action == Qt::IgnoreAction)
        return true;
    if (action != Qt::MoveAction || column > 0 ||
        !mimeData || !mimeData->hasFormat(MimeType))
        return false;
    if (TaskItem *item = itemForIndex(parent)) {
        emit stopTiming();
        QByteArray xmlData = qUncompress(mimeData->data(MimeType));
        QXmlStreamReader reader(xmlData);
        if (row == -1)
            row = parent.isValid() ? parent.row()
                                   : rootItem->childCount();
        beginInsertRows(parent, row, row);
        readTasks(&reader, item);
        endInsertRows();
        return true;
    }
    return false;
}
示例#15
0
QString BaseStateAbstract::readString(QStringRef val)
{
    QString ret;

    QByteArray data = val.toString().toUtf8();
    if (data.isEmpty())
        return ret;

    bool compressed = false;

    if (data.at(0) == COMPRESSED_MARKER) {
        compressed = true;
        data = data.mid(1);
    }

    data = QByteArray::fromBase64(data);

    if (compressed)
        data = qUncompress(data);

    ret = QString::fromUtf8(data.constData(), data.size());
    return ret;
}
static QImage uic_findImage( const QString& name )
{
    for ( int i=0; embed_image_vec[i].data; i++ ) {
	if ( QString::fromUtf8(embed_image_vec[i].name) == name ) {
	    QByteArray baunzip;
	    baunzip = qUncompress( embed_image_vec[i].data, 
		embed_image_vec[i].compressed );
	    QImage img((uchar*)baunzip.data(),
			embed_image_vec[i].width,
			embed_image_vec[i].height,
			embed_image_vec[i].depth,
			(QRgb*)embed_image_vec[i].colorTable,
			embed_image_vec[i].numColors,
			QImage::BigEndian
		);
	    img = img.copy();
	    if ( embed_image_vec[i].alpha )
		img.setAlphaBuffer(TRUE);
	    return img;
        }
    }
    return QImage();
}
void KMoneyThingMainWidget::slotOpen()
{
  QString fileName;
  KURL kurl = KFileDialog::getOpenURL(0, i18n("*.kmt|KMoneyThing files (*.kmt)"), this);
  if (kurl.path() == "")
    return;
  mCurrentFile->setKurl(kurl);

  emit(setStatus(i18n("Downloading file...")));
  KIO::NetAccess::download(kurl, fileName, this);
  
  emit(setStatus(i18n("Reading file...")));
  QByteArray dump;
  QString temp;
  QFile file(fileName);
  file.open(IO_ReadOnly);
  QDataStream stream(&file);
  
  stream >> temp;
  if (temp != "KMoneyThingFile")
  {
    KMessageBox::error(this, i18n("Unknown file format: %1").arg(temp));
    file.close();
    KIO::NetAccess::removeTempFile(fileName);
    emit(setStatus(i18n("Ready.")));
    return;
  }
  stream >> dump;
  file.close();
  KIO::NetAccess::removeTempFile(fileName);
  
  emit(setStatus(i18n("Parsing file...")));
  mCurrentFile->loadDump(qUncompress(dump));
  emit(setStatus(i18n("Ready.")));
  
  emit signalRefresh();
}
示例#18
0
QByteArray resourceAsByteArray(const QString &pResource)
{
    // Retrieve a resource as a QByteArray

    QResource resource(pResource);

    if (resource.isValid()) {
        if (resource.isCompressed())
            // The resource is compressed, so uncompress it before returning it

            return qUncompress(resource.data(), resource.size());
        else
            // The resource is not compressed, so just return it after doing the
            // right conversion

            return QByteArray(reinterpret_cast<const char *>(resource.data()),
                              resource.size());
    }
    else {
        // The resource doesn't exist, so...

        return QByteArray();
    }
}
QByteArray OsmAnd::CoreResourcesEmbeddedBundle_P::getResource(const QString& name, const float displayDensityFactor, bool* ok /*= nullptr*/) const
{
    const auto citResourceEntry = _resources.constFind(name);
    if (citResourceEntry == _resources.cend())
    {
        if (ok)
            *ok = false;
        return QByteArray();
    }
    const auto& resourceEntry = *citResourceEntry;

    auto itByDisplayDensityFactor = iteratorOf(constOf(resourceEntry.variantsByDisplayDensityFactor));
    while (itByDisplayDensityFactor.hasNext())
    {
        const auto byDisplayDensityFactorEntry = itByDisplayDensityFactor.next();
        const auto& testDisplayDensityFactor = byDisplayDensityFactorEntry.key();
        const auto& resourceData = byDisplayDensityFactorEntry.value();

        if (qFuzzyCompare(displayDensityFactor, testDisplayDensityFactor) ||
            testDisplayDensityFactor >= displayDensityFactor ||
            !itByDisplayDensityFactor.hasNext())
        {
            if (ok)
                *ok = true;
            if (!name.endsWith(QString(".png")))
                return qUncompress(resourceData.data, resourceData.size);
            else {
                return QByteArray(reinterpret_cast<const char*>(resourceData.data) + 4, resourceData.size - 4);
            }
        }
    }

    if (ok)
        *ok = false;
    return QByteArray();
}
示例#20
0
DatabaseManager::TriggerList DatabaseManager::uncommittedTriggers() {

	TriggerList l;

	if ( !__db.isOpen() )
	    return l;

	QSqlQuery query(QString("SELECT data FROM main.Trigger WHERE status=0 OR status=1 OR status=2"));

	while ( query.next() ) {
		QByteArray data = qUncompress(query.value(0).toByteArray());
		QDataStream stream(&data, QIODevice::ReadOnly);
#if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0))
		stream.setVersion(QDataStream::Qt_4_8);
#else
		stream.setVersion(QDataStream::Qt_4_6);
#endif
		Trigger* trig = Trigger::create("");
		trig->fromDataStream(stream);
		l << trig;
	}

	return l;
}
示例#21
0
DatabaseManager::DispatchList DatabaseManager::dispatchs() {

	DispatchList l;

	if ( !__db.isOpen() )
	    return l;

	QSqlQuery query(QString("SELECT data FROM main.Dispatch"));

	while ( query.next() ) {
		QByteArray data = qUncompress(query.value(0).toByteArray());
		QDataStream stream(&data, QIODevice::ReadOnly);
#if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0))
		stream.setVersion(QDataStream::Qt_4_8);
#else
		stream.setVersion(QDataStream::Qt_4_6);
#endif
		DispatchJob* job = DispatchJob::create();
		job->fromDataStream(stream);
		l << job;
	}

	return l;
}
QByteArray OsmAnd::CoreResourcesEmbeddedBundle_P::getResource(const QString& name, bool* ok /*= nullptr*/) const
{
    const auto citResourceEntry = _resources.constFind(name);
    if (citResourceEntry == _resources.cend())
    {
        if (ok)
            *ok = false;
        return QByteArray();
    }
    const auto& resourceEntry = *citResourceEntry;
    if (!resourceEntry.defaultVariant.data)
    {
        if (ok)
            *ok = false;
        return QByteArray();
    }

    if (ok)
        *ok = true;
    if (!name.endsWith(QString(".png")))
        return qUncompress(resourceEntry.defaultVariant.data, resourceEntry.defaultVariant.size);
    else
        return QByteArray(reinterpret_cast<const char*>(resourceEntry.defaultVariant.data) + 4, resourceEntry.defaultVariant.size - 4);
}
示例#23
0
QByteArray SessionMgr::openSessionFile(const QString& name)
{
    QFile file(getFolder() + name);
    if(!file.open(QIODevice::ReadOnly))
        return QByteArray();

    QByteArray data;
    QByteArray str = file.read(4);
    file.seek(0);

    if(str == QByteArray::fromRawData("LDTA", 4))
    {
        try {
            data = DataFileBuilder::readAndCheck(file, DATAFILE_SESSION);
        }
        catch(const QString& ex) {
            Utils::showErrorBox(tr("Error loading session file: %1").arg(ex));
            return data;
        }
    }
    // Legacy
    else
    {
        QByteArray magic = file.read(sizeof(CLDTA_DATA_MAGIC));
        if(magic.size() != sizeof(CLDTA_DATA_MAGIC))
            return QByteArray();

        for(quint8 i = 0; i < sizeof(CLDTA_DATA_MAGIC); ++i)
            if(magic[i] != CLDTA_DATA_MAGIC[i])
                return QByteArray();

        data = qUncompress(file.readAll());
    }

    return data;
}
示例#24
0
/// This method is run by QtConcurrent:
msg_ptr
MsgProcessor::process( msg_ptr msg, quint32 mode, quint32 threshold )
{
    // uncompress if needed
    if( (mode & UNCOMPRESS_ALL) && msg->is( Msg::COMPRESSED ) )
    {
        qDebug() << "MsgProcessor::UNCOMPRESSING";
        msg->m_payload = qUncompress( msg->payload() );
        msg->m_length  = msg->m_payload.length();
        msg->m_flags ^= Msg::COMPRESSED;
    }

    // parse json payload into qvariant if needed
    if( (mode & PARSE_JSON) &&
        msg->is( Msg::JSON ) &&
        msg->m_json_parsed == false )
    {
        qDebug() << "MsgProcessor::PARSING JSON";
        bool ok;
        QJson::Parser parser;
        msg->m_json = parser.parse( msg->payload(), &ok );
        msg->m_json_parsed = true;
    }

    // compress if needed
    if( (mode & COMPRESS_IF_LARGE) &&
        !msg->is( Msg::COMPRESSED )
        && msg->length() > threshold )
    {
        qDebug() << "MsgProcessor::COMPRESSING";
        msg->m_payload = qCompress( msg->payload(), 9 );
        msg->m_length  = msg->m_payload.length();
        msg->m_flags |= Msg::COMPRESSED;
    }
    return msg;
}
示例#25
0
void GameCFGWidget::setParam(const QString & param, const QStringList & slValue)
{
    if (slValue.size() == 1)
    {
        QString value = slValue[0];
        if (param == "MAP")
        {
            pMapContainer->setMap(value);
            return;
        }
        if (param == "SEED")
        {
            pMapContainer->setSeed(value);
            return;
        }
        if (param == "THEME")
        {
            pMapContainer->setTheme(value);
            return;
        }
        if (param == "TEMPLATE")
        {
            pMapContainer->setTemplateFilter(value.toUInt());
            return;
        }
        if (param == "MAPGEN")
        {
            pMapContainer->setMapgen((MapGenerator)value.toUInt());
            return;
        }
        if (param == "FEATURE_SIZE")
        {
            pMapContainer->setFeatureSize(value.toUInt());
            return;
        }
        if (param == "MAZE_SIZE")
        {
            pMapContainer->setMazeSize(value.toUInt());
            return;
        }
        if (param == "SCRIPT")
        {
            Scripts->setCurrentIndex(Scripts->findText(value));
            pMapContainer->setScript(Scripts->itemData(Scripts->currentIndex(), GameStyleModel::ScriptRole).toString().toUtf8(), schemeData(43).toString());
            return;
        }
        if (param == "DRAWNMAP")
        {
            pMapContainer->setDrawnMapData(qUncompress(QByteArray::fromBase64(slValue[0].toLatin1())));
            return;
        }
    }

    if (slValue.size() == 2)
    {
        if (param == "AMMO")
        {
            setNetAmmo(slValue[0], slValue[1]);
            return;
        }
    }

    if (slValue.size() == 6)
    {
        if (param == "FULLMAPCONFIG")
        {
            QString seed = slValue[4];

            pMapContainer->setAllMapParameters(
                slValue[1],
                (MapGenerator)slValue[2].toUInt(),
                slValue[3].toUInt(),
                seed,
                slValue[5].toUInt(),
                slValue[0].toUInt()
            );
            return;
        }
    }

    qWarning("Got bad config param from net");
}
示例#26
0
文件: qsciapis.cpp 项目: Esenin/qreal
// Load the prepared API information.
bool QsciAPIs::loadPrepared(const QString &filename)
{
    QString pname = prepName(filename);

    if (pname.isEmpty())
        return false;

    // Read the prepared data and decompress it.
    QFile pf(pname);

    if (!pf.open(QIODevice::ReadOnly))
        return false;

    QByteArray cpdata = pf.readAll();

    pf.close();

    if (cpdata.count() == 0)
        return false;

    QByteArray pdata = qUncompress(cpdata);

    // Extract the data.
    QDataStream pds(pdata);

    unsigned char vers;
    pds >> vers;

    if (vers > PreparedDataFormatVersion)
        return false;

    char *lex_name;
    pds >> lex_name;

    if (qstrcmp(lex_name, lexer()->lexer()) != 0)
    {
        delete[] lex_name;
        return false;
    }

    delete[] lex_name;

    prep->wdict.clear();
    pds >> prep->wdict;

    if (!lexer()->caseSensitive())
    {
        // Build up the case dictionary.
        prep->cdict.clear();

        QMap<QString, WordIndexList>::const_iterator it = prep->wdict.begin();

        while (it != prep->wdict.end())
        {
            prep->cdict[it.key().toUpper()] = it.key();

            ++it;
        }

    }

    prep->raw_apis.clear();
    pds >> prep->raw_apis;

    // Allow the raw API information to be modified.
    apis = prep->raw_apis;

    return true;
}
示例#27
0
文件: client.cpp 项目: bakwc/Epsilon5
void TClient::OnDataReceived(const QByteArray &data)
{
    EPacketType packetType;
    quint16 packedDataSize;
    quint16 originDataSize;
    QByteArray content;
    QByteArray receivedPacket = data;
    const int midSize = sizeof(quint16);
    const int posOrigin = sizeof(char);
    const int posPacked = posOrigin + midSize;
    const int posContent = posPacked + midSize;

    try {
        while (receivedPacket.size() > 0) {
            packetType = (EPacketType)(char)(receivedPacket[0]);
            originDataSize = qFromBigEndian<quint16>(
                (const uchar*)receivedPacket.mid(posOrigin, midSize).constData());
            packedDataSize = qFromBigEndian<quint16>(
                (const uchar*)receivedPacket.mid(posPacked, midSize).constData());
            content = qUncompress(receivedPacket.mid(posContent, packedDataSize));

            if( content.isEmpty() && (originDataSize || packedDataSize) )
                throw UException("Wrong packet: cannot unpack data");

            // Retrieve another packet from current.
            // We can receive more than one packet at once
            receivedPacket = receivedPacket.mid(
                packedDataSize + sizeof(char) + 2*midSize);

            switch (packetType) {
            case PT_Control: {
            if (!(PlayerStatus == PS_Spawned || PlayerStatus == PS_Dead)) {
                    throw UException("Player not spawned!");
                }
                Epsilon5::Control control;

                if (control.ParseFromArray(content.data(), content.size())) {
                    size_t currentPacket = control.packet_number();
                    if (control.has_need_full()) {
                        if (control.need_full()) {
                            Server()->NeedFullPacket(Id);
                        }
                    }
                    Server()->Application()->GetWorld()->SetPingForPlayer(Id, currentPacket);
                    SetSeen();
                    emit ControlReceived(control);
                } else {
                    throw UException("Parse error: control packet");
                }
            }
                break;
            case PT_PlayerAuth: {
                if (PlayerStatus != PS_AuthWait) {
                    throw UException("Player not waiting for auth!");
                }
                Epsilon5::Auth auth;
                if (auth.ParseFromArray(content.data(), content.size())) {
                    try {
                        SetSeen();
                        NickName = auth.name().c_str();
                        SendPlayerInfo();

                        QTime dieTime= QTime::currentTime().addSecs(1);
                        while( QTime::currentTime() < dieTime ) {
                            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
                        }

                    qDebug() << "Player " << NickName << "("
                             << Addr.toString() << ") connected";

                    Team = rand() % 2 == 1 ? T_One : T_Second; // throw to random team
                    ETeam NewTeam = Server()->AutoBalance();
                    if (NewTeam != T_Neutral) {
                        Team = NewTeam;
                    }

                    emit PlayerConnected();
                    ReSpawn(true);

                    } catch (const std::exception& e){
                    qDebug() << "Exceptiong: " << Q_FUNC_INFO
                             << ": Error spawning player: " << e.what();
                    }
                } else {
                    throw UException("Parse error: auth packet");
                }
            }
                break;
            default:
                throw UException("Unknown packet type!");
                break;
            }
        }
    } catch (const UException& e) {
        qDebug() << "Exceptiong: " << Q_FUNC_INFO << ": " << e.what();
    }
}
示例#28
0
QString TupCompress::uncompressAndDecode64(const QString &str)
{
    return QString::fromLocal8Bit(qUncompress(QByteArray::fromBase64(str.toLocal8Bit())));
}
示例#29
0
文件: CMisc.cpp 项目: ray-x/SMonitor
QString CMisc::Decrypt(const QString& src)
{
	QByteArray byteArray = QByteArray::fromBase64(src.toLatin1());
	QString result = qUncompress(byteArray);
	return result;
}
示例#30
0
文件: main.cpp 项目: mamins1376/lmms
int main( int argc, char * * argv )
{
	// initialize memory managers
	MemoryManager::init();
	NotePlayHandleManager::init();

	// intialize RNG
	srand( getpid() + time( 0 ) );

	disable_denormals();

	bool coreOnly = false;
	bool fullscreen = true;
	bool exitAfterImport = false;
	bool allowRoot = false;
	bool renderLoop = false;
	bool renderTracks = false;
	QString fileToLoad, fileToImport, renderOut, profilerOutputFile, configFile;

	// first of two command-line parsing stages
	for( int i = 1; i < argc; ++i )
	{
		QString arg = argv[i];

		if( arg == "--help"    || arg == "-h" ||
		    arg == "--version" || arg == "-v" ||
		    arg == "--render"  || arg == "-r" )
		{
			coreOnly = true;
		}
		else if( arg == "--rendertracks" )
		{
			coreOnly = true;
			renderTracks = true;
		}
		else if( arg == "--allowroot" )
		{
			allowRoot = true;
		}
		else if( arg == "--geometry" || arg == "-geometry")
		{
			if( arg == "--geometry" )
			{
				// Delete the first "-" so Qt recognize the option
				strcpy(argv[i], "-geometry");
			}
			// option -geometry is filtered by Qt later,
			// so we need to check its presence now to
			// determine, if the application should run in
			// fullscreen mode (default, no -geometry given).
			fullscreen = false;
		}
	}

#if !defined(LMMS_BUILD_WIN32) && !defined(LMMS_BUILD_HAIKU)
	if ( ( getuid() == 0 || geteuid() == 0 ) && !allowRoot )
	{
		printf( "LMMS cannot be run as root.\nUse \"--allowroot\" to override.\n\n" );
		return EXIT_FAILURE;
	}	
#endif

	QCoreApplication * app = coreOnly ?
			new QCoreApplication( argc, argv ) :
					new MainApplication( argc, argv );

	Mixer::qualitySettings qs( Mixer::qualitySettings::Mode_HighQuality );
	OutputSettings os( 44100, OutputSettings::BitRateSettings(160, false), OutputSettings::Depth_16Bit );
	ProjectRenderer::ExportFileFormats eff = ProjectRenderer::WaveFile;

	// second of two command-line parsing stages
	for( int i = 1; i < argc; ++i )
	{
		QString arg = argv[i];

		if( arg == "--version" || arg == "-v" )
		{
			printVersion( argv[0] );
			return EXIT_SUCCESS;
		}
		else if( arg == "--help" || arg  == "-h" )
		{
			printHelp();
			return EXIT_SUCCESS;
		}
		else if( arg == "--upgrade" || arg == "-u" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			DataFile dataFile( QString::fromLocal8Bit( argv[i] ) );

			if( argc > i+1 ) // output file specified
			{
				dataFile.writeFile( QString::fromLocal8Bit( argv[i+1] ) );
			}
			else // no output file specified; use stdout
			{
				QTextStream ts( stdout );
				dataFile.write( ts );
				fflush( stdout );
			}

			return EXIT_SUCCESS;
		}
		else if( arg == "--allowroot" )
		{
			// Ignore, processed earlier
#ifdef LMMS_BUILD_WIN32
			if( allowRoot )
			{
				printf( "\nOption \"--allowroot\" will be ignored on this platform.\n\n" );
			}
#endif
			
		}
		else if( arg == "--dump" || arg == "-d" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			QFile f( QString::fromLocal8Bit( argv[i] ) );
			f.open( QIODevice::ReadOnly );
			QString d = qUncompress( f.readAll() );
			printf( "%s\n", d.toUtf8().constData() );

			return EXIT_SUCCESS;
		}
		else if( arg == "--render" || arg == "-r" || arg == "--rendertracks" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			fileToLoad = QString::fromLocal8Bit( argv[i] );
			renderOut = fileToLoad;
		}
		else if( arg == "--loop" || arg == "-l" )
		{
			renderLoop = true;
		}
		else if( arg == "--output" || arg == "-o" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo output file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			renderOut = QString::fromLocal8Bit( argv[i] );
		}
		else if( arg == "--format" || arg == "-f" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo output format specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			const QString ext = QString( argv[i] );

			if( ext == "wav" )
			{
				eff = ProjectRenderer::WaveFile;
			}
#ifdef LMMS_HAVE_OGGVORBIS
			else if( ext == "ogg" )
			{
				eff = ProjectRenderer::OggFile;
			}
#endif
			else
			{
				printf( "\nInvalid output format %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--samplerate" || arg == "-s" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo samplerate specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			sample_rate_t sr = QString( argv[i] ).toUInt();
			if( sr >= 44100 && sr <= 192000 )
			{
				os.setSampleRate(sr);
			}
			else
			{
				printf( "\nInvalid samplerate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--bitrate" || arg == "-b" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo bitrate specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			int br = QString( argv[i] ).toUInt();

			if( br >= 64 && br <= 384 )
			{
				OutputSettings::BitRateSettings bitRateSettings = os.getBitRateSettings();
				bitRateSettings.setBitRate(br);
				os.setBitRateSettings(bitRateSettings);
			}
			else
			{
				printf( "\nInvalid bitrate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg =="--float" || arg == "-a" )
		{
			os.setBitDepth(OutputSettings::Depth_32Bit);
		}
		else if( arg == "--interpolation" || arg == "-i" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo interpolation method specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			const QString ip = QString( argv[i] );

			if( ip == "linear" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_Linear;
			}
			else if( ip == "sincfastest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincFastest;
			}
			else if( ip == "sincmedium" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincMedium;
			}
			else if( ip == "sincbest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincBest;
			}
			else
			{
				printf( "\nInvalid interpolation method %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--oversampling" || arg == "-x" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo oversampling specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			int o = QString( argv[i] ).toUInt();

			switch( o )
			{
				case 1:
		qs.oversampling = Mixer::qualitySettings::Oversampling_None;
		break;
				case 2:
		qs.oversampling = Mixer::qualitySettings::Oversampling_2x;
		break;
				case 4:
		qs.oversampling = Mixer::qualitySettings::Oversampling_4x;
		break;
				case 8:
		qs.oversampling = Mixer::qualitySettings::Oversampling_8x;
		break;
				default:
				printf( "\nInvalid oversampling %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--import" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo file specified for importing.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			fileToImport = QString::fromLocal8Bit( argv[i] );

			// exit after import? (only for debugging)
			if( QString( argv[i + 1] ) == "-e" )
			{
				exitAfterImport = true;
				++i;
			}
		}
		else if( arg == "--profile" || arg == "-p" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo profile specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			profilerOutputFile = QString::fromLocal8Bit( argv[i] );
		}
		else if( arg == "--config" || arg == "-c" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo configuration file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}

			configFile = QString::fromLocal8Bit( argv[i] );
		}
		else
		{
			if( argv[i][0] == '-' )
			{
				printf( "\nInvalid option %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
			fileToLoad = QString::fromLocal8Bit( argv[i] );
		}
	}

	// Test file argument before continuing
	if( !fileToLoad.isEmpty() )
	{
		fileCheck( fileToLoad );
	}
	else if( !fileToImport.isEmpty() )
	{
		fileCheck( fileToImport );
	}

	ConfigManager::inst()->loadConfigFile(configFile);

	// set language
	QString pos = ConfigManager::inst()->value( "app", "language" );
	if( pos.isEmpty() )
	{
		pos = QLocale::system().name().left( 2 );
	}

#ifdef LMMS_BUILD_WIN32
#undef QT_TRANSLATIONS_DIR
#define QT_TRANSLATIONS_DIR ConfigManager::inst()->localeDir()
#endif

#ifdef QT_TRANSLATIONS_DIR
	// load translation for Qt-widgets/-dialogs
	loadTranslation( QString( "qt_" ) + pos,
					QString( QT_TRANSLATIONS_DIR ) );
#endif
	// load actual translation for LMMS
	loadTranslation( pos );


	// try to set realtime priority
#ifdef LMMS_BUILD_LINUX
#ifdef LMMS_HAVE_SCHED_H
#ifndef __OpenBSD__
	struct sched_param sparam;
	sparam.sched_priority = ( sched_get_priority_max( SCHED_FIFO ) +
				sched_get_priority_min( SCHED_FIFO ) ) / 2;
	if( sched_setscheduler( 0, SCHED_FIFO, &sparam ) == -1 )
	{
		printf( "Notice: could not set realtime priority.\n" );
	}
#endif
#endif
#endif

#ifdef LMMS_BUILD_WIN32
	if( !SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) )
	{
		printf( "Notice: could not set high priority.\n" );
	}
#endif

#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
	struct sigaction sa;
	sa.sa_handler = SIG_IGN;
	sa.sa_flags = SA_SIGINFO;
	if ( sigemptyset( &sa.sa_mask ) )
	{
		fprintf( stderr, "Signal initialization failed.\n" );
	}
	if ( sigaction( SIGPIPE, &sa, NULL ) )
	{
		fprintf( stderr, "Signal initialization failed.\n" );
	}
#endif

	bool destroyEngine = false;

	// if we have an output file for rendering, just render the song
	// without starting the GUI
	if( !renderOut.isEmpty() )
	{
		Engine::init( true );
		destroyEngine = true;

		printf( "Loading project...\n" );
		Engine::getSong()->loadProject( fileToLoad );
		if( Engine::getSong()->isEmpty() )
		{
			printf("The project %s is empty, aborting!\n", fileToLoad.toUtf8().constData() );
			exit( EXIT_FAILURE );
		}
		printf( "Done\n" );

		Engine::getSong()->setExportLoop( renderLoop );

		// when rendering multiple tracks, renderOut is a directory
		// otherwise, it is a file, so we need to append the file extension
		if ( !renderTracks )
		{
			renderOut = baseName( renderOut ) +
				ProjectRenderer::getFileExtensionFromFormat(eff);
		}

		// create renderer
		RenderManager * r = new RenderManager( qs, os, eff, renderOut );
		QCoreApplication::instance()->connect( r,
				SIGNAL( finished() ), SLOT( quit() ) );

		// timer for progress-updates
		QTimer * t = new QTimer( r );
		r->connect( t, SIGNAL( timeout() ),
				SLOT( updateConsoleProgress() ) );
		t->start( 200 );

		if( profilerOutputFile.isEmpty() == false )
		{
			Engine::mixer()->profiler().setOutputFile( profilerOutputFile );
		}

		// start now!
		if ( renderTracks )
		{
			r->renderTracks();
		}
		else
		{
			r->renderProject();
		}
	}
	else // otherwise, start the GUI
	{
		new GuiApplication();

		// re-intialize RNG - shared libraries might have srand() or
		// srandom() calls in their init procedure
		srand( getpid() + time( 0 ) );

		// recover a file?
		QString recoveryFile = ConfigManager::inst()->recoveryFile();

		bool recoveryFilePresent = QFileInfo( recoveryFile ).exists() &&
				QFileInfo( recoveryFile ).isFile();
		bool autoSaveEnabled =
			ConfigManager::inst()->value( "ui", "enableautosave" ).toInt();
		if( recoveryFilePresent )
		{
			QMessageBox mb;
			mb.setWindowTitle( MainWindow::tr( "Project recovery" ) );
			mb.setText( QString(
				"<html>"
				"<p style=\"margin-left:6\">%1</p>"
				"<table cellpadding=\"3\">"
				"  <tr>"
				"    <td><b>%2</b></td>"
				"    <td>%3</td>"
				"  </tr>"
				"  <tr>"
				"    <td><b>%4</b></td>"
				"    <td>%5</td>"
				"  </tr>"
				"  <tr>"
				"    <td><b>%6</b></td>"
				"    <td>%7</td>"
				"  </tr>"
				"</table>"
				"</html>" ).arg(
				MainWindow::tr( "There is a recovery file present. "
					"It looks like the last session did not end "
					"properly or another instance of LMMS is "
					"already running. Do you want to recover the "
					"project of this session?" ),
				MainWindow::tr( "Recover" ),
				MainWindow::tr( "Recover the file. Please don't run "
					"multiple instances of LMMS when you do this." ),
				MainWindow::tr( "Ignore" ),
				MainWindow::tr( "Launch LMMS as usual but with "
					"automatic backup disabled to prevent the "
					"present recover file from being overwritten." ),
				MainWindow::tr( "Discard" ),
				MainWindow::tr( "Launch a default session and delete "
					"the restored files. This is not reversible." )
							) );

			mb.setIcon( QMessageBox::Warning );
			mb.setWindowIcon( embed::getIconPixmap( "icon" ) );
			mb.setWindowFlags( Qt::WindowCloseButtonHint );

			QPushButton * recover;
			QPushButton * discard;
			QPushButton * ignore;
			QPushButton * exit;
			
			#if QT_VERSION >= 0x050000
				// setting all buttons to the same roles allows us 
				// to have a custom layout
				discard = mb.addButton( MainWindow::tr( "Discard" ),
									QMessageBox::AcceptRole );
				ignore = mb.addButton( MainWindow::tr( "Ignore" ),
									QMessageBox::AcceptRole );
				recover = mb.addButton( MainWindow::tr( "Recover" ),
									QMessageBox::AcceptRole );

			# else 
				// in qt4 the button order is reversed
				recover = mb.addButton( MainWindow::tr( "Recover" ),
									QMessageBox::AcceptRole );
				ignore = mb.addButton( MainWindow::tr( "Ignore" ),
									QMessageBox::AcceptRole );
				discard = mb.addButton( MainWindow::tr( "Discard" ),
									QMessageBox::AcceptRole );

			#endif
			
			// have a hidden exit button
			exit = mb.addButton( "", QMessageBox::RejectRole);
			exit->setVisible(false);
			
			// set icons
			recover->setIcon( embed::getIconPixmap( "recover" ) );
			discard->setIcon( embed::getIconPixmap( "discard" ) );
			ignore->setIcon( embed::getIconPixmap( "ignore" ) );

			mb.setDefaultButton( recover );
			mb.setEscapeButton( exit );

			mb.exec();
			if( mb.clickedButton() == discard )
			{
				gui->mainWindow()->sessionCleanup();
			}
			else if( mb.clickedButton() == recover ) // Recover
			{
				fileToLoad = recoveryFile;
				gui->mainWindow()->setSession( MainWindow::SessionState::Recover );
			}
			else if( mb.clickedButton() == ignore )
			{
				if( autoSaveEnabled )
				{
					gui->mainWindow()->setSession( MainWindow::SessionState::Limited );
				}
			}
			else // Exit
			{
				return 0;
			}
		}

		// first show the Main Window and then try to load given file

		// [Settel] workaround: showMaximized() doesn't work with
		// FVWM2 unless the window is already visible -> show() first
		gui->mainWindow()->show();
		if( fullscreen )
		{
			gui->mainWindow()->showMaximized();
		}

		// Handle macOS-style FileOpen QEvents
		QString queuedFile = static_cast<MainApplication *>( app )->queuedFile();
		if ( !queuedFile.isEmpty() ) {
			fileToLoad = queuedFile;
		}

		if( !fileToLoad.isEmpty() )
		{
			if( fileToLoad == recoveryFile )
			{
				Engine::getSong()->createNewProjectFromTemplate( fileToLoad );
			}
			else
			{
				Engine::getSong()->loadProject( fileToLoad );
			}
		}
		else if( !fileToImport.isEmpty() )
		{
			ImportFilter::import( fileToImport, Engine::getSong() );
			if( exitAfterImport )
			{
				return EXIT_SUCCESS;
			}
		}
		// If enabled, open last project if there is one. Else, create
		// a new one. Also skip recently opened file if limited session to
		// lower the chance of opening an already opened file.
		else if( ConfigManager::inst()->
				value( "app", "openlastproject" ).toInt() &&
			!ConfigManager::inst()->
				recentlyOpenedProjects().isEmpty() &&
			gui->mainWindow()->getSession() !=
				MainWindow::SessionState::Limited )
		{
			QString f = ConfigManager::inst()->
					recentlyOpenedProjects().first();
			QFileInfo recentFile( f );

			if ( recentFile.exists() )
			{
				Engine::getSong()->loadProject( f );
			}
			else
			{
				Engine::getSong()->createNewProject();
			}
		}
		else
		{
			Engine::getSong()->createNewProject();
		}

		// Finally we start the auto save timer and also trigger the
		// autosave one time as recover.mmp is a signal to possible other
		// instances of LMMS.
		if( autoSaveEnabled &&
			gui->mainWindow()->getSession() != MainWindow::SessionState::Limited )
		{
			gui->mainWindow()->autoSaveTimerReset();
			gui->mainWindow()->autoSave();
		}
	}

	const int ret = app->exec();
	delete app;

	if( destroyEngine )
	{
		Engine::destroy();
	}

	// cleanup memory managers
	MemoryManager::cleanup();

	// ProjectRenderer::updateConsoleProgress() doesn't return line after render
	if( coreOnly )
	{
		printf( "\n" );
	}

	return ret;
}