Ejemplo n.º 1
0
void UpdateChecker::unpackUpdate() {
	QByteArray packed;
	if (!outputFile.open(QIODevice::ReadOnly)) {
		LOG(("Update Error: cant read updates file!"));
		return fatalFail();
	}

#ifdef Q_OS_WIN // use Lzma SDK for win
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header
#else // Q_OS_WIN
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header
#endif // Q_OS_WIN

	QByteArray compressed = outputFile.readAll();
	int32 compressedLen = compressed.size() - hSize;
	if (compressedLen <= 0) {
		LOG(("Update Error: bad compressed size: %1").arg(compressed.size()));
		return fatalFail();
	}
	outputFile.close();

	QString tempDirPath = cWorkingDir() + qsl("tupdates/temp"), readyFilePath = cWorkingDir() + qsl("tupdates/temp/ready");
	psDeleteDir(tempDirPath);

	QDir tempDir(tempDirPath);
	if (tempDir.exists() || QFile(readyFilePath).exists()) {
		LOG(("Update Error: cant clear tupdates/temp dir!"));
		return fatalFail();
	}

	uchar sha1Buffer[20];
	bool goodSha1 = !memcmp(compressed.constData() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, compressedLen + hPropsLen + hOriginalSizeLen, sha1Buffer), hShaLen);
	if (!goodSha1) {
		LOG(("Update Error: bad SHA1 hash of update file!"));
		return fatalFail();
	}

	RSA *pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>(AppAlphaVersion ? UpdatesPublicAlphaKey : UpdatesPublicKey), -1), 0, 0, 0);
	if (!pbKey) {
		LOG(("Update Error: cant read public rsa key!"));
		return fatalFail();
	}
	if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature
		RSA_free(pbKey);
		if (cAlphaVersion() || cBetaVersion()) { // try other public key, if we are in alpha or beta version
			pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>(AppAlphaVersion ? UpdatesPublicKey : UpdatesPublicAlphaKey), -1), 0, 0, 0);
			if (!pbKey) {
				LOG(("Update Error: cant read public rsa key!"));
				return fatalFail();
			}
			if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature
				RSA_free(pbKey);
				LOG(("Update Error: bad RSA signature of update file!"));
				return fatalFail();
			}
		} else {
			LOG(("Update Error: bad RSA signature of update file!"));
			return fatalFail();
		}
	}
	RSA_free(pbKey);

	QByteArray uncompressed;

	int32 uncompressedLen;
	memcpy(&uncompressedLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen);
	uncompressed.resize(uncompressedLen);

	size_t resultLen = uncompressed.size();
#ifdef Q_OS_WIN // use Lzma SDK for win
	SizeT srcLen = compressedLen;
	int uncompressRes = LzmaUncompress((uchar*)uncompressed.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE);
	if (uncompressRes != SZ_OK) {
		LOG(("Update Error: could not uncompress lzma, code: %1").arg(uncompressRes));
		return fatalFail();
	}
#else // Q_OS_WIN
	lzma_stream stream = LZMA_STREAM_INIT;

	lzma_ret ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED);
	if (ret != LZMA_OK) {
		const char *msg;
		switch (ret) {
		case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
		case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break;
		case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break;
		default: msg = "Unknown error, possibly a bug"; break;
		}
		LOG(("Error initializing the decoder: %1 (error code %2)").arg(msg).arg(ret));
		return fatalFail();
	}

	stream.avail_in = compressedLen;
	stream.next_in = (uint8_t*)(compressed.constData() + hSize);
	stream.avail_out = resultLen;
	stream.next_out = (uint8_t*)uncompressed.data();

	lzma_ret res = lzma_code(&stream, LZMA_FINISH);
	if (stream.avail_in) {
		LOG(("Error in decompression, %1 bytes left in _in of %2 whole.").arg(stream.avail_in).arg(compressedLen));
		return fatalFail();
	} else if (stream.avail_out) {
		LOG(("Error in decompression, %1 bytes free left in _out of %2 whole.").arg(stream.avail_out).arg(resultLen));
		return fatalFail();
	}
	lzma_end(&stream);
	if (res != LZMA_OK && res != LZMA_STREAM_END) {
		const char *msg;
		switch (res) {
		case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
		case LZMA_FORMAT_ERROR: msg = "The input data is not in the .xz format"; break;
		case LZMA_OPTIONS_ERROR: msg = "Unsupported compression options"; break;
		case LZMA_DATA_ERROR: msg = "Compressed file is corrupt"; break;
		case LZMA_BUF_ERROR: msg = "Compressed data is truncated or otherwise corrupt"; break;
		default: msg = "Unknown error, possibly a bug"; break;
		}
		LOG(("Error in decompression: %1 (error code %2)").arg(msg).arg(res));
		return fatalFail();
	}
#endif // Q_OS_WIN

	tempDir.mkdir(tempDir.absolutePath());

	quint32 version;
	{
		QBuffer buffer(&uncompressed);
		buffer.open(QIODevice::ReadOnly);
		QDataStream stream(&buffer);
		stream.setVersion(QDataStream::Qt_5_1);

		stream >> version;
		if (stream.status() != QDataStream::Ok) {
			LOG(("Update Error: cant read version from downloaded stream, status: %1").arg(stream.status()));
			return fatalFail();
		}

		quint64 betaVersion = 0;
		if (version == 0x7FFFFFFF) { // beta version
			stream >> betaVersion;
			if (stream.status() != QDataStream::Ok) {
				LOG(("Update Error: cant read beta version from downloaded stream, status: %1").arg(stream.status()));
				return fatalFail();
			}
			if (!cBetaVersion() || betaVersion <= cBetaVersion()) {
				LOG(("Update Error: downloaded beta version %1 is not greater, than mine %2").arg(betaVersion).arg(cBetaVersion()));
				return fatalFail();
			}
		} else if (int32(version) <= AppVersion) {
Ejemplo n.º 2
0
void IconSettings::cmdGetIcon_Click(){
    QString fileName, searchPath=this->prefix_path;

    if ((!txtWorkDir->text().isEmpty()) and (QDir(txtWorkDir->text()).exists())){
        searchPath = txtWorkDir->text();
    } else {
        if (QDir(this->prefix_path).exists()){
           searchPath=this->prefix_path;
        } else {
           searchPath=QDir::homePath();
        }
    }

    QFileDialog dialog(this);
      dialog.setFilter(QDir::Dirs | QDir::Files | QDir::Hidden);
      dialog.setFileMode(QFileDialog::ExistingFile);
      dialog.setWindowTitle(tr("Open image file"));

#if QT_VERSION >= 0x040500
      if (CoreLib->getSetting("advanced", "useNativeFileDialog", false, 1)==0){
          dialog.setOptions(QFileDialog::DontUseNativeDialog);
      }
#endif

      if ((!iconPath.isEmpty()) and (QFile(iconPath).exists())){
          QStringList list = iconPath.split("/");
          searchPath = iconPath.left(iconPath.length() - list.last().length());
      }
      dialog.setDirectory(searchPath);

        #ifndef WITH_ICOUTILS
        dialog.setNameFilter(tr("Image files (*.png *.jpg *.gif *.bmp *.xpm)"));
        #else
        dialog.setNameFilter(tr("Image and Win32 binary files (*.png *.jpg *.gif *.bmp *.xpm *.exe *.dll);;Image files (*.png *.jpg *.gif *.bmp *.xpm);;Win32 Executable (*.exe);;Win32 Shared libraies (*.dll);;Win32 Executable and Shared libraies (*.exe *.dll)"));
        #endif
      //dialog.setSidebarUrls(add_prefix_urls);

     if (dialog.exec())
        fileName = dialog.selectedFiles().first();

    if(!fileName.isEmpty()){
        if ((fileName.toLower().right(3)!="exe") && (fileName.toLower().right(3)!="dll")){
            cmdGetIcon->setIcon (QIcon(fileName));
        } else {

            QStringList args;
            args << "-x";
            args << "-t" << "14";

            QString tmpDir="";
            QStringList list1 = fileName.split("/");

            tmpDir.append(QDir::homePath());
            tmpDir.append("/.config/");
            tmpDir.append(APP_SHORT_NAME);
            tmpDir.append("/tmp/");
            tmpDir.append(list1.last());

            QDir tmp(tmpDir);
            tmp.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
            QFileInfoList list = tmp.entryInfoList();

            if (tmp.exists(tmpDir)){
                for (int i = 0; i < list.size(); ++i) {
                    QFileInfo fileInfo = list.at(i);
                    if (!tmp.remove(fileInfo.filePath()))
                        qDebug()<<"[EE] - Can't delete files at: "<<fileInfo.filePath();
                }
            } else {
                if (!tmp.mkdir(tmpDir)){
                    qDebug()<<"[EE] - Can't create temp directory at: "<<tmpDir;
                }
            }

            args << "-o" << tmpDir;
            args << fileName;

            Process exportProcess(args, CoreLib->getSetting("icotool", "wrestool").toString(), QDir::homePath(), tr("Exporting icon from binary file.<br>This can take a while..."), tr("Exporting icon"), FALSE);

            if (exportProcess.exec()==QDialog::Accepted){
            //icotool -x -o ./regedit.png --width=32 --height=32 ./regedit.exe_14_100_0.ico
                args.clear();
                args << "-x";

                QDir ico_dir(tmpDir);
                // Updating file index
                list = ico_dir.entryInfoList();

                //Creating file list for converting
                for (int i = 0; i < list.size(); ++i) {
                    QFileInfo fileInfo = list.at(i);
                    qDebug() << fileInfo.fileName();
                    if (fileInfo.fileName().right(3)=="ico")
                        args << fileInfo.filePath();
                }

                args << "-o" << QString("%1/").arg(tmpDir);

                //Converting ico files to png

                //Look here, this function checks is some icons found, or not. 5 -- is default number of arguments,
                //if more -- then we have some ico file to convert
                if (args.size()>=4){
                    Process exportProcess(args, CoreLib->getSetting("icotool", "icotool").toString(), QDir::homePath(), tr("Convering icon from binary file.<br>This can take a while..."), tr("Converting icon"), FALSE);
                    if (exportProcess.exec()==QDialog::Accepted){
                        IconsView iconsView(tmpDir);
                        if (iconsView.exec()==QDialog::Accepted){
                            fileName=iconsView.selectedFile;
                            cmdGetIcon->setIcon (QIcon(fileName));
                        } else {
                            fileName.clear();
                        }
                    }
                } else {
                    IconsView iconsView(tmpDir);
                    if (iconsView.exec()==QDialog::Accepted){
                        fileName=iconsView.selectedFile;
                        cmdGetIcon->setIcon (QIcon(fileName));
                    } else {
                        fileName.clear();
                    }
                }
            } else {
                qDebug()<<"wrestool testing Rejected";
                fileName.clear();
            }

            //Clearing temp files
            list = tmp.entryInfoList();

                //Creating file list for converting
            for (int i = 0; i < list.size(); ++i) {
                QFileInfo fileInfo = list.at(i);
                    if (!QFile::remove(fileInfo.filePath()))
                        qDebug()<<"[EE] - Can't delete files at: "<<fileInfo.filePath();
            }

            if (!tmp.rmdir(tmpDir))
                qDebug()<<"[EE] - Can't delete tmp dir: "<<tmpDir;
        }

        if (!fileName.isEmpty())
            iconPath=fileName;
    }

    return;
}
Ejemplo n.º 3
0
void TaskManagementMainTab::startNewTaskButtonClicked() {
    CURLcode code;
    long httpCode;
    FILE *tasknml;
    struct httpResponse header;

    auto postdata = QString("csrfmiddlewaretoken=%0&data=<currentTask>%1</currentTask>").arg(taskState::CSRFToken(), state->taskState->taskFile);

    QDir taskDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/tasks");
    taskDir.mkpath(".");

    state->taskState->taskFile = taskDir.absolutePath() + "/task.tmp.nml";

    tasknml = fopen(state->taskState->taskFile.toUtf8().constData(), "w");
    if (tasknml == nullptr) {
        statusLabel->setText("<font color='red'>Failed to get new task. No write permission in this folder.</font>");
        return;
    }

    auto url = state->taskState->host + "/knossos/newTask/";

    header.length = 0;
    header.content = (char *)calloc(1, header.length + 1);

    setCursor(Qt::WaitCursor);
    httpResponse response;
    response.length = 0;
    response.content = (char *)calloc(1, 10240);
    bool success = taskState::httpFileGET(url.toUtf8().data(), postdata.toUtf8().data(), &response, &header, &httpCode, state->taskState->cookieFile.toUtf8().data(), &code, 5);
    setCursor(Qt::ArrowCursor);
    if(success == false) {
        resetSession(QString("<font color='red'>Could not find session cookie. Please login again.</font><br />%0").arg(response.content));
        return;
    }
    if(code != CURLE_OK) {
        setResponse(QString("<font color='red'>Request failed. Please check your connection.</font><br />%0").arg(response.content));
        taskState::removeCookie();
        free(header.content);
        return;
    }

    if(httpCode == 400) {
        setResponse(QString("<font color='red'>Current task not finished or no new task available.</font><br />%0").arg(response.content));
        QFile(state->taskState->taskFile).remove();
        free(header.content);
        return;
    }
    else if(httpCode == 403) {
        setResponse(QString("<font color='red'>You are not authenticated. Permission denied.</font><br />%0").arg(response.content));
        QFile(state->taskState->taskFile).remove();
        free(header.content);
        return;
    }
    else if(httpCode != 200){
        setResponse(QString("<font color='red'>Error received from server.</font><br />%0").arg(response.content));
        QFile(state->taskState->taskFile).remove();
        free(header.content);
        return;
    }
    fwrite(response.content, 1, response.length, tasknml);
    fclose(tasknml);
    // 200 - success. Retrieve the filename from response header and rename the previously created tmp.nml
    char filename[1024] = {};
    if (taskState::copyInfoFromHeader(filename, &header, "filename")) {
        QFile tmpFile(state->taskState->taskFile);
        tmpFile.rename(filename);
        state->taskState->taskFile = tmpFile.fileName();
    }
    // get task name
    char taskname[1024] = {};
    taskState::copyInfoFromHeader(taskname, &header, "taskname");
    state->taskState->taskName = taskname;
    setTask(state->taskState->taskName);

    // get task category description and task comment
    QByteArray descriptionBuffer(8192, '\0');
    QByteArray commentBuffer(8192, '\0');
    taskState::copyInfoFromHeader(descriptionBuffer.data(), &header, "description");
    taskState::copyInfoFromHeader(commentBuffer.data(), &header, "comment");
    QString description = QByteArray::fromBase64(descriptionBuffer);
    QString comment = QByteArray::fromBase64(commentBuffer);

    QMessageBox prompt;
    prompt.setWindowFlags(Qt::WindowStaysOnTopHint);
    prompt.setIcon(QMessageBox::Information);
    prompt.setWindowTitle(state->taskState->taskName);
    prompt.setText(QString("<p style='width:200px;'><b>Category %1:</b> %2<br><br><b>Task %3:</b> %4</p>")
                   .arg(taskState::getCategory())
                   .arg(description)
                   .arg(taskState::getTask())
                   .arg(comment));
    prompt.addButton("Ok", QMessageBox::ActionRole); // closes prompt by default
    prompt.resize(400, 300);
    prompt.exec();
    emit setDescriptionSignal(description);
    emit setCommentSignal(comment);
    emit loadSkeletonSignal(state->taskState->taskFile);
    setResponse("<font color='green'>Loaded task successfully.</font>");
    free(header.content);
}
Ejemplo n.º 4
0
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    qsrand(time(NULL));
    QStringList args = QCoreApplication::arguments();
    int subcmd = subCommands()->value(args.value(1), Invalid);

    switch (subcmd) {
    case Invalid:
        qCritical("invalid argument");
        return 1;
        break;

    case Help:
        usage();
        break;

    case New:
        // Creates new project
        if (!createNewApplication(args.value(2))) {
            return 1;
        }
        break;

    case ShowDrivers:
        printf("Available database drivers for Qt:\n");
        for (QStringListIterator i(TableSchema::databaseDrivers()); i.hasNext(); ) {
            printf("  %s\n", qPrintable(i.next()));
        }
        break;

    case ShowDriverPath: {
        QString path = QLibraryInfo::location(QLibraryInfo::PluginsPath) + QDir::separator() + "sqldrivers";
        QFileInfo fi(path);
        if (!fi.exists() || !fi.isDir()) {
            qCritical("Error: database driver's directory not found");
            return 1;
        }
        printf("%s\n", qPrintable(fi.canonicalFilePath()));
        break; }

    case ShowTables:
        if (checkIniFile()) {
            QStringList tables = TableSchema::tables();
            if (!tables.isEmpty()) {
                printf("-----------------\nAvailable tables:\n");
                for (QStringListIterator i(tables); i.hasNext(); ) {
                    printf("  %s\n", qPrintable(i.next()));
                }
                putchar('\n');
            }
        } else {
            return 2;
        }
        break;

    case ShowCollections:
        if (checkIniFile()) {
            // MongoDB settings
            QString mongoini = appSettings.value("MongoDbSettingsFile").toString().trimmed();
            QString mnginipath = QLatin1String("config") + QDir::separator() + mongoini;

            if (mongoini.isEmpty() || !QFile(mnginipath).exists()) {
                qCritical("MongoDB settings file not found");
                return 2;
            }

            MongoCommand mongo(mnginipath);
            if (!mongo.open("dev")) {
                return 2;
            }

            QStringList colls = mongo.getCollectionNames();
            printf("-----------------\nExisting collections:\n");
            for (QStringListIterator i(colls); i.hasNext(); ) {
                printf("  %s\n", qPrintable(i.next()));
            }
            putchar('\n');
        }
        break;

    default: {
        if (argc < 3) {
            qCritical("invalid argument");
            return 1;
        }

        if (!checkIniFile()) {
            return 2;
        }

        // Sets codec
        QTextCodec *codec = QTextCodec::codecForName(appSettings.value("InternalEncoding").toByteArray().trimmed());
        codec = (codec) ? codec : QTextCodec::codecForLocale();
        QTextCodec::setCodecForLocale(codec);
#if QT_VERSION < 0x050000
        QTextCodec::setCodecForTr(codec);
        QTextCodec::setCodecForCStrings(codec);
#endif

        // ERB or Otama
        templateSystem = devSettings.value("TemplateSystem").toString().toLower();
        if (templateSystem.isEmpty()) {
            templateSystem = appSettings.value("TemplateSystem", "Erb").toString().toLower();
        }

        switch (subcmd) {
        case Controller: {
            QString ctrl = args.value(2);
            ControllerGenerator crtlgen(ctrl, args.mid(3));
            crtlgen.generate(D_CTRLS);

            // Create view directory
            QDir dir(D_VIEWS + ((ctrl.contains('_')) ? ctrl.toLower() : fieldNameToVariableName(ctrl).toLower()));
            mkpath(dir, ".");
            break; }

        case Model: {
            ModelGenerator modelgen(ModelGenerator::Sql, args.value(3), args.value(2));
            modelgen.generate(D_MODELS);
            break; }

        case UserModel: {
            ModelGenerator modelgen(ModelGenerator::Sql, args.value(5), args.value(2), args.mid(3, 2));
            modelgen.generate(D_MODELS, true);
            break; }

        case SqlObject: {
            SqlObjGenerator sqlgen(args.value(3), args.value(2));
            QString path = sqlgen.generate(D_MODELS);

            // Generates a project file
            ProjectFileGenerator progen(D_MODELS + "models.pro");
            progen.add(QStringList(path));
            break; }

        case MongoScaffold: {
            ModelGenerator modelgen(ModelGenerator::Mongo, args.value(2));
            bool success = modelgen.generate(D_MODELS);

            ControllerGenerator crtlgen(modelgen.model(), modelgen.fieldList(), modelgen.primaryKeyIndex(), modelgen.lockRevisionIndex());
            success &= crtlgen.generate(D_CTRLS);

            // Generates view files of the specified template system
            if (templateSystem == "otama") {
                OtamaGenerator viewgen(modelgen.model(), modelgen.fieldList(), modelgen.primaryKeyIndex(), modelgen.autoValueIndex());
                viewgen.generate(D_VIEWS);
            } else if (templateSystem == "erb") {
                ErbGenerator viewgen(modelgen.model(), modelgen.fieldList(), modelgen.primaryKeyIndex(), modelgen.autoValueIndex());
                viewgen.generate(D_VIEWS);
            } else {
                qCritical("Invalid template system specified: %s", qPrintable(templateSystem));
                return 2;
            }

            if (success) {
                printSuccessMessage(modelgen.model());
            }
            break; }

        case MongoModel: {
            ModelGenerator modelgen(ModelGenerator::Mongo, args.value(2));
            modelgen.generate(D_MODELS);
            break; }

        case Validator: {
            ValidatorGenerator validgen(args.value(2), D_HELPERS);
            validgen.generate();
            break; }

        case Mailer: {
            MailerGenerator mailgen(args.value(2), args.mid(3), D_CTRLS);
            mailgen.generate();
            copy(dataDirPath + "mail.erb", D_VIEWS + "mailer" + SEP +"mail.erb");
            break; }

        case Scaffold: {
            ModelGenerator modelgen(ModelGenerator::Sql, args.value(3), args.value(2));
            bool success = modelgen.generate(D_MODELS);

            if (!success)
                return 2;

            int pkidx = modelgen.primaryKeyIndex();
            if (pkidx < 0) {
                qWarning("Primary key not found. [table name: %s]", qPrintable(args.value(2)));
                return 2;
            }

            ControllerGenerator crtlgen(modelgen.model(), modelgen.fieldList(), pkidx, modelgen.lockRevisionIndex());
            success &= crtlgen.generate(D_CTRLS);

            // Generates view files of the specified template system
            if (templateSystem == "otama") {
                OtamaGenerator viewgen(modelgen.model(), modelgen.fieldList(), pkidx, modelgen.autoValueIndex());
                viewgen.generate(D_VIEWS);
            } else if (templateSystem == "erb") {
                ErbGenerator viewgen(modelgen.model(), modelgen.fieldList(), pkidx, modelgen.autoValueIndex());
                viewgen.generate(D_VIEWS);
            } else {
                qCritical("Invalid template system specified: %s", qPrintable(templateSystem));
                return 2;
            }

            if (success) {
                printSuccessMessage(modelgen.model());
            }
            break; }

        case Delete: {
            // Removes files
            int ret = deleteScaffold(args.value(2));
            if (ret)
                return ret;
            break; }

        default:
            qCritical("internal error");
            return 1;
        }
        break; }
    }
    return 0;
}
Ejemplo n.º 5
0
void QgsGeometryCheckerSetupTab::runChecks()
{
  // Get selected layer
  QList<QgsVectorLayer *> layers = getSelectedLayers();
  if ( layers.isEmpty() )
    return;

  if ( ui.radioButtonOutputNew->isChecked() )
  {
    for ( QgsVectorLayer *layer : layers )
    {
      if ( layer->dataProvider()->dataSourceUri().startsWith( ui.lineEditOutputDirectory->text() ) )
      {
        QMessageBox::critical( this, tr( "Invalid Output Directory" ), tr( "The chosen output directory contains one or more input layers." ) );
        return;
      }
    }
  }
  QgsVectorLayer *lineLayerCheckLayer = ui.comboLineLayerIntersection->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) ) : nullptr;
  QgsVectorLayer *followBoundaryCheckLayer = ui.comboBoxFollowBoundaries->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboBoxFollowBoundaries->currentData().toString() ) ) : nullptr;
  if ( layers.contains( lineLayerCheckLayer ) || layers.contains( followBoundaryCheckLayer ) )
  {
    QMessageBox::critical( this, tr( "Error" ), tr( "The test layer set contains a layer selected for a topology check." ) );
    return;
  }

  for ( QgsVectorLayer *layer : layers )
  {
    if ( layer->isEditable() )
    {
      QMessageBox::critical( this, tr( "Editable Input Layer" ), tr( "Input layer are not allowed to be in editing mode." ) );
      return;
    }
  }
  bool selectedOnly = ui.checkBoxInputSelectedOnly->isChecked();

  // Set window busy
  setCursor( Qt::WaitCursor );
  mRunButton->setEnabled( false );
  ui.labelStatus->setText( tr( "<b>Preparing output...</b>" ) );
  ui.labelStatus->show();
  QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );

  QList<QgsVectorLayer *> processLayers;
  if ( ui.radioButtonOutputNew->isChecked() )
  {
    // Get output directory and file extension
    QDir outputDir = QDir( ui.lineEditOutputDirectory->text() );
    QString outputDriverName = ui.comboBoxOutputFormat->currentText();
    QgsVectorFileWriter::MetaData metadata;
    if ( !QgsVectorFileWriter::driverMetadata( outputDriverName, metadata ) )
    {
      QMessageBox::critical( this, tr( "Unknown Output Format" ), tr( "The specified output format cannot be recognized." ) );
      mRunButton->setEnabled( true );
      ui.labelStatus->hide();
      unsetCursor();
      return;
    }
    QString outputExtension = metadata.ext;

    // List over input layers, check which existing project layers need to be removed and create output layers
    QString filenamePrefix = ui.lineEditFilenamePrefix->text();
    QSettings().setValue( "/geometry_checker/previous_values/filename_prefix", filenamePrefix );
    QStringList toRemove;
    QStringList createErrors;
    for ( QgsVectorLayer *layer : layers )
    {
      QString outputPath = outputDir.absoluteFilePath( filenamePrefix + layer->name() + "." + outputExtension );

      // Remove existing layer with same uri from project
      for ( QgsVectorLayer *projectLayer : QgsProject::instance()->layers<QgsVectorLayer *>() )
      {
        if ( projectLayer->dataProvider()->dataSourceUri().startsWith( outputPath ) )
        {
          toRemove.append( projectLayer->id() );
        }
      }

      // Create output layer
      QString errMsg;
      QgsVectorFileWriter::WriterError err =  QgsVectorFileWriter::writeAsVectorFormat( layer, outputPath, layer->dataProvider()->encoding(), layer->crs(), outputDriverName, selectedOnly, &errMsg );
      if ( err != QgsVectorFileWriter::NoError )
      {
        createErrors.append( errMsg );
        continue;
      }

      QgsVectorLayer *newlayer = new QgsVectorLayer( outputPath, QFileInfo( outputPath ).completeBaseName(), QStringLiteral( "ogr" ) );
      if ( selectedOnly )
      {
        QgsFeature feature;

        // Get features to select (only selected features were written up to this point)
        QgsFeatureIds selectedFeatures = newlayer->allFeatureIds();

        // Write non-selected feature ids
        QgsFeatureList features;
        QgsFeatureIterator it = layer->getFeatures();
        while ( it.nextFeature( feature ) )
        {
          if ( !layer->selectedFeatureIds().contains( feature.id() ) )
          {
            features.append( feature );
          }
        }
        newlayer->dataProvider()->addFeatures( features );

        // Set selected features
        newlayer->selectByIds( selectedFeatures );
      }
      processLayers.append( newlayer );
    }

    //  Remove layers from project
    if ( !toRemove.isEmpty() )
    {
      QgsProject::instance()->removeMapLayers( toRemove );
    }

    // Error if an output layer could not be created
    if ( !createErrors.isEmpty() )
    {
      QMessageBox::critical( this, tr( "Layer Creation Failed" ), tr( "Failed to create one or moure output layers:\n%1" ).arg( createErrors.join( "\n" ) ) );
      mRunButton->setEnabled( true );
      ui.labelStatus->hide();
      unsetCursor();
      return;
    }
  }
  else
  {
    processLayers = layers;
  }

  // Check if output layers are editable
  QList<QgsVectorLayer *> nonEditableLayers;
  for ( QgsVectorLayer *layer : processLayers )
  {
    if ( ( layer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeGeometries ) == 0 )
    {
      nonEditableLayers.append( layer );
    }
  }
  if ( !nonEditableLayers.isEmpty() )
  {
    QStringList nonEditableLayerNames;
    for ( QgsVectorLayer *layer : nonEditableLayers )
    {
      nonEditableLayerNames.append( layer->name() );
    }
    if ( QMessageBox::Yes != QMessageBox::question( this, tr( "Non-editable Output Layers" ), tr( "The following output layers are ina format that does not support editing features:\n%1\n\nThe geometry check can be performed, but it will not be possible to fix any errors. Do you want to continue?" ).arg( nonEditableLayerNames.join( "\n" ) ), QMessageBox::Yes, QMessageBox::No ) )
    {
      if ( ui.radioButtonOutputNew->isChecked() )
      {
        for ( QgsVectorLayer *layer : processLayers )
        {
          QString layerPath = layer->dataProvider()->dataSourceUri();
          delete layer;
          if ( ui.comboBoxOutputFormat->currentText() == QLatin1String( "ESRI Shapefile" ) )
          {
            QgsVectorFileWriter::deleteShapeFile( layerPath );
          }
          else
          {
            QFile( layerPath ).remove();
          }
        }
        mRunButton->setEnabled( true );
        ui.labelStatus->hide();
        unsetCursor();
      }
      return;
    }
  }

  // Setup checker
  ui.labelStatus->setText( tr( "<b>Building spatial index...</b>" ) );
  QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );
  QMap<QString, QgsFeaturePool *> featurePools;
  for ( QgsVectorLayer *layer : processLayers )
  {
    double layerToMapUntis = mIface->mapCanvas()->mapSettings().layerToMapUnits( layer );
    QgsCoordinateTransform layerToMapTransform = QgsCoordinateTransformCache::instance()->transform( layer->crs().authid(), mIface->mapCanvas()->mapSettings().destinationCrs().authid() );
    featurePools.insert( layer->id(), new QgsFeaturePool( layer, layerToMapUntis, layerToMapTransform, selectedOnly ) );
  }
  // LineLayerIntersection check is enabled, make sure there is also a feature pool for that layer
  if ( ui.checkLineLayerIntersection->isChecked() && !featurePools.keys().contains( ui.comboLineLayerIntersection->currentData().toString() ) )
  {
    QgsVectorLayer *layer = dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) );
    Q_ASSERT( layer );
    double layerToMapUntis = mIface->mapCanvas()->mapSettings().layerToMapUnits( layer );
    QgsCoordinateTransform layerToMapTransform = QgsCoordinateTransformCache::instance()->transform( layer->crs().authid(), mIface->mapCanvas()->mapSettings().destinationCrs().authid() );
    featurePools.insert( layer->id(), new QgsFeaturePool( layer, layerToMapUntis, layerToMapTransform, selectedOnly ) );
  }

  QgsGeometryCheckerContext *context = new QgsGeometryCheckerContext( ui.spinBoxTolerance->value(), mIface->mapCanvas()->mapSettings().destinationCrs().authid(), featurePools );

  QList<QgsGeometryCheck *> checks;
  for ( const QgsGeometryCheckFactory *factory : QgsGeometryCheckFactoryRegistry::getCheckFactories() )
  {
    QgsGeometryCheck *check = factory->createInstance( context, ui );
    if ( check )
    {
      checks.append( check );
    }
  }
  QgsGeometryChecker *checker = new QgsGeometryChecker( checks, context );

  emit checkerStarted( checker );

  if ( ui.radioButtonOutputNew->isChecked() )
  {
    QList<QgsMapLayer *> addLayers;
    for ( QgsVectorLayer *layer : processLayers )
    {
      addLayers.append( layer );
    }
    QgsProject::instance()->addMapLayers( addLayers );
  }

  // Run
  ui.buttonBox->addButton( mAbortButton, QDialogButtonBox::ActionRole );
  mRunButton->hide();
  ui.progressBar->setRange( 0, 0 );
  ui.labelStatus->hide();
  ui.progressBar->show();
  ui.widgetInputs->setEnabled( false );
  QEventLoop evLoop;
  QFutureWatcher<void> futureWatcher;
  connect( checker, &QgsGeometryChecker::progressValue, ui.progressBar, &QProgressBar::setValue );
  connect( &futureWatcher, &QFutureWatcherBase::finished, &evLoop, &QEventLoop::quit );
  connect( mAbortButton, &QAbstractButton::clicked, &futureWatcher, &QFutureWatcherBase::cancel );
  connect( mAbortButton, &QAbstractButton::clicked, this, &QgsGeometryCheckerSetupTab::showCancelFeedback );

  int maxSteps = 0;
  futureWatcher.setFuture( checker->execute( &maxSteps ) );
  ui.progressBar->setRange( 0, maxSteps );
  evLoop.exec();

  // Restore window
  unsetCursor();
  mAbortButton->setEnabled( true );
  ui.buttonBox->removeButton( mAbortButton );
  mRunButton->setEnabled( true );
  mRunButton->show();
  ui.progressBar->hide();
  ui.labelStatus->hide();
  ui.widgetInputs->setEnabled( true );

  // Show result
  emit checkerFinished( !futureWatcher.isCanceled() );
}
Ejemplo n.º 6
0
// Refresh not up to date metrics and metrics after date
void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate)
{
    // only if we have established a connection to the database
    if (dbaccess == NULL || main->isclean==true) return;

    // first check db structure is still up to date
    // this is because metadata.xml may add new fields
    dbaccess->checkDBVersion();

    // Get a list of the ride files
    QRegExp rx = RideFileFactory::instance().rideFileRegExp();
    QStringList filenames = RideFileFactory::instance().listRideFiles(home);
    QStringListIterator i(filenames);

    // get a Hash map of statistic records and timestamps
    QSqlQuery query(dbaccess->connection());
    QHash <QString, status> dbStatus;
    bool rc = query.exec("SELECT filename, timestamp, fingerprint FROM metrics ORDER BY ride_date;");
    while (rc && query.next()) {
        status add;
        QString filename = query.value(0).toString();
        add.timestamp = query.value(1).toInt();
        add.fingerprint = query.value(2).toInt();
        dbStatus.insert(filename, add);
    }

    // begin LUW -- byproduct of turning off sync (nosync)
    dbaccess->connection().transaction();

    // Delete statistics for non-existant ride files
    QHash<QString, status>::iterator d;
    for (d = dbStatus.begin(); d != dbStatus.end(); ++d) {
        if (QFile(home.absolutePath() + "/" + d.key()).exists() == false) {
            dbaccess->deleteRide(d.key());
#ifdef GC_HAVE_LUCENE
            main->lucene->deleteRide(d.key());
#endif
        }
    }

    unsigned long zoneFingerPrint = zones->getFingerprint() + hrzones->getFingerprint(); // crc of *all* zone data (HR and Power)

    // update statistics for ride files which are out of date
    // showing a progress bar as we go
    QTime elapsed;
    elapsed.start();
    QString title = tr("Refreshing Ride Statistics...\nStarted");
    QProgressDialog bar(title, tr("Abort"), 0, filenames.count(), main);
    bar.setWindowModality(Qt::WindowModal);
    bar.setMinimumDuration(0);
    bar.show();

    int processed=0;
    QApplication::processEvents(); // get that dialog up!

    // log of progress
    QFile log(home.absolutePath() + "/" + "metric.log");
    log.open(QIODevice::WriteOnly);
    log.resize(0);
    QTextStream out(&log);
    out << "METRIC REFRESH STARTS: " << QDateTime::currentDateTime().toString() + "\r\n";

    while (i.hasNext()) {
        QString name = i.next();
        QFile file(home.absolutePath() + "/" + name);

        // if it s missing or out of date then update it!
        status current = dbStatus.value(name);
        unsigned long dbTimeStamp = current.timestamp;
        unsigned long fingerprint = current.fingerprint;

        RideFile *ride = NULL;

        // update progress bar
        long elapsedtime = elapsed.elapsed();
        QString elapsedString = QString("%1:%2:%3").arg(elapsedtime/3600000,2)
                                                .arg((elapsedtime%3600000)/60000,2,10,QLatin1Char('0'))
                                                .arg((elapsedtime%60000)/1000,2,10,QLatin1Char('0'));
        QString title = tr("Refreshing Ride Statistics...\nElapsed: %1\n%2").arg(elapsedString).arg(name);
        bar.setLabelText(title);
        bar.setValue(++processed);
        QApplication::processEvents();

        if (dbTimeStamp < QFileInfo(file).lastModified().toTime_t() ||
            zoneFingerPrint != fingerprint ||
            (!forceAfterThisDate.isNull() && name >= forceAfterThisDate.toString("yyyy_MM_dd_hh_mm_ss"))) {
            QStringList errors;

            // log
            out << "Opening ride: " << name << "\r\n";

            // read file and process it if we didn't already...
            if (ride == NULL) ride = RideFileFactory::instance().openRideFile(main, file, errors);

            out << "File open completed: " << name << "\r\n";

            if (ride != NULL) {

                out << "Updating statistics: " << name << "\r\n";
                importRide(home, ride, name, zoneFingerPrint, (dbTimeStamp > 0));

            }
        }

        // update cache (will check timestamps itself)
        // if ride wasn't opened it will do it itself
        // we only want to check so passing check=true
        // because we don't actually want the results now
        RideFileCache updater(main, home.absolutePath() + "/" + name, ride, true);

        // free memory - if needed
        if (ride) delete ride;

        if (bar.wasCanceled()) {
            out << "METRIC REFRESH CANCELLED\r\n";
            break;
        }
    }

    // stop logging
    out << "METRIC REFRESH ENDS: " << QDateTime::currentDateTime().toString() + "\r\n";
    log.close();

    // end LUW -- now syncs DB
    dbaccess->connection().commit();
#ifdef GC_HAVE_LUCENE
    main->lucene->optimise();
#endif
    main->isclean = true;

    dataChanged(); // notify models/views
}
IDEGreetingWindow::IDEGreetingWindow(QWidget *parent, IDEProject *project) :
    QDialog(parent)
{
    this->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    this->setWindowTitle("Welcome");
    this->project = project;

    welcomeframe = new QFrame(this, 0);
    welcomeframe->show();
    welcomeframe->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);

    radiobuttonlist = new QBoxLayout(QBoxLayout::TopToBottom, welcomeframe);
    radiobuttonlist->setSizeConstraint(QLayout::SetMinimumSize);

    greetingtext = new QLabel("Welcome to the blitwizard development environment!\n"
                              "Please specify what you want to do:");
    radiobuttonlist->addWidget((QWidget*)greetingtext);
    greetingtext->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);

    choicenewproject = new QRadioButton("Start new project", 0);
    radiobuttonlist->addWidget((QWidget*)choicenewproject);
    choicenewproject->setChecked(true);

    choiceopenproject = new QRadioButton("Open project from file", 0);
    radiobuttonlist->addWidget((QWidget*)choiceopenproject);

    choicerecentproject = new QRadioButton("Choose from recently opened projects:", 0);
    radiobuttonlist->addWidget((QWidget*)choicerecentproject);

    recentprojectlist = new QListWidget();
    radiobuttonlist->addWidget((QWidget*)recentprojectlist);

    // add recent projects to list:
    std::vector<QString> recentlyOpened = GetApplicationInstance()->settings->getRecentlyOpenedProjects();
    int i = recentlyOpened.size() - 1;
    while (i >= 0) {
        QString f = recentlyOpened[i];
        recentprojectlist->addItem(
                    QString(QFileInfo(QFile(f)).fileName()) + QString(" (") + QString(f) + QString(")"));
        i--;
    }
    if (recentlyOpened.size() == 0) {
        // disable recent project option if no recent projects:
        choicerecentproject->setDisabled(true);
    } else {
        // make recent project the default choice:
        choicerecentproject->setChecked(true);
        choicenewproject->setChecked(false);
        recentprojectlist->setCurrentRow(0);
        QObject::connect(recentprojectlist, SIGNAL(currentRowChanged(int)), this, SLOT(recentProjectChoiceClicked()));
        QObject::connect(recentprojectlist, SIGNAL(clicked(QModelIndex)), this, SLOT(recentProjectChoiceClicked()));
    }

    buttonrowwidget = new QWidget(0, 0);
    radiobuttonlist->addWidget((QWidget*)buttonrowwidget);
    buttonrowwidget->show();
    buttonrowwidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    buttonrowlayout = new QBoxLayout(QBoxLayout::RightToLeft, buttonrowwidget);

    continuebutton = new QPushButton("Continue", 0);
    buttonrowlayout->addWidget((QWidget*)continuebutton);
    continuebutton->show();
    QObject::connect(continuebutton, SIGNAL(clicked()), this, SLOT(clickedContinue()));

    cancelbutton = new QPushButton("Cancel", 0);
    buttonrowlayout->addWidget((QWidget*)cancelbutton);
    cancelbutton->show();
    QObject::connect(cancelbutton, SIGNAL(clicked()), this, SLOT(clickedCancel()));

    // set proper minimum size:
    this->setMinimumSize(welcomeframe->sizeHint());
}
Ejemplo n.º 8
0
void KIOExec::slotRunApp()
{
    if ( fileList.isEmpty() ) {
        qDebug() << "No files downloaded -> exiting";
        mExited = true;
        QApplication::exit(1);
        return;
    }

    KService service(QStringLiteral("dummy"), command, QString());

    QList<QUrl> list;
    // Store modification times
    QList<FileInfo>::Iterator it = fileList.begin();
    for ( ; it != fileList.end() ; ++it )
    {
        QFileInfo info(QFile::encodeName(it->path));
        it->time = info.lastModified();
        QUrl url = QUrl::fromLocalFile(it->path);
        list << url;
    }

    KIO::DesktopExecParser execParser(service, list);
    QStringList params = execParser.resultingArguments();

    qDebug() << "EXEC " << params.join(QStringLiteral(" "));

#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
    // propagate the startup identification to the started process
    KStartupInfoId id;
    QByteArray startupId;
#if HAVE_X11
    if (QX11Info::isPlatformX11()) {
        startupId = QX11Info::nextStartupId();
    }
#endif
    id.initId(startupId);
    id.setupStartupEnv();
#endif

    QString exe( params.takeFirst() );
    const int exit_code = QProcess::execute( exe, params );

#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
    KStartupInfo::resetStartupEnv();
#endif

    qDebug() << "EXEC done";

    // Test whether one of the files changed
    for(it = fileList.begin(); it != fileList.end(); ++it )
    {
        QString src = it->path;
        const QUrl dest = it->url;
        QFileInfo info(src);
        if ( info.exists() && (it->time != info.lastModified()) )
        {
            if ( mTempFiles )
            {
                if ( KMessageBox::questionYesNo( 0L,
                                                 i18n( "The supposedly temporary file\n%1\nhas been modified.\nDo you still want to delete it?", dest.toDisplayString(QUrl::PreferLocalFile)),
                                                 i18n( "File Changed" ), KStandardGuiItem::del(), KGuiItem(i18n("Do Not Delete")) ) != KMessageBox::Yes )
                    continue; // don't delete the temp file
            }
            else if ( ! dest.isLocalFile() )  // no upload when it's already a local file
            {
                if ( KMessageBox::questionYesNo( 0L,
                                                 i18n( "The file\n%1\nhas been modified.\nDo you want to upload the changes?" , dest.toDisplayString()),
                                                 i18n( "File Changed" ), KGuiItem(i18n("Upload")), KGuiItem(i18n("Do Not Upload")) ) == KMessageBox::Yes )
                {
                    qDebug() << "src='" << src << "'  dest='" << dest << "'";
                    // Do it the synchronous way.
                    KIO::CopyJob* job = KIO::copy(QUrl::fromLocalFile(src), dest);
                    if ( !job->exec() )
                    {
                        KMessageBox::error( 0L, job->errorText() );
                        continue; // don't delete the temp file
                    }
                }
            }
        }

        if ((!dest.isLocalFile() || mTempFiles) && exit_code == 0) {
            // Wait for a reasonable time so that even if the application forks on startup (like OOo or amarok)
            // it will have time to start up and read the file before it gets deleted. #130709.
            qDebug() << "sleeping...";
            QThread::currentThread()->sleep(180); // 3 mn
            qDebug() << "about to delete " << src;
            QFile( QFile::encodeName(src) ).remove();
        }
    }

    mExited = true;
    QApplication::exit(exit_code);
}
bool PathHelper::isFileExistsAndItsReallyAFile(QString filePath)
{
    return (!filePath.isEmpty() && QFile(filePath).exists() && !QDir(filePath).exists());
}
Ejemplo n.º 10
0
void Settings::loadPersonal(Profile* profile)
{
    QMutexLocker locker{&bigLock};

    QDir dir(getSettingsDirPath());
    QString filePath = dir.filePath(globalSettingsFile);

    // load from a profile specific friend data list if possible
    QString tmp = dir.filePath(profile->getName() + ".ini");
    if (QFile(tmp).exists()) // otherwise, filePath remains the global file
        filePath = tmp;

    qDebug()<<"Loading personal settings from"<<filePath;

    SettingsSerializer ps(filePath, profile->getPassword());
    ps.load();
    friendLst.clear();

    ps.beginGroup("Privacy");
        typingNotification = ps.value("typingNotification", true).toBool();
        enableLogging = ps.value("enableLogging", true).toBool();
    ps.endGroup();

    ps.beginGroup("Friends");
        int size = ps.beginReadArray("Friend");
        friendLst.reserve(size);
        for (int i = 0; i < size; i ++)
        {
            ps.setArrayIndex(i);
            friendProp fp;
            fp.addr = ps.value("addr").toString();
            fp.alias = ps.value("alias").toString();
            fp.note = ps.value("note").toString();
            fp.autoAcceptDir = ps.value("autoAcceptDir").toString();
            fp.circleID = ps.value("circle", -1).toInt();

            if (getEnableLogging())
                fp.activity = ps.value("activity", QDate()).toDate();

            friendLst[ToxId(fp.addr).publicKey] = fp;
        }
        ps.endArray();
    ps.endGroup();

    ps.beginGroup("General");
        compactLayout = ps.value("compactLayout", true).toBool();
    ps.endGroup();

    ps.beginGroup("Circles");
        size = ps.beginReadArray("Circle");
        circleLst.clear();
        circleLst.reserve(size);
        for (int i = 0; i < size; i ++)
        {
            ps.setArrayIndex(i);
            circleProp cp;
            cp.name = ps.value("name").toString();
            cp.expanded = ps.value("expanded", true).toBool();
            circleLst.push_back(cp);
        }
        ps.endArray();
    ps.endGroup();
}
Ejemplo n.º 11
0
void Settings::loadGlobal()
{
    QMutexLocker locker{&bigLock};

    if (loaded)
        return;

    createSettingsDir();

    if (QFile(globalSettingsFile).exists())
    {
        QSettings ps(globalSettingsFile, QSettings::IniFormat);
        ps.setIniCodec("UTF-8");
        ps.beginGroup("General");
            makeToxPortable = ps.value("makeToxPortable", false).toBool();
        ps.endGroup();
    }
    else
    {
        makeToxPortable = false;
    }

    QDir dir(getSettingsDirPath());
    QString filePath = dir.filePath(globalSettingsFile);

    // If no settings file exist -- use the default one
    if (!QFile(filePath).exists())
    {
        qDebug() << "No settings file found, using defaults";
        filePath = ":/conf/" + globalSettingsFile;
    }

    qDebug() << "Loading settings from " + filePath;

    QSettings s(filePath, QSettings::IniFormat);
    s.setIniCodec("UTF-8");
    s.beginGroup("Login");
        autoLogin = s.value("autoLogin", false).toBool();
    s.endGroup();

    s.beginGroup("DHT Server");
        if (s.value("useCustomList").toBool())
        {
            useCustomDhtList = true;
            qDebug() << "Using custom bootstrap nodes list";
            int serverListSize = s.beginReadArray("dhtServerList");
            for (int i = 0; i < serverListSize; i ++)
            {
                s.setArrayIndex(i);
                DhtServer server;
                server.name = s.value("name").toString();
                server.userId = s.value("userId").toString();
                server.address = s.value("address").toString();
                server.port = s.value("port").toInt();
                dhtServerList << server;
            }
            s.endArray();
        }
        else
        {
            useCustomDhtList=false;
        }
    s.endGroup();

    s.beginGroup("General");
        enableIPv6 = s.value("enableIPv6", true).toBool();
        translation = s.value("translation", "en").toString();
        showSystemTray = s.value("showSystemTray", SHOW_SYSTEM_TRAY_DEFAULT).toBool();
        makeToxPortable = s.value("makeToxPortable", false).toBool();
        autostartInTray = s.value("autostartInTray", false).toBool();
        closeToTray = s.value("closeToTray", false).toBool();
        forceTCP = s.value("forceTCP", false).toBool();
        setProxyType(s.value("proxyType", static_cast<int>(ProxyType::ptNone)).toInt());
        proxyAddr = s.value("proxyAddr", "").toString();
        proxyPort = s.value("proxyPort", 0).toInt();
        if (currentProfile.isEmpty())
        {
            currentProfile = s.value("currentProfile", "").toString();
            currentProfileId = makeProfileId(currentProfile);
        }
        autoAwayTime = s.value("autoAwayTime", 10).toInt();
        checkUpdates = s.value("checkUpdates", true).toBool();
        showWindow = s.value("showWindow", true).toBool();
        showInFront = s.value("showInFront", false).toBool();
        notifySound = s.value("notifySound", true).toBool();
        groupAlwaysNotify = s.value("groupAlwaysNotify", false).toBool();
        fauxOfflineMessaging = s.value("fauxOfflineMessaging", true).toBool();
        autoSaveEnabled = s.value("autoSaveEnabled", false).toBool();
        globalAutoAcceptDir = s.value("globalAutoAcceptDir",
                                      QStandardPaths::locate(QStandardPaths::HomeLocation, QString(), QStandardPaths::LocateDirectory)
                                      ).toString();
        separateWindow = s.value("separateWindow", false).toBool();
        dontGroupWindows = s.value("dontGroupWindows", true).toBool();
        groupchatPosition = s.value("groupchatPosition", true).toBool();
        markdownPreference = static_cast<MarkdownType>(s.value("markdownPreference", 1).toInt());
    s.endGroup();

    s.beginGroup("Advanced");
        int sType = s.value("dbSyncType", static_cast<int>(Db::syncType::stFull)).toInt();
        setDbSyncType(sType);
    s.endGroup();

    s.beginGroup("Widgets");
        QList<QString> objectNames = s.childKeys();
        for (const QString& name : objectNames)
            widgetSettings[name] = s.value(name).toByteArray();

    s.endGroup();

    s.beginGroup("GUI");
        const QString DEFAULT_SMILEYS = ":/smileys/Universe/emoticons.xml";
        smileyPack = s.value("smileyPack", DEFAULT_SMILEYS).toString();
        if (!SmileyPack::isValid(smileyPack))
        {
            smileyPack = DEFAULT_SMILEYS;
        }
        emojiFontPointSize = s.value("emojiFontPointSize", 16).toInt();
        firstColumnHandlePos = s.value("firstColumnHandlePos", 50).toInt();
        secondColumnHandlePosFromRight = s.value("secondColumnHandlePosFromRight", 50).toInt();
        timestampFormat = s.value("timestampFormat", "hh:mm:ss").toString();
        dateFormat = s.value("dateFormat", "dddd, MMMM d, yyyy").toString();
        minimizeOnClose = s.value("minimizeOnClose", false).toBool();
        minimizeToTray = s.value("minimizeToTray", false).toBool();
        lightTrayIcon = s.value("lightTrayIcon", false).toBool();
        useEmoticons = s.value("useEmoticons", true).toBool();
        statusChangeNotificationEnabled = s.value("statusChangeNotificationEnabled", false).toBool();
        themeColor = s.value("themeColor", 0).toInt();
        style = s.value("style", "").toString();
        if (style == "") // Default to Fusion if available, otherwise no style
        {
            if (QStyleFactory::keys().contains("Fusion"))
                style = "Fusion";
            else
                style = "None";
        }
    s.endGroup();

    s.beginGroup("State");
        windowGeometry = s.value("windowGeometry", QByteArray()).toByteArray();
        windowState = s.value("windowState", QByteArray()).toByteArray();
        splitterState = s.value("splitterState", QByteArray()).toByteArray();
        dialogGeometry = s.value("dialogGeometry", QByteArray()).toByteArray();
        dialogSplitterState = s.value("dialogSplitterState", QByteArray()).toByteArray();
        dialogSettingsGeometry = s.value("dialogSettingsGeometry", QByteArray()).toByteArray();
    s.endGroup();

    s.beginGroup("Audio");
        inDev = s.value("inDev", "").toString();
        outDev = s.value("outDev", "").toString();
        inVolume = s.value("inVolume", 100).toInt();
        outVolume = s.value("outVolume", 100).toInt();
        filterAudio = s.value("filterAudio", false).toBool();
    s.endGroup();

    s.beginGroup("Video");
        videoDev = s.value("videoDev", "").toString();
        camVideoRes = s.value("camVideoRes",QSize()).toSize();
        camVideoFPS = s.value("camVideoFPS", 0).toUInt();
    s.endGroup();

    // Read the embedded DHT bootstrap nodes list if needed
    if (dhtServerList.isEmpty())
    {
        QSettings rcs(":/conf/settings.ini", QSettings::IniFormat);
        rcs.setIniCodec("UTF-8");
        rcs.beginGroup("DHT Server");
            int serverListSize = rcs.beginReadArray("dhtServerList");
            for (int i = 0; i < serverListSize; i ++)
            {
                rcs.setArrayIndex(i);
                DhtServer server;
                server.name = rcs.value("name").toString();
                server.userId = rcs.value("userId").toString();
                server.address = rcs.value("address").toString();
                server.port = rcs.value("port").toInt();
                dhtServerList << server;
            }
            rcs.endArray();
        rcs.endGroup();
    }

    loaded = true;
}
Ejemplo n.º 12
0
void MainWindow::loadConfig()
{
    // Default geometry values
    QRect windowGeometry(50, 50, 700, 400);

    // Load and parse config file if exists
    bool configExists = QFile(this->userFolder + CONFIG_FILE).exists();
    if (configExists)
    {
        QFile file(this->userFolder + CONFIG_FILE);
        if (file.open(QFile::ReadOnly | QIODevice::Text))
        {
            QTextStream in(&file);
            QString data("");
            while (!in.atEnd())
            {
                QString line(in.readLine().trimmed());

                if (line.startsWith("#") || line.isEmpty())
                    continue;

                QStringList parts = line.split("=");
                if (parts.count() != 2)
                    continue;
                QString key = parts.at(0).trimmed().toLower();
                QString value = parts.at(1).trimmed();

                if (key == "serverip")
                    this->serverIp.setAddress(value);
                if (key == "serverport")
                    this->serverPort = value.toInt();
                if (key == "timeoutvalue")
                    this->timeoutValue = value.toInt();
                if (key == "timeoutenabled")
                    this->timeoutEnabled = (value == "1") ? true : false;
                if (key == "windowx")
                    windowGeometry.setX(value.toInt());
                if (key == "windowy")
                    windowGeometry.setY(value.toInt());
                if (key == "windoww")
                    windowGeometry.setWidth(value.toInt());
                if (key == "windowh")
                    windowGeometry.setHeight(value.toInt());
                if (key == "tab1caption")
                    this->tabCaptions[0] = value;
                if (key == "tab2caption")
                    this->tabCaptions[1] = value;
                if (key == "tab3caption")
                    this->tabCaptions[2] = value;
                if (key == "tab4caption")
                    this->tabCaptions[3] = value;
                if (key == "tab5caption")
                    this->tabCaptions[4] = value;
                if (key == "controlsvisible")
                    this->controlsVisible = (value == "1") ? true : false;
                if (key == "layout")
                    this->layoutType = (LayoutType) value.toInt();
            }
            file.close();
        }
    }

    // Load and parse styles file if exists
    bool stylesExists = QFile(this->userFolder + STYLES_FILE).exists();
    if (stylesExists)
    {
        QFile file(this->userFolder + STYLES_FILE);
        if (file.open(QFile::ReadOnly | QIODevice::Text))
        {
            QTextStream in(&file);
            QString data("");
            while (!in.atEnd())
            {
                QString line(in.readLine().trimmed());

                if (line.startsWith("#") || line.isEmpty())
                    continue;

                QStringList parts = line.split("=");
                if (parts.count() != 2)
                    continue;
                QString key = parts.at(0).trimmed().toLower();
                QString value = parts.at(1).trimmed();

                this->styles[key] = value;
            }
            file.close();
        }
    }

    // Apply geometry values
    this->setGeometry(windowGeometry);
}
Ejemplo n.º 13
0
bool SmileyPack::isValid(const QString& filename)
{
    return QFile(filename).exists();
}
Ejemplo n.º 14
0
FetchSqlite::~FetchSqlite()
{
    if(m_db.isOpen()) m_db.close();
    QFile(m_databaseFile).remove();
}
Ejemplo n.º 15
0
/**
 * Copies selected files into sandbox. Existing files in sandbox are not overwriten.
 *
 * @c QDir::NoDotAndDotDot is always added into @a filters.
 */
bool Sandbox::addWorldFiles(const QString &directory, QDir::Filters filters,
    const QStringList &filterNames, bool recurse){
  Q_ASSERT(!isActive());
  Q_ASSERT(!directory.isEmpty());

  if (!prepare()){
    return false;
  }

  const QString sandboxedDirectory = m_workingSandboxDir.filePath(
      QDir::root().relativeFilePath(
        QFileInfo(directory).absoluteFilePath()));

  if (!QFileInfo(directory).exists()){
    // Accept missing world directory - allow to create directories inside sandbox
    qDebug("%s: Directory does not exist - an empty one will be created instead of copied: '%s'",
        Q_FUNC_INFO, qPrintable(directory));
  } else if (!QFileInfo(directory).isDir()){
    qWarning("%s: Is not a directory: '%s'", Q_FUNC_INFO, qPrintable(directory));
    return false;
  }

  if (!QFileInfo(sandboxedDirectory).exists()){
    if (!QDir().mkpath(sandboxedDirectory)){
      qWarning("%s: Failed to create sandbox directory '%s'", Q_FUNC_INFO,
          qPrintable(sandboxedDirectory));
      return false;
    }
  } else if (!QFileInfo(sandboxedDirectory).isDir()){
    qWarning("%s: Failed to create sandbox directory '%s': Is not a directory", Q_FUNC_INFO,
        qPrintable(sandboxedDirectory));
    return false;
  }

  if (filters == QDir::NoFilter){
    filters = QDir::AllEntries;
  }

  filters |= QDir::NoDotAndDotDot;

  foreach (const QFileInfo &worldEntryInfo, QDir(directory).entryInfoList(filterNames, filters)){

    const QFileInfo sandboxEntryInfo(QDir(sandboxedDirectory).filePath(worldEntryInfo.fileName()));

    if (worldEntryInfo.isDir()){
      if (!sandboxEntryInfo.exists()){
        if (!QDir(sandboxedDirectory).mkdir(worldEntryInfo.fileName())){
          qWarning("%s: Failed to create overlay directory '%s/%s'", Q_FUNC_INFO,
              qPrintable(sandboxedDirectory), qPrintable(worldEntryInfo.fileName()));
          return false;
        }
      } else if (!sandboxEntryInfo.isDir()){
          qWarning("%s: Failed to create sandboxed copy '%s': Is not a directory", Q_FUNC_INFO,
              qPrintable(sandboxEntryInfo.filePath()));
          return false;
      }

      if (recurse){
        if (!addWorldFiles(worldEntryInfo.absoluteFilePath(), filters, filterNames, true)){
          return false;
        }
      }
    } else{
      if (!sandboxEntryInfo.exists()){
        if (!QFile(worldEntryInfo.filePath()).copy(sandboxEntryInfo.filePath())){
          qWarning("%s: Failed to copy file into sandbox '%s'", Q_FUNC_INFO,
              qPrintable(worldEntryInfo.filePath()));
          return false;
        }
      } else if (sandboxEntryInfo.isDir()){
          qWarning("%s: Failed to create sandboxed copy '%s': Is a directory", Q_FUNC_INFO,
              qPrintable(sandboxEntryInfo.filePath()));
          return false;
      }
    }
  }

  return true;
}
Ejemplo n.º 16
0
bool ImportIconsWizard::initialLoad(QString name)
{

    QString dirpath = GetConfDir();
    QDir configDir(dirpath);
    if (!configDir.exists() && !configDir.mkdir(dirpath))
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Could not create %1").arg(dirpath));
    }

    m_strChannelDir = QString("%1/%2").arg(configDir.absolutePath())
                      .arg("/channels");
    QDir strChannelDir(m_strChannelDir);
    if (!strChannelDir.exists() && !strChannelDir.mkdir(m_strChannelDir))
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("Could not create %1").arg(m_strChannelDir));
    }
    m_strChannelDir += "/";

    bool closeDialog = false;

    QString querystring("SELECT chanid, name, xmltvid, callsign,"
                        "dtv_multiplex.transportid, atsc_major_chan, "
                        "atsc_minor_chan, dtv_multiplex.networkid, "
                        "channel.serviceid, channel.mplexid,"
                        "dtv_multiplex.mplexid, channel.icon, channel.visible "
                        "FROM channel LEFT JOIN dtv_multiplex "
                        "ON channel.mplexid = dtv_multiplex.mplexid "
                        "WHERE ");
    if (!name.isEmpty())
        querystring.append("name=\"" + name + "\"");
    else
        querystring.append("channel.visible");
    querystring.append(" ORDER BY name");

    MSqlQuery query(MSqlQuery::InitCon());
    query.prepare(querystring);

    m_listEntries.clear();
    m_nCount=0;
    m_nMaxCount=0;
    m_missingMaxCount=0;

    if (query.exec() && query.size() > 0)
    {
        m_progressDialog =
            new MythUIProgressDialog(tr("Initializing, please wait..."),
                                     m_popupStack, "IconImportInitProgress");

        if (m_progressDialog->Create())
        {
            m_popupStack->AddScreen(m_progressDialog);
            m_progressDialog->SetTotal(query.size());
            QCoreApplication::processEvents();
        }
        else
        {
            delete m_progressDialog;
            m_progressDialog = NULL;
        }

        while(query.next())
        {
            CSVEntry entry;
            QString relativeIconPath = query.value(11).toString();
            QString absoluteIconPath = QString("%1%2").arg(m_strChannelDir)
                                       .arg(relativeIconPath);

            if (m_fRefresh && !relativeIconPath.isEmpty() &&
                    QFile(absoluteIconPath).exists() &&
                    !QImage(absoluteIconPath).isNull())
            {
                LOG(VB_GENERAL, LOG_NOTICE, QString("Icon already exists, skipping (%1)").arg(absoluteIconPath));
            }
            else
            {
                entry.strChanId=query.value(0).toString();
                entry.strName=query.value(1).toString();
                entry.strXmlTvId=query.value(2).toString();
                entry.strCallsign=query.value(3).toString();
                entry.strTransportId=query.value(4).toString();
                entry.strAtscMajorChan=query.value(5).toString();
                entry.strAtscMinorChan=query.value(6).toString();
                entry.strNetworkId=query.value(7).toString();
                entry.strServiceId=query.value(8).toString();
                entry.strIconCSV= QString("%1,%2,%3,%4,%5,%6,%7,%8,%9\n").
                                  arg(escape_csv(entry.strChanId)).
                                  arg(escape_csv(entry.strName)).
                                  arg(escape_csv(entry.strXmlTvId)).
                                  arg(escape_csv(entry.strCallsign)).
                                  arg(escape_csv(entry.strTransportId)).
                                  arg(escape_csv(entry.strAtscMajorChan)).
                                  arg(escape_csv(entry.strAtscMinorChan)).
                                  arg(escape_csv(entry.strNetworkId)).
                                  arg(escape_csv(entry.strServiceId));
                entry.strNameCSV=escape_csv(entry.strName);
                LOG(VB_CHANNEL, LOG_INFO,
                    QString("chanid %1").arg(entry.strIconCSV));

                m_listEntries.append(entry);
            }

            m_nMaxCount++;
            if (m_progressDialog)
            {
                m_progressDialog->SetProgress(m_nMaxCount);
                QCoreApplication::processEvents();
            }
        }

        if (m_progressDialog)
        {
            m_progressDialog->Close();
            m_progressDialog = NULL;
        }
    }

    m_iter = m_listEntries.begin();

    m_progressDialog = new MythUIProgressDialog(
        tr("Downloading, please wait..."), m_popupStack,
        "IconImportInitProgress");

    if (m_progressDialog->Create())
    {
        m_popupStack->AddScreen(m_progressDialog);
        m_progressDialog->SetTotal(m_listEntries.size());
        QCoreApplication::processEvents();
    }
    else
    {
        delete m_progressDialog;
        m_progressDialog = NULL;
    }

    /*: %1 is the current channel position,
     *  %2 is the total number of channels,
     */
    QString downloadMessage = tr("Downloading %1 of %2");

    while (!closeDialog && (m_iter != m_listEntries.end()))
    {
        QString message = downloadMessage.arg(m_nCount+1)
                          .arg(m_listEntries.size());

        LOG(VB_GENERAL, LOG_NOTICE, message);

        if (m_missingEntries.size() > 0)
        {
            message.append("\n");
            message.append(tr("Could not find %n icon(s).", "",
                              m_missingEntries.size()));
        }

        if (!findmissing((*m_iter).strIconCSV))
        {
            m_missingEntries.append((*m_iter));
            m_missingMaxCount++;
        }

        m_nCount++;
        m_iter++;
        if (m_progressDialog)
        {
            m_progressDialog->SetMessage(message);
            m_progressDialog->SetProgress(m_nCount);
            QCoreApplication::processEvents();
        }
    }

    if (m_progressDialog)
    {
        m_progressDialog->Close();
        m_progressDialog = NULL;
    }

    if (m_missingEntries.size() == 0 || closeDialog)
        return false;

    if (m_nMaxCount <= 0)
        return false;

    return true;
}
Ejemplo n.º 17
0
void StelFileMgr::init()
{
	// Set the userDir member.
#ifdef Q_OS_WIN
	QString winApiPath = getWin32SpecialDirPath(CSIDL_APPDATA);
	if (!winApiPath.isEmpty())
	{
		userDir = winApiPath + "\\Stellarium";
	}
#elif defined(Q_OS_MAC)
	userDir = QDir::homePath() + "/Library/Application Support/Stellarium";
#else
	userDir = QDir::homePath() + "/.stellarium";
#endif

#if QT_VERSION >= 0x050A00
	if (qEnvironmentVariableIsSet("STEL_USERDIR"))
	{
		userDir=qEnvironmentVariable("STEL_USERDIR");
	}
#else
	QByteArray userDirCand=qgetenv("STEL_USERDIR");
	if (userDirCand.length()>0)
	{
		userDir=QString::fromLocal8Bit(userDirCand);
	}
#endif

	if (!QFile(userDir).exists())
	{
		qWarning() << "User config directory does not exist: " << QDir::toNativeSeparators(userDir);
	}
	try
	{
		makeSureDirExistsAndIsWritable(userDir);
	}
	catch (std::runtime_error &e)
	{
		qFatal("Error: cannot create user config directory: %s", e.what());
	}

	// OK, now we have the userDir set, add it to the search path
	fileLocations.append(userDir);
	
	// Determine install data directory location
	QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
	QString envRoot = env.value("STELLARIUM_DATA_ROOT", ".");

	if (QFileInfo(envRoot + QDir::separator() + QString(CHECK_FILE)).exists())
	{
		installDir = envRoot;
	}	
	else
	{
	#if defined(Q_OS_MAC)
		QString relativePath = "/../Resources";
		if (QCoreApplication::applicationDirPath().contains("src")) {
			relativePath = "/../..";
		}
		QFileInfo MacOSdir(QCoreApplication::applicationDirPath() + relativePath);
		// These two lines are used to see if the Qt bug still exists.
		// The output from C: should simply be the parent of what is show for B:
		// qDebug() << "B: " << MacOSdir.absolutePath();
		// qDebug() << "C: " << MacOSdir.dir().absolutePath();

		QDir ResourcesDir(MacOSdir.absolutePath());
		if (!QCoreApplication::applicationDirPath().contains("src")) {
			ResourcesDir.cd(QString("Resources"));
		}
		QFileInfo installLocation(ResourcesDir.absolutePath());
		QFileInfo checkFile(installLocation.filePath() + QDir::separator() + QString(CHECK_FILE));
	#elif defined(Q_OS_WIN)		
		QFileInfo installLocation(QCoreApplication::applicationDirPath());
		QFileInfo checkFile(installLocation.filePath() + QDir::separator() + QString(CHECK_FILE));
	#else
		// Linux, BSD, Solaris etc.
		// We use the value from the config.h filesystem
		QFileInfo installLocation(QFile::decodeName(INSTALL_DATADIR));
		QFileInfo checkFile(QFile::decodeName(INSTALL_DATADIR "/" CHECK_FILE));
	#endif

	#ifdef DEBUG
		if (!checkFile.exists())
		{	// for DEBUG use sources location 
			QString debugDataPath = INSTALL_DATADIR_FOR_DEBUG;
			checkFile = QFileInfo(debugDataPath + QDir::separator() + CHECK_FILE);
			installLocation = QFileInfo(debugDataPath);
		}
	#endif

		if (checkFile.exists())
		{
			installDir = installLocation.filePath();
		}
		else
		{
			qWarning() << "WARNING StelFileMgr::StelFileMgr: could not find install location:"
					 << QDir::toNativeSeparators(installLocation.filePath())
					 << " (we checked for "
					 << QDir::toNativeSeparators(checkFile.filePath()) << ").";

			qWarning() << "Maybe this is AppImage or something similar? Let's check relative path...";
			// This hook has been added after reverse-engineering an AppImage application
			QString relativePath =  QCoreApplication::applicationDirPath() + QString("/../share/stellarium");
			checkFile = QFileInfo(relativePath + QDir::separator() + CHECK_FILE);
			if (checkFile.exists())
			{
				installDir = relativePath;
			}
			else
			{
				qWarning() << "WARNING StelFileMgr::StelFileMgr: could not find install location:"
						 << QDir::toNativeSeparators(relativePath)
						 << " (we checked for "
						 << QDir::toNativeSeparators(checkFile.filePath()) << ").";

				qWarning() << "Maybe this is development environment? Let's check source directory path...";

				QString sourceDirPath = STELLARIUM_SOURCE_DIR; // The variable is defined in CMakeLists.txt file
				checkFile = QFileInfo(sourceDirPath + QDir::separator() + CHECK_FILE);
				if (checkFile.exists())
				{
					installDir = sourceDirPath;
				}
				else
				{
					qWarning() << "WARNING StelFileMgr::StelFileMgr: could not find install location:"
							 << QDir::toNativeSeparators(sourceDirPath)
							 << " (we checked for "
							 << QDir::toNativeSeparators(checkFile.filePath()) << ").";

					#ifndef UNIT_TEST
					// NOTE: Hook for buildbots (using within testEphemeris)
					qFatal("Couldn't find install directory location.");
					#endif
				}
			}
		}
	}

	// Then add the installation directory to the search path
	fileLocations.append(installDir);
}
/**
 * 五组原图显示函数
 */
bool ImageViewer::updateImages()
{
    if (!hasinitmodel)
        return false;

    QString tmpcamid;
    bool ret = true;
    QString tmpcamimgdir;

    QLabel * tmpcamimg1 = NULL;
    QLabel * tmpcamimg2 = NULL;
    QLabel * tmpcamimg3 = NULL;
    QLabel * tmpcamimg4 = NULL;
    QLabel * tmpcamimg5 = NULL;
    QLabel * tmpcamimg = NULL;
    tmphasfc1 = false;
    tmphasfc2 = false;
    tmphasfc3 = false;
    tmphasfc4 = false;
    tmphasfc5 = false;

    for (int i = 0; i < 5; i++)
    {
        switch (i)
        {
            case 0: tmpcamid = ui->cam1->currentText(); 
                tmpcamimg1 = ui->cam1img1;
                tmpcamimg2 = ui->cam1img2;
                tmpcamimg3 = ui->cam1img3;
                tmpcamimg4 = ui->cam1img4;
                tmpcamimg5 = ui->cam1img5;
                break;
            case 1: tmpcamid = ui->cam2->currentText(); 
                tmpcamimg1 = ui->cam2img1;
                tmpcamimg2 = ui->cam2img2;
                tmpcamimg3 = ui->cam2img3;
                tmpcamimg4 = ui->cam2img4;
                tmpcamimg5 = ui->cam2img5;
                break;
            case 2: tmpcamid = ui->cam3->currentText(); 
                tmpcamimg1 = ui->cam3img1;
                tmpcamimg2 = ui->cam3img2;
                tmpcamimg3 = ui->cam3img3;
                tmpcamimg4 = ui->cam3img4;
                tmpcamimg5 = ui->cam3img5;
                break;
            case 3: tmpcamid = ui->cam4->currentText(); 
                tmpcamimg1 = ui->cam4img1;
                tmpcamimg2 = ui->cam4img2;
                tmpcamimg3 = ui->cam4img3;
                tmpcamimg4 = ui->cam4img4;
                tmpcamimg5 = ui->cam4img5;
                break;
            case 4: tmpcamid = ui->cam5->currentText(); 
                tmpcamimg1 = ui->cam5img1;
                tmpcamimg2 = ui->cam5img2;
                tmpcamimg3 = ui->cam5img3;
                tmpcamimg4 = ui->cam5img4;
                tmpcamimg5 = ui->cam5img5;
                break;
            default:break;
        }

        __int64 & tmpcurrentfc = getTmpCurrentfc(i);

        if (tmpcamid.trimmed().compare("") == 0)
        {
            tmpcamimg1->clear();
            tmpcamimg2->clear();
            tmpcamimg3->clear();
            tmpcamimg4->clear();
            tmpcamimg5->clear();
            continue;
        }
        tmpcamimgdir = currenttmpimgpath + "_" + tmpcamid + "/";

        // 每个相机的5张图
        for (int j = -2; j < 3; j++)
        {
            switch (j)
            {
                case -2: tmpcamimg = tmpcamimg1; break;
                case -1: tmpcamimg = tmpcamimg2; break;
                case 0: tmpcamimg = tmpcamimg3; break;
                case 1: tmpcamimg = tmpcamimg4; break;
                case 2: tmpcamimg = tmpcamimg5; break;
                default:break;
            }

            QString filename3 = (QString("%1/%2.jpg").arg(tmpcamimgdir).arg(tmpcurrentfc + j));
            if (!QFile(filename3).exists())
            {
                // 清空显示
                tmpcamimg->clear();
                qDebug() << QObject::tr("图片目录:") << filename3 << QObject::tr("不存在!");

                ret = false;
                continue;
            }
            qDebug() << QObject::tr("图片目录:") << filename3;

            bool & tmphasfc = getTmphasfc(j + 2);
            tmphasfc = true;

            // 做图像增强处理
            QByteArray tmpba = filename3.toLocal8Bit();
            cv::Mat img = cv::imread(tmpba.constData(), CV_LOAD_IMAGE_GRAYSCALE);
            float sclae = 0.3; // 缩放比例
            cv::Size size = cv::Size(img.size().width * sclae, img.size().height * sclae);
            cv::resize(img, img, size);
            //cv::imshow("win1",img);
            //cv::waitKey(0);
            if (ifimgenhance == 2)
            {
                
                double alpha = 2;  
                double beta = 50; 

                // 调整对比度,RGB调整,速度慢
                /*
                result = Mat::zeros(img.size(),img.type()); 
                for (int i = 0;i<img.rows;++i)  
                    for(int j= 0;j<img.cols;++j)  
                        for (int k = 0; k < 3; k++)
                            result.at(i,j)[k] = cv::saturate_cast<uchar>(img.at(i,j)[k]*alpha+beta);  
                cv::cvtColor(result,result, CV_BGRA2GRAY);
                */

                // 调整对比度,灰度调整,速度快
                cv::Mat result = cv::Mat(size, CV_8U);
                for( int i=0;i<img.rows;i++)  
                {  
                    uchar* dataimg = img.ptr<uchar>(i);
                    uchar* dataresult = result.ptr<uchar>(i);  
                    for(int j=0;j<img.cols;j++)  
                    {  
                        dataresult[j] = cv::saturate_cast<uchar>(dataimg[j]*alpha+beta);   
                    }  
                } 
                bigpm = MatToQImage(result);
            
                // 直方图均衡化---效果较差
                //cv::equalizeHist(img, result);
                //cv::imwrite("D:\\2.png", result);
                //cv::imshow("win1",result);
                //cv::waitKey(0);
            }
            else if (ifimgenhance == 1)
            {
                // 直方图规定化处理---By Ding
                cv::Mat result;
                LzCalculator::argument(img, result); 
                //cv::GaussianBlur(result, result, Size(5,5), 1.5, 1.5);
                bigpm = MatToQImage(result);
            }
            else
            {
                bigpm = MatToQImage(img);
            }
            
            smallpm = bigpm.scaled(TN_WIDTH, TN_HEIGHT, Qt::KeepAspectRatio);
            tmpcamimg->setPixmap(QPixmap::fromImage(smallpm));
            tmpcamimg->show();
        }
    }

    qDebug() << "has fc?: " << tmphasfc1 << tmphasfc2 << tmphasfc3 << tmphasfc4 << tmphasfc5;

    QLabel * tmpfclabel = NULL;
    QLabel * tmpmilelabel = NULL;

    // 每个相机的masterfc号
    for (int j = -2; j < 3; j++)
    {
        switch (j)
        {
            case -2: tmpfclabel = ui->fc1; tmpmilelabel = ui->mile1; break;
            case -1: tmpfclabel = ui->fc2; tmpmilelabel = ui->mile2; break;
            case 0: tmpfclabel = ui->fc3; tmpmilelabel = ui->mile3; break;
            case 1: tmpfclabel = ui->fc4; tmpmilelabel = ui->mile4; break;
            case 2: tmpfclabel = ui->fc5; tmpmilelabel = ui->mile5; break;
            default:break;
        }
        bool & tmphasfc = getTmphasfc(j + 2);
        if (tmphasfc)
        {
            tmpfclabel->setText(QString("%1").arg(current_fc_master + j));
            tmpmilelabel->setText(QString("%1").arg(current_fc_master + j));
        }
        else
        {
            tmpfclabel->setText(QString("%1无数据").arg(current_fc_master + j));
            tmpmilelabel->setText(QString("%1无数据").arg(current_fc_master + j));
        }
    }

    // 强制更新显示
    this->repaint();
    
    return ret;
}
int DropBoxOperations::synchronyze(){
    qint64 rc;
    QString cursor = "";
    bool hasMore = true;
    QDropboxFileInfoMap file_cache;    
    QMap<QString,QString> hashVersionDict ;
    QString fileRevision;
    QMap<QString,QString>::iterator hashIterator ;
    QFile hashVersionTab(documents + QDir::separator() + playListDir + QDir::separator()  + "hashVersionTab.dat") ;
    hashVersionTab.open(QIODevice::ReadWrite | QIODevice::Text);


    if(hashVersionTab.exists()){
        //Chargement du tableau des versions locale
        QTextStream in(&hashVersionTab);
        while (!in.atEnd()) {
            QString line = in.readLine();
            hashVersionDict[line.split(";")[0]]=line.split(";")[1];
        }
    }
    hashVersionTab.close();


    // Delete example.csv if exists
    if(QFile(documents + "/playlists/example.csv").exists())
        QFile(documents + "/playlists/example.csv").remove();

    currentFile = "" ;
    emit currentdownloadChanged();    
    do
    {
        currentFile = tr("\nRetrieving changes ...") ;
        emit currentdownloadChanged();        
        QDropboxDeltaResponse r = dropbox->requestDeltaAndWait(cursor, "");
        cursor = r.getNextCursor();
        hasMore = r.hasMore();

        const QDropboxDeltaEntryMap entries = r.getEntries();

        for(QDropboxDeltaEntryMap::const_iterator i = entries.begin(); i != entries.end(); i++)
        {
            if(i.value().isNull())
            {
                file_cache.remove(i.key());
            }
            else
            {
                file_cache.insert(convToUTF8(i.key()), i.value());
            }
        }

    } while (hasMore);

    // Dropbox to Local
    for(QDropboxFileInfoMap::const_iterator i = file_cache.begin(); i != file_cache.end(); i++)    {                

        if(i.value()->isDir()){
            // It's a directory
            if(!QDir( documents + QDir::separator()  + playListDir + QDir::separator()  + i.key().mid(1)).exists()){
                // Create local directory
                currentFile=currentFile + tr("\nCreate Dir") + i.key().mid(1) ;
                emit currentdownloadChanged();
                if(!QDir( documents + QDir::separator()  + playListDir).mkpath(i.key().mid(1))){                    
                    currentFile=currentFile + tr(" ... ERROR Create dir");
                    emit currentdownloadChanged();
                    return -2;
                }                
            }
        }
        else{
            // It's a file            
            if (QFile( documents + QDir::separator()  + playListDir + QDir::separator()  + i.key().mid(1)).exists()) {

                if(!hashVersionDict.contains(i.key().mid(1))){
                    fileRevision = "NEW";
                }
                else{
                    fileRevision=hashVersionDict[i.key().mid(1)];
                }

                // TEst si le fichier est nouveau ou pas
                if ( fileRevision != i.value()->revisionHash() && fileRevision != "LOCALYMODIFY")  {
                    hashVersionDict[i.key().mid(1)]=i.value()->revisionHash() ;
                    // Si la version du fichier est differente de NEW, on le met à jour.
                    // Si egale NEW cela veut dire que c'est soit une nouvelle install soit une ancienne version
                    if(fileRevision!="NEW"){
                        //Update existing file
                        currentFile=currentFile + "\n" + i.key() + " ... ";
                        emit currentdownloadChanged();
                        emit downloadanimChanged();
                        rc=getfile(i.key(),dropbox,"update");
                        if(rc < 0){
                            currentFile=QString::number(rc) + "KO" + currentFile ;
                            emit currentdownloadChanged();
                        }
                   }
                }
                else{
                    // If local file is newer, upload local version to dropbox
                    if(fileRevision=="LOCALYMODIFY"){
                        // Update only lyrics and setlits
                        if(i.key().indexOf("audio") == -1 && i.key().indexOf("chords") == -1) {
                            currentFile=currentFile + "\n->" + i.key() + " ... ";
                            emit currentdownloadChanged();
                            emit downloadanimChanged();
                            rc=putfile(i.key(),dropbox,&fileRevision,"update");
                            if(rc < 0){
                                currentFile=QString::number(rc) + "KO" + currentFile ;
                                emit currentdownloadChanged();
                                //return rc;
                            }
                            else{
                                currentFile=currentFile + "OK";
                                hashVersionDict[i.key().mid(1)]=fileRevision;
                            }
                        }
                    }
                }

            }
            else{
                // New file                
                hashVersionDict[i.key().mid(1)]=i.value()->revisionHash() ;
                currentFile=currentFile + "\n" + i.key() + " ... ";
                emit currentdownloadChanged();
                state=true;
                emit downloadanimChanged();
                rc=getfile(i.key(),dropbox,"new");
                state=false;
                emit downloadanimChanged();
                if(rc < 0){                    
                    currentFile=QString::number(rc) + "KO" + currentFile ;
                    emit currentdownloadChanged();                    
                }
                else {
                    currentFile=currentFile + "OK";
                    emit currentdownloadChanged();
                }
            }
        }
    }

    // Traite les nouveau fichier locaux
    for(hashIterator=hashVersionDict.begin();hashIterator!=hashVersionDict.end();hashIterator++){
        if(hashIterator.value() == "LOCALYMODIFY" ){
            if(hashIterator.key().indexOf("audio") == -1 && hashIterator.key().indexOf("chords") == -1) {
                currentFile=currentFile + "\n->" + hashIterator.key() + " ... ";
                emit currentdownloadChanged();
                emit downloadanimChanged();
                rc=putfile("/"+hashIterator.key(),dropbox,&fileRevision,"new");
                if(rc < 0){
                    currentFile=QString::number(rc) + "KO" + currentFile ;
                    emit currentdownloadChanged();
                }
                else{
                    hashVersionDict[hashIterator.key()]=fileRevision;
                }
            }
        }
    }

    //Ecriture de la nouvelle table des versions
    hashVersionTab.remove() ;
    hashVersionTab.open(QIODevice::ReadWrite | QIODevice::Text);

    QTextStream out(&hashVersionTab);
    for(hashIterator=hashVersionDict.begin();hashIterator!=hashVersionDict.end();hashIterator++){
        out << hashIterator.key() << ";" << hashIterator.value() << "\n";
    }

    hashVersionTab.close();

    currentFile=currentFile + tr("\nSynchro completed") ;
    emit currentdownloadChanged();
    done=true;
    emit downloaddoneChanged();
    return 0;
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
    QOptions options(get_common_options());
    options.add("QMLPlayer options")
            ("scale", 1.0, "scale of graphics context. 0: auto")
            ;
    options.parse(argc, argv);
    if (options.value("help").toBool()) {
        options.print();
        return 0;
    }

    QGuiApplication app(argc, argv);
    set_opengl_backend(options.option("gl").value().toString(), app.arguments().first());
    load_qm(QStringList() << "QMLPlayer", options.value("language").toString());
    QtQuick2ApplicationViewer viewer;
    viewer.engine()->rootContext()->setContextProperty("PlayerConfig", &Config::instance());
    qDebug(">>>>>>>>devicePixelRatio: %f", qApp->devicePixelRatio());
    QScreen *sc = app.primaryScreen();
    qDebug() << "dpi phy: " << sc->physicalDotsPerInch() << ", logical: " << sc->logicalDotsPerInch() << ", dpr: " << sc->devicePixelRatio()
                << "; vis rect:" << sc->virtualGeometry();
    // define a global var for js and qml
    viewer.engine()->rootContext()->setContextProperty("screenPixelDensity", qApp->primaryScreen()->physicalDotsPerInch()*qApp->primaryScreen()->devicePixelRatio());
    qreal r = sc->physicalDotsPerInch()/sc->logicalDotsPerInch();
    if (std::isinf(r) || std::isnan(r))
#if defined(Q_OS_ANDROID)
        r = 2.0;
#else
        r = 1.0;
#endif
    float sr = options.value("scale").toFloat();
#if defined(Q_OS_ANDROID)
    sr = r;
#endif
    if (qFuzzyIsNull(sr))
        sr = r;
    viewer.engine()->rootContext()->setContextProperty("scaleRatio", sr);
    QString qml = "qml/QMLPlayer/main.qml";
    if (QFile(qApp->applicationDirPath() + "/" + qml).exists())
        qml.prepend(qApp->applicationDirPath() + "/");
    else
        qml.prepend("qrc:///");
    viewer.setMainQmlFile(qml);
    viewer.showExpanded();
    QOption op = options.option("width");
    if (op.isSet())
        viewer.setWidth(op.value().toInt());
    op = options.option("height");
    if (op.isSet())
        viewer.setHeight(op.value().toInt());
    op = options.option("x");
    if (op.isSet())
        viewer.setX(op.value().toInt());
    op = options.option("y");
    if (op.isSet())
        viewer.setY(op.value().toInt());
    if (options.value("fullscreen").toBool())
        viewer.showFullScreen();

    viewer.setTitle("QMLPlayer based on QtAV. [email protected]");
    /*
     * find root item, then root.init(argv). so we can deal with argv in qml
     */
#if 1
    QString json = app.arguments().join("\",\"");
    json.prepend("[\"").append("\"]");
    json.replace("\\", "/"); //FIXME
    QMetaObject::invokeMethod(viewer.rootObject(), "init", Q_ARG(QVariant, json));
//#else
    QObject *player = viewer.rootObject()->findChild<QObject*>("player");
    if (player) {
        AppEventFilter *ae = new AppEventFilter(player, player);
        qApp->installEventFilter(ae);
    }
    if (app.arguments().size() > 1) {
        QString file = options.value("file").toString();
        if (file.isEmpty()) {
            if (argc > 1 && !app.arguments().last().startsWith('-') && !app.arguments().at(argc-2).startsWith('-'))
                file = app.arguments().last();
        }
        if (player && !file.isEmpty()) {
            if (QFile(file).exists())
                file.prepend("file:"); //qml use url and will add qrc: if no scheme
            file.replace("\\", "/"); //qurl
            QMetaObject::invokeMethod(player, "play", Q_ARG(QUrl, QUrl(file)));
        }
    }
#endif
    QObject::connect(viewer.rootObject(), SIGNAL(requestFullScreen()), &viewer, SLOT(showFullScreen()));
    QObject::connect(viewer.rootObject(), SIGNAL(requestNormalSize()), &viewer, SLOT(showNormal()));
    ScreenSaver::instance().disable(); //restore in dtor
    return app.exec();
}
Ejemplo n.º 21
0
Archivo: main.cpp Proyecto: m2otech/emm
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MainWindow w;

    QPixmap pixmap(":/app/icons/splash.png");

    SplashScreen *s = new SplashScreen(pixmap);
    s->show();
    s->showMessage("Event Music Machine starten...");

    QString path = Configuration::getStorageLocation();
    if (path == "") {
        QFileDialog dia(s);
        dia.setViewMode(QFileDialog::List);
        dia.setFileMode(QFileDialog::Directory);
        dia.setAcceptMode(QFileDialog::AcceptOpen);
        dia.setOptions(QFileDialog::ShowDirsOnly);
        dia.setWindowTitle(QObject::tr("Bitte selektieren Sie einen Ordner in dem die Konfigurations-Dateien abgelegt werden sollen."));
        if (dia.exec() == 1) {
            path = dia.selectedFiles().at(0);
            Configuration::setStorageLocation(path);
        }
    }

    s->showMessage("Slotspeicher verbinden...");
    if (!QFile(Configuration::getStorageLocation() + "/slotstore.emm").exists())
    {
        QMessageBox::information(s,"Slot-Speicher anlegen",QObject::tr("Es wurde keine gültige Slot-Datenbank gefunden. Sie wurde jetzt angelegt."));
        QFile::copy(":/slot-store.sqlite", Configuration::getStorageLocation() + "/slotstore.emm");
        QFile::setPermissions(Configuration::getStorageLocation() + "/slotstore.emm",QFile::ReadOther | QFile::WriteOther);
    }

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(Configuration::getStorageLocation() + "/slotstore.emm");
    if (!db.open())
    {
        QMessageBox::warning(s,QObject::tr("Keine Verbindung zum Slot-Speicher"),QObject::tr("Es konnte keine Verbindung zum Slot-Speicher hergestellt werden!"));
    }

    s->showMessage("Verbindung zur Tastatur herstellen...");
    KeyboardController *keyController = KeyboardController::getInstance();
    QObject::connect(keyController, SIGNAL(errorOccured(QString)), s, SLOT(showErrorMessage(QString)));
    QObject::connect(keyController, SIGNAL(keyPressed(int,int)), &w, SLOT(keyboardSignal(int,int)));
    keyController->initializeKeyboardController();

    s->showMessage("Audiogeräte initialisieren...");

    AudioProcessor::getInstance()->initDevices(&w);

    s->showMessage("Audio-Plugins laden...");
    PluginLoader::loadPlugins();

    s->showMessage("Slots laden und überprüfen...");

    int number = 1;
    Configuration *config = Configuration::getInstance();
    for (int i=0;i<config->getLayer();i++)
    {
        for (int j=0;j<config->getVerticalSlots();j++)
        {
            for (int k=0;k<config->getHorizontalSlots();k++)
            {
                CartSlot *slot = AudioProcessor::getInstance()->getCartSlotWithNumber(number);
                s->showMessage("Slots laden und überprüfen...\r\n"+slot->getText1());
                if (slot->isMissing()) {
                    QMessageBox::information(s,"Datei wurde nicht gefunden","Slot "+QString::number(slot->getNumber())+" ("+slot->getText1()+") konnte nicht geladen werden, weil die Datei nicht gefunden wurde!");
                }
                number++;
            }
        }
    }
    s->showMessage("Benutzeroberfläche initialisieren...");
    w.init();
    s->close();


    w.show();
    return a.exec();
}
Ejemplo n.º 22
0
		/**
  Returns whether or not this page contains the image which is the scan of this page.  returns false if we only have the default/missing image instead
  */
		QBool Page::hasImage() {
			if (!QFile(data.getImagePath()).exists()) {
				return QBool(false);
			}
			return QBool(true);
		}
Ejemplo n.º 23
0
static void updateTsFiles(const Translator &fetchedTor, const QStringList &tsFileNames,
    const QByteArray &codecForTr, const QString &sourceLanguage, const QString &targetLanguage,
    UpdateOptions options, bool *fail)
{
    QDir dir;
    QString err;
    foreach (const QString &fileName, tsFileNames) {
        QString fn = dir.relativeFilePath(fileName);
        ConversionData cd;
        Translator tor;
        cd.m_sortContexts = !(options & NoSort);
        if (QFile(fileName).exists()) {
            if (!tor.load(fileName, cd, QLatin1String("auto"))) {
                qWarning( "%s", qPrintable( cd.error() ) );
                *fail = true;
                continue;
            }
            tor.resolveDuplicates();
            cd.clearErrors();
            if (!codecForTr.isEmpty() && codecForTr != tor.codecName())
                qWarning("lupdate warning: Codec for tr() '%s' disagrees with "
                         "existing file's codec '%s'. Expect trouble.",
                         codecForTr.constData(), tor.codecName().constData());
            if (!targetLanguage.isEmpty() && targetLanguage != tor.languageCode())
                qWarning("lupdate warning: Specified target language '%s' disagrees with "
                         "existing file's language '%s'. Ignoring.",
                         qPrintable(targetLanguage), qPrintable(tor.languageCode()));
            if (!sourceLanguage.isEmpty() && sourceLanguage != tor.sourceLanguageCode())
                qWarning("lupdate warning: Specified source language '%s' disagrees with "
                         "existing file's language '%s'. Ignoring.",
                         qPrintable(sourceLanguage), qPrintable(tor.sourceLanguageCode()));
        } else {
            if (!codecForTr.isEmpty())
                tor.setCodecName(codecForTr);
            if (!targetLanguage.isEmpty())
                tor.setLanguageCode(targetLanguage);
            if (!sourceLanguage.isEmpty())
                tor.setSourceLanguageCode(sourceLanguage);
        }
        tor.makeFileNamesAbsolute(QFileInfo(fileName).absoluteDir());
        if (options & NoLocations)
            tor.setLocationsType(Translator::NoLocations);
        else if (options & RelativeLocations)
            tor.setLocationsType(Translator::RelativeLocations);
        else if (options & AbsoluteLocations)
            tor.setLocationsType(Translator::AbsoluteLocations);
        if (options & Verbose)
            printOut(QObject::tr("Updating '%1'...\n").arg(fn));

        if (tor.locationsType() == Translator::NoLocations) // Could be set from file
            options |= NoLocations;
        Translator out = merge(tor, fetchedTor, options, err);
        if (!codecForTr.isEmpty())
            out.setCodecName(codecForTr);

        if ((options & Verbose) && !err.isEmpty()) {
            printOut( qPrintable( err ) );
            err.clear();
        }
        if (options & PluralOnly) {
            if (options & Verbose)
                printOut(QObject::tr("Stripping non plural forms in '%1'...\n").arg(fn));
            out.stripNonPluralForms();
        }
        if (options & NoObsolete)
            out.stripObsoleteMessages();
        out.stripEmptyContexts();

        if (!out.save(fileName, cd, QLatin1String("auto"))) {
            qWarning( "%s", qPrintable( cd.error() ) );
            *fail = true;
        }
    }
Ejemplo n.º 24
0
void AutoImportWindow::importImage() {
    
    if(continuous->isChecked()) {
        analyzeImport(true);
    }
    
    if(toBeImported_.isEmpty()) {
        finishExecution();
        return;
    }

    if (imageExecuting_) {
        QString numberExec = imageExecuting_->directory();
        if (!numberExec.isEmpty()) {
            if (dirToRowNumber_.keys().contains(numberExec)) {
                if (dirToRowNumber_[numberExec] < resultsTable_->rowCount()) {
                    if (resultsTable_->item(dirToRowNumber_[numberExec], 0)) {
                        resultsTable_->item(dirToRowNumber_[numberExec], 0)->setIcon(ApplicationData::icon("process_done"));
                    }
                }
            }
        }
    }
    
    QString number;
    number = toBeImported_.keys().first();

    QStringList files = toBeImported_[number];
    toBeImported_.remove(number);
    
    //Get the original file name used for search
    QString baseName = files.first();
    
    //Deduce parameters from baseName
    QMap<QString, QString> fileNameParams = FileNameParserDialog::parseFileName(baseName);
    
    QString importGroup_ = projectData.projectParameterData()->getValue("import_target_group");
    QString importGroupSuffix = projectData.projectParameterData()->getValue("import_target_group_suffix");
    
    //Add suffix to group name
    QString suffix = "";
    
    //case importGroupSuffix=1 => parameter = specimennumber
    if(importGroupSuffix == "1") { 
        //If the file name contains this param take it from there, otherwise search master.cfg 
        if(fileNameParams.contains("specimennumber")) suffix = fileNameParams["specimennumber"];
        else {
            suffix = projectData.projectParameterData()->getValue("specimennumber");
        }
    }
    
    if(suffix == "-") suffix = "";
    
    importGroup_ = importGroup_ + suffix;
    
    if (dirToRowNumber_.keys().contains(number)) {
        if (dirToRowNumber_[number] < resultsTable_->rowCount()) {
            if(resultsTable_->item(dirToRowNumber_[number], 0)) {
                resultsTable_->item(dirToRowNumber_[number], 0)->setIcon(ApplicationData::icon("process_executing"));
                resultsTable_->scrollToItem(resultsTable_->item(dirToRowNumber_[number], 0));
            }
        }
    }
    
    statusLabel_->setText(QString("Currently importing and %2 are in queue...").arg(toBeImported_.keys().size()));
    projectData.projectParameterData()->set("import_imagenumber", number);
    
    //Create dir
    QDir workingDir = QDir(projectData.projectDir().canonicalPath() + "/" + importGroup_ + "/" + number);
    
    //create import group
    projectData.projectDir().mkpath(importGroup_);
    QFile(projectData.projectDir().absolutePath() + "/merge").link("../2dx_master.cfg", projectData.projectDir().absolutePath() + "/" + importGroup_ + "/2dx_master.cfg");
    
    //create Dir
    projectData.projectDir().mkpath(importGroup_ + "/" + number);
    workingDir.mkpath("proc");
    workingDir.mkpath("LOGS");

    //Copy Config File
    projectData.projectParameterData()->saveAs(workingDir.canonicalPath() + "/2dx_image.cfg", true);

    imageExecuting_ = projectData.addImage(importGroup_, number);
    ParametersConfiguration* conf = imageExecuting_->parameters();
    conf->set("imagenumber", number, false);
    
    bool hasAveraged = false;
    bool hasAligned = false;
    bool hasRaw = false;
    
    //Check for the averaged file
    if(files.size() > 1 && !files[1].isEmpty()) {
        conf->set("imagename", "image_2dx", false);
        conf->set("nonmaskimagename", "image_2dx", false);
        conf->set("imagename_original", files[1], false);
        conf->set("import_original_time", QString::number(QFileInfo(files[1]).created().toMSecsSinceEpoch()), false);
        scriptsToBeExecuted_.append("cp -f " + files[1] + " " + workingDir.canonicalPath() + "/" + "image_2dx.mrc");
        if(deleteCheck->isChecked()) scriptsToBeExecuted_.append("rm -f " + files[1]);
        hasAveraged = true;
    }
    
    //Check for aligned file
    if (files.size() > 2 && !files[2].isEmpty()) {
        conf->set("movie_stackname", "movie_aligned", false);
        conf->set("movie_stackname_original", files[2], false);
        conf->set("import_original_time", QString::number(QFileInfo(files[2]).created().toMSecsSinceEpoch()), false);
        scriptsToBeExecuted_.append("cp -f " + files[2] + " " + workingDir.canonicalPath() + "/" + "movie_aligned.mrcs");
        if(deleteCheck->isChecked()) scriptsToBeExecuted_.append("rm -f " + files[2]);
        hasAligned = true;
    }

    //Check for raw file
    if (files.size() > 3 && !files[3].isEmpty()) {
        int rawOption = conf->getVariant("import_rawstack_type").toInt();
        if(rawOption == 1) {
            conf->set("import_rawstack", baseName + '.' + QFileInfo(files[3]).suffix(), false);
            conf->set("import_rawstack_original", files[3], false);
            conf->set("import_original_time", QString::number(QFileInfo(files[3]).created().toMSecsSinceEpoch()), false);
            scriptsToBeExecuted_.append("cp -f " + files[3] + " " + workingDir.canonicalPath() + "/" + baseName + '.' + QFileInfo(files[3]).suffix());
            if(deleteCheck->isChecked()) scriptsToBeExecuted_.append("rm -f " + files[3]);
            hasRaw = true;
        } else if (rawOption == 2) {
            conf->set("import_rawstack", baseName + '.' + QFileInfo(files[3]).suffix(), false);
            conf->set("import_rawstack_original", files[3], false);
            conf->set("raw_gaincorrectedstack", "raw_gaincorrectedstack", false);
            conf->set("raw_gaincorrectedstack_original", files[3], false);
            conf->set("import_original_time", QString::number(QFileInfo(files[3]).created().toMSecsSinceEpoch()), false);
            scriptsToBeExecuted_.append("cp -f " + files[3] + " " + workingDir.canonicalPath() + "/" + "raw_gaincorrectedstack.mrcs");
            if(deleteCheck->isChecked()) scriptsToBeExecuted_.append("rm -f " + files[3]);
            hasRaw = true;
        }
    }

    //Check for defects list file
    QString defectsFile = conf->getValue("import_defects_original");
    if(QFileInfo(defectsFile).exists()) {
        conf->set("import_defects", "../" + QFileInfo(defectsFile).fileName(), false);
        scriptsToBeExecuted_.append("rsync -auvP " + defectsFile + " " + workingDir.canonicalPath() + "/../" + QFileInfo(defectsFile).fileName());
    }
    
    //Check for gain reference file
    QString gainRefFile = conf->getValue("import_gainref_original");
    if(QFileInfo(gainRefFile).exists()) {
        conf->set("import_gainref", "../" + QFileInfo(gainRefFile).fileName(), false);
        scriptsToBeExecuted_.append("rsync -auvP " + gainRefFile + " " + workingDir.canonicalPath() + "/../" + QFileInfo(gainRefFile).fileName());
    }
    
    //Set the parameters from filename
    for(QString param : fileNameParams.keys()) {
        if(parameterMaster.containsParameter(param)) {
            conf->set(param, fileNameParams[param], false);
            //qDebug() << "Parameter set: " << param << " => " << fileNameParams[param];
        }
    }
    
    conf->setModified(true);
    
    //Write to status folder if required
    if(userPreferenceData.get("status_folder_update") == "y" && QFileInfo(userPreferenceData.get("status_folder")).isDir()) {
        long currentMSecs = conf->getValue("import_original_time").toLong();
        
        //Write the last imported data
        QFile saveFile(userPreferenceData.get("status_folder") + "/last.txt");
        long lastMSecs = 0;
        if(saveFile.exists()) {
            if (saveFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
                while (!saveFile.atEnd()) {
                    lastMSecs = QString(saveFile.readLine().simplified()).toLong();
                }
		saveFile.close();
            }
            saveFile.remove();
        }
        
	QString toBeWritten;
        if(currentMSecs >= lastMSecs) toBeWritten = QString::number(currentMSecs);
        else toBeWritten = QString::number(lastMSecs);
        if (saveFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
            saveFile.write(toBeWritten.toLatin1());
        }
        saveFile.close();
        
        //Write the time stamp in the last hour processed data
        ProjectData::writeStatisticsToStatusFolder("last_recorded.txt", currentMSecs);
        ProjectData::writeStatisticsToStatusFolder("last_imported.txt");
    }
     
    //register that this image was imported
    ImportFolderSettings(QDir(conf->getValue("import_dir"))).addImportedImage(baseName, importGroup_ + "/" + number, hasAveraged, hasAligned, hasRaw);
    
    //Add the scripts to be executed during import
    QStringList scripts = importSelectorDialog.scriptPaths(ProjectPreferences().scripts("import"));
    for(QString script : scripts) {
        if(!script.isEmpty()) scriptsToBeExecuted_.append("SCRIPT:" + script);
    }
    continueExecution();
}
Ejemplo n.º 25
0
void IconSettings::getIconReccord(){
    QHash<QString, QString> iconRec;

    iconRec = db_icon.getByName(this->prefix_name, this->dir_name, this->icon_name);

    txtName->setText(iconRec.value("name"));
    txtCmdArgs->setText(iconRec.value("cmdargs"));
    txtProgramPath->setText(iconRec.value("exec"));

    iconPath = iconRec.value("icon_path");

    if (!iconPath.isEmpty()){
        if (QFile(iconPath).exists()){
            cmdGetIcon->setIcon (QIcon(iconPath));
        } else {
            QIcon ico = CoreLib->loadIcon(QString("data/%1.png").arg(iconPath));

            // Do not work due to: https://bugreports.qt-project.org/browse/QTBUG-999
            //if (ico.isNull()){
            if (ico.availableSizes().isEmpty()){
                ico = CoreLib->loadIcon("data/exec_wine.png");
                iconPath="";
            }

            cmdGetIcon->setIcon(ico);
        }
    }

    txtDesc->setText(iconRec.value("desc"));
    txtDisplay->setText(iconRec.value("display"));
    txtWinedebug->setText(iconRec.value("winedebug"));
    txtWorkDir->setText(iconRec.value("wrkdir"));
    txtEnvLang->setText(iconRec.value("lang"));

    if (iconRec.value("desktop").isEmpty()){
        cboxDesktopSize->setCurrentIndex(0);
    } else {
        cboxDesktopSize->setCurrentIndex(cboxDesktopSize->findText(iconRec.value("desktop")));
    }

    spinNice->setValue(iconRec.value("nice").toInt());

    if (iconRec.value("useconsole")=="1"){
        cbUseConsole->setCheckState(Qt::Checked);
        txtWinedebug->setEnabled(TRUE);
    } else {
        cbUseConsole->setCheckState(Qt::Unchecked);
        txtWinedebug->setEnabled(FALSE);
    }

    QStringList override = iconRec.value("override").split(";");
    QString overrideorder="";

    for (int i=0; i<override.count()-1; i++){
        QStringList list2 = override.at(i).split("=");
            twDlls->insertRow (0);
            std::auto_ptr<QTableWidgetItem> newItem (new QTableWidgetItem(list2.at(0)));
            newItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable );
            twDlls->setItem(0, 0, newItem.release());

            if (list2.at(1)=="n")
                overrideorder = tr("Native");
            if (list2.at(1)=="b")
                overrideorder = tr("Built-in");
            if (list2.at(1)=="n,b")
                overrideorder = tr("Native, Built-in");
            if (list2.at(1)=="b,n")
                overrideorder = tr("Built-in, Native");

            newItem.reset(new QTableWidgetItem(overrideorder));
            newItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable );
            twDlls->setItem(0, 1, newItem.release());
    }

    txtPreRun->setText(iconRec.value("prerun"));
    txtPostRun->setText(iconRec.value("postrun"));

    return;
}
Ejemplo n.º 26
0
void qFacets::exportFacets()
{
	assert(m_app);
	if (!m_app)
		return;

	//disclaimer accepted?
	if (!ShowDisclaimer(m_app))
		return;

	//Retrive selected facets
	FacetSet facets;
	getFacetsInCurrentSelection(facets);

	if (facets.empty())
	{
		m_app->dispToConsole("Couldn't find any facet in the current selection!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}
	assert(!facets.empty());

	FacetsExportDlg fDlg(FacetsExportDlg::SHAPE_FILE_IO,m_app->getMainWindow());

	//persistent settings (default export path)
	QSettings settings;
	settings.beginGroup("qFacets");
	QString facetsSavePath = settings.value("exportPath",QApplication::applicationDirPath()).toString();
	fDlg.destinationPathLineEdit->setText(facetsSavePath + QString("/facets.shp"));

	if (!fDlg.exec())
		return;

	QString filename = fDlg.destinationPathLineEdit->text();

	//save current export path to persistent settings
	settings.setValue("exportPath",QFileInfo(filename).absolutePath());

	if (QFile(filename).exists())
	{
		//if the file already exists, ask for confirmation!
		if (QMessageBox::warning(m_app->getMainWindow(),"File already exists!","File already exists! Are you sure you want to overwrite it?",QMessageBox::Yes,QMessageBox::No) == QMessageBox::No)
			return;
	}

	//fields (shapefile) - WARNING names must not have more than 10 chars!
	ShpFilter::IntegerField  facetIndex("index");
	ShpFilter::DoubleField   facetSurface("surface");
	ShpFilter::DoubleField   facetRMS("rms");
	ShpFilter::IntegerField  facetDipDir("dip_dir");
	ShpFilter::IntegerField  facetDip("dip");
	ShpFilter::IntegerField  familyIndex("family_ind");
	ShpFilter::IntegerField  subfamilyIndex("subfam_ind");
	ShpFilter::DoubleField3D facetNormal("normal");
	ShpFilter::DoubleField3D facetBarycenter("center");
	ShpFilter::DoubleField   horizExtension("horiz_ext");
	ShpFilter::DoubleField   vertExtension("vert_ext");
	ShpFilter::DoubleField   surfaceExtension("surf_ext");

	size_t facetCount = facets.size();
	assert(facetCount != 0);
	try
	{
		facetIndex.values.reserve(facetCount);
		facetSurface.values.reserve(facetCount);
		facetRMS.values.reserve(facetCount);
		facetDipDir.values.reserve(facetCount);
		facetDip.values.reserve(facetCount);
		familyIndex.values.reserve(facetCount);
		subfamilyIndex.values.reserve(facetCount);
		facetNormal.values.reserve(facetCount);
		facetBarycenter.values.reserve(facetCount);
		horizExtension.values.reserve(facetCount);
		vertExtension.values.reserve(facetCount);
		surfaceExtension.values.reserve(facetCount);
	}
	catch (const std::bad_alloc&)
	{
		m_app->dispToConsole("Not enough memory!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}

	ccHObject toSave("facets");

	//depending on the 'main orientation', the job is more or less easy ;)
	bool useNativeOrientation = fDlg.nativeOriRadioButton->isChecked();
	bool useGlobalOrientation = fDlg.verticalOriRadioButton->isChecked();
	bool useCustomOrientation = fDlg.customOriRadioButton->isChecked();

	//Default base
	CCVector3 X(1,0,0), Y(0,1,0), Z(0,0,1);

	//'vertical' orientation (potentially specified by the user)
	if (!useNativeOrientation)
	{
		if (useCustomOrientation)
		{
			Z = CCVector3(	static_cast<PointCoordinateType>(fDlg.nXLineEdit->text().toDouble()),
							static_cast<PointCoordinateType>(fDlg.nYLineEdit->text().toDouble()),
							static_cast<PointCoordinateType>(fDlg.nZLineEdit->text().toDouble()) );
			Z.normalize();
		}
		else if (useGlobalOrientation)
		{
			//we compute the mean orientation (weighted by each facet's surface)
			CCVector3d Nsum(0,0,0);
			for (FacetSet::iterator it = facets.begin(); it != facets.end(); ++it)
			{
				double surf = (*it)->getSurface();
				CCVector3 N = (*it)->getNormal();
				Nsum.x += static_cast<double>(N.x) * surf;
				Nsum.y += static_cast<double>(N.y) * surf;
				Nsum.z += static_cast<double>(N.z) * surf;
			}
			Nsum.normalize();

			Z = CCVector3(	static_cast<PointCoordinateType>(Nsum.x),
							static_cast<PointCoordinateType>(Nsum.y),
							static_cast<PointCoordinateType>(Nsum.z) );
		}

		//update X & Y
		CCVector3 D = Z.cross(CCVector3(0,0,1));
		if (D.norm2() > ZERO_TOLERANCE) //otherwise the vertical dir hasn't changed!
		{
			X = -D;
			X.normalize();
			Y = Z.cross(X);
		}
	}

	//we compute the mean center (weighted by each facet's surface)
	CCVector3 C(0,0,0);
	{
		double weightSum = 0;
		for (FacetSet::iterator it = facets.begin(); it != facets.end(); ++it)
		{
			double surf = (*it)->getSurface();
			CCVector3 Ci = (*it)->getCenter();
			C += Ci * static_cast<PointCoordinateType>(surf);
			weightSum += surf;
		}
		if (weightSum)
			C /= static_cast<PointCoordinateType>(weightSum);
	}

	//determine the 'global' orientation matrix
	ccGLMatrix oriRotMat;
	oriRotMat.toIdentity();
	if (!useNativeOrientation)
	{
		oriRotMat.getColumn(0)[0] = static_cast<float>(X.x);
		oriRotMat.getColumn(0)[1] = static_cast<float>(X.y);
		oriRotMat.getColumn(0)[2] = static_cast<float>(X.z);
		oriRotMat.getColumn(1)[0] = static_cast<float>(Y.x);
		oriRotMat.getColumn(1)[1] = static_cast<float>(Y.y);
		oriRotMat.getColumn(1)[2] = static_cast<float>(Y.z);
		oriRotMat.getColumn(2)[0] = static_cast<float>(Z.x);
		oriRotMat.getColumn(2)[1] = static_cast<float>(Z.y);
		oriRotMat.getColumn(2)[2] = static_cast<float>(Z.z);
		oriRotMat.invert();

		ccGLMatrix transMat;
		transMat.setTranslation(-C);
		oriRotMat = oriRotMat * transMat;
		oriRotMat.setTranslation(oriRotMat.getTranslationAsVec3D() + C);
	}

	//for each facet
	for (FacetSet::iterator it=facets.begin(); it!=facets.end(); ++it)
	{
		ccFacet* facet = *it;
		ccPolyline* poly = facet->getContour();

		//if necessary, we create a (temporary) new facet
		if (!useNativeOrientation)
		{
			CCLib::GenericIndexedCloudPersist* vertices = poly->getAssociatedCloud();
			if (!vertices || vertices->size() < 3)
				continue;

			//create (temporary) new polyline
			ccPolyline* newPoly = new ccPolyline(*poly);
			ccPointCloud* pc = (newPoly ? dynamic_cast<ccPointCloud*>(newPoly->getAssociatedCloud()) : 0);
			if (pc)
			{
				pc->applyGLTransformation_recursive(&oriRotMat);
			}
			else
			{
				m_app->dispToConsole(QString("Failed to change the orientation of polyline '%1'! (not enough memory)").arg(poly->getName()),ccMainAppInterface::WRN_CONSOLE_MESSAGE);
				continue;
			}

			newPoly->set2DMode(true);
			poly = newPoly;
		}

		toSave.addChild(poly, useNativeOrientation ? ccHObject::DP_NONE : ccHObject::DP_PARENT_OF_OTHER);

		//save associated meta-data as 'shapefile' fields
		{
			//main parameters
			FacetMetaData data;
			GetFacetMetaData(facet, data);

			//horizontal and vertical extensions
			double horizExt = 0, vertExt = 0;
			ComputeFacetExtensions(data.normal,poly,horizExt,vertExt);

			facetIndex.values.push_back(data.facetIndex);
			facetSurface.values.push_back(data.surface);
			facetRMS.values.push_back(data.rms);
			facetDipDir.values.push_back(data.dipDir_deg);
			facetDip.values.push_back(data.dip_deg);
			familyIndex.values.push_back(data.familyIndex);
			subfamilyIndex.values.push_back(data.subfamilyIndex);
			facetNormal.values.push_back(CCVector3d(data.normal.x,data.normal.y,data.normal.z));
			facetBarycenter.values.push_back(CCVector3d(data.center.x,data.center.y,data.center.z));
			vertExtension.values.push_back(vertExt);
			horizExtension.values.push_back(horizExt);
			surfaceExtension.values.push_back(horizExt*vertExt);
		}
	}

	//save entities
	if (toSave.getChildrenNumber())
	{
		std::vector<ShpFilter::GenericField*> fields;
		fields.push_back(&facetIndex);
		fields.push_back(&facetBarycenter);
		fields.push_back(&facetNormal);
		fields.push_back(&facetRMS);
		fields.push_back(&horizExtension);
		fields.push_back(&vertExtension);
		fields.push_back(&surfaceExtension);
		fields.push_back(&facetSurface);
		fields.push_back(&facetDipDir);
		fields.push_back(&facetDip);
		fields.push_back(&familyIndex);
		fields.push_back(&subfamilyIndex);
		ShpFilter filter;
		filter.treatClosedPolylinesAsPolygons(true);
		ShpFilter::SaveParameters params;
		params.alwaysDisplaySaveDialog = false;
		if (filter.saveToFile(&toSave,fields,filename,params) == CC_FERR_NO_ERROR)
		{
			m_app->dispToConsole(QString("[qFacets] File '%1' successfully saved").arg(filename),ccMainAppInterface::STD_CONSOLE_MESSAGE);
		}
		else
		{
			m_app->dispToConsole(QString("[qFacets] Failed to save file '%1'!").arg(filename),ccMainAppInterface::WRN_CONSOLE_MESSAGE);
		}
	}
}
Ejemplo n.º 27
0
void ItemDoor::contextMenu(QGraphicsSceneMouseEvent *mouseEvent)
{
    m_scene->m_contextMenuIsOpened = true; //bug protector

    //Remove selection from non-bgo items
    if(!this->isSelected())
    {
        m_scene->clearSelection();
        this->setSelected(true);
    }

    this->setSelected(1);
    QMenu ItemMenu;

    QAction *openLvl = ItemMenu.addAction(tr("Open target level: %1").arg(m_data.lname).replace("&", "&&&"));
    openLvl->setVisible((!m_data.lname.isEmpty()) && (QFile(m_scene->m_data->meta.path + "/" + m_data.lname).exists()));
    openLvl->deleteLater();

    /*************Layers*******************/
    QMenu *LayerName =     ItemMenu.addMenu(tr("Layer: ") + QString("[%1]").arg(m_data.layer).replace("&", "&&&"));
    QAction *setLayer;
    QList<QAction *> layerItems;

    QAction *newLayer =    LayerName->addAction(tr("Add to new layer..."));
    LayerName->addSeparator()->deleteLater();;
    for(LevelLayer &layer : m_scene->m_data->layers)
    {
        //Skip system layers
        if((layer.name == "Destroyed Blocks") || (layer.name == "Spawned NPCs")) continue;

        setLayer = LayerName->addAction(layer.name.replace("&", "&&&") + ((layer.hidden) ? "" + tr("[hidden]") : ""));
        setLayer->setData(layer.name);
        setLayer->setCheckable(true);
        setLayer->setEnabled(true);
        setLayer->setChecked(layer.name == m_data.layer);
        layerItems.push_back(setLayer);
    }
    ItemMenu.addSeparator();
    /*************Layers*end***************/

    QAction *jumpTo = NULL;
    if(this->data(ITEM_TYPE).toString() == "Door_enter")
    {
        jumpTo =                ItemMenu.addAction(tr("Jump to exit"));
        jumpTo->setVisible((m_data.isSetIn) && (m_data.isSetOut));
    }
    else if(this->data(ITEM_TYPE).toString() == "Door_exit")
    {
        jumpTo =                ItemMenu.addAction(tr("Jump to entrance"));
        jumpTo->setVisible((m_data.isSetIn) && (m_data.isSetOut));
    }
    ItemMenu.addSeparator();
    QAction *NoTransport =     ItemMenu.addAction(tr("No Vehicles"));
    NoTransport->setCheckable(true);
    NoTransport->setChecked(m_data.novehicles);

    QAction *AllowNPC =        ItemMenu.addAction(tr("Allow NPC"));
    AllowNPC->setCheckable(true);
    AllowNPC->setChecked(m_data.allownpc);

    QAction *Locked =          ItemMenu.addAction(tr("Locked"));
    Locked->setCheckable(true);
    Locked->setChecked(m_data.locked);
    QAction *BombNeed =        ItemMenu.addAction(tr("Need a bomb"));
    BombNeed->setCheckable(true);
    BombNeed->setChecked(m_data.need_a_bomb);
    QAction *SpecialStReq =    ItemMenu.addAction(tr("Required special state"));
    SpecialStReq->setCheckable(true);
    SpecialStReq->setChecked(m_data.special_state_required);

    /*************Copy Preferences*******************/
    ItemMenu.addSeparator();
    QMenu *copyPreferences =   ItemMenu.addMenu(tr("Copy preferences"));
    QAction *copyPosXY =        copyPreferences->addAction(tr("Position: X, Y"));
    QAction *copyPosXYWH =      copyPreferences->addAction(tr("Position: X, Y, Width, Height"));
    QAction *copyPosLTRB =      copyPreferences->addAction(tr("Position: Left, Top, Right, Bottom"));
    /*************Copy Preferences*end***************/

    ItemMenu.addSeparator();
    QAction *remove =           ItemMenu.addAction(tr("Remove"));

    ItemMenu.addSeparator();
    QAction *props =            ItemMenu.addAction(tr("Properties..."));

    /*****************Waiting for answer************************/
    QAction *selected = ItemMenu.exec(mouseEvent->screenPos());
    /***********************************************************/

    if(!selected)
        return;

    if(selected == openLvl)
        m_scene->m_mw->OpenFile(m_scene->m_data->meta.path + "/" + m_data.lname);
    else if(selected == jumpTo)
    {
        //scene->doCopy = true ;
        if(this->data(ITEM_TYPE).toString() == "Door_enter")
        {
            if(m_data.isSetOut)
                m_scene->m_mw->activeLvlEditWin()->goTo(m_data.ox, m_data.oy, true, QPoint(0, 0), true);
        }
        else if(this->data(ITEM_TYPE).toString() == "Door_exit")
        {
            if(m_data.isSetIn)
                m_scene->m_mw->activeLvlEditWin()->goTo(m_data.ix, m_data.iy, true, QPoint(0, 0), true);
        }
    }
    else if(selected == NoTransport)
    {
        LevelData modDoors;
        for(QGraphicsItem *SelItem : m_scene->selectedItems())
        {
            if((SelItem->data(ITEM_TYPE).toString() == "Door_exit") || (SelItem->data(ITEM_TYPE).toString() == "Door_enter"))
            {
                if(SelItem->data(ITEM_TYPE).toString() == "Door_exit")
                {
                    LevelDoor door = ((ItemDoor *) SelItem)->m_data;
                    door.isSetOut = true;
                    door.isSetIn = false;
                    modDoors.doors.push_back(door);
                }
                else if(SelItem->data(ITEM_TYPE).toString() == "Door_enter")
                {
                    LevelDoor door = ((ItemDoor *) SelItem)->m_data;
                    door.isSetOut = false;
                    door.isSetIn = true;
                    modDoors.doors.push_back(door);
                }
                ((ItemDoor *) SelItem)->m_data.novehicles = NoTransport->isChecked();
                ((ItemDoor *) SelItem)->arrayApply();
            }
        }
        m_scene->m_history->addChangeSettings(modDoors, HistorySettings::SETTING_NOVEHICLE, QVariant(NoTransport->isChecked()));
        m_scene->m_mw->dock_LvlWarpProps->setDoorData(-2);
    }
    else if(selected == AllowNPC)
    {
        LevelData modDoors;
        for(QGraphicsItem *SelItem : m_scene->selectedItems())
        {
            if((SelItem->data(ITEM_TYPE).toString() == "Door_exit") || (SelItem->data(ITEM_TYPE).toString() == "Door_enter"))
            {
                if(SelItem->data(ITEM_TYPE).toString() == "Door_exit")
                {
                    LevelDoor door = ((ItemDoor *) SelItem)->m_data;
                    door.isSetOut = true;
                    door.isSetIn = false;
                    modDoors.doors.push_back(door);
                }
                else if(SelItem->data(ITEM_TYPE).toString() == "Door_enter")
                {
                    LevelDoor door = ((ItemDoor *) SelItem)->m_data;
                    door.isSetOut = false;
                    door.isSetIn = true;
                    modDoors.doors.push_back(door);
                }
                ((ItemDoor *) SelItem)->m_data.allownpc = AllowNPC->isChecked();
                ((ItemDoor *) SelItem)->arrayApply();
            }
        }
        m_scene->m_history->addChangeSettings(modDoors, HistorySettings::SETTING_ALLOWNPC, QVariant(AllowNPC->isChecked()));
        m_scene->m_mw->dock_LvlWarpProps->setDoorData(-2);
    }
    else if(selected == Locked)
    {
        LevelData modDoors;
        for(QGraphicsItem *SelItem : m_scene->selectedItems())
        {
            if((SelItem->data(ITEM_TYPE).toString() == "Door_exit") || (SelItem->data(ITEM_TYPE).toString() == "Door_enter"))
            {
                if(SelItem->data(ITEM_TYPE).toString() == "Door_exit")
                {
                    LevelDoor door = ((ItemDoor *) SelItem)->m_data;
                    door.isSetOut = true;
                    door.isSetIn = false;
                    modDoors.doors.push_back(door);
                }
                else if(SelItem->data(ITEM_TYPE).toString() == "Door_enter")
                {
                    LevelDoor door = ((ItemDoor *) SelItem)->m_data;
                    door.isSetOut = false;
                    door.isSetIn = true;
                    modDoors.doors.push_back(door);
                }
                ((ItemDoor *) SelItem)->m_data.locked = Locked->isChecked();
                ((ItemDoor *) SelItem)->arrayApply();
            }
        }
        m_scene->m_history->addChangeSettings(modDoors, HistorySettings::SETTING_LOCKED, QVariant(Locked->isChecked()));
        m_scene->m_mw->dock_LvlWarpProps->setDoorData(-2);
    }
    else if(selected == BombNeed)
    {
        LevelData modDoors;
        for(QGraphicsItem *SelItem : m_scene->selectedItems())
        {
            if((SelItem->data(ITEM_TYPE).toString() == "Door_exit") || (SelItem->data(ITEM_TYPE).toString() == "Door_enter"))
            {
                if(SelItem->data(ITEM_TYPE).toString() == "Door_exit")
                {
                    LevelDoor door = ((ItemDoor *) SelItem)->m_data;
                    door.isSetOut = true;
                    door.isSetIn = false;
                    modDoors.doors.push_back(door);
                }
                else if(SelItem->data(ITEM_TYPE).toString() == "Door_enter")
                {
                    LevelDoor door = ((ItemDoor *) SelItem)->m_data;
                    door.isSetOut = false;
                    door.isSetIn = true;
                    modDoors.doors.push_back(door);
                }
                ((ItemDoor *) SelItem)->m_data.need_a_bomb = BombNeed->isChecked();
                ((ItemDoor *) SelItem)->arrayApply();
            }
        }
        m_scene->m_history->addChangeSettings(modDoors, HistorySettings::SETTING_NEED_A_BOMB, QVariant(BombNeed->isChecked()));
        m_scene->m_mw->dock_LvlWarpProps->setDoorData(-2);
    }
    else if(selected == SpecialStReq)
    {
        LevelData modDoors;
        for(QGraphicsItem *SelItem : m_scene->selectedItems())
        {
            if((SelItem->data(ITEM_TYPE).toString() == "Door_exit") || (SelItem->data(ITEM_TYPE).toString() == "Door_enter"))
            {
                if(SelItem->data(ITEM_TYPE).toString() == "Door_exit")
                {
                    LevelDoor door = ((ItemDoor *) SelItem)->m_data;
                    door.isSetOut = true;
                    door.isSetIn = false;
                    modDoors.doors.push_back(door);
                }
                else if(SelItem->data(ITEM_TYPE).toString() == "Door_enter")
                {
                    LevelDoor door = ((ItemDoor *) SelItem)->m_data;
                    door.isSetOut = false;
                    door.isSetIn = true;
                    modDoors.doors.push_back(door);
                }
                ((ItemDoor *) SelItem)->m_data.special_state_required = SpecialStReq->isChecked();
                ((ItemDoor *) SelItem)->arrayApply();
            }
        }
        m_scene->m_history->addChangeSettings(modDoors, HistorySettings::SETTING_W_SPECIAL_STATE_REQUIRED, QVariant(SpecialStReq->isChecked()));
        m_scene->m_mw->dock_LvlWarpProps->setDoorData(-2);
    }
    else if(selected == copyPosXY)
    {
        QApplication::clipboard()->setText(
            QString("X=%1; Y=%2;")
            .arg(m_pointSide == D_Entrance ? m_data.ix : m_data.ox)
            .arg(m_pointSide == D_Entrance ? m_data.iy : m_data.oy)
        );
        m_scene->m_mw->showStatusMsg(tr("Preferences have been copied: %1").arg(QApplication::clipboard()->text()));
    }
    else if(selected == copyPosXYWH)
    {
        QApplication::clipboard()->setText(
            QString("X=%1; Y=%2; W=%3; H=%4;")
            .arg(m_pointSide == D_Entrance ? m_data.ix : m_data.ox)
            .arg(m_pointSide == D_Entrance ? m_data.iy : m_data.oy)
            .arg(m_itemSize.width())
            .arg(m_itemSize.height())
        );
        m_scene->m_mw->showStatusMsg(tr("Preferences have been copied: %1").arg(QApplication::clipboard()->text()));
    }
    else if(selected == copyPosLTRB)
    {
        QApplication::clipboard()->setText(
            QString("Left=%1; Top=%2; Right=%3; Bottom=%4;")
            .arg(m_pointSide == D_Entrance ? m_data.ix : m_data.ox)
            .arg(m_pointSide == D_Entrance ? m_data.iy : m_data.oy)
            .arg((m_pointSide == D_Entrance ? m_data.ix : m_data.ox) + m_itemSize.width())
            .arg((m_pointSide == D_Entrance ? m_data.iy : m_data.oy) + m_itemSize.height())
        );
        m_scene->m_mw->showStatusMsg(tr("Preferences have been copied: %1").arg(QApplication::clipboard()->text()));
    }
    else if(selected == remove)
        m_scene->removeSelectedLvlItems();
    else if(selected == props)
        m_scene->m_mw->dock_LvlWarpProps->SwitchToDoor(m_data.meta.array_id);
    else if(selected == newLayer)
    {
        m_scene->setLayerToSelected();
        m_scene->applyLayersVisible();
    }
    else
    {
        //Fetch layers menu
        foreach(QAction *lItem, layerItems)
        {
            if(selected == lItem)
            {
                //FOUND!!!
                m_scene->setLayerToSelected(lItem->data().toString());
                m_scene->applyLayersVisible();
                m_scene->m_mw->dock_LvlWarpProps->setDoorData(-2);
                break;
            }//Find selected layer's item
        }
    }
}
Ejemplo n.º 28
0
bool ProjectSettingsDialog::ExecutableIsValid(QString execLocation)
{
	if (QFile(execLocation).exists())
		return true;
	return false;
}
Ejemplo n.º 29
0
void HttpGet::getFileFinish()
{
    m_cachefile = m_cachedir.absolutePath() + "/rbutil-cache/" + m_hash;
    QString indexFile = m_cachedir.absolutePath() + "/rbutil-cache/cache.txt";
    if(m_usecache) {
        // check if the file is present in cache
        QFileInfo cachefile = QFileInfo(m_cachefile);
        if(cachefile.isReadable()
            && cachefile.size() > 0
            && cachefile.lastModified() > m_serverTimestamp) {

            qDebug() << "[HTTP] Cache: up-to-date file found:" << m_cachefile;

            getRequest = -1;
            QFile c(m_cachefile);
            if(!outputToBuffer) {
                qDebug() << "[HTTP] Cache: copying file to output"
                         << outputFile->fileName();
                c.open(QIODevice::ReadOnly);
                outputFile->open(QIODevice::ReadWrite);
                outputFile->write(c.readAll());
                outputFile->close();
                c.close();
            }
            else {
                qDebug() << "[HTTP] Cache: reading file into buffer";
                c.open(QIODevice::ReadOnly);
                dataBuffer = c.readAll();
                c.close();
            }
            m_response = 200; // fake "200 OK" HTTP response
            m_cached = true;
            httpDone(false); // we're done now. Handle http "done" signal.
            return;
        }
        else {
            // unlink old cache file
            if(cachefile.isReadable()) {
                QFile(m_cachefile).remove();
                qDebug() << "[HTTP] Cache: outdated, timestamp:"
                         << cachefile.lastModified();
            }
            qDebug() << "[HTTP] Cache: caching as" << m_cachefile;
            // update cache index file
            QFile idxFile(indexFile);
            idxFile.open(QIODevice::ReadOnly);
            QByteArray currLine;
            do {
                QByteArray currLine = idxFile.readLine(1000);
                if(currLine.startsWith(m_hash.toUtf8()))
                    break;
            } while(!currLine.isEmpty());
            idxFile.close();
            if(currLine.isEmpty()) {
                idxFile.open(QIODevice::Append);
                QString outline = m_hash + "\t" + m_header.value("Host") + "\t"
                    + m_path + "\t" + m_query + "\n";
                idxFile.write(outline.toUtf8());
                idxFile.close();
            }
        }

    }
    else {
        qDebug() << "[HTTP] cache DISABLED";
    }
    // schedule GET request

    m_header.setRequest("GET", m_path + m_query);
    if(outputToBuffer) {
        qDebug() << "[HTTP] downloading to buffer.";
        getRequest = http.request(m_header);
    }
    else {
        qDebug() << "[HTTP] downloading to file:"
            << qPrintable(outputFile->fileName());
       getRequest = http.request(m_header, 0, outputFile);
    }
    qDebug() << "[HTTP] GET scheduled:   " << getRequest;

    return;
}
Ejemplo n.º 30
0
int main(int argc, char *argv[])
{
    //It cannot properly fall back to Qt Widgets versions of the dialogs if
    // we use a QGuiApplication, which only supports QML stuff.
    //QGuiApplication app(argc, argv);
    QApplication app(argc, argv);

    //This is for the QSettings defaults from things like the qt file dialog and stuff...
    app.setApplicationName("Filmulator");
    app.setOrganizationName("Filmulator");

    QFont sansFont("Sans Serif",9);
    app.setFont(sansFont);
    QQmlApplicationEngine engine;

    QTranslator translator;
    translator.load("filmulatortr_la");
    app.installTranslator(&translator);

    //Prepare database connection.
    //This should create a new db file if there was none.
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    setupDB(&db);

    //Create the object for communicating between SQL classes.
    SignalSwitchboard *switchboard = new SignalSwitchboard;

    //Create a settings object for persistent settings.
    Settings *settingsObj = new Settings;
    engine.rootContext()->setContextProperty("settings", settingsObj);

    //Prepare an object for managing the processing parameters.
    ParameterManager *paramManager = new ParameterManager;
    engine.rootContext()->setContextProperty("paramManager",paramManager);
    QObject::connect(paramManager, SIGNAL(updateTableOut(QString, int)),
                     switchboard, SLOT(updateTableIn(QString, int)));

    //Prepare an image provider object.
    FilmImageProvider *filmProvider = new FilmImageProvider(paramManager);
    //Connect it as an image provider so that qml can get the photos
    engine.addImageProvider(QLatin1String("filmy"), filmProvider);
    //Connect it as a Q_OBJECT so that qml can run methods
    engine.rootContext()->setContextProperty("filmProvider",filmProvider);

    qRegisterMetaType<QFileInfo>();

    //Prepare a model for importing.
    ImportModel *importModel = new ImportModel;
    engine.rootContext()->setContextProperty("importModel", importModel);

    //Prepare a model for the organize view.
    OrganizeModel *organizeModel = new OrganizeModel;
    engine.rootContext()->setContextProperty("organizeModel", organizeModel);
    engine.rootContext()->setContextProperty("dateHistoModel", organizeModel->dateHistogram);
    QObject::connect(switchboard, SIGNAL(updateTableOut(QString,int)),
                     organizeModel, SLOT(updateTable(QString,int)));
    QObject::connect(organizeModel, SIGNAL(updateTableOut(QString,int)),
                     switchboard, SLOT(updateTableIn(QString,int)));

    //Prepare a model for the queue view.
    QueueModel *queueModel = new QueueModel;
    queueModel->setQueueQuery();
    QObject::connect(switchboard, SIGNAL(updateTableOut(QString, int)),
                     queueModel, SLOT(updateTable(QString, int)));
    QObject::connect(importModel, SIGNAL(enqueueThis(QString)),
                     queueModel, SLOT(enQueue(QString)));
    engine.rootContext()->setContextProperty("queueModel", queueModel);

    if (QFile("qml/filmulator-gui/main.qml").exists())
    {
        cout << "loading UI from copy in directory" << endl;
        engine.load(QUrl::fromLocalFile("qml/filmulator-gui/main.qml"));
    }
    else if (QFile("/usr/lib/filmulator-gui/qml/filmulator-gui/main.qml").exists())
    {
        cout << "loading UI from /usr/lib/" << endl;
        engine.load(QUrl::fromLocalFile("/usr/lib/filmulator-gui/qml/filmulator-gui/main.qml"));
    }
    else
    {
        qWarning("QML UI file missing");
        return -1;
    }

    QObject *topLevel = engine.rootObjects().value(0);
    QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
    if (!window) {
        qWarning("Error: your root item has to be a Window");
        return -1;
    }
    window->setIcon(QIcon(":/icons/filmulator64icon.svg"));
    window->show();

    return app.exec();
}