Пример #1
0
bool SDCardFile::open(bool create) {
  if (!exists) {
    if (create) {
      SDCardEntry parentDir(dir);
      if (!parentDir.exists)
	return false;
      
      fat_dir_struct *dd = fat_open_dir(SDCard.fs, &parentDir.dir_entry);
      if (!fat_create_file(dd, name, &dir_entry)
	  && strcmp(name, dir_entry.long_name)) {
	fat_close_dir(dd);
	return false;
      }
      fat_close_dir(dd);
    } else {
      return false;
    }
  }
  
  fd = fat_open_file(SDCard.fs, &dir_entry);
  if (fd != NULL)
    return true;
  else
    return false;
}
Пример #2
0
void QgsGrassModuleInputModel::onDirectoryChanged( const QString &path )
{
  QgsDebugMsg( "path = " + path );

  QString locationPath = QgsGrass::getDefaultLocationPath();
  QDir parentDir( path );
  parentDir.cdUp();
  QString mapset;
  QList<QgsGrassObject::Type> types;
  if ( path == locationPath )
  {
    QgsDebugMsg( "location = " + path );
    QStringList dirNames = locationDirNames();
    //QStringList mapsets = QgsGrass::mapsets( QgsGrass::getDefaultGisdbase(), QgsGrass::getDefaultLocation() );

    for ( int i = rowCount() - 1; i >= 0; i-- )
    {
      QString mapset = item( i )->text();
      if ( !QgsGrass::isMapset( locationPath + "/" + mapset ) )
      {
        QgsDebugMsg( "removed mapset " + mapset );
        removeRows( i, 1 );
      }
    }

    Q_FOREACH ( const QString &dirName, dirNames )
    {
      // Add to watcher in any case, either for WIND, cellhd or vector
      QString dirPath = locationPath + "/" + dirName;
      watch( dirPath );
      if ( QgsGrass::isMapset( dirPath ) && findItems( dirName ).isEmpty() )
      {
        addMapset( dirName );
      }
    }
Пример #3
0
AssetCache::AssetCache(AssetAPI *owner, QString assetCacheDirectory) : 
    QNetworkDiskCache(owner),
    assetAPI(owner),
    cacheDirectory(GuaranteeTrailingSlash(assetCacheDirectory))
{
    LogInfo("Using AssetCache in directory '" + assetCacheDirectory.toStdString() + "'");

    // Check that the main directory exists
    QDir assetDir(cacheDirectory);
    if (!assetDir.exists())
    {
        QString dirName = cacheDirectory.split("/", QString::SkipEmptyParts).last();
        QString parentPath = cacheDirectory;
        parentPath.chop(dirName.length()+1);
        QDir parentDir(parentPath);
        parentDir.mkdir(dirName);
    }

    // Check that the needed subfolders exist
    if (!assetDir.exists("data"))
        assetDir.mkdir("data");
    assetDataDir = QDir(cacheDirectory + "data");
    if (!assetDir.exists("metadata"))
        assetDir.mkdir("metadata");
    assetMetaDataDir = QDir(cacheDirectory + "metadata");

    // Set for QNetworkDiskCache
    setCacheDirectory(cacheDirectory);
}
Пример #4
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DREAM3DSettings::writeToFile()
{
  /* Percolate the information that has changed all the way to the root group
     (The root group is what will ultimately be written to the file) */
  for (int i = m_Stack.size() - 2; i >= 0; i--)
  {
    m_Stack[i]->group[m_Stack[i + 1]->groupName] = m_Stack[i + 1]->group;
  }

  // Write the root to the file
  QFile outputFile(m_FilePath);
  QFileInfo info(outputFile);
  QString parentPath = info.absolutePath();
  QDir parentDir(parentPath);

  if (parentDir.exists() == false)
  {
    parentDir.mkpath(parentPath);
  }

  QJsonDocument doc(m_Stack.front()->group);

  if (outputFile.exists() == true)
  {
    outputFile.remove();
  }
  if (outputFile.open(QIODevice::WriteOnly))
  {
    outputFile.write(doc.toJson());
    outputFile.close();
  }
}
Пример #5
0
AssetCache::AssetCache(AssetAPI *owner, QString assetCacheDirectory) : 
    assetAPI(owner),
    cacheDirectory(GuaranteeTrailingSlash(QDir::fromNativeSeparators(assetCacheDirectory)))
{
    LogInfo("* Asset cache directory  : " + QDir::toNativeSeparators(cacheDirectory));  

    // Check that the main directory exists
    QDir assetDir(cacheDirectory);
    if (!assetDir.exists())
    {
        QString dirName = cacheDirectory.split("/", QString::SkipEmptyParts).last();
        QString parentPath = cacheDirectory;
        parentPath.chop(dirName.length()+1);
        QDir parentDir(parentPath);
        parentDir.mkdir(dirName);
    }

    // Check that the needed subfolders exist
    if (!assetDir.exists("data"))
        assetDir.mkdir("data");
    assetDataDir = QDir(cacheDirectory + "data");

    // Check --clearAssetCache start param
    if (owner->GetFramework()->HasCommandLineParameter("--clearAssetCache") ||
        owner->GetFramework()->HasCommandLineParameter("--clear-asset-cache")) /**< @todo Remove support for the deprecated parameter version at some point. */
    {
        LogInfo("AssetCache: Removing all data and metadata files from cache, found 'clearAssetCache' from the startup params!");
        ClearAssetCache();
    }
}
Пример #6
0
bool CodeEditor::fileSaveAs()			// 另存为缓存区。
{
	QString filePath =
		QFileDialog::getSaveFileName(this,
									 tr("另存为..."),
									 getFilePath(),
									 tr("All Files (*)"));
	
    if (filePath.isEmpty()) {
		return false;
	}

	// 检查是否有父母录的写权限
	QFileInfo fileInfo(filePath);
	QFileInfo parentDir(fileInfo.absolutePath());
	if (!parentDir.exists()){
		QMessageBox::information(this, tr("该文件不存在"),
								 tr("%1").arg(parentDir.absoluteFilePath()),
								 QMessageBox::Ok);
		return false;
	}
	
	QMessageBox::StandardButton ret;
	if (!parentDir.isWritable()){
		ret = QMessageBox::warning(this, tr("权限不够"),
								   tr("无法在此创建文件: %1").arg(parentDir.absoluteFilePath()),
								   QMessageBox::Ok | QMessageBox::Discard,
								   QMessageBox::Ok);
		if (ret == QMessageBox::Ok)
			return false;
		else
			return true;
	}

    QFile file(filePath);
    QTextStream out(&file);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
		ret = QMessageBox::warning(this, tr("写入文件失败"),
								   tr("%1").arg(filePath),
								   QMessageBox::Ok);
		if (ret == QMessageBox::Ok)
			return false;
		else
			return true;
	}
    out << plainEditor->toPlainText(); // 写入文件
	file.close();
	
	QString oldFilePath = getFilePath(); // 暂存修改前的文件名
    setFilePath(filePath); // 更改文件名
    plainEditor->document()->setModified(false);
	emit renamedSignal(oldFilePath, this);
    return true;
} // fileSaveAs
Пример #7
0
bool FileUtils::hasParentDirectory(const QString & path)
{
    QString parentPath = getParentPath(path);

    if (parentPath.length() > 0)
    {
        QDir parentDir(parentPath);
        return parentDir.exists();
    }

    return false;
}
Пример #8
0
bool VNoteFile::copyInternalImages(const QVector<ImageLink> &p_images,
                                   const QString &p_destDirPath,
                                   bool p_isCut,
                                   int *p_nrImageCopied,
                                   QString *p_errMsg)
{
    bool ret = true;
    QDir parentDir(p_destDirPath);
    QSet<QString> processedImages;
    QString opStr = p_isCut ? tr("cut") : tr("copy");
    int nrImageCopied = 0;
    for (int i = 0; i < p_images.size(); ++i) {
        const ImageLink &link = p_images[i];
        if (processedImages.contains(link.m_path)) {
            continue;
        }

        processedImages.insert(link.m_path);

        if (!QFileInfo::exists(link.m_path)) {
            VUtils::addErrMsg(p_errMsg, tr("Source image %1 does not exist.")
                                          .arg(link.m_path));
            ret = false;
            continue;
        }

        QString imageFolder = VUtils::directoryNameFromPath(VUtils::basePathFromPath(link.m_path));
        QString destImagePath = QDir(parentDir.filePath(imageFolder)).filePath(VUtils::fileNameFromPath(link.m_path));

        if (VUtils::equalPath(link.m_path, destImagePath)) {
            VUtils::addErrMsg(p_errMsg, tr("Skip image with the same source and target path %1.")
                                          .arg(link.m_path));
            ret = false;
            continue;
        }

        if (!VUtils::copyFile(link.m_path, destImagePath, p_isCut)) {
            VUtils::addErrMsg(p_errMsg, tr("Fail to %1 image %2 to %3. "
                                           "Please manually %1 it and modify the note.")
                                          .arg(opStr).arg(link.m_path).arg(destImagePath));
            ret = false;
        } else {
            ++nrImageCopied;
            qDebug() << opStr << "image" << link.m_path << "to" << destImagePath;
        }
    }

    *p_nrImageCopied = nrImageCopied;
    return ret;
}
Пример #9
0
void
TMagnify::SaveImage(entry_ref* ref, char* name, bool selectionOnly)
{
	// create a new file
	BFile file;
	BDirectory parentDir(ref);
	parentDir.CreateFile(name, &file);

	// write off the bitmaps bits to the file
	SaveBits(&file, fImageView->Bitmap(), "Data");

	// unfreeze the image, image was frozen before invoke of FilePanel
	EndSave();
}
Пример #10
0
    void File::mkdir() const
    {
        Ogre::String path = fullPath();

        if(isFile())
            path = parentDir().fullPath();

// http://stackoverflow.com/a/10356780
#if defined(_WIN32)
        SYSCALL_ALIAS_mkdir(path.c_str());
#else
        SYSCALL_ALIAS_mkdir(path.c_str(), 0777); // notice that 777 is different from 0777
#endif
    }
Пример #11
0
void QgsSvgSelectorGroupsModel::createTree( QStandardItem* &parentGroup )
{
  QDir parentDir( parentGroup->data().toString() );
  Q_FOREACH ( const QString& item, parentDir.entryList( QDir::Dirs | QDir::NoDotAndDotDot ) )
  {
    QStandardItem* group = new QStandardItem( item );
    group->setData( QVariant( parentDir.path() + "/" + item ) );
    group->setEditable( false );
    group->setCheckable( false );
    group->setToolTip( parentDir.path() + "/" + item );
    group->setIcon( QgsApplication::style()->standardIcon( QStyle::SP_DirIcon ) );
    parentGroup->appendRow( group );
    createTree( group );
  }
}
Пример #12
0
bool SDCardClass::writeFile(const char *path, const uint8_t *buf, uint8_t len, bool createDir) {
  SDCardFile file(path);
  SDCardEntry parentDir(file.dir);
  if (!parentDir.exists) {
    if (createDir) {
      if (!createDirectory(file.dir)) {
	return false;
      }
      parentDir.setPath(file.dir);
    } else {
      return false;
    }
  }

  return (file.writeFile(buf, len) == len);
}
Пример #13
0
bool NetEin::rmDir(const QString &dirPath)
{
    QDir dir(dirPath);
    if (!dir.exists())
        return true;
    foreach(const QFileInfo &info, dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) {
        if (info.isDir()) {
            if (!rmDir(info.filePath()))
                return false;
        } else {
            if (!dir.remove(info.fileName()))
                return false;
        }
    }
    QDir parentDir(QFileInfo(dirPath).path());
    return parentDir.rmdir(QFileInfo(dirPath).fileName());
}
Пример #14
0
/*! DELETE (delete a file/folder)
*/
void QwsClientSocket::handleMessageDELETE(const QwMessage &message)
{
    resetIdleTimer();
    if (!user.privileges().testFlag(Qws::PrivilegeDeleteFiles)) {
        sendError(Qw::ErrorPermissionDenied); return; }

    QString folderBasePath = message.stringArg(0).section('/', 0, -2, QString::SectionSkipEmpty);
    QString folderBaseName = message.stringArg(0).section('/', -1, -1, QString::SectionSkipEmpty);

    qDebug() << this << "Path=" << folderBasePath << "Item=" << folderBaseName;

    QwsFile targetBase;
    targetBase.setRemotePath(message.stringArg(0));
    targetBase.localFilesRoot = filesRootPath;
    if (!targetBase.loadFromLocalPath(true)) {
        sendError(Qw::ErrorFileOrDirectoryNotFound);
        return;
    }

    if (targetBase.localPath() == filesRootPath) {
        sendError(Qw::ErrorFileOrDirectoryNotFound);
        return;
    }

    QFileInfo targetInfo(targetBase.localPath());
    QDir targetFolder(targetBase.localPath());
    if (targetInfo.isDir()) {
        // Directory
        qDebug() << "Deleting a directory.";
        deleteDirRecursive(targetInfo.absoluteFilePath());

    } else {
        // File
        QDir parentDir(targetBase.localPath());
        if (!parentDir.cdUp()) {
            sendError(Qw::ErrorFileOrDirectoryNotFound);
            return;
        }
        if (!parentDir.remove(folderBaseName)) {
            qDebug() << this << "Unable to delete file" << targetBase.localPath();
            sendError(Qw::ErrorFileOrDirectoryNotFound);
            return;
        }
    }

}
Пример #15
0
QString MaItem::absPathToFilename(const QString& filename) const
{
	QString path;

	if (filename.isEmpty())
		return QString();

	if (NULL == mParentItem)
	{
		path = _STORE->location();
		path.append("/");
		path.append(filename);
	}
	else
		path = parentDir().absoluteFilePath(filename);

	return path;
}
Пример #16
0
/**
 * Creates directory recursively. Also access rights can be omitted. Defaults are 700 in unix.
 *
 * @param path full path of the directory created.
 * @param mode directory access rights, optional parameter, default value 0700 (owner: rwx, group: ---, others: ---)
 * @throws IOException exception is thrown if the directory creation failed.
 */
void digidoc::util::File::createDirectory(const std::string& path) throw(IOException)
{
    if(path.empty())
    {
        THROW_IOEXCEPTION("Can not create directory with no name.");
    }

    if(directoryExists(path))
    {
        return;
    }

    std::string parentDir(path);
    if(parentDir[parentDir.size() - 1] == '/' || parentDir[parentDir.size() - 1] == '\\')
    {
        parentDir = parentDir.substr(0, parentDir.size() - 1);
    }
    parentDir = parentDir.substr(0, parentDir.find_last_of("/\\"));

    if(!directoryExists(parentDir))
    {
        createDirectory(parentDir);
    }

    f_string _path = encodeName(path);
#ifdef _WIN32
    int result = _wmkdir(_path.c_str());
    if ( result )
        DEBUG("Creating directory '%s' failed with errno = %d", _path.c_str(), errno);
    else
        DEBUG("Created directory '%s'", _path.c_str());
#else
    umask(0);
    int result = mkdir(_path.c_str(), 0700);
    DEBUG("Created directory '%s' with result = %d", _path.c_str(), result);
#endif

    if(result || !directoryExists(path))
    {
        THROW_IOEXCEPTION("Failed to create directory '%s'", path.c_str());
    }
}
Пример #17
0
bool CController::createFile(const QString &parentFolder, const QString &name)
{
	QDir parentDir(parentFolder);
	if (!parentDir.exists())
		return false;

	const QString newFilePath = parentDir.absolutePath() + "/" + name;
	if (QFile(newFilePath).open(QFile::WriteOnly))
	{
		if (toNativeSeparators(parentDir.absolutePath()) == activePanel().currentDirPathNative())
		{
			// This is required for the UI to know to set the cursor at the new file
			setCursorPositionForCurrentFolder(CFileSystemObject(newFilePath).hash());
		}

		return true;
	}
	else
		return false;
}
Пример #18
0
bool CController::createFolder(const QString &parentFolder, const QString &name)
{
	QDir parentDir(parentFolder);
	if (!parentDir.exists())
		return false;

	const QString posixName = toPosixSeparators(name);
	if (parentDir.mkpath(posixName))
	{
		if (parentDir.absolutePath() == activePanel().currentDirObject().qDir().absolutePath())
		{
			const int slashPosition = posixName.indexOf('/');
			const QString newFolderPath = parentDir.absolutePath() + "/" + (slashPosition > 0 ? posixName.left(posixName.indexOf('/')) : posixName);
			// This is required for the UI to know to set the cursor at the new folder
			setCursorPositionForCurrentFolder(CFileSystemObject(newFolderPath).hash());
		}

		return true;
	}
	else
		return false;
}
Пример #19
0
bool Util::removeDir(const QString &dirPath, const QString &filter)
{
  QFileInfo dirInfo(dirPath);
  if (dirInfo.isFile())
  {
    return QFile (dirPath).remove();
  }

  QDir dir(dirPath);
  if (!dir.exists())
    return true;

  foreach(const QFileInfo &info, dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot))
  {
    if (info.isDir())
    {
      if (!removeDir(info.filePath(), filter))
        return false;
    }
    else
    {
      if (!filter.isEmpty() && !info.fileName().contains(filter))
        continue;

      if (!dir.remove(info.fileName()))
        return false;
    }
  }

  if (filter.isEmpty())
  {
   QDir parentDir(QFileInfo(dirPath).path());
   return parentDir.rmdir(QFileInfo(dirPath).fileName());
  }

  return true;
}
QStringList QDnotifyFileSystemWatcherEngine::addPaths(const QStringList &paths, QStringList *files, QStringList *directories)
{
    QMutexLocker locker(&mutex);

    QStringList p = paths;
    QMutableListIterator<QString> it(p);

    while (it.hasNext()) {
        QString path = it.next();

        QFileInfo fi(path);

        if(!fi.exists()) {
            continue;
        }

        bool isDir = fi.isDir();

        if (isDir && directories->contains(path)) {
            continue; // Skip monitored directories
        } else if(!isDir && files->contains(path)) {
            continue; // Skip monitored files
        }

        if(!isDir)
            path = fi.canonicalPath();

        // Locate the directory entry (creating if needed)
        int fd = pathToFD[path];

        if(fd == 0) {

            QT_DIR *d = QT_OPENDIR(path.toUtf8().constData());
            if(!d) continue; // Could not open directory
            QT_DIR *parent = 0;

            QDir parentDir(path);
            if(!parentDir.isRoot()) {
                parentDir.cdUp();
                parent = QT_OPENDIR(parentDir.path().toUtf8().constData());
                if(!parent) {
                    QT_CLOSEDIR(d);
                    continue;
                }
            }

            fd = qt_safe_dup(::dirfd(d));
            int parentFd = parent ? qt_safe_dup(::dirfd(parent)) : 0;

            QT_CLOSEDIR(d);
            if(parent) QT_CLOSEDIR(parent);

            Q_ASSERT(fd);
            if(::fcntl(fd, F_SETSIG, SIGIO) ||
               ::fcntl(fd, F_NOTIFY, DN_MODIFY | DN_CREATE | DN_DELETE |
                                     DN_RENAME | DN_ATTRIB | DN_MULTISHOT) ||
               (parent && ::fcntl(parentFd, F_SETSIG, SIGIO)) ||
               (parent && ::fcntl(parentFd, F_NOTIFY, DN_DELETE | DN_RENAME |
                                            DN_MULTISHOT))) {
                continue; // Could not set appropriate flags
            }

            Directory dir;
            dir.path = path;
            dir.fd = fd;
            dir.parentFd = parentFd;

            fdToDirectory.insert(fd, dir);
            pathToFD.insert(path, fd);
            if(parentFd)
                parentToFD.insert(parentFd, fd);
        }

        Directory &directory = fdToDirectory[fd];

        if(isDir) {
            directory.isMonitored = true;
        } else {
            Directory::File file;
            file.path = fi.filePath();
            file.lastWrite = fi.lastModified();
            directory.files.append(file);
            pathToFD.insert(fi.filePath(), fd);
        }

        it.remove();

        if(isDir) {
            directories->append(path);
        } else {
            files->append(fi.filePath());
        }
    }

    dnotifySignal()->startNotify();

    return p;
}
Пример #21
0
// -----------------------------------------------------------------------------
// Parses a preprocessor directive at [tz]'s current token
// -----------------------------------------------------------------------------
bool ParseTreeNode::parsePreprocessor(Tokenizer& tz)
{
	// Log::debug(wxString::Format("Preprocessor %s", CHR(tz.current().text)));

	// #define
	if (tz.current() == "#define")
		parser_->define(tz.next().text);

	// #if(n)def
	else if (tz.current() == "#ifdef" || tz.current() == "#ifndef")
	{
		// Continue if condition succeeds
		bool test = true;
		if (tz.current() == "#ifndef")
			test = false;
		auto define = tz.next().text;
		if (parser_->defined(define) == test)
			return true;

		// Failed condition, skip section
		int skip = 0;
		while (true)
		{
			auto& token = tz.next();
			if (token == "#endif")
				skip--;
			else if (token == "#ifdef")
				skip++;
			else if (token == "#ifndef")
				skip++;
			// TODO: #else

			if (skip < 0)
				break;
		}
	}

	// #include
	else if (tz.current() == "#include")
	{
		// Include entry at the given path if we have an archive dir set
		if (archive_dir_)
		{
			// Get entry to include
			auto inc_path  = tz.next().text;
			auto archive   = archive_dir_->archive();
			auto inc_entry = archive->entryAtPath(archive_dir_->path() + inc_path);
			if (!inc_entry) // Try absolute path
				inc_entry = archive->entryAtPath(inc_path);

			// Log::debug(wxString::Format("Include %s", CHR(inc_path)));

			if (inc_entry)
			{
				// Save the current dir and set it to the included entry's dir
				auto orig_dir = archive_dir_;
				archive_dir_  = inc_entry->parentDir();

				// Parse text in the entry
				Tokenizer inc_tz;
				inc_tz.openMem(inc_entry->data(), inc_entry->name());
				bool ok = parse(inc_tz);

				// Reset dir and abort if parsing failed
				archive_dir_ = orig_dir;
				if (!ok)
					return false;
			}
			else
				logError(tz, fmt::format("Include entry {} not found", inc_path));
		}
		else
			tz.adv(); // Skip include path
	}

	// #endif (ignore)
	else if (tz.current() == "#endif")
		return true;

	// TODO: #else

	// Unrecognised
	else
		logError(tz, fmt::format("Unrecognised preprocessor directive \"{}\"", tz.current().text));

	return true;
}
Пример #22
0
Error processEvent(FileEventContext* pContext,
                   struct inotify_event* pEvent,
                   std::vector<FileChangeEvent>* pFileChanges)
{
   // determine event type
   FileChangeEvent::Type eventType = FileChangeEvent::None;
   if (pEvent->mask & IN_CREATE)
      eventType = FileChangeEvent::FileAdded;
   else if (pEvent->mask & IN_DELETE)
      eventType = FileChangeEvent::FileRemoved;
   else if (pEvent->mask & IN_MODIFY)
      eventType = FileChangeEvent::FileModified;
   else if (pEvent->mask & IN_MOVED_TO)
      eventType = FileChangeEvent::FileAdded;
   else if (pEvent->mask & IN_MOVED_FROM)
      eventType = FileChangeEvent::FileRemoved;

   // return event if we got a valid event type and the event applies to a
   // child of the monitored directory (len == 0 occurs for root element)
   if ((eventType != FileChangeEvent::None) && (pEvent->len > 0))
   {
      // find the FileInfo for this wd (ignore if we can't find one)
      Watch watch = pContext->watches.find(pEvent->wd);
      if (watch.empty())
         return Success();

      // get an iterator to the parent dir
      FileInfo parentDir(watch.path, true);
      tcl::unique_tree<FileInfo>::tree_type* pParentNode
                           = impl::findNode(&pContext->fileTree, parentDir);

      // if we can't find a parent then return (this directory may have
      // been excluded from scanning due to a filter)
      if (pParentNode == NULL)
         return Success();

      // get file info
      FilePath filePath = FilePath(pParentNode->get()->absolutePath()).complete(
                                                                 pEvent->name);


      // if the file exists then collect as many extended attributes
      // as necessary -- otherwise just record path and dir status
      FileInfo fileInfo;
      if (filePath.exists())
      {
         fileInfo = FileInfo(filePath, filePath.isSymlink());
      }
      else
      {
         fileInfo = FileInfo(filePath.absolutePath(), pEvent->mask & IN_ISDIR);
      }

      // if this doesn't meet the filter then ignore
      if (pContext->filter && !pContext->filter(fileInfo))
         return Success();

      // handle the various types of actions
      switch(eventType)
      {
         case FileChangeEvent::FileRemoved:
         {
            // generate events
            FileChangeEvent event(FileChangeEvent::FileRemoved, fileInfo);
            std::vector<FileChangeEvent> removeEvents;
            impl::processFileRemoved(pParentNode,
                                     event,
                                     pContext->recursive,
                                     &pContext->fileTree,
                                     &removeEvents);

            // for each directory remove event remove any watches we have for it
            BOOST_FOREACH(const FileChangeEvent& event, removeEvents)
            {
               if (event.fileInfo().isDirectory())
               {
                  Watch watch = pContext->watches.find(
                                             event.fileInfo().absolutePath());
                  if (!watch.empty())
                  {
                     removeWatch(pContext->fd, watch);
                     pContext->watches.erase(watch);
                  }
               }
            }

            // copy to the target events
            std::copy(removeEvents.begin(),
                      removeEvents.end(),
                      std::back_inserter(*pFileChanges));

            break;
         }
         case FileChangeEvent::FileAdded:
         {
            FileChangeEvent event(FileChangeEvent::FileAdded, fileInfo);
            Error error = impl::processFileAdded(pParentNode,
                                                 event,
                                                 pContext->recursive,
                                                 pContext->filter,
                                                 addWatchFunction(pContext),
                                                 &pContext->fileTree,
                                                 pFileChanges);
            // log the error if it wasn't no such file/dir (this can happen
            // in the normal course of business if a file is deleted between
            // the time the change is detected and we try to inspect it)
            if (error &&
               (error.code() != boost::system::errc::no_such_file_or_directory))
            {
               LOG_ERROR(error);
            }
            break;
         }
         case FileChangeEvent::FileModified:
         {
            FileChangeEvent event(FileChangeEvent::FileModified, fileInfo);
            impl::processFileModified(pParentNode,
                                      event,
                                      &pContext->fileTree,
                                      pFileChanges);
            break;
         }
         case FileChangeEvent::None:
            break;
      }
   }
Пример #23
0
bool K3bCueFileParser::findImageFileName( const QString& dataFile )
{
  //
  // CDRDAO does not use this image filename but replaces the extension from the cue file
  // with "bin" to get the image filename, we should take this into account
  //

  m_imageFilenameInCue = true;

  // first try filename as a hole (absolut)
  if( QFile::exists( dataFile ) ) {
    setImageFilename( QFileInfo(dataFile).absFilePath() );
    return true;
  }

  // try the filename in the cue's directory
  if( QFileInfo( K3b::parentDir(filename()) + dataFile.section( '/', -1 ) ).isFile() ) {
    setImageFilename( K3b::parentDir(filename()) + dataFile.section( '/', -1 ) );
    kdDebug() << "(K3bCueFileParser) found image file: " << imageFilename() << endl;
    return true;
  }

  // try the filename ignoring case
  if( QFileInfo( K3b::parentDir(filename()) + dataFile.section( '/', -1 ).lower() ).isFile() ) {
    setImageFilename( K3b::parentDir(filename()) + dataFile.section( '/', -1 ).lower() );
    kdDebug() << "(K3bCueFileParser) found image file: " << imageFilename() << endl;
    return true;
  }

  m_imageFilenameInCue = false;

  // try removing the ending from the cue file (image.bin.cue and image.bin)
  if( QFileInfo( filename().left( filename().length()-4 ) ).isFile() ) {
    setImageFilename( filename().left( filename().length()-4 ) );
    kdDebug() << "(K3bCueFileParser) found image file: " << imageFilename() << endl;
    return true;
  }

  //
  // we did not find the image specified in the cue.
  // Search for another one having the same filename as the cue but a different extension
  //

  QDir parentDir( K3b::parentDir(filename()) );
  QString filenamePrefix = filename().section( '/', -1 );
  filenamePrefix.truncate( filenamePrefix.length() - 3 ); // remove cue extension
  kdDebug() << "(K3bCueFileParser) checking folder " << parentDir.path() << " for files: " << filenamePrefix << "*" << endl;

  //
  // we cannot use the nameFilter in QDir because of the spaces that may occur in filenames
  //
  QStringList possibleImageFiles = parentDir.entryList( QDir::Files );
  int cnt = 0;
  for( QStringList::const_iterator it = possibleImageFiles.constBegin(); it != possibleImageFiles.constEnd(); ++it ) {
    if( (*it).lower() == dataFile.section( '/', -1 ).lower() ||
	(*it).startsWith( filenamePrefix ) && !(*it).endsWith( "cue" ) ) {
      ++cnt;
      setImageFilename( K3b::parentDir(filename()) + *it );
    }
  }

  //
  // we only do this if there is one unique file which fits the requirements. 
  // Otherwise we cannot be certain to have the right file.
  //
  return ( cnt == 1 && QFileInfo( imageFilename() ).isFile() );
}