Пример #1
0
	void Plugin::checkSavedReports ()
	{
		const auto& dolozheeDir = Util::CreateIfNotExists ("dolozhee");

		auto news = dolozheeDir;
		if (!news.cd ("crashreports"))
			return;

		news.mkdir ("old");

		QStringList names;
		for (const auto& name : news.entryList (QDir::Files | QDir::NoDotAndDotDot))
		{
			const auto& newName = news.absoluteFilePath ("old/" + name);
			if (!QFile::rename (news.absoluteFilePath (name), newName))
				continue;

			names << newName;
		}

		if (names.isEmpty ())
			return;

		auto wizard = initiateReporting ();
		wizard->GetReportTypePage ()->ForceReportType (ReportTypePage::Type::Bug);

		auto attachPage = wizard->GetFilePage ();
		for (const auto& name : names)
			attachPage->AddFile (name);
	}
Пример #2
0
void SettingsDialog::accept()
{
    auto autoSave = QFileInfo(ui->autoSaveDirectory->text());
    if (!autoSave.exists())
    {
        QDir().mkpath(autoSave.absoluteFilePath());

    }
    if (!autoSave.exists() || !autoSave.isDir() || !autoSave.isWritable())
    {
        QMessageBox msg(this);
        msg.setIcon(QMessageBox::Warning);
        msg.setText("Can not access auto save directory");
        msg.setInformativeText(QString("Can not access auto save directory %1").arg(autoSave.absoluteFilePath()));
        msg.exec();
        return;
    }
    QSettings settings;
    settings.setValue("colorBackground", ui->background->currentIndex());
    settings.setValue("breakLines", ui->breakLines->isChecked());
    settings.setValue("maxMessages", ui->maxMessages->value());
    settings.setValue("autoSaveDirectory", ui->autoSaveDirectory->text());
    settings.setValue("timestampPrecision", ui->timestampFormat->currentIndex());
    QDialog::accept();
}
Пример #3
0
void Convert(const QString & css_name, const QString & path_in, const QString & path_out )
{
    auto path_css = qApp->applicationDirPath()+"/styles/"+css_name;
    if ( !QFile::exists(path_css) ) {
        path_css = "://highlight/styles/default.css";
    }
    const auto dir = QFileInfo(path_out).absoluteDir();
    QFile::copy(path_css,dir.absoluteFilePath(css_name)) ;
    QFile::copy("://highlight/highlight.pack.js",dir.absoluteFilePath("highlight.pack.js")) ;


    QFile f(path_in);
    if ( !f.open(QFile::ReadOnly|QFile::Text) ) {
        return;
    }
    auto code = QString(f.readAll()).toHtmlEscaped();
    f.close();

    f.setFileName("://highlight/constant.html");
    if ( !f.open(QFile::ReadOnly|QFile::Text) ) {
        return;
    }
    auto html = QString(f.readAll());
    f.close();
    html.replace(g_str_code,code);
    html.replace(g_str_type,QFileInfo(path_in).suffix());
    html.replace(g_str_css,css_name);

    f.setFileName(path_out);
    if ( !f.open(QFile::WriteOnly|QFile::Text) ){
        return;
    }
    f.write(html.toUtf8());
    f.close();
}
Пример #4
0
void LocalDiskRepo::putFileComplete(QIODevice* device, QString file_path)
{
    qDebug() << "saving file";
    disconnect(device, SIGNAL(aboutToClose()), this, SLOT(putFileFailed()));
    QFile* f = (QFile*) device;
    if (!QFile::exists(absoluteFilePath(file_path))) {
        qDebug() << "renaming writebuffer and closing";
        f->rename(absoluteFilePath(file_path));
    } else {
        // keeping as temporary
        qCritical() << "file with file_path:" << file_path << " already exists";
        f->close();
    }
}
Пример #5
0
QUrl searchForResourceSearchPath(const QUrl& baseUrl,
                                 const QUrl& url,
                                 const QStringList& searchPath)
{
  if (url.isRelative()) {
    if (!baseUrl.isLocalFile()) {
      return baseUrl.resolved(url);
    }

    auto path = url.path();
    if (!path.startsWith("/")) {
      auto resolvedUrl = baseUrl.resolved(url);
      if (QFile::exists(resolvedUrl.toLocalFile())) {
        return resolvedUrl;
      }
    } else if (!path.contains("/../")) {
      auto pathRelPart = path.split(QRegularExpression("^/+"))[1];
      for (const auto& str : searchPath) {
        auto dir = QDir(str);
        auto absPath = QDir::cleanPath(dir.absoluteFilePath(pathRelPart));

        if (QFile::exists(absPath)) {
          return QUrl::fromLocalFile(absPath);
        }
      }

      return QUrl();
    } else {
      return QUrl();
    }
  }

  return url;
}
Пример #6
0
bool FileUtils::moveFile(const QString path)
{
    if(currentFilePath == QDir(path).path()){
        qDebug()<<tr("The image wasn't moved\nThe new folder is iqual to the older");
        newFolder = false;
        return false;
    }

    //the new file name
    QString newFileName = path + QDir::separator() + getFileName();

    //check if there is an existing file with the same name
    if(QFile(newFileName).exists()){
        //ask if wish to overwrite
        int result = QMessageBox::question(0, tr("Overwrite?"),
                    tr("File %1 already exists. Do you want to overwrite it?").arg(getFileName()),
                    QMessageBox::Yes|QMessageBox::No);

        //if doesn't want return;
        if (result == QMessageBox::No){
            return false;
        }

        //else remove the previous file
        QFile::remove(newFileName);
    }

    bool d = QFile(absoluteFilePath()).rename(newFileName);
    if(d){
        this->openFile(newFileName);
    }

    return d;
}
Пример #7
0
//-----------------------------------------------------------------
QList<QFileInfo> Utils::findFiles(const QDir initialDir,
                                  const QStringList extensions,
                                  bool with_subdirectories,
                                  const std::function<bool (const QFileInfo &)> &condition)
{
  QList<QFileInfo> otherFilesFound, mp3FilesFound;

  auto startingDir = initialDir;
  startingDir.setFilter(QDir::Files | QDir::Dirs | QDir::NoDot | QDir::NoDotDot);
  startingDir.setNameFilters(extensions);

  auto flag = (with_subdirectories ? QDirIterator::Subdirectories : QDirIterator::NoIteratorFlags);
  QDirIterator it(startingDir, flag);
  while (it.hasNext())
  {
    it.next();

    auto info = it.fileInfo();

    if(!condition(info)) continue;

    auto extension = info.absoluteFilePath().split('.').last().toLower();

    if (isMP3File(info))
    {
      mp3FilesFound << info;
    }
    else
    {
      otherFilesFound << info;
    }
  }

  return mp3FilesFound + otherFilesFound;
}
Пример #8
0
QUrl ModelBaker::getTextureURL(const QFileInfo& textureFileInfo, QString relativeFileName, bool isEmbedded) {
    QUrl urlToTexture;

    // use QFileInfo to easily split up the existing texture filename into its components
    auto apparentRelativePath = QFileInfo(relativeFileName.replace("\\", "/"));

    if (isEmbedded) {
        urlToTexture = _modelURL.toString() + "/" + apparentRelativePath.filePath();
    } else {
        if (textureFileInfo.exists() && textureFileInfo.isFile()) {
            // set the texture URL to the local texture that we have confirmed exists
            urlToTexture = QUrl::fromLocalFile(textureFileInfo.absoluteFilePath());
        } else {
            // external texture that we'll need to download or find

            // this is a relative file path which will require different handling
            // depending on the location of the original model
            if (_modelURL.isLocalFile() && apparentRelativePath.exists() && apparentRelativePath.isFile()) {
                // the absolute path we ran into for the texture in the model exists on this machine
                // so use that file
                urlToTexture = QUrl::fromLocalFile(apparentRelativePath.absoluteFilePath());
            } else {
                // we didn't find the texture on this machine at the absolute path
                // so assume that it is right beside the model to match the behaviour of interface
                urlToTexture = _modelURL.resolved(apparentRelativePath.fileName());
            }
        }
    }

    return urlToTexture;
}
QVariant RecordingsModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
    {
        return QVariant();
    }

    auto fileInfo = mData[index.row()];

    switch (role)
    {
    case FilePath:
        return fileInfo.absoluteFilePath();
    case FileName:
        return fileInfo.fileName();
    case FileDir:
        return fileInfo.absolutePath();
    case Modified:
        return fileInfo.lastModified();
    case Section:
        return RecordingsModel::sectionName(fileInfo.lastModified().date());
    default:
        return QVariant();
    }
}
Пример #10
0
QList<ImageSourceItem> QuaZipImageSource::getImageInfoFromArchive(QuaZip *archive, const QString &extractPath)
{
    archive->open(QuaZip::mdUnzip);

    auto i = 0;
    auto images = QList<ImageSourceItem>();
    auto fileNames = archive->getFileNameList();

    fileNames.sort(Qt::CaseInsensitive);
    for (const auto &fileName : fileNames) {

        // Get the file information.
        auto fileInfo = QFileInfo(extractPath + "/" + fileName);
        auto suffix = fileInfo.suffix();
        auto relativePath = fileName;
        relativePath.chop(fileInfo.fileName().length());

        // Insert the file into the list if it is an image file.
        if (Utility::imageFileTypes().contains(suffix, Qt::CaseInsensitive)) {
            auto extractPath = fileInfo.absoluteFilePath();
            auto image = std::make_shared<ImageInfo>(extractPath, relativePath);
            images.append({++i, image});
        }
    }

    archive->close();

    return images;
}
Пример #11
0
/*!
    Converts the file's path to an absolute path if it is not already in that form.
    Returns true to indicate that the path was converted; otherwise returns false
    to indicate that the path was already absolute.

    \sa filePath(), isRelative()
*/
bool QFileInfo::makeAbsolute()
{
    if (d_ptr.constData()->isDefaultConstructed
            || !d_ptr.constData()->fileEntry.isRelative())
        return false;

    setFile(absoluteFilePath());
    return true;
}
Пример #12
0
QStringList listDir(const QString &path) {
    QStringList result;
    QStringList dirList = {path};
    while (!dirList.isEmpty()) {
        QDir dir(dirList.takeFirst());
        if (!dir.exists())
            continue;
        foreach (auto d, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot)) {
            dirList.append(dir.absoluteFilePath(d));
        }
        auto files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);
        if (files.isEmpty()) {
            result.append(dir.absoluteFilePath(".sxnewdir"));
            continue;
        }
        foreach (auto file, files) {
            result.append(dir.absoluteFilePath(file));
        }
    }
Пример #13
0
    FileReaderPtr QtFileSystem::openFile(const std::string& path)
    {
        std::unique_ptr<QFile> file(new QFile(absoluteFilePath(path)));

        if (!file->open(QFile::ReadOnly)) {
            Z_LOG("Unable to open file \"" << zqUtf8Printable(file->fileName()) << "\": "
                << zqUtf8Printable(file->errorString()) << ".");
            return FileReaderPtr();
        }

        return std::make_shared<QtFileReader>(path, std::move(file));
    }
Пример #14
0
void UIWizardNewVDPage3::onSelectLocationButtonClicked()
{
    /* Get current folder and filename: */
    QFileInfo fullFilePath(mediumPath());
    QDir folder = fullFilePath.path();
    QString strFileName = fullFilePath.fileName();

    /* Set the first parent folder that exists as the current: */
    while (!folder.exists() && !folder.isRoot())
    {
        QFileInfo folderInfo(folder.absolutePath());
        if (folder == QDir(folderInfo.absolutePath()))
            break;
        folder = folderInfo.absolutePath();
    }

    /* But if it doesn't exists at all: */
    if (!folder.exists() || folder.isRoot())
    {
        /* Use recommended one folder: */
        QFileInfo defaultFilePath(absoluteFilePath(strFileName, m_strDefaultPath));
        folder = defaultFilePath.path();
    }

    /* Prepare backends list: */
    QVector<QString> fileExtensions;
    QVector<KDeviceType> deviceTypes;
    CMediumFormat mediumFormat = fieldImp("mediumFormat").value<CMediumFormat>();
    mediumFormat.DescribeFileExtensions(fileExtensions, deviceTypes);
    QStringList validExtensionList;
    for (int i = 0; i < fileExtensions.size(); ++i)
        if (deviceTypes[i] == KDeviceType_HardDisk)
            validExtensionList << QString("*.%1").arg(fileExtensions[i]);
    /* Compose full filter list: */
    QString strBackendsList = QString("%1 (%2)").arg(mediumFormat.GetName()).arg(validExtensionList.join(" "));

    /* Open corresponding file-dialog: */
    QString strChosenFilePath = QIFileDialog::getSaveFileName(folder.absoluteFilePath(strFileName),
                                                              strBackendsList, thisImp(),
                                                              VBoxGlobal::tr("Please choose a location for new virtual hard drive file"));

    /* If there was something really chosen: */
    if (!strChosenFilePath.isEmpty())
    {
        /* If valid file extension is missed, append it: */
        if (QFileInfo(strChosenFilePath).suffix().isEmpty())
            strChosenFilePath += QString(".%1").arg(m_strDefaultExtension);
        m_pLocationEditor->setText(QDir::toNativeSeparators(strChosenFilePath));
        m_pLocationEditor->selectAll();
        m_pLocationEditor->setFocus();
    }
}
Пример #15
0
void RenderDialog::accept()
{
	if (QFileInfo(absoluteFilePath()).exists())
	{
		QMessageBox::StandardButton b = QMessageBox::question(this,
			tr("File already exists"),
			tr("Do you want to overwrite %1?")
				.arg(QFileInfo(absoluteFilePath()).fileName()),
			QMessageBox::Yes | QMessageBox::No,
			QMessageBox::NoButton );
		if (b == QMessageBox::No)
			return;
	}

	QSettings settings;
	size = m_sizeComboBox->currentText();
	preset = m_qualityComboBox->currentText();

	m_sizeComboBox->removeItem(m_sizeComboBox->currentIndex());

	settings.beginWriteArray("renderdialog/sizes");
	settings.setArrayIndex(0);
	settings.setValue("dim", size);

	int cnt = 10;
	for (int i = 0; i < cnt; ++i)
	{
		QString text(m_sizeComboBox->itemText(i));
		if (text.isEmpty())
			break;
		settings.setArrayIndex(i+1);
		settings.setValue("dim", text);
	}
	settings.endArray();
	settings.setValue("renderdialog/last_size", size);
	settings.setValue("renderdialog/last_quality", preset);

	QDialog::accept();
}
Пример #16
0
/*!
 * Enqueues track on channel
 */
bool SingleshotManager::enqueue(int channel) {
    objects_tracks_model->selectObject(container.at(channel)->getOID());
    int tid = objects_tracks_model->selectRandomTrack();
    QString current_library_filter = library_model->filter();
    library_model->setFilter(QString("id=%1").arg(tid));
    QString choice_filename = library_model->data(library_model->index(0, 1)).toString();
    library_model->setFilter(current_library_filter);
    if(choice_filename.isEmpty()) {
        return false;
    }
    container.at(channel)->loadFile(absoluteFilePath(choice_filename), false);
    return true;
}
Пример #17
0
void ImageItem::rotate(short degrees)
{
  if (!degrees)
    return;

  QString file = absoluteFilePath();
  Magick::Image image;
  image.read(file.toStdString());
  image.rotate(degrees);
  image.write(file.toStdString());

  Magick::Blob buffer;
  image.write(&buffer);

  QImage thumbnail;
  thumbnail.loadFromData((const uchar*) buffer.data(), buffer.length());
  thumbnail.save(absoluteThumbPath(), "JPEG");
}
Пример #18
0
void QuaZipImageSource::extractAll()
{
    _archive->open(QuaZip::mdUnzip);
    _archive->goToFirstFile();

    // Keep track of the images that have not been extracted yet.
    auto images = QList<ImageSourceItem>(_images);
    auto index = 0;

    while (!images.isEmpty() && !_extractWatcher.isCanceled()) {

        // If the currently displayed image has changed and has not yet been
        // extracted, change the index to that image.
        if (_currentFileNameChanged) {
            auto i = std::find_if(images.begin(), images.end(), [&](ImageSourceItem a) {
                return a.second->relativeFilePath() == _currentFileName;
            });

            if (i != images.end()) {
                index = i - images.begin();
            }
        }

        // Loop through the list of images.
        if (index >= images.size()) {
            index = 0;
        }

        // Extract the image.
        auto file = images.at(index).second;
        if (!file->exists()) {
            _archive->setCurrentFile(file->relativeFilePath());
            this->extractImage(_archive.get(), file->absoluteFilePath());
            emit imageReady(file->relativeFilePath());
        }

        // Since the image is removed, the index remains the same.
        images.removeAt(index);
    }

    _archive->close();
}
Пример #19
0
/*!
 * Sets delay and starts timefr in media_container
 */
void SfxManager::playDelayed(int cid) {
    #ifdef _WIN32
    qrand();
    #endif
    QStringList channel = objects_tracks.at(cid);
    int min = channel[1].toInt() - channel[2].toInt();
    int max = channel[1].toInt() + channel[3].toInt();
    int start = (qrand()%(max-min+1))+min;
    qDebug() << identifier << cid << "delay" << start;

    container.at(cid)->stop();

    QSqlQuery query;
    query.prepare(QString("SELECT `path` FROM %1 WHERE `id` = :tid LIMIT 1").arg(library_identifier));
    query.bindValue(":tid", channel[0]);
    query.exec();

    if (query.first() && channel.at(4).toInt() == true) {
        container.at(cid)->loadFile(absoluteFilePath(query.value(0).toString()), false);
        container.at(cid)->play(start);
    }
}
Пример #20
0
QImage ImageItem::previewRotate(short degrees)
{
  Magick::Image image;
  if (m_tempImage) {
    m_tempImage->open();
    image.read(m_tempImage->fileName().toStdString());
    image.magick("jpg");
  } else {
    image.read(absoluteFilePath().toStdString());
    m_tempImage = new QTemporaryFile(qApp);
    m_tempImage->open();
  }

  image.rotate(degrees);
  Magick::Blob buffer;
  image.write(&buffer);

  QImage output;
  output.loadFromData((const uchar*) buffer.data(), buffer.length());
  output.save(m_tempImage, "JPEG");
  m_tempImage->close();
  return output;
}
Пример #21
0
//-----------------------------------------------------------------
QString Utils::formatString(const QString filename,
                            const Utils::FormatConfiguration &conf,
                            bool add_mp3_extension)
{
  // works for filenames and plain strings
  QString formattedName = filename;

  auto fileInfo = QFileInfo(filename);
  if(fileInfo.exists())
  {
    formattedName = fileInfo.absoluteFilePath().split('/').last();

    auto extension = formattedName.split('.').last();
    auto extension_id = QString("*.") + extension;
    bool identified = WAVE_FILE_EXTENSIONS.contains(extension_id)   ||
                      MODULE_FILE_EXTENSIONS.contains(extension_id) ||
                      MOVIE_FILE_EXTENSIONS.contains(extension_id);

    if (identified)
    {
      formattedName.remove(formattedName.lastIndexOf('.'), extension.length() + 1);
    }
  }

  if (conf.apply)
  {
    // delete specified chars
    for (int i = 0; i < conf.chars_to_delete.length(); ++i)
    {
      formattedName.remove(conf.chars_to_delete[i], Qt::CaseInsensitive);
    }

    // replace specified strings
    for (int i = 0; i < conf.chars_to_replace.size(); ++i)
    {
      auto charPair = conf.chars_to_replace[i];
      formattedName.replace(charPair.first, charPair.second, Qt::CaseInsensitive);
    }

    // remove consecutive spaces
    QStringList parts = formattedName.split(' ');
    parts.removeAll("");

    formattedName.clear();
    int index = 0;

    // adjust the number prefix and insert the default separator.
    // Format 1: 01 ...
    QRegExp re1("\\d*");
    auto re1_match = re1.exactMatch(parts[index]);

    // Format 2: 1-01 ...
    QRegExp re2("\\d-\\d*");
    auto re2_match = re2.exactMatch(parts[index]);

    // only check number format if it exists
    if (re1_match || re2_match)
    {
      QString number_string, number_disc_id;
      if(re1_match)
      {
        number_string = parts[index];
      }
      else
      {
        auto splits = parts[index].split('-');
        number_disc_id = splits.first();
        number_string = splits.last();
      }

      while (conf.number_of_digits > number_string.length())
      {
        number_string = "0" + number_string;
      }

      if (index != parts.size() - 1)
      {
        if(parts[index + 1] != QString(conf.number_and_name_separator))
        {
          number_string += QString(' ' + conf.number_and_name_separator + ' ');
        }
        else
        {
          parts[index + 1] = QString(' ' + conf.number_and_name_separator);
        }
      }

      if(!number_disc_id.isEmpty() && conf.prefix_disk_num)
      {
        number_string = number_disc_id + QString("-") + number_string;
      }
      formattedName = number_string;
      ++index;
    }

    // capitalize the first letter of every word
    if (conf.to_title_case)
    {
      int i = index;
      while (i < parts.size())
      {
        if (parts[i].isEmpty()) continue;
        bool starts_with_parenthesis = false;
        bool ends_with_parenthesis = false;
        bool starts_with_quote = false;
        bool ends_with_quote = false;
        int begin_quote_num = 0;
        int end_quote_num = 0;

        if(parts[i].startsWith('(') && parts[i].size() > 1)
        {
          starts_with_parenthesis = true;
          parts[i].remove('(');
        }

        if(parts[i].endsWith(')') && parts[i].size() > 1)
        {
          ends_with_parenthesis = true;
          parts[i].remove(')');
        }
        
        if(parts[i].startsWith('\'') && parts[i].size() > 1)
        {
          starts_with_quote = true;
          while(parts[i].at(begin_quote_num) == QChar('\'') && begin_quote_num < parts[i].size())
          {
            ++begin_quote_num;
          }
        }
        
        if(parts[i].endsWith('\'') && parts[i].size() > 1)
        {
          ends_with_quote = true;
          auto part_size = parts[i].size() - 1;
          while(parts[i].at(part_size - end_quote_num) == QChar('\'') && end_quote_num < parts[i].size())
          {
            ++end_quote_num;
          }
        }

        if(starts_with_quote || ends_with_quote)
        {
          parts[i].remove(QChar('\''));
        }

        if(!isRomanNumeral(parts[i]))
        {
          parts[i] = parts[i].toLower();
          parts[i].replace(0, 1, parts[i].at(0).toUpper());
        }

        if(starts_with_quote)
        {
          while(begin_quote_num > 0)
          {
            parts[i].insert(0, QChar('\''));
            --begin_quote_num;
          }
        }

        if(ends_with_quote)
        {
          while(end_quote_num > 0)
          {
            parts[i].append(QChar('\''));
            --end_quote_num;
          }
        }

        if (starts_with_parenthesis)
        {
          parts[i] = QString('(') + parts[i];
        }

        if (ends_with_parenthesis)
        {
          parts[i] = parts[i] + QString(')');
        }

        ++i;
      }
    }

    if(index < parts.size())
    {
      formattedName += parts[index++];
    }

    // compose the name.
    while (index < parts.size())
    {
      formattedName += ' ' + parts[index++];
    }
  }

  if(add_mp3_extension)
  {
    formattedName += ".mp3";
  }

  // remove any unwanted spaces
  formattedName = formattedName.simplified();

  // check for unwanted unicode chars
  while(formattedName.toLatin1().contains('?'))
  {
    auto index = formattedName.toLatin1().indexOf('?');

    switch(formattedName.at(index).category())
    {
      case QChar::Punctuation_InitialQuote:
      case QChar::Punctuation_FinalQuote:
        formattedName = formattedName.replace(formattedName.at(index), QString("''"));
        break;
      case QChar::Punctuation_Dash:
        formattedName = formattedName.replace(formattedName.at(index), '-');
        break;
      default:
        formattedName = formattedName.replace(formattedName.at(index), ' ');
    }
  }

  return formattedName;
}
Пример #22
0
void UTLauncher::startServerBrowser()
{
    splashTimer.singleShot(2000, this, SLOT(closeSplash()));

    if(!settings.value("StartMinimized", false).toBool()) {
        browser->show();
    } else {
        qApp->setQuitOnLastWindowClosed(false); // workaround for app not starting
    }
    browser->setMOTD(bootstrap.MOTD());
    
    auto hasEditorSupport = [=] {
        QString editorPath = bootstrap.editorExePath();
        QString projectPath = bootstrap.projectPath();
        return QFile::exists(editorPath) && QFile::exists(projectPath);
    };
    
    auto openSettings = [=](bool mandatoryEditor = false) {
        ConfigDialog dialog(settings, mandatoryEditor);
        dialog.exec();
        browser->setEditorSupport(hasEditorSupport());
        
        browser->setHideOnClose(settings.value("MinimizeToTrayOnClose").toBool());
    };
    
    connect(browser, &ServerBrowser::openServer, [=](QString url, bool spectate, bool inEditor) {

        if(inEditor) {
            QString editorPath = bootstrap.editorExePath();
            QString projectPath = bootstrap.projectPath();
            if(!editorPath.length() || !projectPath.length()) {
                openSettings(true);
                return;
            }
            QProcess::startDetached(editorPath, QStringList() << projectPath << "-GAME" << (url + (spectate?"?SpectatorOnly=1":"")) );
        } else {
            QString exePath = bootstrap.programExePath();
            if(!exePath.length()) {
                openSettings();
                return;
            }
            const auto serverEntry = browser->serverEntryFromAddress(url);
            auto launch = [=] {
                qDebug() << "Launching!!\n";
              QProcess::startDetached(exePath, QStringList()
#ifdef LAUNCH_WITH_UE4
                << "UnrealTournament"
#endif
                << (url + (spectate?"?SpectatorOnly=1":"")) 
                << "-SaveToUserDir");
            };
                        
            if(serverEntry) {
                if(bootstrap.isStockMap(serverEntry->map)) {
                    launch();
                    return;
                }
                

                QString exePath = bootstrap.programExePath();
                QFileInfo exeInfo(exePath);
                auto contentDir = QDir(exeInfo.dir());
                contentDir.cdUp();
                contentDir.cdUp();
                contentDir.cd("Content");
                auto zipFilePath = contentDir.absoluteFilePath(serverEntry->map + ".zip");
                
                if(QFile::exists(zipFilePath)) {
                    launch();
                    return;
                }

                Download mapDownload;
                mapDownload.setTarget("https://ut.rushbase.net/customcontent/Data/" + serverEntry->map + ".zip");
                QProgressDialog dialog("Downloading map: " + serverEntry->map, "Cancel", 0, 100);
                
                QFile zipFile(zipFilePath);
                zipFile.open(QIODevice::WriteOnly);
                
                int httpCode = 200;
                connect(&mapDownload, &Download::error, [&](int code) {
                    httpCode = code;
                    if(code != 200) {
                        zipFile.remove();
                        QMessageBox::critical(nullptr, "Unable to download map", QString("Got code %1 while trying to download map:<br>%2").arg(code).arg(serverEntry->map));
                    }
                });
                
                connect(&mapDownload, &Download::chunk, [&](QByteArray chunk) {
                    qDebug() << "Reading!\n";
                    zipFile.write(chunk);
                });
                connect(&mapDownload, &Download::progress, [&](double progress) {
                    dialog.setValue(100*progress);
                    if(progress == 1.0) {
                        dialog.accept();
                    }
                });
                
                
                mapDownload.download();
                qDebug() << "Downloading map " << serverEntry->map;
                if(!dialog.exec() || httpCode != 200) {
                    zipFile.remove(); // remove unfinished download
                    return;
                }
                zipFile.close();
                
                QProgressDialog installDialog("Installing map: " + serverEntry->map, "", 0, 100);
                installDialog.setWindowModality(Qt::ApplicationModal);
                installDialog.show();
                installDialog.setValue(0);
                
                qDebug() << "Installed!!\n";
                QuaZip zip(zipFilePath);
                
                auto textCodec = QTextCodec::codecForName("TSCII");
                zip.setFileNameCodec(textCodec);
                zip.setCommentCodec(textCodec);
                zip.open(QuaZip::mdUnzip);

                QuaZipFile file(&zip);

                size_t totalSize = 0;
                for(bool f=zip.goToFirstFile(); f; f=zip.goToNextFile()) {
                    QuaZipFileInfo info;
                    zip.getCurrentFileInfo(&info);
                    totalSize += info.uncompressedSize;
                }
                qDebug() << "Total size " << totalSize;
                size_t accumulatedSize = 0;
                /* TODO!!!!: this whole thing needs to be redone asynchronously */
                for(bool f=zip.goToFirstFile(); f; f=zip.goToNextFile()) {
                    file.open(QIODevice::ReadOnly);
                    //same functionality as QIODevice::readData() -- data is a char*, maxSize is qint64
                    //file.readData(data,maxSize);
                    QString filename = file.getActualFileName();
                    if(file.isOpen()) {
                        qApp->processEvents();
                        qDebug() << installDialog.isVisible() << installDialog.value();
                        if(!installDialog.isVisible() && installDialog.value() != 100 && installDialog.value() != -1)
                            return;
                        bool isDir = (filename.right(1) == "/");
                        if(isDir) {
                            contentDir.mkpath(filename);
                        } else {
                            QFile f(contentDir.absoluteFilePath(filename));
                            f.open(QIODevice::WriteOnly);
                            auto data = file.readAll();
                            accumulatedSize += data.size();
                            qDebug() << accumulatedSize;
                            installDialog.setValue(100 * (double)accumulatedSize / totalSize);
                            qApp->processEvents();
                            qDebug() << installDialog.isVisible() << installDialog.value();
                            if(!installDialog.isVisible() && installDialog.value() != 100 && installDialog.value() != -1)
                                return;

                            f.write(data);
                        }
                        qDebug() << file.getActualFileName() << isDir;
                        
                        //do something with the data
                        if(file.isOpen())
                            file.close();
                        qApp->processEvents();
                        qDebug() << installDialog.isVisible() << installDialog.value();
                        if(!installDialog.isVisible() && installDialog.value() != 100 && installDialog.value() != -1)
                            return;
                    }
                    else {
                        qDebug() << "Cannot open" << filename << "inside zip";;
                    }
                }
                qDebug() << "Closing zip\n";
                zip.close();

                launch();
            }            
        }
    });
    
    disconnect(&bootstrap, &Bootstrap::ready, this, &UTLauncher::prepareConfig);
    
    connect(&bootstrap, &Bootstrap::ready, this, [=] {
        browser->setMOTD(bootstrap.MOTD());
    });
    
    connect(browser, &ServerBrowser::openSettings, openSettings);
    
    browser->setEditorSupport(hasEditorSupport());
    
    browser->setHideOnClose(settings.value("MinimizeToTrayOnClose", false).toBool());
    
    systemTray.setToolTip("UTLauncher");
    auto systemTrayMenu = new QMenu(browser);
    
    auto showBrowser = new QAction(awesome->icon(fa::listalt), "Server List", this);
    connect(showBrowser, &QAction::triggered, [=]() {
        browser->showNormal();
        browser->raise();
        browser->activateWindow();
    });
    
    auto runUTAction = new QAction(awesome->icon( fa::gamepad ),"Run UT", this);
    connect(runUTAction, &QAction::triggered, [=]() {
        QString exePath = bootstrap.programExePath();
        if(!exePath.length()) {
            browser->show();
            openSettings();
            return;
        }
        QProcess::startDetached(exePath
#ifdef LAUNCH_WITH_UE4
        , QStringList() << "UnrealTournament" << "-SaveToUserDir"
#endif
        );
    });

    auto runEditorAction = new QAction(awesome->icon( fa::code ),"Run Editor", this);
    connect(runEditorAction, &QAction::triggered, [=]() {
        QString editorPath = bootstrap.editorExePath();
        QString projectPath = bootstrap.projectPath();
        QProcess::startDetached(editorPath, QStringList() << projectPath);
    });
    

    auto quitAction = new QAction(awesome->icon( fa::signout ),"Quit", this);
    connect(quitAction, &QAction::triggered, [=]() {
        QApplication::quit();
    });
    
    systemTrayMenu->addAction(showBrowser);
    systemTrayMenu->addSeparator();
    systemTrayMenu->addAction(runUTAction);
    systemTrayMenu->addAction(runEditorAction);
    systemTrayMenu->addSeparator();
    systemTrayMenu->addAction(quitAction);
    
    systemTray.setContextMenu(systemTrayMenu);
    systemTray.show();
    
    connect(&systemTray, &QSystemTrayIcon::activated, [=](QSystemTrayIcon::ActivationReason reason) {
        qApp->setQuitOnLastWindowClosed(true);
        
        runEditorAction->setVisible(hasEditorSupport());
        
        switch(reason) {
            
            case QSystemTrayIcon::Trigger:
            {
                if(browser->isHidden()) {
                    browser->show();
                } else {
                    browser->hide();
                }
                break;
            }

        }
    });
    
}
Пример #23
0
QString UIWizardCloneVDPage4::mediumPath() const
{
    return absoluteFilePath(toFileName(m_pDestinationDiskEditor->text(), m_strDefaultExtension), m_strDefaultPath);
}
Пример #24
0
DUrl ShareFileInfo::mimeDataUrl() const
{
    return DUrl::fromLocalFile(absoluteFilePath());
}
Пример #25
0
 bool QtFileSystem::fileExists(const std::string& path)
 {
     return QFile(absoluteFilePath(path)).exists();
 }
Пример #26
0
QString UIWizardNewVDPage3::mediumPath() const
{
    return absoluteFilePath(toFileName(m_pLocationEditor->text(), m_strDefaultExtension), m_strDefaultPath);
}
Пример #27
0
void LegacyUpdate::ModTheJar()
{
	LegacyInstance *inst = (LegacyInstance *)m_inst;

	if (!inst->shouldRebuild())
	{
		emitSucceeded();
		return;
	}

	// Get the mod list
	auto modList = inst->jarModList();

	QFileInfo runnableJar(inst->runnableJar());
	QFileInfo baseJar(inst->baseJar());
	bool base_is_custom = inst->shouldUseCustomBaseJar();

	// Nothing to do if there are no jar mods to install, no backup and just the mc jar
	if (base_is_custom)
	{
		// yes, this can happen if the instance only has the runnable jar and not the base jar
		// it *could* be assumed that such an instance is vanilla, but that wouldn't be safe
		// because that's not something mmc4 guarantees
		if (runnableJar.isFile() && !baseJar.exists() && modList->empty())
		{
			inst->setShouldRebuild(false);
			emitSucceeded();
			return;
		}

		setStatus(tr("Installing mods: Backing up minecraft.jar ..."));
		if (!baseJar.exists() && !QFile::copy(runnableJar.filePath(), baseJar.filePath()))
		{
			emitFailed("It seems both the active and base jar are gone. A fresh base jar will "
					   "be used on next run.");
			inst->setShouldRebuild(true);
			inst->setShouldUpdate(true);
			inst->setShouldUseCustomBaseJar(false);
			return;
		}
	}

	if (!baseJar.exists())
	{
		emitFailed("The base jar " + baseJar.filePath() + " does not exist");
		return;
	}

	if (runnableJar.exists() && !QFile::remove(runnableJar.filePath()))
	{
		emitFailed("Failed to delete old minecraft.jar");
		return;
	}

	// TaskStep(); // STEP 1
	setStatus(tr("Installing mods: Opening minecraft.jar ..."));

	QuaZip zipOut(runnableJar.filePath());
	if (!zipOut.open(QuaZip::mdCreate))
	{
		QFile::remove(runnableJar.filePath());
		emitFailed("Failed to open the minecraft.jar for modding");
		return;
	}
	// Files already added to the jar.
	// These files will be skipped.
	QSet<QString> addedFiles;

	// Modify the jar
	setStatus(tr("Installing mods: Adding mod files..."));
	for (int i = modList->size() - 1; i >= 0; i--)
	{
		auto &mod = modList->operator[](i);

		// do not merge disabled mods.
		if (!mod.enabled())
			continue;

		if (mod.type() == Mod::MOD_ZIPFILE)
		{
			if (!MergeZipFiles(&zipOut, mod.filename(), addedFiles, LegacyUpdate::KeepMetainf))
			{
				zipOut.close();
				QFile::remove(runnableJar.filePath());
				emitFailed("Failed to add " + mod.filename().fileName() + " to the jar.");
				return;
			}
		}
		else if (mod.type() == Mod::MOD_SINGLEFILE)
		{
			auto filename = mod.filename();
			if (!JlCompress::compressFile(&zipOut, filename.absoluteFilePath(),
										  filename.fileName()))
			{
				zipOut.close();
				QFile::remove(runnableJar.filePath());
				emitFailed("Failed to add " + filename.fileName() + " to the jar");
				return;
			}
			addedFiles.insert(filename.fileName());
			QLOG_INFO() << "Adding file " << filename.fileName() << " from "
						<< filename.absoluteFilePath();
		}
		else if (mod.type() == Mod::MOD_FOLDER)
		{
			auto filename = mod.filename();
			QString what_to_zip = filename.absoluteFilePath();
			QDir dir(what_to_zip);
			dir.cdUp();
			QString parent_dir = dir.absolutePath();
			if (!JlCompress::compressSubDir(&zipOut, what_to_zip, parent_dir, true, addedFiles))
			{
				zipOut.close();
				QFile::remove(runnableJar.filePath());
				emitFailed("Failed to add " + filename.fileName() + " to the jar");
				return;
			}
			QLOG_INFO() << "Adding folder " << filename.fileName() << " from "
						<< filename.absoluteFilePath();
		}
	}

	if (!MergeZipFiles(&zipOut, baseJar, addedFiles, LegacyUpdate::IgnoreMetainf))
	{
		zipOut.close();
		QFile::remove(runnableJar.filePath());
		emitFailed("Failed to insert minecraft.jar contents.");
		return;
	}

	// Recompress the jar
	zipOut.close();
	if (zipOut.getZipError() != 0)
	{
		QFile::remove(runnableJar.filePath());
		emitFailed("Failed to finalize minecraft.jar!");
		return;
	}
	inst->setShouldRebuild(false);
	// inst->UpdateVersion(true);
	emitSucceeded();
	return;
}
void CMV_BookManager::updateBookDatabase()
{
    QString path = "book.db";
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "db");
    db.setDatabaseName(path);
    if (!db.open()){
        qDebug()<<"An error occurred while opening the connection: "<< db.lastError().text();
        return;
    }
    QSqlQuery q("", db);
    q.exec("create table Books (id integer primary key, path TEXT)");

    int i = 0;
    QDirIterator ite("/", QDirIterator::Subdirectories);

    while (ite.hasNext()){
        auto inf = ite.fileInfo();
        if(inf.isFile() && (!QString::compare(QStringLiteral("CBZ"), inf.suffix(),
                                              Qt::CaseInsensitive))){
            q.exec(QStringLiteral("insert into Books values (%1, '%2')").arg(QString::number(i++),inf.absoluteFilePath()));


        }
        ite.next();
    }
}
Пример #29
0
void performJourney(std::ostream &output, const OsmAnd::Voyager::Configuration& cfg)
#endif
{
    if(cfg.generateXml)
    {
#if defined(_UNICODE) || defined(UNICODE)
        output << xT("<?xml version=\"1.0\" encoding=\"UTF-16\"?>") << std::endl;
#else
        output << xT("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") << std::endl;
#endif
    }

    QList< std::shared_ptr<OsmAnd::ObfReader> > obfData;
    for(auto itObf = cfg.obfs.begin(); itObf != cfg.obfs.end(); ++itObf)
    {
        auto obf = *itObf;
        std::shared_ptr<OsmAnd::ObfReader> obfReader(new OsmAnd::ObfReader(std::shared_ptr<QIODevice>(new QFile(obf->absoluteFilePath()))));
        obfData.push_back(obfReader);
    }

    OsmAnd::RoutePlannerContext plannerContext(obfData, cfg.routingConfig, cfg.vehicle, false);
    std::shared_ptr<OsmAnd::Model::Road> startRoad;
    if(!OsmAnd::RoutePlanner::findClosestRoadPoint(&plannerContext, cfg.startLatitude, cfg.startLongitude, &startRoad))
    {
        if(cfg.generateXml)
            output << xT("<!--");
        output << xT("Failed to find road near start point");
        if(cfg.generateXml)
            output << xT("-->");
        output << std::endl;
        return;
    }
    std::shared_ptr<OsmAnd::Model::Road> endRoad;
    if(!OsmAnd::RoutePlanner::findClosestRoadPoint(&plannerContext, cfg.endLatitude, cfg.endLongitude, &endRoad))
    {
        if(cfg.generateXml)
            output << xT("<!--");
        output << xT("Failed to find road near end point");
        if(cfg.generateXml)
            output << xT("-->");
        output << std::endl;
        return;
    }

    if(cfg.verbose)
    {
        if(cfg.generateXml)
            output << xT("<!--");
        output << xT("Start point (LAT ") << cfg.startLatitude << xT("; LON ") << cfg.startLongitude << xT("):");
        if(cfg.generateXml)
            output << xT("-->");
        output << std::endl;
        if(cfg.generateXml)
            output << xT("<!--");
        output << xT("\tRoad name(s): ");
        if(startRoad->names.size() == 0)
        {
            output << xT("\t[none] (") << startRoad->id << xT(")");
            if(cfg.generateXml)
                output << xT("-->");
            output << std::endl;
        }
        else
        {
            for(auto itName = startRoad->names.begin(); itName != startRoad->names.end(); ++itName)
                output << QStringToStlString(itName.value()) << xT("; ");
            output << xT(" (") << startRoad->id << xT(")");
            if(cfg.generateXml)
                output << xT("-->");
            output << std::endl;
        }
        output << std::endl;
    
        if(cfg.generateXml)
            output << xT("<!--");
        output << xT("End point (LAT ") << cfg.endLatitude << xT("; LON ") << cfg.endLongitude << xT("):");
        if(cfg.generateXml)
            output << xT("-->");
        output << std::endl;
        if(cfg.generateXml)
            output << xT("<!--");
        output << xT("\tRoad name(s): ");
        if(endRoad->names.size() == 0)
        {
            output << xT("\t[none] (") << endRoad->id << xT(")");
            if(cfg.generateXml)
                output << xT("-->");
            output << std::endl;
        }
        else
        {
            for(auto itName = endRoad->names.begin(); itName != endRoad->names.end(); ++itName)
                output << QStringToStlString(itName.value()) << xT("; ");
            output << xT(" (") << endRoad->id << xT(")");
            if(cfg.generateXml)
                output << xT("-->");
            output << std::endl;
        }
        output << std::endl;
    }

    QList< std::pair<double, double> > points;
    points.push_back(std::pair<double, double>(cfg.startLatitude, cfg.startLongitude));
    for(auto itIntermediatePoint = cfg.waypoints.begin(); itIntermediatePoint != cfg.waypoints.end(); ++itIntermediatePoint)
        points.push_back(*itIntermediatePoint);
    points.push_back(std::pair<double, double>(cfg.endLatitude, cfg.endLongitude));

    QList< std::shared_ptr<OsmAnd::RouteSegment> > route;
    auto routeCalculationStart = std::chrono::steady_clock::now();
    if(cfg.verbose)
    {
        if(cfg.generateXml)
            output << xT("<!--");
        output << xT("Started route calculation ") << QStringToStlString(QTime::currentTime().toString());
        if(cfg.generateXml)
            output << xT("-->");
        output << std::endl;
    }
    OsmAnd::RouteCalculationResult routeFound =
            OsmAnd::RoutePlanner::calculateRoute(&plannerContext, points, cfg.leftSide, nullptr);
    route = routeFound.list;
    auto routeCalculationFinish = std::chrono::steady_clock::now();
    if(cfg.verbose)
    {
        if(cfg.generateXml)
            output << xT("<!--");
        output << xT("Finished route calculation ") << QStringToStlString(QTime::currentTime().toString()) << xT(", took ") << std::chrono::duration<double, std::milli> (routeCalculationFinish - routeCalculationStart).count() << xT(" ms");
        if(cfg.generateXml)
            output << xT("-->");
        output << std::endl;
    }
    if(cfg.doRecalculate)
    {
        auto routeRecalculationStart = std::chrono::steady_clock::now();
        if(cfg.verbose)
        {
            if(cfg.generateXml)
                output << xT("<!--");
            output << xT("Started route recalculation ") << QStringToStlString(QTime::currentTime().toString());
            if(cfg.generateXml)
                output << xT("-->");
            output << std::endl;
        }
        routeFound = OsmAnd::RoutePlanner::calculateRoute(&plannerContext, points, cfg.leftSide, nullptr);
        route = routeFound.list;
        auto routeRecalculationFinish = std::chrono::steady_clock::now();
        if(cfg.verbose)
        {
            if(cfg.generateXml)
                output << xT("<!--");
            output << xT("Finished route recalculation ") << QStringToStlString(QTime::currentTime().toString()) << xT(", took ") << std::chrono::duration<double, std::milli> (routeRecalculationFinish - routeRecalculationStart).count() << xT(" ms");
            if(cfg.generateXml)
                output << xT("-->");
            output << std::endl;
        }
    }
    if(routeFound.warnMessage == "")
    {
        if(cfg.generateXml)
            output << xT("<!--");
        output << xT("FAILED TO FIND ROUTE!") << QStringToStlString(routeFound.warnMessage);
        if(cfg.generateXml)
            output << xT("-->");
        output << std::endl;
    }

    float totalTime = 0.0f;
    float totalDistance = 0.0f;
    for(auto itSegment = route.begin(); itSegment != route.end(); ++itSegment)
    {
        auto segment = *itSegment;

        totalTime += segment->time;
        totalDistance += segment->distance;
    }

    if(cfg.generateXml)
        output << xT("<test") << std::endl;
    else
        output << xT("ROUTE:") << std::endl;

    output << xT("\tregions=\"\"") << std::endl;
    output << xT("\tdescription=\"\"") << std::endl;
    output << xT("\tbest_percent=\"\"") << std::endl;
    output << xT("\tvehicle=\"") << QStringToStlString(cfg.vehicle) << xT("\"") << std::endl;
    output << xT("\tstart_lat=\"") << cfg.startLatitude << xT("\"") << std::endl;
    output << xT("\tstart_lon=\"") << cfg.startLongitude << xT("\"") << std::endl;
    output << xT("\ttarget_lat=\"") << cfg.endLatitude << xT("\"") << std::endl;
    output << xT("\ttarget_lon=\"") << cfg.endLongitude << xT("\"") << std::endl;
    output << xT("\tloadedTiles=\"") << 0 << xT("\"") << std::endl;
    output << xT("\tvisitedSegments=\"") << 0 << xT("\"") << std::endl;
    output << xT("\tcomplete_distance=\"") << totalDistance << xT("\"") << std::endl;
    output << xT("\tcomplete_time=\"") << totalTime << xT("\"") << std::endl;
    output << xT("\trouting_time=\"") << 0 << xT("\"") << std::endl;

    if(cfg.generateXml)
        output << xT(">") << std::endl;
    else
        output << std::endl;

    std::unique_ptr<QFile> gpxFile;
    std::unique_ptr<QTextStream> gpxStream;
    if(!cfg.gpxPath.isEmpty())
    {
        gpxFile.reset(new QFile(cfg.gpxPath));
        gpxFile->open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text);
        gpxStream.reset(new QTextStream(gpxFile.get()));
    }
    if(gpxFile && gpxFile->isOpen())
    {
        *(gpxStream.get()) << "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>\n";
        *(gpxStream.get()) << "<gpx version=\"1.0\" creator=\"OsmAnd Voyager tool\" xmlns=\"http://www.topografix.com/GPX/1/1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n";
        *(gpxStream.get()) << "\t<trk>\n";
        *(gpxStream.get()) << "\t\t<trkseg>\n";
    }
    for(auto itSegment = route.begin(); itSegment != route.end(); ++itSegment)
    {
        auto segment = *itSegment;

        if(cfg.generateXml)
            output << xT("\t<segment") << std::endl;
        else
            output << xT("\tSEGMENT:") << std::endl;

        output << xT("\t\tid=\"") << segment->road->id << xT("\"") << std::endl;
        output << xT("\t\tstart=\"") << segment->startPointIndex << xT("\"") << std::endl;
        output << xT("\t\tend=\"") << segment->endPointIndex << xT("\"") << std::endl;

        QString name;
        if(!segment->road->names.isEmpty())
            name += segment->road->names.begin().value();
        /*String ref = res.getObject().getRef();
        if (ref != null) {
            name += " (" + ref + ") ";
        }*/
        output << xT("\t\tname=\"") << QStringToStlString(name) << xT("\"") << std::endl;

        output << xT("\t\ttime=\"") << segment->time << xT("\"") << std::endl;
        output << xT("\t\tdistance=\"") << segment->distance << xT("\"") << std::endl;
        /*float ms = res.getObject().getMaximumSpeed();
        if(ms > 0) {
            additional.append("maxspeed = \"").append(ms * 3.6f).append("\" ").append(res.getObject().getHighway()).append(" ");
        }*/
        /*
        if (res.getTurnType() != null) {
            additional.append("turn = \"").append(res.getTurnType()).append("\" ");
            additional.append("turn_angle = \"").append(res.getTurnType().getTurnAngle()).append("\" ");
            if (res.getTurnType().getLanes() != null) {
                additional.append("lanes = \"").append(Arrays.toString(res.getTurnType().getLanes())).append("\" ");
            }
        }*/
        output << xT("\t\tstart_bearing=\"") << segment->getBearingBegin() << xT("\"") << std::endl;
        output << xT("\t\tend_bearing=\"") << segment->getBearingEnd() << xT("\"") << std::endl;
        //additional.append("description = \"").append(res.getDescription()).append("\" ");
        
        if(cfg.generateXml)
            output << xT("\t/>") << std::endl;
        else
            output << std::endl;

        if(gpxFile && gpxFile->isOpen())
        {
            output << xT("\t\tstart=\"") << segment->startPointIndex << xT("\"") << std::endl;
            output << xT("\t\tend=\"") << segment->endPointIndex << xT("\"") << std::endl;
            for(auto pointIdx = segment->startPointIndex; pointIdx < segment->endPointIndex; pointIdx++)
            {
                const auto& point = segment->road->points[pointIdx];

                *(gpxStream.get()) << "\t\t\t<trkpt lon=\"" << OsmAnd::Utilities::get31LongitudeX(point.x) << "\" lat=\"" << OsmAnd::Utilities::get31LatitudeY(point.y) << "\"/>\n";
            }
        }
    }

    if(gpxFile && gpxFile->isOpen())
    {
        *(gpxStream.get()) << "\t\t</trkseg>\n";
        *(gpxStream.get()) << "\t</trk>\n";
        *(gpxStream.get()) << "</gpx>\n";
        gpxStream->flush();
        gpxFile->close();
    }

    if(cfg.generateXml)
        output << xT("</test>") << std::endl;
}