示例#1
0
void AppSetting::saveCamera( CCamera cam )
{
	CString path = relativePath(CAMERA_SETTING);
	FILE *f = fopen(path.GetBuffer(), "w");
	if (f)
	{
		vec3d v;
		//Position
		v = cam.m_Pos;
		fprintf(f," %lf %lf %lf ", v.x, v.y,v.z);
		//Up
		v = cam.m_Up;
		fprintf(f," %lf %lf %lf ", v.x, v.y,v.z);
		//Center
		v = cam.m_Center;
		fprintf(f," %lf %lf %lf ", v.x, v.y,v.z);
		// direction
		v = cam.m_Direction;
		fprintf(f," %lf %lf %lf ", v.x, v.y,v.z);
		//rot axis
		v = cam.m_RotAxis;
		fprintf(f," %lf %lf %lf ", v.x, v.y,v.z);
		//distance
		fprintf(f," %lf ", cam.m_Distance);
		// rot angle
		fprintf(f," %lf ", cam.m_RotAngle);
		fclose(f);

		cam.m_RotMatrix.Print(relativePath("cam_rot_mattrix").GetBuffer());
	}
}
示例#2
0
QNetworkReply* AccessManager::createRequest(
    Operation op,
    const QNetworkRequest& req,
    QIODevice* data)
{
  if (req.url().scheme() == "hikki") {
    if (req.url().host() == "note") {
      QString path = relativePath(req);
      NotePtr note = m_notebook->open(path);
      if (note->exists()) {
        QNetworkRequest r(note->rendered());
        QNetworkReply* reply =
            QNetworkAccessManager::
              createRequest(op, r, data);
        emit loading(note);
        return reply;
      }
      else {
        emit noSuchNote(note);
      }
    }
    else if (req.url().host() == "data") {
      QString path = KStandardDirs::locate("appdata", relativePath(req));
      kDebug() << "data:" << path;
      if (!path.isEmpty())
      {
        QNetworkRequest r((QUrl(path)));
        return QNetworkAccessManager::createRequest(op, r, data);
      }
    }
  }  
  return QNetworkAccessManager::
      createRequest(op, req, data);
}
示例#3
0
// This function returns a valid full path if 
// 1. Base directory is specified.
// 2. RelativePath is correctly specified.
// Otherwise, it will return a default/empty pathstring.
EA::IO::Path::PathString8 GetFullPath(const char8_t* pRelativePath, bool useTempDirAsBasePath)
{
    // This function is written in such a manner is that if the GetBaseDirectory() does not return a valid path, it bypasses the code.
    // This ensures that we are backward compatible. 

    char baseDir[EA::IO::kMaxDirectoryLength];
    memset(baseDir, 0, EA::IO::kMaxDirectoryLength);

    bool baseFound = false;
    if (useTempDirAsBasePath)
    {
        baseFound = EA::WebKit::GetFileSystem()->GetTempDirectory(baseDir, EA::IO::kMaxDirectoryLength - 1);
    }
    else
    {
        baseFound = EA::WebKit::GetFileSystem()->GetDataDirectory(baseDir, EA::IO::kMaxDirectoryLength - 1);
    }

    if(baseFound)
    {
        EA::IO::Path::PathString8 fullPath;
        if(baseDir[0])
        {
            EA::IO::Path::PathString8 relativePath(pRelativePath);
            if(EA::IO::Path::IsRelative(relativePath))
            {
                fullPath.assign(baseDir);
                EA::IO::Path::Append(fullPath, relativePath);

                return fullPath;
            }
            else
            {
                EAW_ASSERT_FORMATTED(false , "Base directory specified but %s path is not relative. Base directory is ignored\n", pRelativePath);
            }
        }
        else //Just some safety code
        {
            EA::IO::Path::PathString8 relativePath(pRelativePath);
            if(EA::IO::Path::IsRelative(relativePath))
            {
                EAW_ASSERT_FORMATTED(false , "Base directory not specified but %s path is relative. \n", pRelativePath);
            }
        }
    }

    return EA::IO::Path::PathString8();
}
示例#4
0
std::string ConvertToDDS(const char *filePath, filepath &baseDirectory, filepath &rootInputDirectory, filepath &rootOutputDirectory) {
	filepath relativePath(filePath);
	filepath relativeDDSPath(relativePath);
	relativeDDSPath.replace_extension("dds");
	
	// If the file already exists in the output directory, we don't need to do anything
	filepath outputFilePath(rootOutputDirectory.file_string() + "\\" + relativeDDSPath.file_string());
	if (exists(outputFilePath)) {
		return relativeDDSPath;
	}

	// Guarantee the output directory exists
	filepath outputDirectory(outputFilePath.parent_path());
	create_directories(outputDirectory);

	// If input is already dds, but doesn't exist in the output directory, just copy the file to the output
	filepath inputFilePath(rootInputDirectory.file_string() + "\\" + relativePath.file_string());
	if (_stricmp(relativePath.extension().c_str(), "dds") == 0) {
		copy_file(inputFilePath, outputFilePath);
		return relativeDDSPath;
	}

	// Otherwise, convert the file to DDS
	std::string call = baseDirectory.file_string() + "\\texconv.exe -ft dds -o " + outputDirectory.file_string() + " " + inputFilePath.file_string() + " > NUL";
	std::system(call.c_str());

	return relativeDDSPath;
}
示例#5
0
QString QgsFilePickerWidget::toUrl( const QString& path ) const
{
  QString rep;
  if ( path.isEmpty() )
  {
    rep =  QSettings().value( "qgis/nullValue", "NULL" ).toString();
  }

  QString urlStr = relativePath( path, false );
  QUrl url = QUrl::fromUserInput( urlStr );
  if ( !url.isValid() || !url.isLocalFile() )
  {
    QgsDebugMsg( QString( "URL: %1 is not valid or not a local file !" ).arg( path ) );
    rep =  path;
  }

  QString pathStr = url.toString();
  if ( mFullUrl )
  {
    rep = QString( "<a href=\"%1\">%2</a>" ).arg( pathStr, path );
  }
  else
  {
    QString fileName = QFileInfo( urlStr ).fileName();
    rep = QString( "<a href=\"%1\">%2</a>" ).arg( pathStr, fileName );
  }

  return rep;
}
示例#6
0
void QtMenuBar::addAction(IAction& action, const char* path)
{
	auto qAction = getQAction(action);
	if (qAction == nullptr)
	{
		qAction = createQAction(action);
	}
	assert(qAction != nullptr);

	path = relativePath(path);
	if (path == nullptr || strlen(path) == 0)
	{
		path = action.text();
	}

	auto tok = strchr(path, '.');
	auto menuPath = tok != nullptr ? QString::fromUtf8(path, tok - path) : path;
	QMenu* menu = qMenuBar_.findChild<QMenu*>(menuPath, Qt::FindDirectChildrenOnly);
	if (menu == nullptr)
	{
		menu = qMenuBar_.addMenu(menuPath);
		menu->setObjectName(menuPath);
	}
	path = tok != nullptr ? tok + 1 : nullptr;

	QtMenu::addMenuAction(*menu, *qAction, path);
	qMenuBar_.repaint();
}
示例#7
0
  void LocalProcess::cleanUpRequiredFiles()
  {
    for (std::set<openstudio::path>::const_iterator itr = m_copiedRequiredFiles.begin();
        itr != m_copiedRequiredFiles.end();
        ++itr)
    {
      LOG(Debug, "cleanUpRequiredFiles: " << openstudio::toString(*itr));
      try {
        boost::filesystem::remove(*itr);
      } catch (const std::exception &e) {
        LOG(Trace, "Unable to remove file: " << e.what());
        // no error if it doesn't manage to delete it
      }

      try {
        openstudio::path p = itr->parent_path();

        while (!p.empty() && !relativePath(p, m_outdir).empty() && m_outdir != p)
        {
          // remove the directory if it happens to be empty. 
          boost::filesystem::remove(p);
          p = p.parent_path();
        }
      } catch (const std::exception &e) {
        LOG(Trace, "Unable to remove directory: " << e.what());
        // no error if it doesn't manage to delete it
      }
    }
  }
示例#8
0
void AppSetting::writeVectorReg( CString key, vec3d v )
{
	CString path = relativePath(key);
	FILE* f = fopen(path.GetBuffer(), "w");
	if(f)
	{
		fprintf(f, "%lf %lf %lf", v.x, v.y, v.z);
		fclose(f);
	}
}
示例#9
0
/**
 * Fetches the expand status of the item
 */
bool NoteSubFolder::treeWidgetExpandState() {
    QSettings settings;
    QString settingsKey = treeWidgetExpandStateSettingsKey();

    // load the settings
    QStringList pathList = settings.value(settingsKey).toStringList();
    QString path = relativePath();

    return pathList.contains(path);
}
示例#10
0
CCamera AppSetting::loadcamera()
{
	CString path = relativePath(CAMERA_SETTING);
	FILE *f = fopen(path.GetBuffer(), "r");
	CCamera cam;
	if (f)
	{
		double x,y,z;
		//Position
		fscanf(f," %lf %lf %lf ", &x, &y,&z);
		cam.m_Pos = vec3d(x,y,z);
		//Up
		fscanf(f," %lf %lf %lf ", &x, &y,&z);
		cam.m_Up = vec3d(x,y,z);
		//Center
		fscanf(f," %lf %lf %lf ", &x, &y,&z);
		cam.m_Center = vec3d(x,y,z);
		// direction
		fscanf(f," %lf %lf %lf ", &x, &y,&z);
		cam.m_Direction = vec3d(x,y,z);
		//rot axis
		fscanf(f," %lf %lf %lf ", &x, &y,&z);
		cam.m_RotAxis = vec3d(x,y,z);
		//distance
		fscanf(f," %lf", &x);
		cam.m_Distance = x;
		// rot angle
		fscanf(f," %lf", &x);
		cam.m_RotAngle = x;

		CString rotM = relativePath("cam_rot_mattrix");
		if (GetFileAttributes(rotM) != INVALID_FILE_ATTRIBUTES)
		{
			cam.m_RotMatrix.Read(rotM.GetBuffer());
		}
		

		fclose(f);
	}
	
	return cam;
}
示例#11
0
int main(int argc, char *argv[])
{
	char	*result, *argp;
	int 	errflg, absolute, canon, relative, nextArg;

#if _WIN32
    _setmode(1, _O_BINARY);
#endif

	errflg = 0;
    canon = absolute = relative = 0;

    for (nextArg = 1; nextArg < argc; nextArg++) {
        argp = argv[nextArg];
        if (*argp != '-') {
            break;
        }
        if (strcmp(argp, "-a") == 0) {
			absolute++;
        } else if (strcmp(argp, "-c") == 0) {
			canon++;
        } else if (strcmp(argp, "-r") == 0) {
			relative++;
        } else {
            errflg++;
        }
	}

    if (!absolute && !relative && !canon) {
        canon = 1;
    }
	if (errflg || (absolute + relative + canon) > 1) {
        fprintf(stderr, "Usage: getpath [-arc] files...\n");
        exit(2);
	}

	for (; nextArg < argc; ) {
        if (relative) {
            result = canonPath(relativePath(argv[nextArg]));
        } else if (absolute) {
            result = canonPath(absolutePath(argv[nextArg]));
        } else {
            result = canonPath(argv[nextArg]);
        }
        if (++nextArg < argc) {
            printf("%s ", result);
        } else {
            printf("%s", result);
        }
	}
    printf("\n");

	return 0;
}
示例#12
0
void AnalyseForm::syncSelected()
{
    QList<QTreeWidgetItem *> selected = ui->tree->selectedItems();
    if (!selected.count())
        return;

    QStringList rel_path = relativePath(sf_queue.last());

    AnalyseFile * sf, * sf_i;
    sf = new AnalyseFile("/");

    for (int i = 0; i < selected.count(); ++i) {
        sf_i = ((AnalyseTreeWidgetItem *) selected.at(i))->syncFile();

        for (int i = 0; i < sf_queue.count(); ++i) {
            if (sf_queue.at(i) == sf_i) {
                delete sf;
                sf = sf_i;
                rel_path = relativePath(sf);
                sf_i = NULL;
            }
        }

        if (!sf_i)
            break;

        sf->addSyncFile((SyncFile *) sf_i);
    }

    FolderActionGroup * sync_fag = new FolderActionGroup;
    Folders * folders = page->foldersObject();
    QDir dir;
    QString rel_path_str = rel_path.join("/");
    for (int i = 0; i < folders->count(); ++i) {
        dir.setPath(folders->at(i)->path());
        sync_fag->insert(folders->at(i)->index(), dir.absoluteFilePath(rel_path_str));
    }

    if (sf)
        page->startSync(sf, sync_fag);
}
示例#13
0
void AnalyseForm::openSelected(QAction * action)
{
    int i = ui->open_btn->menu()->actions().indexOf(action);

    if (i < 0 || !current_sf)
        return;

    QStringList path = relativePath(current_sf);
    path.prepend(page->foldersObject()->at(i)->path());

    QDesktopServices::openUrl(QUrl::fromLocalFile(path.join("/")));
}
示例#14
0
/**
 * Renames the note subfolder in the file system
 */
bool NoteSubFolder::rename(QString newName) {
    QDir dir = this->dir();

    if (dir.exists() && !newName.isEmpty()) {
        QString oldPath = fullPath();
        QString oldRelativePath = relativePath();
        setName(newName);
        QString newPath = fullPath();
        QString newRelativePath = relativePath();

        // rename the note sub folder paths of note tag links
        // (needs to be done before the folder rename because folder renaming
        // will cause a reload which would trigger the removal of the tag links)
        Tag::renameNoteSubFolderPathsOfLinks(oldRelativePath, newRelativePath);

        // rename the note subfolder
        return dir.rename(oldPath, newPath);
    }

    return false;
}
示例#15
0
 std::string get_relative_file_path(
     const std::string& absolutePath,
     const C& connection)
 {
   // we erase the data path and username + 2, for the /
   std::string relativePath(
       boost::filesystem::path(absolutePath).generic_string());
   relativePath.erase(
       0,
       connection.get_options().get_data_path().size() +
       connection.get_username().size() +
       2);
   return relativePath;
 }
JNIEXPORT void JNICALL
Java_org_apache_subversion_javahl_SVNRepos_load(
    JNIEnv *env, jobject jthis, jobject jpath, jobject jinputData,
    jobject jrevisionStart, jobject jrevisionEnd,
    jboolean jignoreUUID, jboolean jforceUUID,
    jboolean jusePreCommitHook, jboolean jusePostCommitHook,
    jboolean jvalidateProps, jboolean jignoreDates, jboolean jnormalizeProps,
    jstring jrelativePath, jobject jnotifyCallback)
{
  JNIEntry(SVNRepos, load);
  SVNRepos *cl = SVNRepos::getCppObject(jthis);
  if (cl == NULL)
    {
      JNIUtil::throwError(_("bad C++ this"));
      return;
    }

  File path(jpath);
  if (JNIUtil::isExceptionThrown())
    return;

  InputStream inputData(jinputData);
  if (JNIUtil::isExceptionThrown())
    return;

  JNIStringHolder relativePath(jrelativePath);
  if (JNIUtil::isExceptionThrown())
    return;

  Revision revisionStart(jrevisionStart);
  if (JNIUtil::isExceptionThrown())
    return;

  Revision revisionEnd(jrevisionEnd, true);
  if (JNIUtil::isExceptionThrown())
    return;

  ReposNotifyCallback notifyCallback(jnotifyCallback);

  cl->load(path, inputData, revisionStart, revisionEnd,
           jignoreUUID ? true : false,
           jforceUUID ? true : false,
           jusePreCommitHook ? true : false,
           jusePostCommitHook ? true : false,
           jvalidateProps ? true : false,
           jignoreDates ? true : false,
           jnormalizeProps ? true : false,
           relativePath,
           (jnotifyCallback != NULL ? &notifyCallback : NULL));
}
示例#17
0
path relocatePath(const path& originalPath,
                  const path& originalBase,
                  const path& newBase)
{
  path result;
  path temp = relativePath(originalPath,originalBase);
  LOG_FREE(Debug,"openstudio.utilities.core","Original path '" << toString(originalPath) 
      << "', relative to '" << toString(originalBase) << "' is '" << toString(temp) << "'.");
  if (!temp.empty()) {
    result = newBase / temp;
    LOG_FREE(Debug,"openstudio.utilities.core","Relocating path to '" << toString(result) << "'.");
  }
  return result;
}
示例#18
0
vec3d AppSetting::readVectorSetting( CString key , vec3d defalut)
{
	vec3d v = defalut;
	CString path = relativePath(key);
	FILE* f = fopen(path.GetBuffer(), "r");
	if(f)
	{
		double x,y,z;
		fscanf(f, "%lf %lf %lf", &x, &y, &z);
		v.x = x; v.y = y; v.z = z;
		fclose(f);
	}
	return v;
}
示例#19
0
bool FileReference::makePathRelative(const openstudio::path& basePath) {
  openstudio::path newPath;
  if (basePath.empty()) {
    newPath = path().filename();
  }
  else {
    newPath = relativePath(path(),basePath);
  }
  if (newPath.empty()) {
    return false;
  }
  m_path = newPath;
  m_versionUUID = createUUID();
  return true;
}
示例#20
0
bool ResourceFile::save()
{
    m_error_message.clear();

    if (m_file_name.isEmpty()) {
        m_error_message = msgFileNameEmpty();
        return false;
    }

    QFile file(m_file_name);
    if (!file.open(QIODevice::WriteOnly)) {
        m_error_message = file.errorString();
        return false;
    }

    QDomDocument doc;
    QDomElement root = doc.createElement(QLatin1String("RCC"));
    doc.appendChild(root);

    const QStringList name_list = prefixList();

    foreach (const QString &name, name_list) {
        FileList file_list;
        QString lang;
        foreach (const Prefix *pref, m_prefix_list) {
            if (pref->name == name){
                file_list += pref->file_list;
                lang = pref->lang;
            }
        }

        QDomElement relt = doc.createElement(QLatin1String("qresource"));
        root.appendChild(relt);
        relt.setAttribute(QLatin1String("prefix"), name);
        if (!lang.isEmpty())
            relt.setAttribute(QLatin1String("lang"), lang);

        foreach (const File *f, file_list) {
            const File &file = *f;
            QDomElement felt = doc.createElement(QLatin1String("file"));
            relt.appendChild(felt);
            const QString conv_file = relativePath(file.name).replace(QDir::separator(), QLatin1Char('/'));
            const QDomText text = doc.createTextNode(conv_file);
            felt.appendChild(text);
            if (!file.alias.isEmpty())
                felt.setAttribute(QLatin1String("alias"), file.alias);
        }
    }
示例#21
0
 bool WeatherFile_Impl::makeUrlRelative(const openstudio::path& basePath) {
   boost::optional<openstudio::path> currentPath = this->path();
   if (currentPath){
     openstudio::path newPath;
     if (basePath.empty()) {
       newPath = toPath(currentPath->filename());
     } else {
       newPath = relativePath(*currentPath,basePath);
     }
     if (!newPath.empty()) {
       std::string weatherFileUrl = toString(toURL(newPath));
       LOG(Debug,"Setting weather file url to " << weatherFileUrl);
       return setString(OS_WeatherFileFields::Url,weatherFileUrl);
     }
   }
   return false;
 }
示例#22
0
/**
 * Saves the expand status of the item
 */
void NoteSubFolder::saveTreeWidgetExpandState(bool expanded) {
    QSettings settings;
    QString settingsKey = treeWidgetExpandStateSettingsKey();

    // load the settings
    QStringList pathList = settings.value(settingsKey).toStringList();
    QString path = relativePath();

    if (!expanded) {
        // if item is not expanded remove the path from the list
        pathList.removeAll(path);
    } else if (!pathList.contains(path)) {
        // if item is collapsed and not already exists in the list then add it
        pathList.append(path);
    }

    // store the settings again
    settings.setValue(settingsKey, pathList);
}
示例#23
0
void AnalyseForm::blacklistSelected(QAction * action)
{
    ExceptionBundle * bundle = page->exceptionBundleById(action->data().toInt());
    ExceptionGroup * group;
    if (current_sf->isDir())
        group = bundle->groupByType(ExceptionGroup::FolderBlacklist);
    else
        group = bundle->groupByType(ExceptionGroup::FileBlacklist);

    QStringList path = relativePath(current_sf);
    path.prepend(page->foldersObject()->first()->path());

    group->addItem(path.join("/"));

    if (page->exceptionBundleChecked(bundle->index())) {
        delete current_sf;
        delete ui->tree->selectedItems().first();
    }
}
VProjectItem* VProjectItemFolder::Instantiate( const XBOX::VString& inFolderName, VProjectItem *inParent)
{
	VProjectItem *result = NULL;

	VProjectItemFolder *behaviour = new VProjectItemFolder( NULL);
	if (behaviour != NULL)
	{
		result = new VProjectItem( behaviour);
		if (result != NULL)
		{
			result->SetName( inFolderName);
			result->SetDisplayName( inFolderName);
			VString relativePath( inFolderName);
			relativePath += FOLDER_SEPARATOR;
			result->SetRelativePath( relativePath);

			if (inParent != NULL)
				inParent->AttachChild( result);
		}
	}
	return result;
}
示例#25
0
void AnalyseForm::updateSelectedInfo(AnalyseTreeWidgetItem * item)
{
    AnalyseFile * sf = item->syncFile();
    current_sf = sf;

    QStringList rel_path = relativePath(sf);
    ui->rel_path_le->clear();
    ui->rel_path_le->setText(rel_path.join("/"));

    ui->folder_chb->setChecked(sf->isDir());
    num_copy_item->setText(QVariant(sf->numNotFound()).toString());
    num_delete_item->setText(QVariant(sf->numDeleted()).toString());
    num_update_item->setText(QVariant(sf->numObsolete()).toString());

    ui->folder_items_status_table->setHidden(!(sf->isDir() && sf->numNotSynced()));

    Folders * folders = page->foldersObject();
    QTableWidgetItem * folder_item;
    for (int i = 0; i < folders->count(); ++i) {
        folder_item = ui->folders_table->item(i, 1);
        switch (sf->fileStatusInFolder(folders->at(i)->index())) {
        case AnalyseFile::OK:
            folder_item->setText(tr("OK"));
            break;

        case AnalyseFile::Obsolete:
            folder_item->setText(tr("Obsolete"));
            break;

        case AnalyseFile::Deleted:
            folder_item->setText(tr("Deleted"));
            break;

        default:
            folder_item->setText(tr("Not found"));
            break;
        }
    }
}
示例#26
0
path relativePath(const path& p,const path& base) {
  path wp = p;
  path wBase = base;

  path::const_iterator wpIt = wp.begin();
  path::const_iterator wpEnd = wp.end();
  path::const_iterator wBaseIt = wBase.begin();
  path::const_iterator wBaseEnd = wBase.end();
  while ((wpIt != wpEnd) && (wBaseIt != wBaseEnd) && ((*wpIt) == (*wBaseIt))) {
    ++wpIt;
    ++wBaseIt;
  }
  // p is not an extension of base, try to complete, then return p
  if (!((wBaseIt == wBaseEnd) || (toString(*wBaseIt) == "."))) { 
    path completeP = boost::filesystem::complete(p);
    path completeBase = boost::filesystem::complete(base);
    if ((completeP != wp) || (completeBase != wBase)) { 
      LOG_FREE(Debug,"openstudio.utilities.core","Path '" << toString(p) 
        << "' does not extend base '" << toString(base) 
        << "'. Try again after completing both paths.");
      return relativePath(completeP,completeBase);
    }
    else {
      LOG_FREE(Debug,"openstudio.utilities.core","Path '" << toString(p) 
        << "' does not extend base '" << toString(base) << "'.");
      return path(); 
    }
  }

  // p is an extension of base, keep whatever remains of p
  path result;
  while (wpIt != wpEnd) {
    result = result/(*wpIt);
    ++wpIt;
  }
  return result;
}
示例#27
0
void QgsFilePickerWidget::openFileDialog()
{
  QSettings settings;
  QString oldPath;

  // If we use fixed default path
  if ( !mDefaultRoot.isEmpty() )
  {
    oldPath = QDir::cleanPath( mDefaultRoot );
  }
  // if we use a relative path option, we need to obtain the full path
  else if ( !mFilePath.isEmpty() )
  {
    oldPath = relativePath( mFilePath, false );
  }

  // If there is no valid value, find a default path to use
  QUrl theUrl = QUrl::fromUserInput( oldPath );
  if ( !theUrl.isValid() )
  {
    QString defPath = QDir::cleanPath( QgsProject::instance()->fileInfo().absolutePath() );
    if ( defPath.isEmpty() )
    {
      defPath = QDir::homePath();
    }
    oldPath = settings.value( "/UI/lastExternalResourceWidgetDefaultPath", defPath ).toString();
  }

  // Handle Storage
  QString fileName;
  QString title;
  if ( mStorageMode == File )
  {
    title = !mDialogTitle.isEmpty() ? mDialogTitle : tr( "Select a file" );
    fileName = QFileDialog::getOpenFileName( this, title, QFileInfo( oldPath ).absoluteFilePath() );
  }
  else if ( mStorageMode == Directory )
  {
    title = !mDialogTitle.isEmpty() ? mDialogTitle : tr( "Select a directory" );
    fileName = QFileDialog::getExistingDirectory( this, title, QFileInfo( oldPath ).absoluteFilePath(),  QFileDialog::ShowDirsOnly );
  }

  if ( fileName.isEmpty() )
    return;


  fileName = QDir::toNativeSeparators( QDir::cleanPath( QFileInfo( fileName ).absoluteFilePath() ) );
  // Store the last used path:

  if ( mStorageMode == File )
  {
    settings.setValue( "/UI/lastFileNameWidgetDir", QFileInfo( fileName ).absolutePath() );
  }
  else if ( mStorageMode == Directory )
  {
    settings.setValue( "/UI/lastFileNameWidgetDir", fileName );
  }

  // Handle relative Path storage
  fileName = relativePath( fileName, true );

  // Keep the new value
  setFilePath( fileName );
}
示例#28
0
/**
 * Gets the full path of the note sub folder
 */
QString NoteSubFolder::fullPath() {
    return Note::getFullNoteFilePathForFile(relativePath());
}
示例#29
0
int main(int argc, char** argv)
{
	Waifu2x::init_liblary(argc, argv);

	// Caffeのエラーでないログを保存しないようにする
	google::SetLogDestination(google::INFO, "");
	google::SetLogDestination(google::WARNING, "");

	// Caffeのエラーログを「error_log_〜」に出力
	google::SetLogDestination(google::ERROR, "error_log_");
	google::SetLogDestination(google::FATAL, "error_log_");

	// definition of command line arguments
	TCLAP::CmdLine cmd("waifu2x reimplementation using Caffe", ' ', "1.0.0");

	TCLAP::ValueArg<std::string> cmdInputFile("i", "input_path",
		"path to input image file", true, "",
		"string", cmd);

	TCLAP::ValueArg<std::string> cmdOutputFile("o", "output_path",
		"path to output image file (when input_path is folder, output_path must be folder)", false,
		"(auto)", "string", cmd);

	TCLAP::ValueArg<std::string> cmdInputFileExt("l", "input_extention_list",
		"extention to input image file when input_path is folder", false, "png:jpg:jpeg:tif:tiff:bmp:tga",
		"string", cmd);

	TCLAP::ValueArg<std::string> cmdOutputFileExt("e", "output_extention",
		"extention to output image file when output_path is (auto) or input_path is folder", false,
		"png", "string", cmd);

	std::vector<std::string> cmdModeConstraintV;
	cmdModeConstraintV.push_back("noise");
	cmdModeConstraintV.push_back("scale");
	cmdModeConstraintV.push_back("noise_scale");
	cmdModeConstraintV.push_back("auto_scale");
	TCLAP::ValuesConstraint<std::string> cmdModeConstraint(cmdModeConstraintV);
	TCLAP::ValueArg<std::string> cmdMode("m", "mode", "image processing mode",
		false, "noise_scale", &cmdModeConstraint, cmd);

	std::vector<int> cmdNRLConstraintV;
	cmdNRLConstraintV.push_back(1);
	cmdNRLConstraintV.push_back(2);
	cmdNRLConstraintV.push_back(3);
	TCLAP::ValuesConstraint<int> cmdNRLConstraint(cmdNRLConstraintV);
	TCLAP::ValueArg<int> cmdNRLevel("n", "noise_level", "noise reduction level",
		false, 1, &cmdNRLConstraint, cmd);

	TCLAP::ValueArg<double> cmdScaleRatio("s", "scale_ratio",
		"custom scale ratio", false, 2.0, "double", cmd);

	TCLAP::ValueArg<double> cmdScaleWidth("w", "scale_width",
		"custom scale width", false, 0, "double", cmd);

	TCLAP::ValueArg<double> cmdScaleHeight("h", "scale_height",
		"custom scale height", false, 0, "double", cmd);

	TCLAP::ValueArg<std::string> cmdModelPath("", "model_dir",
		"path to custom model directory (don't append last / )", false,
		"models/anime_style_art_rgb", "string", cmd);

	std::vector<std::string> cmdProcessConstraintV;
	cmdProcessConstraintV.push_back("cpu");
	cmdProcessConstraintV.push_back("gpu");
	cmdProcessConstraintV.push_back("cudnn");
	TCLAP::ValuesConstraint<std::string> cmdProcessConstraint(cmdProcessConstraintV);
	TCLAP::ValueArg<std::string> cmdProcess("p", "process", "process mode",
		false, "gpu", &cmdProcessConstraint, cmd);

	TCLAP::ValueArg<int> cmdOutputQuality("q", "output_quality",
		"output image quality", false,
		-1, "int", cmd);

	TCLAP::ValueArg<int> cmdOutputDepth("d", "output_depth",
		"output image chaneel depth bit", false,
		8, "int", cmd);

	TCLAP::ValueArg<int> cmdCropSizeFile("c", "crop_size",
		"input image split size", false,
		128, "int", cmd);

	TCLAP::ValueArg<int> cmdCropWidth("", "crop_w",
		"input image split size(width)", false,
		128, "int", cmd);

	TCLAP::ValueArg<int> cmdCropHeight("", "crop_h",
		"input image split size(height)", false,
		128, "int", cmd);

	TCLAP::ValueArg<int> cmdBatchSizeFile("b", "batch_size",
		"input batch size", false,
		1, "int", cmd);

	TCLAP::ValueArg<int> cmdGPUNoFile("", "gpu",
		"gpu device no", false,
		0, "int", cmd);

	std::vector<int> cmdTTAConstraintV;
	cmdTTAConstraintV.push_back(0);
	cmdTTAConstraintV.push_back(1);
	TCLAP::ValuesConstraint<int> cmdTTAConstraint(cmdTTAConstraintV);
	TCLAP::ValueArg<int> cmdTTALevel("t", "tta", "8x slower and slightly high quality",
		false, 0, &cmdTTAConstraint, cmd);

	// definition of command line argument : end

	TCLAP::Arg::enableIgnoreMismatched();

	// parse command line arguments
	try
	{
		cmd.parse(argc, argv);
	}
	catch (std::exception &e)
	{
		printf("エラー: %s\n", e.what());
		return 1;
	}

	boost::optional<double> ScaleRatio;
	boost::optional<int> ScaleWidth;
	boost::optional<int> ScaleHeight;

	int valid_num = 0;
	if (cmdScaleWidth.getValue() > 0)
		valid_num++;
	if (cmdScaleHeight.getValue() > 0)
		valid_num++;

	if (valid_num > 1)
	{
		printf("エラー: scale_widthとscale_heightは同時に指定できません\n");
		return 1;
	}

	int crop_w = cmdCropSizeFile.getValue();
	int crop_h = cmdCropSizeFile.getValue();

	if (cmdCropWidth.isSet())
		crop_w = cmdCropWidth.getValue();

	if (cmdCropHeight.isSet())
		crop_h = cmdCropHeight.getValue();

	if (cmdScaleWidth.getValue() > 0)
		ScaleWidth = cmdScaleWidth.getValue();
	else if (cmdScaleHeight.getValue() > 0)
		ScaleHeight = cmdScaleHeight.getValue();
	else
		ScaleRatio = cmdScaleRatio.getValue();

	const boost::filesystem::path input_path(boost::filesystem::absolute((cmdInputFile.getValue())));

	std::string outputExt = cmdOutputFileExt.getValue();
	if (outputExt.length() > 0 && outputExt[0] != '.')
		outputExt = "." + outputExt;

	const std::string ModelName = Waifu2x::GetModelName(cmdModelPath.getValue());

	const bool use_tta = cmdTTALevel.getValue() == 1;

	std::vector<std::pair<std::string, std::string>> file_paths;
	if (boost::filesystem::is_directory(input_path)) // input_pathがフォルダならそのディレクトリ以下の画像ファイルを一括変換
	{
		boost::filesystem::path output_path;

		if (cmdOutputFile.getValue() == "(auto)")
		{
			// 「test」なら「test_noise_scale(Level1)(x2.000000)」みたいな感じにする

			std::string addstr("(");
			addstr += ModelName;
			addstr += ")";

			const std::string &mode = cmdMode.getValue();

			addstr += "(" + mode + ")";

			if (mode.find("noise") != mode.npos || mode.find("auto_scale") != mode.npos)
				addstr += "(Level" + std::to_string(cmdNRLevel.getValue()) + ")";

			if (use_tta)
				addstr += "(tta)";
			if (mode.find("scale") != mode.npos)
			{
				if(ScaleRatio)
					addstr += "(x" + std::to_string(*ScaleRatio) + ")";
				else if (ScaleWidth)
					addstr += "(width " + std::to_string(*ScaleWidth) + ")";
				else
					addstr += "(height " + std::to_string(*ScaleHeight) + ")";
			}

			if (cmdOutputDepth.getValue() != 8)
				addstr += "(" + std::to_string(cmdOutputDepth.getValue()) + "bit)";

			output_path = input_path.branch_path() / (input_path.stem().string() + addstr);
		}
		else
			output_path = cmdOutputFile.getValue();

		output_path = boost::filesystem::absolute(output_path);

		if (!boost::filesystem::exists(output_path))
		{
			if (!boost::filesystem::create_directory(output_path))
			{
				printf("エラー: 出力フォルダ「%s」の作成に失敗しました\n", output_path.string().c_str());
				return 1;
			}
		}

		std::vector<std::string> extList;
		{
			// input_extention_listを文字列の配列にする

			typedef boost::char_separator<char> char_separator;
			typedef boost::tokenizer<char_separator> tokenizer;

			char_separator sep(":", "", boost::drop_empty_tokens);
			tokenizer tokens(cmdInputFileExt.getValue(), sep);

			for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter)
			{
				std::string ext(*tok_iter);
				std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
				extList.push_back("." + ext);
			}
		}

		// 変換する画像の入力、出力パスを取得
		const auto func = [&extList, &input_path, &output_path, &outputExt, &file_paths](const boost::filesystem::path &path)
		{
			BOOST_FOREACH(const boost::filesystem::path& p, std::make_pair(boost::filesystem::recursive_directory_iterator(path),
				boost::filesystem::recursive_directory_iterator()))
			{
				if (boost::filesystem::is_directory(p))
				{
					const auto out_relative = relativePath(p, input_path);
					const auto out_absolute = output_path / out_relative;

					if (!boost::filesystem::exists(out_absolute))
					{
						if (!boost::filesystem::create_directory(out_absolute))
						{
							printf("エラー: 出力フォルダ「%s」の作成に失敗しました\n", out_absolute.string().c_str());
							return false;
						}
					}
				}
				else
				{
					std::string ext(p.extension().string());
					std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
					if (std::find(extList.begin(), extList.end(), ext) != extList.end())
					{
						const auto out_relative = relativePath(p, input_path);
						const auto out_absolute = output_path / out_relative;

						const auto out = (out_absolute.branch_path() / out_absolute.stem()).string() + outputExt;

						file_paths.emplace_back(p.string(), out);
					}
				}
			}

			return true;
		};

		if (!func(input_path))
			return 1;
	}
	else
	{
示例#30
0
int main(int argc, char** argv)
{
	// definition of command line arguments
	TCLAP::CmdLine cmd("waifu2x reimplementation using Caffe", ' ', "1.0.0");

	TCLAP::ValueArg<std::string> cmdInputFile("i", "input_path",
		"path to input image file", true, "",
		"string", cmd);

	TCLAP::ValueArg<std::string> cmdOutputFile("o", "output_path",
		"path to output image file (when input_path is folder, output_path must be folder)", false,
		"(auto)", "string", cmd);

	TCLAP::ValueArg<std::string> cmdInputFileExt("l", "input_extention_list",
		"extention to input image file when input_path is folder", false, "png:jpg:jpeg:tif:tiff:bmp",
		"string", cmd);

	TCLAP::ValueArg<std::string> cmdOutputFileExt("e", "output_extention",
		"extention to output image file when output_path is (auto) or input_path is folder", false,
		"png", "string", cmd);

	std::vector<std::string> cmdModeConstraintV;
	cmdModeConstraintV.push_back("noise");
	cmdModeConstraintV.push_back("scale");
	cmdModeConstraintV.push_back("noise_scale");
	cmdModeConstraintV.push_back("auto_scale");
	TCLAP::ValuesConstraint<std::string> cmdModeConstraint(cmdModeConstraintV);
	TCLAP::ValueArg<std::string> cmdMode("m", "mode", "image processing mode",
		false, "noise_scale", &cmdModeConstraint, cmd);

	std::vector<int> cmdNRLConstraintV;
	cmdNRLConstraintV.push_back(1);
	cmdNRLConstraintV.push_back(2);
	TCLAP::ValuesConstraint<int> cmdNRLConstraint(cmdNRLConstraintV);
	TCLAP::ValueArg<int> cmdNRLevel("n", "noise_level", "noise reduction level",
		false, 1, &cmdNRLConstraint, cmd);

	TCLAP::ValueArg<double> cmdScaleRatio("s", "scale_ratio",
		"custom scale ratio", false, 2.0, "double", cmd);

	TCLAP::ValueArg<std::string> cmdModelPath("", "model_dir",
		"path to custom model directory (don't append last / )", false,
		"models", "string", cmd);

	std::vector<std::string> cmdProcessConstraintV;
	cmdProcessConstraintV.push_back("cpu");
	cmdProcessConstraintV.push_back("gpu");
	cmdProcessConstraintV.push_back("cudnn");
	TCLAP::ValuesConstraint<std::string> cmdProcessConstraint(cmdProcessConstraintV);
	TCLAP::ValueArg<std::string> cmdProcess("p", "process", "process mode",
		false, "gpu", &cmdProcessConstraint, cmd);

	TCLAP::ValueArg<int> cmdCropSizeFile("c", "crop_size",
		"input image split size", false,
		128, "int", cmd);

	TCLAP::ValueArg<int> cmdBatchSizeFile("b", "batch_size",
		"input batch size", false,
		1, "int", cmd);

	// definition of command line argument : end

	TCLAP::Arg::enableIgnoreMismatched();

	// parse command line arguments
	try
	{
		cmd.parse(argc, argv);
	}
	catch (std::exception &e)
	{
		printf("エラー: %s\n", e.what());
		return 1;
	}

	const boost::filesystem::path input_path(boost::filesystem::absolute((cmdInputFile.getValue())));

	std::string outputExt = cmdOutputFileExt.getValue();
	if (outputExt.length() > 0 && outputExt[0] != '.')
		outputExt = "." + outputExt;

	std::vector<std::pair<std::string, std::string>> file_paths;
	if (boost::filesystem::is_directory(input_path)) // input_pathがフォルダならそのディレクトリ以下の画像ファイルを一括変換
	{
		boost::filesystem::path output_path;

		if (cmdOutputFile.getValue() == "(auto)")
		{
			// 「test」なら「test_noise_scale(Level1)(x2.000000)」みたいな感じにする

			std::string addstr("_" + cmdMode.getValue());

			const std::string &mode = cmdMode.getValue();
			if (mode.find("noise") != mode.npos || mode.find("auto_scale") != mode.npos)
				addstr += "(Level" + std::to_string(cmdNRLevel.getValue()) + ")";
			if (mode.find("scale") != mode.npos)
				addstr += "(x" + std::to_string(cmdScaleRatio.getValue()) + ")";

			output_path = input_path.branch_path() / (input_path.stem().string() + addstr);
		}
		else
			output_path = cmdOutputFile.getValue();

		output_path = boost::filesystem::absolute(output_path);

		if (!boost::filesystem::exists(output_path))
		{
			if (!boost::filesystem::create_directory(output_path))
			{
				printf("エラー: 出力フォルダ「%s」の作成に失敗しました\n", output_path.string().c_str());
				return 1;
			}
		}

		std::vector<std::string> extList;
		{
			// input_extention_listを文字列の配列にする

			typedef boost::char_separator<char> char_separator;
			typedef boost::tokenizer<char_separator> tokenizer;

			char_separator sep(":", "", boost::drop_empty_tokens);
			tokenizer tokens(cmdInputFileExt.getValue(), sep);

			for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter)
				extList.push_back("." + *tok_iter);
		}

		// 変換する画像の入力、出力パスを取得
		const auto func = [&extList, &input_path, &output_path, &outputExt, &file_paths](const boost::filesystem::path &path)
		{
			BOOST_FOREACH(const boost::filesystem::path& p, std::make_pair(boost::filesystem::recursive_directory_iterator(path),
				boost::filesystem::recursive_directory_iterator()))
			{
				if (boost::filesystem::is_directory(p))
				{
					const auto out_relative = relativePath(p, input_path);
					const auto out_absolute = output_path / out_relative;

					if (!boost::filesystem::exists(out_absolute))
					{
						if (!boost::filesystem::create_directory(out_absolute))
						{
							printf("エラー: 出力フォルダ「%s」の作成に失敗しました\n", out_absolute.string().c_str());
							return false;
						}
					}
				}
				else if (std::find(extList.begin(), extList.end(), p.extension().string()) != extList.end())
				{
					const auto out_relative = relativePath(p, input_path);
					const auto out_absolute = output_path / out_relative;

					const auto out = (out_absolute.branch_path() / out_absolute.stem()).string() + outputExt;

					file_paths.emplace_back(p.string(), out);
				}
			}

			return true;
		};

		if (!func(input_path))
			return 1;
	}
	else
	{