コード例 #1
0
ファイル: rcc.cpp プロジェクト: setanta/Tools
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice, QString fname, QString currentPath)
{
    if (!currentPath.isEmpty() && !currentPath.endsWith(QLatin1String("/")))
        currentPath += '/';

    QDomDocument document;
    {
        QString errorMsg;
        int errorLine, errorColumn;
        if(!document.setContent(inputDevice, &errorMsg, &errorLine, &errorColumn)) {
            fprintf(stderr, "pyrcc4 Parse Error:%s:%d:%d [%s]\n", fname.toLatin1().constData(),
                    errorLine, errorColumn, errorMsg.toLatin1().constData());
            return false;
        }
    }
    for(QDomElement root = document.firstChild().toElement(); !root.isNull();
        root = root.nextSibling().toElement()) {
        if (root.tagName() != QLatin1String(TAG_RCC))
            continue;

        for (QDomElement child = root.firstChild().toElement(); !child.isNull();
             child = child.nextSibling().toElement()) {
            if (child.tagName() == QLatin1String(TAG_RESOURCE)) {
                QLocale lang = QLocale::c();
                if (child.hasAttribute(ATTRIBUTE_LANG))
                    lang = QLocale(child.attribute(ATTRIBUTE_LANG));

                QString prefix;
                if (child.hasAttribute(ATTRIBUTE_PREFIX))
                    prefix = child.attribute(ATTRIBUTE_PREFIX);
                if (!prefix.startsWith(QLatin1String("/")))
                    prefix.prepend('/');
                if (!prefix.endsWith(QLatin1String("/")))
                    prefix += '/';


                for (QDomNode res = child.firstChild(); !res.isNull(); res = res.nextSibling()) {
                    if (res.toElement().tagName() == QLatin1String(TAG_FILE)) {

                        QString fileName(res.firstChild().toText().data());
                        if (fileName.isEmpty())
                            fprintf(stderr, "Warning: Null node in XML\n");

                        QString alias;
                        if (res.toElement().hasAttribute(ATTRIBUTE_ALIAS))
                            alias = res.toElement().attribute(ATTRIBUTE_ALIAS);
                        else
                            alias = fileName;

                        int compressLevel = mCompressLevel;
                        if (res.toElement().hasAttribute(ATTRIBUTE_COMPRESS))
                            compressLevel = res.toElement().attribute(ATTRIBUTE_COMPRESS).toInt();
                        int compressThreshold = mCompressThreshold;
                        if (res.toElement().hasAttribute(ATTRIBUTE_THRESHOLD))
                            compressThreshold = res.toElement().attribute(ATTRIBUTE_THRESHOLD).toInt();

                        // Special case for -no-compress. Overrides all other settings.
                        if (mCompressLevel == -2)
                            compressLevel = 0;

                        alias = QDir::cleanPath(alias);
                        while (alias.startsWith("../"))
                            alias.remove(0, 3);
                        alias = prefix + alias;

                        QFileInfo file(currentPath + fileName);
                        if (!file.exists()) {
                            fprintf(stderr, "Cannot find file: %s\n", fileName.toLatin1().constData());
                            continue ;
                        } else if (file.isFile()) {
                            addFile(alias, RCCFileInfo(alias.section('/', -1), file, lang,
                                                       RCCFileInfo::NoFlags, compressLevel, compressThreshold));
                        } else {
                            QDir dir;
                            if(file.isDir()) {
                                dir.setPath(file.filePath());
                            } else {
                                dir.setPath(file.path());
                                dir.setNameFilters(QStringList(file.fileName()));
                                if(alias.endsWith(file.fileName()))
                                    alias = alias.left(alias.length()-file.fileName().length());
                            }
                            if (!alias.endsWith(QLatin1String("/")))
                                alias += '/';
                            QFileInfoList children = dir.entryInfoList();
                            for(int i = 0; i < children.size(); ++i) {
                                if(children[i].fileName() != QLatin1String(".") &&
                                   children[i].fileName() != QLatin1String(".."))
                                    addFile(alias + children[i].fileName(),
                                            RCCFileInfo(children[i].fileName(), children[i], lang,
                                                        RCCFileInfo::NoFlags, compressLevel, compressThreshold));
                            }
                        }
                    }
                }
            }
        }
    }
    if(this->root == 0) {
        fprintf(stderr, "No resources in resource description.\n");
        return false;
    }
    return true;
}
コード例 #2
0
ファイル: IndexEnvironment.cpp プロジェクト: fedorn/lemur
void indri::api::IndexEnvironment::addFile( const std::string& fileName ) {
  std::string extension = indri::file::Path::extension( fileName );
  addFile( fileName, extension );
}
コード例 #3
0
ファイル: fileorganiserwidget.cpp プロジェクト: A1kmm/opencor
void FileOrganiserWidget::dropEvent(QDropEvent *pEvent)
{
    // Note: the MIME data definitely contains the FileSystemMimeType MIME type
    //       (for objects originating from outside this widget), but it may also
    //       contain the FileOrganiserMimeType MIME type (for objects
    //       originating from within this widget). FileOrganiserMimeType is used
    //       by this widget while FileSystemMimeType by external widgets. So,
    //       this means that we must check for FileOrganiserMimeType first

    // Files have been dropped, so add them to the widget and this at the right
    // place (i.e. above/on/below a folder, above/below a file or on the
    // invisible root folder)

    // First, determine the item above/on/below which objects are to be dropped,
    // as well as the drop position (i.e. above, on or below)

    QStandardItem *dropItem;
    DropIndicatorPosition dropPosition = dropIndicatorPosition();

    if (dropPosition == QAbstractItemView::OnViewport) {
        // We dropped the files on the viewport, so...

        dropItem = mModel->invisibleRootItem();

        // Change the drop position since we know that we want want the objects
        // to be dropped on the root folder

        dropPosition = QAbstractItemView::OnItem;
    } else {
        // We dropped the files above/on/below a folder or above/below a file,
        // so...

        dropItem = mModel->itemFromIndex(indexAt(pEvent->pos()));
    }

    // Check the type of MIME data to be dropped

    if (pEvent->mimeData()->hasFormat(FileOrganiserMimeType)) {
        // The user is dropping folders/files from ourselves, i.e. s/he wants
        // some folders/files to be moved around

        // Retrieve the list of indexes to move around and clean it

        QByteArray data = pEvent->mimeData()->data(FileOrganiserMimeType);
        QModelIndexList indexes = cleanIndexList(mModel->decodeData(data));

        // Convert our list of indexes to a list of items
        // Note: indeed, by moving the item corresponding to a particular index,
        //       we may mess up the other indexes, meaning that we may not be
        //       able to retrieve their corresponding item, so...

        QList<QStandardItem *> items;

        for (int i = 0, iMax = indexes.count(); i < iMax; ++i)
            items << mModel->itemFromIndex(indexes[i]);

        // Move the contents of the list to its final destination

        if (dropPosition != QAbstractItemView::BelowItem)
            // Move the items in the order they were dropped

            for (int i = 0, iMax = items.count(); i < iMax; ++i)
                moveItem(items[i], dropItem, dropPosition);
        else
            // Move the items in a reverse order to that they were dropped since
            // we want them moved below the current item

            for (int i = items.count()-1; i >= 0; --i)
                moveItem(items[i], dropItem, dropPosition);
    } else {
        // The user wants to drop files, so add them to the widget and this at
        // the right place

        QList<QUrl> urls = pEvent->mimeData()->urls();

        if (dropPosition != QAbstractItemView::BelowItem)
            // Add the files in the order they were dropped

            for (int i = 0, iMax = urls.count(); i < iMax; ++i)
                addFile(urls[i].toLocalFile(), dropItem, dropPosition);
        else
            // Add the files in a reverse order to that they were dropped since
            // we want them added below the current item

            for (int i = urls.count()-1; i >= 0; --i)
                addFile(urls[i].toLocalFile(), dropItem, dropPosition);
    }

    // Accept the proposed action for the event

    pEvent->acceptProposedAction();

    // Reset the state of the widget
    // Note: there doesn't seem to be and there shouldn't be a need to reset the
    //       state after the widget (the resetting seems to be done elsewhere),
    //       but if don't reset the state of the widget, then the drop indicator
    //       may, in some cases, remain visible (a bug in Qt?), so...

    setState(QAbstractItemView::NoState);
}
コード例 #4
0
void ossimFreeTypeFontFactory::initializeDefaults()
{
   const ossimKeywordlist& kwl = ossimPreferences::instance()->preferencesKWL();
   ossimString regExpressionDir =  ossimString("^(") + "font.dir[0-9]+)";
   ossimString regExpressionFile =  ossimString("^(") + "font.file[0-9]+)";
   vector<ossimString> dirs =
      kwl.getSubstringKeyList( regExpressionDir );
   vector<ossimString> files =
      kwl.getSubstringKeyList( regExpressionFile );
   
   int idx = 0;
   for(idx = 0; idx < (int)dirs.size();++idx)
   {
      const char* directoryLocation = kwl.find(dirs[idx]);
      if(directoryLocation)
      {
         ossimDirectory d;
	 
         if(d.open(ossimFilename(directoryLocation)))
         {
            ossimFilename file;
	    
            if(d.getFirst(file, ossimDirectory::OSSIM_DIR_FILES))
            {
               do
               {
                  addFile(file);
               }while(d.getNext(file));
            }
         }
      }
   }
   for(idx = 0; idx < (int)files.size();++idx)
   {
      const char* fileName = kwl.find(files[idx]);
      
      if(fileName)
      {
         addFile(ossimFilename(fileName));
      }
   }   
#if 0
   if(!numberOfDirs&&!numberOfFiles)
   {
#ifdef __UNIX__
      ossimFilename file("/usr/X11R6/lib/X11/fonts/Type1");
      
      if(file.exists())
      {
         ossimDirectory d;
         if(d.open(file))
         {
            if(d.getFirst(file, ossimDirectory::OSSIM_DIR_FILES))
            {
               do
               {
                  addFile(file);
               }while(d.getNext(file));
            }
         }
      }
#endif
   }
#endif
}
コード例 #5
0
		// called when the directory is actually changed
		// means a file has been added or removed
		// rescans the watched directory adding/removing files and sending notices
		void rescan()
		{
			// if new file, call addFile
			// if missing file, call removeFile
			// if timestamp modified, call handleAction(filename, ACTION_MODIFIED);
			DIR* dir = opendir(mDirName.c_str());
			if(!dir)
				return;
			
			struct dirent* dentry;
			KEvent* ke = &mChangeList[1];
			EntryStruct* entry = 0;
			struct stat attrib;			
			bool bRescanRequired = false; //if files are added or deleted we need a rescan.
			while((dentry = readdir(dir)) != NULL)
			{
                std::string fname = mDirName.m_string + "/" + dentry->d_name;
				stat(fname.c_str(), &attrib);
				if(!S_ISREG(attrib.st_mode))
					continue;
				
				if(ke <= &mChangeList[mChangeListCount])
				{
					entry = (EntryStruct*)ke->udata;
					int result = strcmp(entry->mFilename, fname.c_str());
					//fprintf(stderr, "[%s cmp %s]\n", entry->mFilename, fname.c_str());
					if(result == 0)
					{
						stat(entry->mFilename, &attrib);
						time_t timestamp = attrib.st_mtime;
						
						if(entry->mModifiedTime != timestamp)
						{
							entry->mModifiedTime = timestamp;
							handleAction(entry->mFilename, Actions::Modified);
						}
						ke++;
					}
                    else
                    {
                        // file might have been added or deleted
                        // if we find the file in our list, then we have some deletions up to that point
                        // otherwise we have an add
                        bRescanRequired = true;
                        KEvent* currKe = ke+1;
                        while( currKe <= &mChangeList[mChangeListCount])
                        {
                            entry = (EntryStruct*)currKe->udata;
                            int res = strcmp(entry->mFilename, fname.c_str());
                            if(res == 0)
                            {
                                //have found the file in our list
                                break;
                            }
                            ++currKe;
                        }
                        
                        //process events but don't add/remove to list.
                        if( currKe <= &mChangeList[mChangeListCount] )
                        {
                           //have some deletions.
                           while( ke < currKe )
                           {
                               entry = (EntryStruct*)ke->udata;
                               handleAction(entry->mFilename, Actions::Delete);
                               ++ke;
                           }
                            ++ke;
                        }
                        else
                        {
                            //we don't increment ke here as it's an add in the middle.
                            handleAction(fname.c_str(), Actions::Add);
                        }
                    }
                    /*
					else if(result < 0)
					{
						// f1 was deleted
						removeFile(entry->mFilename);
						ke++;
					}
					else
					{
						// f2 was created
						addFile(fname);
						ke++;
					}
                     */
				}
				else
				{
					// just add
					addFile(fname);
					ke++;
				}
			}//end while
			
			closedir(dir);
            
            while( ke <= &mChangeList[mChangeListCount] )
            {
                // the last files have been deleted...
                bRescanRequired = true;
                entry = (EntryStruct*)ke->udata;
                handleAction(entry->mFilename, Actions::Delete);
                ++ke;
                
            }
            
            if( bRescanRequired )
            {
                removeAll();
                addAll();
            }
		};
コード例 #6
0
ファイル: breakpoint.C プロジェクト: BillTheBest/k42
void breakpoint_init(FileInfoVirtFSDir* sysFS) {
    addFile(new BreakProc("breakpoint"), sysFS);
}
コード例 #7
0
ファイル: rcc.cpp プロジェクト: Suneal/qt
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice,
    const QString &fname, QString currentPath, bool ignoreErrors)
{
    Q_ASSERT(m_errorDevice);
    const QChar slash = QLatin1Char('/');
    if (!currentPath.isEmpty() && !currentPath.endsWith(slash))
        currentPath += slash;

    QDomDocument document;
    {
        QString errorMsg;
        int errorLine = 0;
        int errorColumn = 0;
        if (!document.setContent(inputDevice, &errorMsg, &errorLine, &errorColumn)) {
            if (ignoreErrors)
                return true;
            const QString msg = QString::fromUtf8("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMsg);
            m_errorDevice->write(msg.toUtf8());
            return false;
        }
    }

    QDomElement domRoot = document.firstChildElement(m_strings.TAG_RCC).toElement();
    if (!domRoot.isNull() && domRoot.tagName() == m_strings.TAG_RCC) {
        for (QDomNode node = domRoot.firstChild(); !node.isNull(); node = node.nextSibling()) {
            if (!node.isElement())
                continue;

            QDomElement child = node.toElement();
            if (!child.isNull() && child.tagName() == m_strings.TAG_RESOURCE) {
                QLocale::Language language = QLocale::c().language();
                QLocale::Country country = QLocale::c().country();

                if (child.hasAttribute(m_strings.ATTRIBUTE_LANG)) {
                    QString attribute = child.attribute(m_strings.ATTRIBUTE_LANG);
                    QLocale lang = QLocale(attribute);
                    language = lang.language();
                    if (2 == attribute.length()) {
                        // Language only
                        country = QLocale::AnyCountry;
                    } else {
                        country = lang.country();
                    }
                }

                QString prefix;
                if (child.hasAttribute(m_strings.ATTRIBUTE_PREFIX))
                    prefix = child.attribute(m_strings.ATTRIBUTE_PREFIX);
                if (!prefix.startsWith(slash))
                    prefix.prepend(slash);
                if (!prefix.endsWith(slash))
                    prefix += slash;

                for (QDomNode res = child.firstChild(); !res.isNull(); res = res.nextSibling()) {
                    if (res.isElement() && res.toElement().tagName() == m_strings.TAG_FILE) {

                        QString fileName(res.firstChild().toText().data());
                        if (fileName.isEmpty()) {
                            const QString msg = QString::fromUtf8("RCC: Warning: Null node in XML of '%1'\n").arg(fname);
                            m_errorDevice->write(msg.toUtf8());
                        }
                        QString alias;
                        if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_ALIAS))
                            alias = res.toElement().attribute(m_strings.ATTRIBUTE_ALIAS);
                        else
                            alias = fileName;

                        int compressLevel = m_compressLevel;
                        if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_COMPRESS))
                            compressLevel = res.toElement().attribute(m_strings.ATTRIBUTE_COMPRESS).toInt();
                        int compressThreshold = m_compressThreshold;
                        if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_THRESHOLD))
                            compressThreshold = res.toElement().attribute(m_strings.ATTRIBUTE_THRESHOLD).toInt();

                        // Special case for -no-compress. Overrides all other settings.
                        if (m_compressLevel == -2)
                            compressLevel = 0;

                        alias = QDir::cleanPath(alias);
                        while (alias.startsWith(QLatin1String("../")))
                            alias.remove(0, 3);
                        alias = QDir::cleanPath(m_resourceRoot) + prefix + alias;

                        QString absFileName = fileName;
                        if (QDir::isRelativePath(absFileName))
                            absFileName.prepend(currentPath);
                        QFileInfo file(absFileName);
                        if (!file.exists()) {
                            m_failedResources.push_back(absFileName);
                            const QString msg = QString::fromUtf8("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName);
                            m_errorDevice->write(msg.toUtf8());
                            if (ignoreErrors)
                                continue;
                            else
                                return false;
                        } else if (file.isFile()) {
                            const bool arc =
                                addFile(alias,
                                        RCCFileInfo(alias.section(slash, -1),
                                                    file,
                                                    language,
                                                    country,
                                                    RCCFileInfo::NoFlags,
                                                    compressLevel,
                                                    compressThreshold)
                                        );
                            if (!arc)
                                m_failedResources.push_back(absFileName);
                        } else {
                            QDir dir;
                            if (file.isDir()) {
                                dir.setPath(file.filePath());
                            } else {
                                dir.setPath(file.path());
                                dir.setNameFilters(QStringList(file.fileName()));
                                if (alias.endsWith(file.fileName()))
                                    alias = alias.left(alias.length()-file.fileName().length());
                            }
                            if (!alias.endsWith(slash))
                                alias += slash;
                            QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories);
                            while (it.hasNext()) {
                                it.next();
                                QFileInfo child(it.fileInfo());
                                if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) {
                                    const bool arc =
                                        addFile(alias + child.fileName(),
                                                RCCFileInfo(child.fileName(),
                                                            child,
                                                            language,
                                                            country,
                                                            RCCFileInfo::NoFlags,
                                                            compressLevel,
                                                            compressThreshold)
                                                );
                                    if (!arc)
                                        m_failedResources.push_back(child.fileName());
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (m_root == 0) {
        const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname);
        m_errorDevice->write(msg.toUtf8());
        if (!ignoreErrors && m_format == Binary) {
            // create dummy entry, otherwise loading qith QResource will crash
            m_root = new RCCFileInfo(QString(), QFileInfo(),
                    QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory);
        }
    }

    return true;
}
コード例 #8
0
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice,
    const QString &fname, QString currentPath, bool ignoreErrors)
{
    Q_ASSERT(m_errorDevice);
    const QChar slash = QLatin1Char('/');
    if (!currentPath.isEmpty() && !currentPath.endsWith(slash))
        currentPath += slash;

    QXmlStreamReader reader(inputDevice);
    QStack<RCCXmlTag> tokens;

    QString prefix;
    QLocale::Language language = QLocale::c().language();
    QLocale::Country country = QLocale::c().country();
    QString alias;
    int compressLevel = m_compressLevel;
    int compressThreshold = m_compressThreshold;

    while (!reader.atEnd()) {
        QXmlStreamReader::TokenType t = reader.readNext();
        switch (t) {
        case QXmlStreamReader::StartElement:
            if (reader.name() == m_strings.TAG_RCC) {
                if (!tokens.isEmpty())
                    reader.raiseError(QLatin1String("expected <RCC> tag"));
                else
                    tokens.push(RccTag);
            } else if (reader.name() == m_strings.TAG_RESOURCE) {
                if (tokens.isEmpty() || tokens.top() != RccTag) {
                    reader.raiseError(QLatin1String("unexpected <RESOURCE> tag"));
                } else {
                    tokens.push(ResourceTag);

                    QXmlStreamAttributes attributes = reader.attributes();
                    language = QLocale::c().language();
                    country = QLocale::c().country();

                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_LANG)) {
                        QString attribute = attributes.value(m_strings.ATTRIBUTE_LANG).toString();
                        QLocale lang = QLocale(attribute);
                        language = lang.language();
                        if (2 == attribute.length()) {
                            // Language only
                            country = QLocale::AnyCountry;
                        } else {
                            country = lang.country();
                        }
                    }

                    prefix.clear();
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_PREFIX))
                        prefix = attributes.value(m_strings.ATTRIBUTE_PREFIX).toString();
                    if (!prefix.startsWith(slash))
                        prefix.prepend(slash);
                    if (!prefix.endsWith(slash))
                        prefix += slash;
                }
            } else if (reader.name() == m_strings.TAG_FILE) {
                if (tokens.isEmpty() || tokens.top() != ResourceTag) {
                    reader.raiseError(QLatin1String("unexpected <FILE> tag"));
                } else {
                    tokens.push(FileTag);

                    QXmlStreamAttributes attributes = reader.attributes();
                    alias.clear();
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_ALIAS))
                        alias = attributes.value(m_strings.ATTRIBUTE_ALIAS).toString();

                    compressLevel = m_compressLevel;
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_COMPRESS))
                        compressLevel = attributes.value(m_strings.ATTRIBUTE_COMPRESS).toString().toInt();

                    compressThreshold = m_compressThreshold;
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_THRESHOLD))
                        compressThreshold = attributes.value(m_strings.ATTRIBUTE_THRESHOLD).toString().toInt();

                    // Special case for -no-compress. Overrides all other settings.
                    if (m_compressLevel == -2)
                        compressLevel = 0;
                }
            } else {
                reader.raiseError(QString(QLatin1String("unexpected tag: %1")).arg(reader.name().toString()));
            }
            break;

        case QXmlStreamReader::EndElement:
            if (reader.name() == m_strings.TAG_RCC) {
                if (!tokens.isEmpty() && tokens.top() == RccTag)
                    tokens.pop();
                else
                    reader.raiseError(QLatin1String("unexpected closing tag"));
            } else if (reader.name() == m_strings.TAG_RESOURCE) {
                if (!tokens.isEmpty() && tokens.top() == ResourceTag)
                    tokens.pop();
                else
                    reader.raiseError(QLatin1String("unexpected closing tag"));
            } else if (reader.name() == m_strings.TAG_FILE) {
                if (!tokens.isEmpty() && tokens.top() == FileTag)
                    tokens.pop();
                else
                    reader.raiseError(QLatin1String("unexpected closing tag"));
            }
            break;

        case QXmlStreamReader::Characters:
            if (reader.isWhitespace())
                break;
            if (tokens.isEmpty() || tokens.top() != FileTag) {
                reader.raiseError(QLatin1String("unexpected text"));
            } else {
                QString fileName = reader.text().toString();
                if (fileName.isEmpty()) {
                    const QString msg = QString::fromLatin1("RCC: Warning: Null node in XML of '%1'\n").arg(fname);
                    m_errorDevice->write(msg.toUtf8());
                }

                if (alias.isNull())
                    alias = fileName;

                alias = QDir::cleanPath(alias);
                while (alias.startsWith(QLatin1String("../")))
                    alias.remove(0, 3);
                alias = QDir::cleanPath(m_resourceRoot) + prefix + alias;

                QString absFileName = fileName;
                if (QDir::isRelativePath(absFileName))
                    absFileName.prepend(currentPath);
                QFileInfo file(absFileName);
                if (!file.exists()) {
                    m_failedResources.push_back(absFileName);
                    const QString msg = QString::fromLatin1("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName);
                    m_errorDevice->write(msg.toUtf8());
                    if (ignoreErrors)
                        continue;
                    else
                        return false;
                } else if (file.isFile()) {
                    const bool arc =
                        addFile(alias,
                                RCCFileInfo(alias.section(slash, -1),
                                            file,
                                            language,
                                            country,
                                            RCCFileInfo::NoFlags,
                                            compressLevel,
                                            compressThreshold)
                                );
                    if (!arc)
                        m_failedResources.push_back(absFileName);
                } else {
                    QDir dir;
                    if (file.isDir()) {
                        dir.setPath(file.filePath());
                    } else {
                        dir.setPath(file.path());
                        dir.setNameFilters(QStringList(file.fileName()));
                        if (alias.endsWith(file.fileName()))
                            alias = alias.left(alias.length()-file.fileName().length());
                    }
                    if (!alias.endsWith(slash))
                        alias += slash;
                    QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories);
                    while (it.hasNext()) {
                        it.next();
                        QFileInfo child(it.fileInfo());
                        if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) {
                            const bool arc =
                                addFile(alias + child.fileName(),
                                        RCCFileInfo(child.fileName(),
                                                    child,
                                                    language,
                                                    country,
                                                    child.isDir() ? RCCFileInfo::Directory : RCCFileInfo::NoFlags,
                                                    compressLevel,
                                                    compressThreshold)
                                        );
                            if (!arc)
                                m_failedResources.push_back(child.fileName());
                        }
                    }
                }
            }
            break;

        default:
            break;
        }
    }

    if (reader.hasError()) {
        if (ignoreErrors)
            return true;
        int errorLine = reader.lineNumber();
        int errorColumn = reader.columnNumber();
        QString errorMessage = reader.errorString();
        QString msg = QString::fromLatin1("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMessage);
        m_errorDevice->write(msg.toUtf8());
        return false;
    }

    if (m_root == 0) {
        const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname);
        m_errorDevice->write(msg.toUtf8());
        if (!ignoreErrors && m_format == Binary) {
            // create dummy entry, otherwise loading with QResource will crash
            m_root = new RCCFileInfo(QString(), QFileInfo(),
                    QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory);
        }
    }

    return true;
}
コード例 #9
0
ファイル: qtextodfwriter.cpp プロジェクト: wpbest/copperspice
 virtual void addFile(const QString &fileName, const QString &mimeType, const QByteArray &bytes)
 {
     zip.addFile(fileName, bytes);
     addFile(fileName, mimeType);
 }
コード例 #10
0
ファイル: qicon.cpp プロジェクト: Blizzard/qt4
/*!
    Constructs an icon from the file with the given \a fileName. The
    file will be loaded on demand.

    If \a fileName contains a relative path (e.g. the filename only)
    the relevant file must be found relative to the runtime working
    directory.

    The file name can be either refer to an actual file on disk or to
    one of the application's embedded resources.  See the
    \l{resources.html}{Resource System} overview for details on how to
    embed images and other resource files in the application's
    executable.

    Use the QImageReader::supportedImageFormats() and
    QImageWriter::supportedImageFormats() functions to retrieve a
    complete list of the supported file formats.
*/
QIcon::QIcon(const QString &fileName)
    : d(0)
{
    addFile(fileName);
}
コード例 #11
0
ファイル: commitlog.cpp プロジェクト: Andrew-L/Gource
void RCommit::addFile(const std::string& filename, const std::string& action) {
    addFile(filename, action, fileColour(filename));
}
コード例 #12
0
ファイル: MainWindow.cpp プロジェクト: tixsys/esteid
void MainWindow::buttonClicked( int button )
{
	switch( button )
	{
	case HeadSettings:
		showSettings();
		break;
	case HeadHelp:
		QDesktopServices::openUrl( QUrl( "http://code.google.com/p/esteid/wiki/QDigiDocHelp" ) );
		break;
	case HomeView:
	{
		QString file = QFileDialog::getOpenFileName( this, tr("Open container"),
			QDesktopServices::storageLocation( QDesktopServices::DocumentsLocation ),
			tr("Documents (*.bdoc *.BDOC *.ddoc *.DDOC)") );
		if( !file.isEmpty() && doc->open( file ) )
			setCurrentPage( doc->signatures().isEmpty() ? Sign : View );
		break;
	}
	case HomeCrypt:
		if( !Common::startDetached( "qdigidoccrypto" ) )
			showWarning( tr("Failed to start process 'qdigidoccrypto'") );
		break;
	case HomeSign:
		if( stack->currentIndex() == Home &&
			Settings().value( "Client/Intro", true ).toBool() )
		{
			introCheck->setChecked( false );
			setCurrentPage( Intro );
			break;
		}
	case IntroNext:
	{
		if( !params.isEmpty() )
		{
			Q_FOREACH( const QString &param, params )
			{
				const QFileInfo f( param );
				if( !f.isFile() )
					continue;
				QStringList exts = QStringList() << "bdoc" << "ddoc";
				if( doc->isNull() && exts.contains( f.suffix(), Qt::CaseInsensitive ) )
				{
					if( doc->open( f.absoluteFilePath() ) )
						setCurrentPage( doc->signatures().isEmpty() ? Sign : View );
					params.clear();
					return;
				}
				else if( !addFile( f.absoluteFilePath() ) )
					break;
			}
			params.clear();
			if( !doc->isNull() )
				setCurrentPage( Sign );
		}
		else
		{
			QStringList list = QFileDialog::getOpenFileNames( this, tr("Select documents"),
				QDesktopServices::storageLocation( QDesktopServices::DocumentsLocation ) );
			if( !list.isEmpty() )
			{
				Q_FOREACH( const QString &file, list )
				{
					if( !addFile( file ) )
						return;
				}
				setCurrentPage( Sign );
			}
			else if( doc->isNull() )
コード例 #13
0
/**
	Load or append a file.
	The file type is determined automatically and the ad-hoc video decoder is spawned


*/
uint8_t ADM_Composer::addFile (char *name, uint8_t mode)
{
  uint8_t    ret =    0;
  aviInfo    info;
  WAVHeader *    _wavinfo;
//  aviHeader *    tmp;
  fileType    type =    Unknown_FileType;

UNUSED_ARG(mode);
	_haveMarkers=0; // by default no markers are present
  ADM_assert (_nb_segment < max_seg);
  ADM_assert (_nb_video < MAX_VIDEO);

  if (!identify (name, &type))
    return 0;


#define OPEN_AS(x,y) case x:\
						_videos[_nb_video]._aviheader=new y; \
						 ret = _videos[_nb_video]._aviheader->open(name); \
						break;
  switch (type)
    {
      case VCodec_FileType:
      		loadVideoCodecConf(name);      		
		return ADM_IGN; // we do it but it wil fail, no problem with that
      		break;
      OPEN_AS (Mp4_FileType, mp4Header);
      OPEN_AS (H263_FileType, h263Header);
      
      case ASF_FileType:
              _videos[_nb_video]._aviheader=new asfHeader; 
              ret = _videos[_nb_video]._aviheader->open(name); 
              if(!ret)
              {
                delete _videos[_nb_video]._aviheader;;
                printf("Trying mpeg\n"); 
                goto thisIsMpeg; 
              }
              break;
      OPEN_AS (NewMpeg_FileType,dmxHeader);
      // For AVI we first try top open it as openDML
      case AVI_FileType:
      			_videos[_nb_video]._aviheader=new OpenDMLHeader; 
			 ret = _videos[_nb_video]._aviheader->open(name); 			
			break;
      
    case Nuppel_FileType:
	{ // look if the idx exists
	  char *tmpname = (char*)ADM_alloc(strlen(name)+strlen(".idx")+1);
		ADM_assert(tmpname);
		sprintf(tmpname,"%s.idx",name);
		if(addFile(tmpname))
		{
			return 1; // Memleak ?
		}
		ADM_dealloc(tmpname);
		// open .nuv file
		_videos[_nb_video]._aviheader=new nuvHeader;
		ret = _videos[_nb_video]._aviheader->open(name);
		// we store the native .nuv file in the edl
		// the next load of the edl will open .idx instead
		break;
	}
      OPEN_AS (BMP_FileType, picHeader);
      OPEN_AS (Matroska_FileType, mkvHeader);
      OPEN_AS (AvsProxy_FileType, avsHeader);
      OPEN_AS (_3GPP_FileType, _3GPHeader);
       OPEN_AS (Ogg_FileType, oggHeader);

    case Mpeg_FileType:
thisIsMpeg:
    	// look if the idx exists
	char tmpname[256];
	ADM_assert(strlen(name)+5<256);;
	strcpy(tmpname,name);
	strcat(tmpname,".idx");
        if(ADM_fileExist(tmpname))
        {
	       return addFile(tmpname);
        }
	/* check for "Read-only file system" */
	{
                int fd = open(tmpname,O_CREAT|O_EXCL|O_WRONLY,S_IRUSR|S_IWUSR);
                if( fd >= 0 )
                {
                    close(fd);
                    unlink(tmpname);
                    printf("Filesystem is writable\n");
		}else if( errno == EROFS ){
		  char *tmpdir = getenv("TMPDIR");
#ifdef CYG_MANGLING
                        printf("Filesystem is not writable, looking for somewhere else\n");
			if( !tmpdir )
				tmpdir = "c:";
			snprintf(tmpname,256,"%s%s.idx",tmpdir,strrchr(name,'\\'));
#else
			if( !tmpdir )
				tmpdir = "/tmp";
			snprintf(tmpname,256,"%s%s.idx",tmpdir,strrchr(name,'/'));
#endif
			tmpname[255] = 0;
                        printf("Storing index in %s\n",tmpname);
                    if(ADM_fileExist(tmpname))
                    {
                        printf("Index present, loading it\n");
                        return addFile(tmpname);
                    }
                }
        }
        if(tryIndexing(name,tmpname))
        {
                return addFile (tmpname);
        }
        return 0;
      break;
	case WorkBench_FileType:

  		return loadWorbench(name);
#if 0
        case Script_FileType:
                return parseScript(name);
#endif
	case ECMAScript_FileType:
                printf("****** This is an ecmascript, run it with avidemux2 --run yourscript *******\n");
                printf("****** This is an ecmascript, run it with avidemux2 --run yourscript *******\n");
                printf("****** This is an ecmascript, run it with avidemux2 --run yourscript *******\n");
                return 0;
		
                
    default:
      if (type == Unknown_FileType)
	{
	  printf ("\n not identified ...\n");
	}
      else
        GUI_Error_HIG(_("File type identified but no loader support detected..."),
                      _("May be related to an old index file."));
      return 0;
    }

   // check opening was successful
   if (ret == 0) {
     char str[512+1];
     snprintf(str,512,_("Attempt to open %s failed!"), name);
      str[512] = '\0';
      GUI_Error_HIG(str,NULL);
      delete _videos[_nb_video]._aviheader;;
      return 0;
   }

   /* check for resolution */
   if( _nb_video ){
      /* append operation */
      aviInfo info0, infox;
      _videos[   0     ]._aviheader->getVideoInfo (&info0);
      _videos[_nb_video]._aviheader->getVideoInfo (&infox);
      if( info0.width != infox.width || info0.height != infox.height ){
        char str[512+1];
         str[0] = '\0';
         if( info0.width != infox.width )
            strcpy(str,"width");
         if( info0.height != infox.height )
            snprintf(str+strlen(str),512-strlen(str),
              "%sheight%sdifferent between first and this video stream",
                 (strlen(str)?" and ":""),
                 (strlen(str)?" are ":" is ") );
         str[512] = '\0';
         GUI_Error_HIG(str,_("You cannot mix different video dimensions yet. Using the partial video filter later, will not work around this problem. The workaround is:\n1.) \"resize\" / \"add border\" / \"crop\" each stream to the same resolution\n2.) concatinate them together"));
         delete _videos[_nb_video]._aviheader;;
         return 0;
      }
   }
 
  // else update info
  _videos[_nb_video]._aviheader->getVideoInfo (&info);
  _videos[_nb_video]._aviheader->setMyName (name);
  // 1st if it is our first video we update postproc
 if(!_nb_video)
 {
        uint32_t type,value;

        if(!prefs->get(DEFAULT_POSTPROC_TYPE,&type)) type=3;
        if(!prefs->get(DEFAULT_POSTPROC_VALUE,&value)) value=3; 	

	deletePostProc(&_pp );
 	initPostProc(&_pp,info.width,info.height);
	_pp.postProcType=type;
	_pp.postProcStrength=value;
	_pp.forcedQuant=0;
	updatePostProc(&_pp);

	if(_imageBuffer) delete _imageBuffer;
	_imageBuffer=new ADMImage(info.width,info.height);
 	_imageBuffer->_qSize= ((info.width+15)>>4)*((info.height+15)>>4);
	_imageBuffer->quant=new uint8_t[_imageBuffer->_qSize];
	_imageBuffer->_qStride=(info.width+15)>>4;
 }
コード例 #14
0
ファイル: toproject.cpp プロジェクト: Daniel1892/tora
toProject::toProject(toProjectTemplateItem *top, QWidget *parent)
    : QWidget(parent)
{
    Root = top;

    QVBoxLayout *vbox = new QVBoxLayout;
    vbox->setSpacing(0);
    vbox->setContentsMargins(0, 0, 0, 0);

    QToolBar *toolbar = toAllocBar(this, tr("SQL project"));
    vbox->addWidget(toolbar);

    toolbar->addAction(QIcon(QPixmap(const_cast<const char**>(addproject_xpm))),
                       tr("Add file to project"),
                       this,
                       SLOT(addFile()));

    toolbar->addAction(QIcon(QPixmap(const_cast<const char**>(filesave_xpm))),
                       tr("Save project"),
                       this,
                       SLOT(saveProject()));

    DelFile = toolbar->addAction(QIcon(QPixmap(const_cast<const char**>(trash_xpm))),
                                 tr("Remove file from project"),
                                 this,
                                 SLOT(delFile()));

    toolbar->addSeparator();

    toolbar->addAction(QIcon(QPixmap(const_cast<const char**>(new_xpm))),
                       tr("Add new subproject"),
                       this,
                       SLOT(newProject()));

    toolbar->addAction(QIcon(QPixmap(const_cast<const char**>(sql_xpm))),
                       tr("Generate SQL for this project"),
                       this,
                       SLOT(generateSQL()));

    toolbar->addSeparator();

    toolbar->addAction(QIcon(QPixmap(const_cast<const char**>(up_xpm))),
                       tr("Move up in project"),
                       this,
                       SLOT(moveUp()));

    toolbar->addAction(QIcon(QPixmap(const_cast<const char**>(down_xpm))),
                       tr("Move down in project"),
                       this,
                       SLOT(moveDown()));

    toolbar->addWidget(new toSpacer());

    Project = new toListView(this);
    Project->addColumn(tr("File"));
    Project->addColumn(tr("Size"));
    Project->setSelectionMode(toTreeWidget::Single);
    Project->setRootIsDecorated(true);
    Project->setSorting(0);
    connect(Project,
            SIGNAL(selectionChanged()),
            this,
            SLOT(selectionChanged()));
    vbox->addWidget(Project);

    setLayout(vbox);
    update();
}
コード例 #15
0
ファイル: datafilesmodel.cpp プロジェクト: dougmencken/openmw
void DataFilesModel::addMasters(const QString &path)
{
    QDir dir(path);
    dir.setNameFilters(QStringList(QLatin1String("*.esp")));

    // Read the dependencies from the plugins
    foreach (const QString &path, dir.entryList()) {
        try {
            ESM::ESMReader fileReader;
            ToUTF8::Utf8Encoder encoder (ToUTF8::calculateEncoding(mEncoding.toStdString()));
            fileReader.setEncoder(&encoder);
            fileReader.open(dir.absoluteFilePath(path).toStdString());

            ESM::ESMReader::MasterList mlist = fileReader.getMasters();

            for (unsigned int i = 0; i < mlist.size(); ++i) {
                QString master = QString::fromStdString(mlist[i].name);

                // Add the plugin to the internal dependency map
                mDependencies[master].append(path);

                // Don't add esps
                if (master.endsWith(".esp", Qt::CaseInsensitive))
                    continue;

                QFileInfo info(dir.absoluteFilePath(master));

                EsmFile *file = new EsmFile(master);
                file->setDates(info.lastModified(), info.lastRead());
                file->setPath(info.absoluteFilePath());

                // Add the master to the table
                if (findItem(master) == 0)
                    addFile(file);


            }

        } catch(std::runtime_error &e) {
            // An error occurred while reading the .esp
            qWarning() << "Error reading esp: " << e.what();
            continue;
        }
    }

    // See if the masters actually exist in the filesystem
    dir.setNameFilters(QStringList(QLatin1String("*.esm")));

    foreach (const QString &path, dir.entryList()) {
        QFileInfo info(dir.absoluteFilePath(path));

        if (findItem(path) == 0) {
            EsmFile *file = new EsmFile(path);
            file->setDates(info.lastModified(), info.lastRead());

            addFile(file);
        }

        // Make the master selectable
        mAvailableFiles.append(path);
    }
}
コード例 #16
0
ファイル: cgiClass.cpp プロジェクト: davidmc/w3metasite
 // data consumption is line oriented until we get to a file attachment
 bool consume( istream & argstream )
 {
   bool bret = true;
   ocString test;
   while(  argstream.rdstate() == ios::goodbit &&
           state != eof &&
           getline( argstream ) )
   {
     writelog2("Consumed",testline);
     switch( state )
     {
     case init:
       // check to see if we just consumed the boundary
       if( boundary != testline )
       {
         state = eof;
       }
       else
       {
         state = newData;
       }
       break;
     case newData:
       // should be reading the content disposition line
       test = testline.parse(": ");
       transform(test.begin(),test.end(),test.begin(),::tolower);
       writelog2("Testing",test);
       if( test == "content-disposition" )
       {
         // good - see what the data is
         test = testline.parse("; ");          
         // Added :: prefix to tolower so SGI recognizes global scope C function
         transform(test.begin(),test.end(),test.begin(),::tolower);          
         // expect it to be form-data
         writelog2("Content Testing",test);
         if( test == "form-data" )
         {
           // parse any remaining parameters
           while( testline.length() && !testline.endOfParse() )
           {
             ocString test = testline.parse("; ");
             writelog2("Param Testing",test);
             if( test.length() )
             {
               string paramname=test.parse("=\"");
               // Added :: prefix to tolower so SGI recognizes global scope C function
               transform(paramname.begin(),paramname.end(),paramname.begin(),::tolower);
               // could be name or filename
               if( paramname == "name" )
               {
                 // set the name
                 name = test.parse("\"");
                 state = dataSep;
               }
               else if( paramname == "filename" )
               {
                 writelog2("Fix Filename",test);
                 fixupFilename(test.parse("\""));
                 writelog("Filename Fixed");
                 state = fileType;
               }
             }
           }
         }
       }
       else
       {
         // unexpected place so abort method call
         state = eof;
       }
       break;
     case fileType:
       // expect Content-Type: image/jpeg
       test = testline.parse(": ");
       // Added :: prefix to tolower so SGI recognizes global scope C function
       transform(test.begin(),test.end(),test.begin(),::tolower);
       if( test == "content-type" )
       {
         type = testline.remainder();
         state = fileSep;
       }
       else
       {
         state = eof;
       }
       break;
     case fileSep:
       if(testline.length() == 0)
       {
         state = readFile;
       }
       else
       {
         state = eof;
       }
       break;
     case dataSep:
       // expect an empty line
       if(testline.length() == 0)
       {
         state = readData;
       }
       else
       {
         state = eof;
       }
       break;
     case readData:
       // expect the data
       dataConsume(argstream);
       break;
     case readFile:
       fileConsume(argstream);
       addFile();
       addDataItem();
       // fileConsume also consumes the boundary (up to the (potential) -- closing)
       state = fileRead;
       break;
     case fileRead:
       if( testline == "--" )
       {
         state = eof;
       }
       state = newData;
       break;
     case finished:
       // see if there is another boundary:
       if( boundary == testline )
       {
         state = newData; // note that the terminating boundary will have -- at the end
       }
       else
       {
         state = eof;
       }
       break;
     default:
       state = eof;
       break;
     } // end switch
   }  // end while
   return bret;
 }
コード例 #17
0
void CodeFileList::addFile (const juce::File& file)
{
    addFile (file.getFullPathName().trim());
}
コード例 #18
0
void QHttpUploader::addFile(QFile & file){
	addFile(&file);
}
コード例 #19
0
		// called when the directory is actually changed
		// means a file has been added or removed
		// rescans the watched directory adding/removing files and sending notices
		void rescan()
		{
			// if new file, call addFile
			// if missing file, call removeFile
			// if timestamp modified, call handleAction(filename, ACTION_MODIFIED);
			DIR* dir = opendir(mDirName.c_str());
			if(!dir)
				return;
			
			struct dirent* dentry;
			size_t fileIndex = 0;
			struct stat attrib;			
			bool bRescanRequired = false; //if files are added or deleted we need a rescan.
			while((dentry = readdir(dir)) != NULL)
			{
                std::string fname = mDirName.m_string + "/" + dentry->d_name;
				stat(fname.c_str(), &attrib);
				if(!S_ISREG(attrib.st_mode))
					continue;
				
				if (fileIndex < mFileListCount)
				{
					FileInfo& entry = mFileList[fileIndex];
					int result = strcmp(entry.mFilename, fname.c_str());
					if(result == 0)
					{
						stat(entry.mFilename, &attrib);
						time_t timestamp = attrib.st_mtime;
						
						if(entry.mModifiedTime != timestamp)
						{
							entry.mModifiedTime = timestamp;
							handleAction(entry.mFilename, Actions::Modified);
						}
						++fileIndex;
					}
                    else
                    {
                        // file might have been added or deleted
                        // if we find the file in our list, then we have some deletions up to that point
                        // otherwise we have an add
                        bRescanRequired = true;
                        size_t currFile = fileIndex+1;
                        while(currFile < mFileListCount)
                        {
                            FileInfo& entry = mFileList[currFile];
                            int res = strcmp(entry.mFilename, fname.c_str());
                            if(res == 0)
                            {
                                //have found the file in our list
                                break;
                            }
                            ++currFile;
                        }
                        
                        //process events but don't add/remove to list.
                        if (currFile < mFileListCount)
                        {
                           //have some deletions.
                           while(fileIndex < currFile)
                           {
                               FileInfo& entry = mFileList[currFile];
                               handleAction(entry.mFilename, Actions::Delete);
                               ++fileIndex;
                           }
                            ++fileIndex;
                        }
                        else
                        {
                            //we don't increment fileIndex here as it's an add in the middle.
                            handleAction(fname.c_str(), Actions::Add);
                        }
                    }
 				}
				else
				{
					// just add
 					addFile(fname);
                    handleAction(fname.c_str(), Actions::Add);
					++fileIndex;
				}
			}//end while
			
			closedir(dir);
            
            while(fileIndex < mFileListCount) {
                // the last files have been deleted...
                bRescanRequired = true;
                FileInfo& entry = mFileList[fileIndex];
                handleAction(entry.mFilename, Actions::Delete);
                ++fileIndex;
            }
            
            if (bRescanRequired) {
                removeAll();
                addAll(false);
            }
		};
コード例 #20
0
void QHttpUploader::addFile(QString & file){
	addFile(new QFile(file));
}
コード例 #21
0
ファイル: projectgenerator.cpp プロジェクト: BGmot/Qt
void
ProjectGenerator::init()
{
    if(init_flag)
        return;
    int file_count = 0;
    init_flag = true;
    verifyCompilers();

    project->read(QMakeProject::ReadFeatures);
    project->variables()["CONFIG"].clear();

    QMap<QString, QStringList> &v = project->variables();
    QString templ = Option::user_template.isEmpty() ? QString("app") : Option::user_template;
    if(!Option::user_template_prefix.isEmpty())
        templ.prepend(Option::user_template_prefix);
    v["TEMPLATE_ASSIGN"] += templ;

    //figure out target
    if(Option::output.fileName() == "-")
        v["TARGET_ASSIGN"] = QStringList("unknown");
    else
        v["TARGET_ASSIGN"] = QStringList(QFileInfo(Option::output).baseName());

    //the scary stuff
    if(project->first("TEMPLATE_ASSIGN") != "subdirs") {
        QString builtin_regex = project_builtin_regx();
        QStringList dirs = Option::projfile::project_dirs;
        if(Option::projfile::do_pwd) {
            if(!v["INCLUDEPATH"].contains("."))
                v["INCLUDEPATH"] += ".";
            dirs.prepend(qmake_getpwd());
        }

        for(int i = 0; i < dirs.count(); ++i) {
            QString dir, regex, pd = dirs.at(i);
            bool add_depend = false;
            if(exists(pd)) {
                QFileInfo fi(fileInfo(pd));
                if(fi.isDir()) {
                    dir = pd;
                    add_depend = true;
                    if(dir.right(1) != Option::dir_sep)
                        dir += Option::dir_sep;
                    if(Option::recursive == Option::QMAKE_RECURSIVE_YES) {
                        QStringList files = QDir(dir).entryList(QDir::Files);
                        for(int i = 0; i < (int)files.count(); i++) {
                            if(files[i] != "." && files[i] != "..")
                                dirs.append(dir + files[i] + QDir::separator() + builtin_regex);
                        }
                    }
                    regex = builtin_regex;
                } else {
                    QString file = pd;
                    int s = file.lastIndexOf(Option::dir_sep);
                    if(s != -1)
                        dir = file.left(s+1);
                    if(addFile(file)) {
                        add_depend = true;
                        file_count++;
                    }
                }
            } else { //regexp
                regex = pd;
            }
            if(!regex.isEmpty()) {
                int s = regex.lastIndexOf(Option::dir_sep);
                if(s != -1) {
                    dir = regex.left(s+1);
                    regex = regex.right(regex.length() - (s+1));
                }
                if(Option::recursive == Option::QMAKE_RECURSIVE_YES) {
                    QStringList entries = QDir(dir).entryList(QDir::Dirs);
                    for(int i = 0; i < (int)entries.count(); i++) {
                        if(entries[i] != "." && entries[i] != "..") {
                            dirs.append(dir + entries[i] + QDir::separator() + regex);
                        }
                    }
                }
                QStringList files = QDir(dir).entryList(QDir::nameFiltersFromString(regex));
                for(int i = 0; i < (int)files.count(); i++) {
                    QString file = dir + files[i];
                    if (addFile(file)) {
                        add_depend = true;
                        file_count++;
                    }
                }
            }
            if(add_depend && !dir.isEmpty() && !v["DEPENDPATH"].contains(dir, Qt::CaseInsensitive)) {
                QFileInfo fi(fileInfo(dir));
                if(fi.absoluteFilePath() != qmake_getpwd())
                    v["DEPENDPATH"] += fileFixify(dir);
            }
        }
    }
    if(!file_count) { //shall we try a subdir?
        QStringList knownDirs = Option::projfile::project_dirs;
        if(Option::projfile::do_pwd)
            knownDirs.prepend(".");
        const QString out_file = fileFixify(Option::output.fileName());
        for(int i = 0; i < knownDirs.count(); ++i) {
            QString pd = knownDirs.at(i);
            if(exists(pd)) {
                QString newdir = pd;
                QFileInfo fi(fileInfo(newdir));
                if(fi.isDir()) {
                    newdir = fileFixify(newdir);
                    QStringList &subdirs = v["SUBDIRS"];
                    if(exists(fi.filePath() + QDir::separator() + fi.fileName() + Option::pro_ext) &&
                       !subdirs.contains(newdir, Qt::CaseInsensitive)) {
                        subdirs.append(newdir);
                    } else {
                        QStringList profiles = QDir(newdir).entryList(QStringList("*" + Option::pro_ext), QDir::Files);
                        for(int i = 0; i < (int)profiles.count(); i++) {
                            QString nd = newdir;
                            if(nd == ".")
                                nd = "";
                            else if(!nd.isEmpty() && !nd.endsWith(QString(QChar(QDir::separator()))))
                                nd += QDir::separator();
                            nd += profiles[i];
                            fileFixify(nd);
                            if(profiles[i] != "." && profiles[i] != ".." &&
                               !subdirs.contains(nd, Qt::CaseInsensitive) && !out_file.endsWith(nd))
                                subdirs.append(nd);
                        }
                    }
                    if(Option::recursive == Option::QMAKE_RECURSIVE_YES) {
                        QStringList dirs = QDir(newdir).entryList(QDir::Dirs);
                        for(int i = 0; i < (int)dirs.count(); i++) {
                            QString nd = fileFixify(newdir + QDir::separator() + dirs[i]);
                            if(dirs[i] != "." && dirs[i] != ".." && !knownDirs.contains(nd, Qt::CaseInsensitive))
                                knownDirs.append(nd);
                        }
                    }
                }
            } else { //regexp
                QString regx = pd, dir;
                int s = regx.lastIndexOf(Option::dir_sep);
                if(s != -1) {
                    dir = regx.left(s+1);
                    regx = regx.right(regx.length() - (s+1));
                }
                QStringList files = QDir(dir).entryList(QDir::nameFiltersFromString(regx), QDir::Dirs);
                QStringList &subdirs = v["SUBDIRS"];
                for(int i = 0; i < (int)files.count(); i++) {
                    QString newdir(dir + files[i]);
                    QFileInfo fi(fileInfo(newdir));
                    if(fi.fileName() != "." && fi.fileName() != "..") {
                        newdir = fileFixify(newdir);
                        if(exists(fi.filePath() + QDir::separator() + fi.fileName() + Option::pro_ext) &&
                           !subdirs.contains(newdir)) {
                           subdirs.append(newdir);
                        } else {
                            QStringList profiles = QDir(newdir).entryList(QStringList("*" + Option::pro_ext), QDir::Files);
                            for(int i = 0; i < (int)profiles.count(); i++) {
                                QString nd = newdir + QDir::separator() + files[i];
                                fileFixify(nd);
                                if(files[i] != "." && files[i] != ".." && !subdirs.contains(nd, Qt::CaseInsensitive)) {
                                    if(newdir + files[i] != Option::output_dir + Option::output.fileName())
                                        subdirs.append(nd);
                                }
                            }
                        }
                        if(Option::recursive == Option::QMAKE_RECURSIVE_YES
                           && !knownDirs.contains(newdir, Qt::CaseInsensitive))
                            knownDirs.append(newdir);
                    }
                }
            }
        }
        v["TEMPLATE_ASSIGN"] = QStringList("subdirs");
        return;
    }

    //setup deplist
    QList<QMakeLocalFileName> deplist;
    {
        const QStringList &d = v["DEPENDPATH"];
        for(int i = 0; i < d.size(); ++i)
            deplist.append(QMakeLocalFileName(d[i]));
    }
    setDependencyPaths(deplist);

    QStringList &h = v["HEADERS"];
    bool no_qt_files = true;
    QString srcs[] = { "SOURCES", "YACCSOURCES", "LEXSOURCES", "FORMS", QString() };
    for(int i = 0; !srcs[i].isNull(); i++) {
        const QStringList &l = v[srcs[i]];
        QMakeSourceFileInfo::SourceFileType type = QMakeSourceFileInfo::TYPE_C;
        QMakeSourceFileInfo::addSourceFiles(l, QMakeSourceFileInfo::SEEK_DEPS, type);
        for(int i = 0; i < l.size(); ++i) {
            QStringList tmp = QMakeSourceFileInfo::dependencies(l[i]);
            if(!tmp.isEmpty()) {
                for(int dep_it = 0; dep_it < tmp.size(); ++dep_it) {
                    QString dep = tmp[dep_it];
                    dep = fixPathToQmake(dep);
                    QString file_dir = dep.section(Option::dir_sep, 0, -2),
                        file_no_path = dep.section(Option::dir_sep, -1);
                    if(!file_dir.isEmpty()) {
                        for(int inc_it = 0; inc_it < deplist.size(); ++inc_it) {
                            QMakeLocalFileName inc = deplist[inc_it];
                            if(inc.local() == file_dir && !v["INCLUDEPATH"].contains(inc.real(), Qt::CaseInsensitive))
                                v["INCLUDEPATH"] += inc.real();
                        }
                    }
                    if(no_qt_files && file_no_path.indexOf(QRegExp("^q[a-z_0-9].h$")) != -1)
                        no_qt_files = false;
                    QString h_ext;
                    for(int hit = 0; hit < Option::h_ext.size(); ++hit) {
                        if(dep.endsWith(Option::h_ext.at(hit))) {
                            h_ext = Option::h_ext.at(hit);
                            break;
                        }
                    }
                    if(!h_ext.isEmpty()) {
                        for(int cppit = 0; cppit < Option::cpp_ext.size(); ++cppit) {
                            QString src(dep.left(dep.length() - h_ext.length()) +
                                        Option::cpp_ext.at(cppit));
                            if(exists(src)) {
                                QStringList &srcl = v["SOURCES"];
                                if(!srcl.contains(src, Qt::CaseInsensitive))
                                    srcl.append(src);
                            }
                        }
                    } else if(dep.endsWith(Option::lex_ext) &&
                              file_no_path.startsWith(Option::lex_mod)) {
                        addConfig("lex_included");
                    }
                    if(!h.contains(dep, Qt::CaseInsensitive))
                        h += dep;
                }
            }
        }
    }

    //strip out files that are actually output from internal compilers (ie temporary files)
    const QStringList &quc = project->variables()["QMAKE_EXTRA_COMPILERS"];
    for(QStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
        QString tmp_out = project->variables()[(*it) + ".output"].first();
        if(tmp_out.isEmpty())
            continue;

        QStringList var_out = project->variables()[(*it) + ".variable_out"];
        bool defaults = var_out.isEmpty();
        for(int i = 0; i < var_out.size(); ++i) {
            QString v = var_out.at(i);
            if(v.startsWith("GENERATED_")) {
                defaults = true;
                break;
            }
        }
        if(defaults) {
            var_out << "SOURCES";
            var_out << "HEADERS";
            var_out << "FORMS";
        }
        const QStringList &tmp = project->variables()[(*it) + ".input"];
        for(QStringList::ConstIterator it2 = tmp.begin(); it2 != tmp.end(); ++it2) {
            QStringList &inputs = project->variables()[(*it2)];
            for(QStringList::Iterator input = inputs.begin(); input != inputs.end(); ++input) {
                QString path = replaceExtraCompilerVariables(tmp_out, (*input), QString());
                path = fixPathToQmake(path).section('/', -1);
                for(int i = 0; i < var_out.size(); ++i) {
                    QString v = var_out.at(i);
                    QStringList &list = project->variables()[v];
                    for(int src = 0; src < list.size(); ) {
                        if(list[src] == path || list[src].endsWith("/" + path))
                            list.removeAt(src);
                        else
                            ++src;
                    }
                }
            }
        }
    }
}
コード例 #22
0
void QHttpUploader::addFile(char* file){
	addFile(QString(file));
}
コード例 #23
0
ファイル: exports.cpp プロジェクト: 469306621/Languages
unsigned int com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure){return addFile(fileName,aAllowDuplicateInclude,aIgnoreLoadFailure);}
コード例 #24
0
ファイル: qhp.cpp プロジェクト: fjtc/doxygen
void Qhp::addIndexFile(const char * name)
{
  addFile(name);
}
コード例 #25
0
int main(int argc, char *argv[]) {
    pid_t pid;
    int command;
    int flag = 1;
        
    pid = fork();
    
    if (pid < 0) {
        printf("fork error\n");
        return -1;
    }
    else if (pid == 0) {
        // child
        notificationReceiver();
    }
    else {
        // father
        fileList_root = NULL;
        tail = fileList_root;
        
        protectfd = open(PROC_PROTECT, O_RDWR);
        ctrlfd = open(PROC_NOTI, O_RDWR);
        notifd = open(PROC_NOTI, O_RDWR);
        
        if (protectfd < 0 || ctrlfd < 0 || notifd < 0) {
            printf("open file error!\n");
            exitall();
            return -1;
        }

        printmenu();
        while (flag) {
            scanf("%d", &command);
            switch (command) {
                case 1:
                    printFileList();
                    break;
                case 2:
                    addFile();
                    break;
                case 3:
                    
                    break;
                case 9:
                    if (kill(pid, SIGTERM) < 0) {
                        printf("kill error\n");
                    }
                    else {
                        exitall();
                        flag = 0;
                    }
                    break;
                case 4:
                    
                    break;
                default:
                    printmenu();
                    break;
            }
        }
    }
}
コード例 #26
0
ファイル: qhp.cpp プロジェクト: fjtc/doxygen
void Qhp::addImageFile(const char *fileName)
{
  addFile(fileName);
}
コード例 #27
0
void HandleTCPClient(int clntSocket, char* clientIP) {
	char buffer[BUFSIZE]; // Buffer for echo string

	if(DEBUG) printf("[NapsterServerUtility] Handling TCP Client %s\n",clientIP);
	// Receive message from client
	ssize_t numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
	if (numBytesRcvd < 0)
		DieWithSystemMessage("recv() failed");
	buffer[numBytesRcvd] = '\0';
	if(DEBUG) printf("[NapsterServerUtility] Received: %s\n",buffer);

	state = malloc(sizeof(char*));
	strncpy(state,buffer,1);
	char* idleState = "0";
	char* addState = "1";
	char* listState = "2";

	// Send received string and receive again until end of stream
	while (numBytesRcvd > 0) { // 0 indicates end of stream
			// Echo message back to client
			if(DEBUG) printf("[NapsterServerUtility] echoing %s\n",buffer);
			ssize_t numBytesSent = send(clntSocket, buffer, numBytesRcvd, 0);
			if(DEBUG) printf("[NapsterServerUtility] Message Echoed\n");
			if (numBytesSent < 0)
				DieWithSystemMessage("send() failed");
			else if (numBytesSent != numBytesRcvd)
				DieWithUserMessage("send()", "sent unexpected number of bytes");

		if(strncmp(addState,state,1)==0){
			memmove(buffer,buffer+1,strlen(buffer));
			buffer[strlen(buffer)] = '\0';
			if(DEBUG) printf("[NapsterServerUtility] Line in %s: %d\n",filename,file_line);
			if(DEBUG) printf("[NapsterServerUtility] Previous file line: %s\n",list[file_line-1].filename);


			//write the data to the file
			int file_add = addFile(buffer,clientIP);
			if(!file_add){
				DieWithSystemMessage("addFile() failed");
			}

			if(DEBUG) printf("[NapsterServerUtility] Echo message back to client %s\n", list[file_line-1].filename);


			state = idleState;
		}
		else if(strncmp(listState,state,1)==0){
			if(DEBUG) printf("[NapsterServerUtility] Listing files!\n");
			char length[BUFSIZE];
			int list_size = sizeof(list);
			sprintf(length,"%d",list_size);
			if(DEBUG) printf("[NapsterServerUtility] Data to Send: %d %s\n",list_size,length);

			//sending file size to client
			if(DEBUG) printf("[NapsterServerUtility] sending file size to client\n");
			ssize_t numBytesSent = send(clntSocket,length,strlen(length),0);

			if (numBytesSent < 0)
				DieWithSystemMessage("send() failed");
			else if (numBytesSent != numBytesRcvd)
				DieWithUserMessage("send()", "sent unexpected number of bytes");

			//recv ack
			char ackbuffer[BUFSIZE];
			ssize_t numBytesAck1 = recv(clntSocket,ackbuffer,BUFSIZE, 0);

			if(numBytesAck1 < 0){
				DieWithSystemMessage("recv() failed");
			}

			char* file_list;
			file_list = malloc(file_line*sizeof(char*));
			sprintf(file_list,"%s %s\n",list[0].origin_ip_address,list[0].filename);
			int i;
			for(i = 1; i<file_line;i++){
				if(DEBUG) printf("[NapsterServerUtility] %d %s %s\n",i,list[i].origin_ip_address,list[i].filename);
				strcat(file_list,list[i].origin_ip_address);
				strcat(file_list," ");
				strcat(file_list,list[i].filename);
				strcat(file_list,"\n");
			}

			if(DEBUG) printf("[NapsterServerUtility]\n%s\n",file_list);
			if(DEBUG) printf("[NapsterServerUtility] sending file to client\n");
			//sending file to client
			ssize_t numBytesSentList = send(clntSocket,list,strlen(file_list),0);
			if(numBytesSentList<0)
				DieWithSystemMessage("send() failed");
			if(DEBUG) printf("[NapsterServerUtility] filelist sent\n");

			state = idleState;
		}
		else if(state == idleState){
		// See if there is more data to receive
			if(DEBUG) printf("[NapsterServerUtility] waiting for more data\n");
			numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
			buffer[numBytesRcvd] = '\0';
			if(DEBUG) printf("[NapsterServerUtility] done waiting for more data received: %s numBytesRcvd  %zu\n",buffer,numBytesRcvd);
			if (numBytesRcvd < 0)
				DieWithSystemMessage("recv() failed");
			state = malloc(sizeof(char*));
			strncpy(state,buffer,1);
			if(DEBUG) printf("[NapsterServerUtility] state after recv: %s\n",state);
		//		printf("[NapsterServerUtility] Leaving HandleTCPClient()\n");
		//		
		}
	}

	  close(clntSocket); // Close client socket
}
コード例 #28
0
ファイル: qhp.cpp プロジェクト: fjtc/doxygen
void Qhp::addStyleSheetFile(const char *fileName)
{
  addFile(fileName);
}
コード例 #29
0
ファイル: datafilesmodel.cpp プロジェクト: Adrian-Revk/openmw
void DataFilesModel::addFiles(const QString &path)
{
    QDir dir(path);
    QStringList filters;
    filters << "*.esp" << "*.esm";
    dir.setNameFilters(filters);

    // Create a decoder for non-latin characters in esx metadata
    QTextCodec *codec;

    if (mEncoding == QLatin1String("win1252")) {
        codec = QTextCodec::codecForName("windows-1252");
    } else if (mEncoding == QLatin1String("win1251")) {
        codec = QTextCodec::codecForName("windows-1251");
    } else if (mEncoding == QLatin1String("win1250")) {
        codec = QTextCodec::codecForName("windows-1250");
    } else {
        return; // This should never happen;
    }

    QTextDecoder *decoder = codec->makeDecoder();

    foreach (const QString &path, dir.entryList()) {
        QFileInfo info(dir.absoluteFilePath(path));
        EsmFile *file = new EsmFile(path);

        try {
            ESM::ESMReader fileReader;
            ToUTF8::Utf8Encoder encoder(ToUTF8::calculateEncoding(mEncoding.toStdString()));
            fileReader.setEncoder(&encoder);
            fileReader.open(dir.absoluteFilePath(path).toStdString());

            std::vector<ESM::Header::MasterData> mlist = fileReader.getMasters();

            QStringList masters;

            for (unsigned int i = 0; i < mlist.size(); ++i) {
                QString master = QString::fromStdString(mlist[i].name);
                masters.append(master);
            }

            file->setAuthor(decoder->toUnicode(fileReader.getAuthor().c_str()));
            file->setSize(info.size());
            file->setDates(info.lastModified(), info.lastRead());
            file->setVersion(fileReader.getFVer());
            file->setPath(info.absoluteFilePath());
            file->setMasters(masters);
            file->setDescription(decoder->toUnicode(fileReader.getDesc().c_str()));


            // Put the file in the table
            if (findItem(path) == 0)
                addFile(file);
        } catch(std::runtime_error &e) {
            // An error occurred while reading the .esp
            qWarning() << "Error reading esp: " << e.what();
            continue;
        }

    }

    delete decoder;
}
コード例 #30
0
ファイル: Archive.cpp プロジェクト: sithlord48/ff7tk
/*!
 * \overload
 *
 * Add a new file named \a filePath with \a data.
 * Returns false if the file exists; otherwise returns
 * true.
 * \sa addFile()
 */
bool Archive::addFileData(const QString &filePath, const QByteArray &data)
{
	QBuffer *buf = new QBuffer();
	buf->setData(data);
	return addFile(filePath, buf);
}