Пример #1
0
DocEntry *DocMetaInfo::scanMetaInfoDir(const QString &dirName, DocEntry *parent)
{
    QDir dir(dirName);
    if(!dir.exists())
        return 0;

    const QFileInfoList_qt3 *entryList = dir.entryInfoList_qt3();
    QFileInfoListIterator it(*entryList);
    QFileInfo *fi;
    for(; (fi = it.current()); ++it)
    {
        DocEntry *entry = 0;
        if(fi->isDir() && fi->fileName() != "." && fi->fileName() != "..")
        {
            DocEntry *dirEntry = addDirEntry(QDir(fi->absFilePath()), parent);
            entry = scanMetaInfoDir(fi->absFilePath(), dirEntry);
        }
        else if(fi->extension(false) == "desktop")
        {
            entry = addDocEntry(fi->absFilePath());
            if(parent && entry)
                parent->addChild(entry);
        }
    }

    return 0;
}
void FileSystemScanner::rescanFolder(Folder* folder, bool forceEXIF)
{
    QString currentFolderPath = folder->dir()->absPath();

    tracer->sdebug(__func__) << "adding files in folder: " << folder->id() << ": " << currentFolderPath << endl;

    emit(progress_scanningFolder(currentFolderPath));
    
    // this method is called regularly while rescanning the filesystem
    // before doing something here we process all outstanding events!
    KApplication::kApplication()->processEvents();
    if (m_cancel) {
        return;
    }

    if (!folder->dir()->exists()) {
        tracer->swarning(__func__) << "folder: " << folder->id() << ": " << currentFolderPath
                << " does no longer exist --> ignoring it!!!" << endl;
    }

    // get a list with all files in the current folder
    const QFileInfoList* filelist = folder->dir()->entryInfoList(QDir::Files);
    if (filelist) {
        QFileInfoListIterator iterator( *filelist );
        QFileInfo* fileInfo;
        while ((fileInfo = iterator.current()) != 0) {

            // only add jpeg files
            if (mustHandleFile(fileInfo->fileName())) {

                File* file = m_engine->m_fileDict->find(fileInfo->absFilePath());
                if (!file) {
                    // the file is seen for the first time --> create it
                    tracer->sdebug(__func__) << "found new file to add: '" << fileInfo->absFilePath() << "'" << endl;
                    file = new File(m_engine, folder, new QFileInfo(*fileInfo));
                    m_engine->dirtyfy();

                    folder->appendFile(file);
                    m_engine->m_fileList->append(file);
                    m_engine->m_fileDict->insert(file->fileInfo()->absFilePath(), file);

                    emit(newFile(file));
                    
                    // read exif data from the file and store this data in the database
                    readEXIF(file);
                } else {
                    // this file already exists in the database --> reread EXIF data if forceEXIF is true
                    if (forceEXIF) {
                        readEXIF(file);
                    }
                }
            }
            ++iterator;
        }
    }
}
Пример #3
0
// Return installed API files.
QStringList QsciAPIs::installedAPIFiles() const
{
    const char *qtdir = getenv("QTDIR");

    if (!qtdir)
        return QStringList();

    QDir apidir = QDir(QString("%1/qsci/api/%2").arg(qtdir).arg(lexer()->lexer()));
    QStringList filenames;

    const QFileInfoList *flist = apidir.entryInfoList("*.api", QDir::Files, QDir::IgnoreCase);

    if (flist)
    {
        QPtrListIterator<QFileInfo> it(*flist);
        QFileInfo *fi;

        while ((fi = it.current()) != 0)
        {
            filenames << fi->absFilePath();
            ++it;
        }
    }

    return filenames;
}
Пример #4
0
Biff::Biff( QWidget *parent, const char *name )
    : QWidget( parent, name, WShowModal | WType_Dialog )
{
    QFileInfo fi = QString(getenv( "MAIL" ));
    if ( !fi.exists() ) {
	QString s( "/var/spool/mail/" );
	s += getlogin();
	fi.setFile( s );
    }

    if ( fi.exists() ) {
	mailbox = fi.absFilePath();
	startTimer( 1000 );
    }

    setMinimumSize( 48, 48 );
    setMaximumSize( 48, 48 );
    resize( 48, 48 );

    hasNewMail.loadFromData( hasmail_bmp_data, hasmail_bmp_len );
    noNewMail.loadFromData( nomail_bmp_data, nomail_bmp_len );

    gotMail = FALSE;
    lastModified = fi.lastModified();
}
void AdminDatabase::fillList()
{
	m_listView->clear();
	const QFileInfoList *files = m_dumpDir->entryInfoList("*.sql");
	
	if ( files )
	{
		QFileInfoListIterator it( *files );
		QFileInfo * fi = 0;
		while( (fi=it.current()) != 0 )
		{
			++it;
			KListViewItem *item = new KListViewItem(m_listView);
			
			item->setText(0, fi->baseName().section('.', 0,0) );
			
			QFile tmp(fi->absFilePath());
			tmp.open(IO_ReadOnly);
			QTextStream stream( &tmp );
			item->setText(1, stream.readLine().section("--",1,1));
			tmp.close();
			item->setText(2, fi->created().toString(Qt::ISODate));
		}
		
	}
}
Пример #6
0
/**
 * Parses the command line, after it was stripped of its KDE options.
 * The command line may contain one of the following options:
 * 1. A project file (named cscope.proj)
 * 2. A Cscope cross-reference database
 * 3. A list of source files
 * @param	pArgs	Command line arguments
 */
void KScope::parseCmdLine(KCmdLineArgs* pArgs)
{
	QString sArg;
	QFileInfo fi;
	int i;

	// Loop over all arguments
	for (i = 0; i < pArgs->count(); i++) {
		// Verify the argument is a file or directory name
		sArg = pArgs->arg(i);
		fi.setFile(sArg);
		if (!fi.exists())
			continue;
			
		// Handle the current argument
		if (fi.isFile()) {
			if (fi.fileName() == "cscope.proj") {
				// Open a project file
				openProject(fi.dirPath(true));
				return;
			} else if (openCscopeOut(sArg)) {
				// Opened the file as a cross-reference database
				return;
			} else {
				// Assume this is a source file
				slotShowEditor(sArg, 0);
			}
		} else if (fi.isDir()) {
			// Treat the given path as a project directory
			openProject(fi.absFilePath());
			return;
		}
	}
}
Пример #7
0
biff::biff(QWidget *parent, const char *name) : QWidget(parent, name)
{
    QString s(getenv("MAIL"));
    QFileInfo fi = s;
    if(! fi.exists())
    {
        s = MAILDIR;
        s += getlogin();
        fi.setFile(s);
    }

    if(fi.exists())
    {
        mailfile = fi.absFilePath();
        startTimer(3000);
    }
    else
    {
        perror((const char *)s);
        exit(1);
    }

    hasmail = QPixmap((const char **)mail_xpm);
    newmail = QPixmap((const char **)newmail_xpm);

    mailstate = Empty;
}
Пример #8
0
QString Util::findResource(QString filename)
{
    QFileInfo fi = QFileInfo(filename);
    if (fi.exists()) {
        return fi.absFilePath();
    }

    fi = QFileInfo(EXECUTABLE_PATH + "/" + filename);
    if (fi.exists()) {
        return fi.absFilePath();
    }

    fi = QFileInfo(QString("/usr/share/poa/") + filename);
    if (fi.exists()) {
        return fi.absFilePath();
    }

    return QString();
}
Пример #9
0
void QtFileIconView::readDir( const QDir &dir )
{
    if ( !dir.isReadable() )
        return;

    if ( isRoot( dir.absPath() ) )
        emit disableUp();
    else
        emit enableUp();

    clear();

    emit directoryChanged( dir.absPath() );

    const QFileInfoList *filist = dir.entryInfoList( QDir::DefaultFilter, QDir::DirsFirst | QDir::Name );

    emit startReadDir( filist->count() );

    QFileInfoListIterator it( *filist );
    QFileInfo *fi;
    bool allowRename = FALSE, allowRenameSet = FALSE;
    while ( ( fi = it.current() ) != 0 ) {
        ++it;
        if ( fi && fi->fileName() == ".." && ( fi->dirPath() == "/" || fi->dirPath().isEmpty() ) )
            continue;
        emit readNextDir();
        QtFileIconViewItem *item = new QtFileIconViewItem( this, new QFileInfo( *fi ) );
        if ( fi->isDir() )
            item->setKey( QString( "000000%1" ).arg( fi->fileName() ) );
        else
            item->setKey( fi->fileName() );
        if ( !allowRenameSet ) {
            if ( !QFileInfo( fi->absFilePath() ).isWritable() ||
                    item->text() == "." || item->text() == ".." )
                allowRename = FALSE;
            else
                allowRename = TRUE;
            if ( item->text() == "." || item->text() == ".." )
                allowRenameSet = FALSE;
            else
                allowRenameSet = TRUE;
        }
        item->setRenameEnabled( allowRename );
    }

    if ( !QFileInfo( dir.absPath() ).isWritable() )
        emit disableMkdir();
    else
        emit enableMkdir();

    emit readDirDone();
}
Пример #10
0
QString KStandardDirs::findExe( const QString& appname,
				const QString& pstr, bool ignore)
{
#ifdef Q_WS_WIN
    QString real_appname = appname + ".exe";
#else
    QString real_appname = appname;
#endif
    QFileInfo info;

    // absolute or relative path given
    if (real_appname.find(QDir::separator()) >= 0)
    {
        info.setFile( real_appname );
        if( info.exists() && ( ignore || info.isExecutable() )
            && info.isFile() ) {
            return info.absFilePath();
        }
        return QString::null;
    }

    QString p = QString("%1/%2").arg(kfsstnd_defaultbindir()).arg(real_appname);
    info.setFile( p );
    if( info.exists() && ( ignore || info.isExecutable() )
         && ( info.isFile() || info.isSymLink() )  ) {
         return p;
    }

    QStringList exePaths = systemPaths( pstr );
    for (QStringList::ConstIterator it = exePaths.begin(); it != exePaths.end(); ++it)
    {
	p = (*it) + "/";
	p += real_appname;

	// Check for executable in this tokenized path
	info.setFile( p );

	if( info.exists() && ( ignore || info.isExecutable() )
           && ( info.isFile() || info.isSymLink() )  ) {
	    return p;
	}
    }

    // If we reach here, the executable wasn't found.
    // So return empty string.

    return QString::null;
}
Пример #11
0
QString SoundFile::getNextTempFilename()
{
    //QString tempFileFolder = gdata->settings.getString("General", "tempFilesFolder");
    QString tempFileFolder = gdata->qsettings->value("General/tempFilesFolder", QDir::convertSeparators(QDir::currentDirPath())).toString();
    QDir dir = QDir(tempFileFolder);
    QFileInfo fileInfo;
    QString fileName;
    bool fileExists;
    int index = 1;
    do {
        fileExists = false;
        fileName.sprintf("temp%03d.wav", index);
        //printf("trying %s\n", fileName.latin1());
        fileInfo.setFile(dir, fileName);
        if(fileInfo.exists()) {
            fileExists = true;
            index++;
        }
    } while(fileExists);
    return fileInfo.absFilePath();
}
Пример #12
0
short KApplicationTree::parseKdelnkDir( QDir d, KTreeList *tree, KAppTreeListItem *item)
{
  if( !d.exists() )
    return -1;

  d.setSorting( SORT_SPEC );
  QList <QString> item_list;
	
  const QFileInfoList *list = d.entryInfoList();
  QFileInfoListIterator it( *list );
  QFileInfo *fi;

  if( it.count() < 3 )
    return -1;

  while( ( fi = it.current() ) )
  {
    if( fi->fileName() == "." || fi->fileName() == ".." )
    {
      ++it;
      continue;
    }
    if( fi->isDir() )
    {
      parseKdelnkFile( fi, tree, item );
    }
    else 
    {
      if( !isKdelnkFile( fi->absFilePath() ) )
      {
	++it;
	continue;
      }
      parseKdelnkFile( fi, tree, item );
    } 
    ++it;
  }
  
  return 0;
}
Пример #13
0
/*!
    \fn myQLoader::findModules()
 */
void myQLoader::findModules()
{
  QString s; // = qApp->applicationDirPath();
  setAplDir(s);
  QDir d(s+"/modules");
  
  d.setFilter(QDir::Files);
  d.setNameFilter("*.so");
  
  const QFileInfoList *list = d.entryInfoList();
  QFileInfoListIterator it( *list );
  QFileInfo *fi;
  
  myInfo_modules one_module;

  while ( (fi = it.current()) != 0 ) {
	
	one_module.exec = fi->absFilePath();
	
	if(getModule_Info(one_module))
	  addToList(one_module);
	++it;
  }
}
Пример #14
0
int loadLogs() {
  int logsize = 0;

  QString logdirname = locateLocal("data", "kppp/Log/");
  QDir logdir(logdirname, "*.log");

  kdDebug(5002) << "logdirname: " << logdirname << endl;
  
  // get log file size
  const QFileInfoList_qt3 *list = logdir.entryInfoList_qt3();
  QFileInfoListIterator it( *list );
  QFileInfo *fi;

  while ((fi = it.current()) != 0) {
    logsize += fi->size();
    ++it;
  }

  dlg = new QProgressDialog(i18n("Loading log files"),
			     QString::null,
			     logsize);
  dlg->setProgress(0);

  // load logs
  list = logdir.entryInfoList_qt3();
  QFileInfoListIterator it1( *list );

  int retval = 0;
  while ((fi = it1.current()) != 0) {
    retval += loadLog(fi->absFilePath());
    ++it1;
  }

  delete dlg; 
  return retval;
}
Пример #15
0
void PanelBrowserMenu::initialize()
{
    _lastpress = QPoint(-1, -1);

    // don't change menu if already visible
    if (isVisible())
        return;

    if (_dirty) {
        // directory content changed while menu was visible
        slotClear();
        setInitialized(false);
        _dirty = false;
    }

    if (initialized()) return;
    setInitialized(true);

    // start watching if not already done
    if (!_dirWatch.contains(path()))
        _dirWatch.addDir( path() );

    // setup icon map
    initIconMap();

    // read configuration
    KConfig *c = KGlobal::config();
    c->setGroup("menus");
    _showhidden = c->readBoolEntry("ShowHiddenFiles", false);
    _maxentries = c->readNumEntry("MaxEntries2", 30);

    // clear maps
    _filemap.clear();
    _mimemap.clear();

    int filter = QDir::Dirs | QDir::Files;
    if(_showhidden)
        filter |= QDir::Hidden;

    QDir dir(path(), QString::null, QDir::DirsFirst | QDir::Name | QDir::IgnoreCase, filter);

    // does the directory exist?
    if (!dir.exists()) {
        insertItem(i18n("Failed to Read Folder"));
    return;
    }

    // get entry list
    const QFileInfoList *list = dir.entryInfoList();

    // no list -> read error
    if (!list) {
    insertItem(i18n("Failed to Read Folder"));
    return;
    }

    KURL url;
    url.setPath(path());
    if (!kapp->authorizeURLAction("list", KURL(), url))
    {
        insertItem(i18n("Not Authorized to Read Folder"));
        return;
    }

    // insert file manager and terminal entries
    // only the first part menu got them
    if(_startid == 0 && !_filesOnly) {
       insertTitle(path());
       insertItem(CICON("kfm"), i18n("Open in File Manager"), this, SLOT(slotOpenFileManager()));
        if (kapp->authorize("shell_access"))
            insertItem(CICON("terminal"), i18n("Open in Terminal"), this, SLOT(slotOpenTerminal()));
    }


    bool first_entry = true;
    bool dirfile_separator = false;
    int item_count = 0;
    int run_id = _startid;

    // get list iterator
    QFileInfoListIterator it(*list);

    // jump to startid
    it += _startid;

    // iterate over entry list
    for (; it.current(); ++it)
    {
        // bump id
        run_id++;

        QFileInfo *fi = it.current();
        // handle directories
        if (fi->isDir())
        {
            QString name = fi->fileName();

            // ignore . and .. entries
            if (name == "." || name == "..") continue;

            QPixmap icon;
            QString path = fi->absFilePath();

            // parse .directory if it does exist
            if (QFile::exists(path + "/.directory")) {

                KSimpleConfig c(path + "/.directory", true);
                c.setDesktopGroup();
                QString iconPath = c.readEntry("Icon");

                if ( iconPath.startsWith("./") )
                    iconPath = path + '/' + iconPath.mid(2);

                icon = KGlobal::iconLoader()->loadIcon(iconPath,
                                                       KIcon::Small, KIcon::SizeSmall,
                                                       KIcon::DefaultState, 0, true);
                if(icon.isNull())
                    icon = CICON("folder");
                name = c.readEntry("Name", name);
            }

            // use cached folder icon for directories without special icon
            if (icon.isNull())
                icon = CICON("folder");

            // insert separator if we are the first menu entry
            if(first_entry) {
                if (_startid == 0 && !_filesOnly)
                    insertSeparator();
                first_entry = false;
            }

            // append menu entry
            PanelBrowserMenu *submenu = new PanelBrowserMenu(path, this);
            submenu->_filesOnly = _filesOnly;
            append(icon, name, submenu);

            // bump item count
            item_count++;

            dirfile_separator = true;
        }
        // handle files
        else if(fi->isFile())
        {
            QString name = fi->fileName();
            QString title = KIO::decodeFileName(name);

            QPixmap icon;
            QString path = fi->absFilePath();

            bool mimecheck = false;

            // .desktop files
            if(KDesktopFile::isDesktopFile(path))
            {
                KSimpleConfig c(path, true);
                c.setDesktopGroup();
                title = c.readEntry("Name", title);

                QString s = c.readEntry("Icon");
                if(!_icons->contains(s)) {
                    icon  = KGlobal::iconLoader()->loadIcon(s, KIcon::Small, KIcon::SizeSmall,
                                                            KIcon::DefaultState, 0, true);

                    if(icon.isNull()) {
                        QString type = c.readEntry("Type", "Application");
                        if (type == "Directory")
                            icon = CICON("folder");
                        else if (type == "Mimetype")
                            icon = CICON("txt");
                        else if (type == "FSDevice")
                            icon = CICON("chardevice");
                        else
                            icon = CICON("exec");
                    }
                    else
                        _icons->insert(s, icon);
                }
                else
                    icon = CICON(s);
            }
            else {
                // set unknown icon
                icon = CICON("unknown");

                // mark for delayed mimetime check
                mimecheck = true;
            }

            // insert separator if we are the first menu entry
            if(first_entry) {
                if(_startid == 0 && !_filesOnly)
                    insertSeparator();
                first_entry = false;
            }

            // insert separator if we we first file after at least one directory
            if (dirfile_separator) {
                insertSeparator();
                dirfile_separator = false;
            }

            // append file entry
            append(icon, title, name, mimecheck);

            // bump item count
            item_count++;
        }

        if(item_count == _maxentries) {
            // Only insert a "More" item if there are actually more items.
            ++it;
            if( it.current() ) {
                insertSeparator();
                append(CICON("kdisknav"), i18n("More"), new PanelBrowserMenu(path(), this, 0, run_id));
            }
            break;
        }
    }

#if 0
    // WABA: tear off handles don't work together with dynamically updated
    // menus. We can't update the menu while torn off, and we don't know
    // when it is torn off.
    if(KGlobalSettings::insertTearOffHandle() && item_count > 0)
        insertTearOffHandle();
#endif

    adjustSize();

    QString dirname = path();

    int maxlen = contentsRect().width() - 40;
    if(item_count == 0)
        maxlen = fontMetrics().width(dirname);

    if (fontMetrics().width(dirname) > maxlen) {
        while ((!dirname.isEmpty()) && (fontMetrics().width(dirname) > (maxlen - fontMetrics().width("..."))))
            dirname = dirname.remove(0, 1);
        dirname.prepend("...");
    }
    setCaption(dirname);

    // setup and start delayed mimetype check timer
    if(_mimemap.count() > 0) {

        if(!_mimecheckTimer)
            _mimecheckTimer = new QTimer(this);

        connect(_mimecheckTimer, SIGNAL(timeout()), SLOT(slotMimeCheck()));
        _mimecheckTimer->start(0);
    }
}
bool DiffAnalystWindow::startCAProfDiffSession(QString session0, 
				QString session1, 
				QString diffSessName)
{
	SESSION_DIFF_INFO_VEC sessionInfoVec;
	QFileInfo fInfo;

	if(!session0.isEmpty() && !session1.isEmpty())
	{
		sessionInfoVec.clear();
		SESSION_DIFF_INFO info0,info1;
		bool isOk = false;

		while(1)
		{
			info0.sessionFile 	= session0.section(":",0,0);
			fInfo.setFile(info0.sessionFile);
			if(!fInfo.exists()) break;
		
			info0.task		= session0.section(":",1,1);
			if(!info0.task.isEmpty()
			&& info0.task.compare("All Tasks"))
			{
				fInfo.setFile(info0.task);
				if(!fInfo.exists()) break;
			}

			info0.module		= session0.section(":",2,2);
			fInfo.setFile(info0.module);
			if(!fInfo.exists()) break; 

			sessionInfoVec.push_back(info0);

			info1.sessionFile 	= session1.section(":",0,0);
			fInfo.setFile(info1.sessionFile);
			if(!fInfo.exists()) break;
		
			info1.task		= session1.section(":",1,1);
			if(!info1.task.isEmpty()
			&& info1.task.compare("All Tasks"))
			{
				fInfo.setFile(info1.task);
				if(!fInfo.exists()) break;
			}
		
			info1.module		= session1.section(":",2,2);
			fInfo.setFile(info1.module);
			if(!fInfo.exists()) break;

			isOk = true;
			break;
		}
	
		if(!isOk)
		{
			QMessageBox::critical(this,"DiffAnalyst Error",QString() +
				"Path not found: " + fInfo.absFilePath() + "\n\n" +
				"Please check command-line options, or use New Session Wizard.\n" );
			return false;
		}
	
		sessionInfoVec.push_back(info1);

		if(diffSessName.isEmpty())	
			diffSessName = "Untitle-1";
	}else{
		int sessionCnt = 0;

		/////////////////////////////////////////
		// Query NewSessionWizard
		if(m_pNewSessWzd == NULL)
			return false;
		
		if((sessionCnt = m_pNewSessWzd->getSessionDiffInfo(&sessionInfoVec)) <= 0)
		{
			return false;
		}


		/////////////////////////////////////////
		// Setup DiffAnalystWindowName
		diffSessName = m_pNewSessWzd->getSessionDiffName();

	}

	/////////////////////////////////////////
	// Setup DiffSession
	DiffSession *diffSess = new DiffSession(m_pWs,diffSessName.toAscii().data());
	if(diffSess == NULL) return false;
	if(!diffSess->init(sessionInfoVec)) return false;

	diffSess->showMaximized();
	
	m_pFileMenu->setItemEnabled (m_SaveId, true);
	m_pFileMenu->setItemEnabled (m_SaveAsId, true);
	m_ToolsToolId [TM_FILESAVE]->setEnabled(true);

	return true;

} //DiffAnalystWindow::startCAProfDiffSession
Пример #17
0
PDB_Country::PDB_Country(QWidget *parent) : QWidget(parent) {
  QLabel *l = new QLabel(i18n("Select the location where you plan to use this\n"
			    "account from the list below. If your country or\n"
			    "location is not listed, you have to create the\n"
			    "account with the normal, dialog based setup.\n\n"
			    "If you click \"Cancel\", the dialog based setup\n"
			    "will start."),
		       this);
  QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
  tl->addWidget(l);

  QHBoxLayout *l1 = new QHBoxLayout;
  tl->addLayout(l1);
  l1->addStretch(1);

  lb = new QListBox(this);
  connect(lb, SIGNAL(highlighted(int)),
	  this, SLOT(selectionChanged(int)));
  lb->setMinimumSize(220, 100);
  l1->addWidget(lb, 2);
  l1->addStretch(1);

  list = new QStringList;

  // fill the listbox
  // set up filter
  QDir d(KGlobal::dirs()->findDirs("appdata", "Provider").first());
  d.setFilter(QDir::Dirs);
  d.setSorting(QDir::Name);

  // read the list of files
  const QFileInfoList *flist = d.entryInfoList();
  if(flist) {
    QFileInfoListIterator it( *flist );
    QFileInfo *fi;
    // traverse the flist and insert into a map for sorting
    QMap<QString, QString> countries;
    for(; (fi = it.current()) != 0; ++it) {
      if(fi->fileName() != "." && fi->fileName() != "..") {
        QString dirFile(fi->absFilePath()+"/.directory");
        QString entryName;
        if(QFile::exists(dirFile)){
          KSimpleConfig config(dirFile);
          config.setDesktopGroup();
          entryName = config.readEntry("Name");
        }
        if (entryName.isNull()) entryName = fi->fileName();
	countries.insert(entryName, fi->fileName());
      }
    }
    // insert sorted entries into list box and string list
    QMap<QString, QString>::const_iterator mit = countries.begin();
    QMap<QString, QString>::const_iterator mend = countries.end();
    while(mit != mend) {
        lb->insertItem(mit.key());
        list->append(*mit);
	++mit;
    }
  }

  tl->activate();
}
Пример #18
0
void SkyBackgroundPluginForm::setupSkyBackground( const QDir dir, const bool zUp )
{	
	try
	{
		skyBackground = NullFC;
		
		bool imageLoaded[6] = {false, false, false, false, false, false};

		const QFileInfoList* fileList = dir.entryInfoList();
		QFileInfoListIterator it(*fileList);
		QFileInfo* fileInfo;

		while ((fileInfo = it.current()) != 0)
		{
			QString qstr = fileInfo->absFilePath();
			const char *filename = qstr.latin1();

			if (((qstr.find("north") >= 0) || (qstr.find("front") >= 0)) && !imageLoaded[0])
			{
				beginEditCP(images[5]);
				if (images[5]->read(filename))
				{
					beginEditCP(textures[5]);
					textures[5]->setImage(images[5]);
					endEditCP(textures[5]);
					vrLog::info("Sky Background: Front/North image loaded.");
					imageLoaded[0] = true;
				}
				endEditCP(images[5]);
			}
			if (((qstr.find("south") >= 0) || (qstr.find("back") >= 0)) && !imageLoaded[1])
			{
				beginEditCP(images[4]);
				if (images[4]->read(filename))
				{
					if (zUp)
						vrImage::rotateImage180Degrees(images[4]);
					beginEditCP(textures[4]);
					textures[4]->setImage(images[4]);
					endEditCP(textures[4]);
					vrLog::info("Sky Background: Back/South image loaded.");
					imageLoaded[1] = true;
				}
				endEditCP(images[4]);
			}
			if (((qstr.find("down") >= 0) || (qstr.find("bottom") >= 0)) && !imageLoaded[2])
			{
				beginEditCP(images[3]);
				if (images[3]->read(filename))
				{
					beginEditCP(textures[3]);
					textures[3]->setImage(images[3]);
					endEditCP(textures[3]);
					vrLog::info("Sky Background: Bottom/Down image loaded.");
					imageLoaded[2] = true;
				}
				endEditCP(images[3]);
			}
			if (((qstr.find("up") >= 0) || (qstr.find("top") >= 0)) && !imageLoaded[3])
			{
				beginEditCP(images[2]);
				if (images[2]->read(filename))
				{
					if (zUp)
						vrImage::rotateImage180Degrees(images[2]);
					beginEditCP(textures[2]);
					textures[2]->setImage(images[2]);
					endEditCP(textures[2]);
					vrLog::info("Sky Background: Top/Up image loaded.");
					imageLoaded[3] = true;
				}
				endEditCP(images[2]);
			}
			if (((qstr.find("east") >= 0) || (qstr.find("right") >= 0)) && !imageLoaded[4])
			{
				beginEditCP(images[1]);
				if (images[1]->read(filename))
				{
					if (zUp)
						vrImage::rotate90Left(images[1]);
					beginEditCP(textures[1]);
					textures[1]->setImage(images[1]);
					endEditCP(textures[1]);
					vrLog::info("Sky Background: Right/East image loaded.");
					imageLoaded[4] = true;
				}
				endEditCP(images[1]);
			}
			if (((qstr.find("west") >= 0) || (qstr.find("left") >= 0)) && !imageLoaded[5])
			{
				beginEditCP(images[0]);
				if (images[0]->read(filename))
				{
					if (zUp)
						vrImage::rotate90Right(images[0]);
					beginEditCP(textures[0]);
					textures[0]->setImage(images[0]);
					endEditCP(textures[0]);
					vrLog::info("Sky Background: Left/West image loaded.");
					imageLoaded[5] = true;
				}
				endEditCP(images[0]);
			}

			++it;
		}

		skyBackground = SkyBackground::create();
		beginEditCP(skyBackground);
		if (!zUp)
		{
			skyBackground->setFrontTexture(textures[5]);
			skyBackground->setBackTexture(textures[4]);
			skyBackground->setBottomTexture(textures[3]);
			skyBackground->setTopTexture(textures[2]);
			skyBackground->setRightTexture(textures[1]);
			skyBackground->setLeftTexture(textures[0]);
		}
		else
		{
			skyBackground->setFrontTexture(textures[3]);
			skyBackground->setBackTexture(textures[2]);
			skyBackground->setBottomTexture(textures[4]);
			skyBackground->setTopTexture(textures[5]);
			skyBackground->setRightTexture(textures[1]);
			skyBackground->setLeftTexture(textures[0]);
		}
		endEditCP(skyBackground);

		vrOSGWidget *gl = vrOSGWidget::getMGLW(-1);
		ViewportPtr vredViewport = gl->getViewport();
		//oldBackground = vredViewport->getBackground();
		beginEditCP(vredViewport);
		vredViewport->setBackground(skyBackground);
		endEditCP(vredViewport);

		directoryLineEdit->setText(dir.absPath());

		// read light settings
		if (SetLightingCheckBox->isChecked())
		{
			string lightName = LightNameLineEdit->text().ascii();
			if (!QFile::exists(dir.absPath() + "/LightSettings.xml"))
				vrLog::warning("Light Settings not found.");
			else
			{
				QFile* file = new QFile(dir.absPath() + "/LightSettings.xml");
				if (file->open(IO_ReadOnly))
				{
					LightSettingsHandler handler;
					QXmlSimpleReader reader;
					reader.setContentHandler(&handler);
					reader.setErrorHandler(&handler);
					QXmlInputSource source(file);
					reader.parse(source);
					file->close();
					handler.direction.normalize();

					vector<NodePtr> lights;
					vrLights::getLights(lights);
					bool lightSet = false;
					for (vector<NodePtr>::const_iterator it = lights.begin();
						it != lights.end(); ++it)
					{
						LightPtr light = LightPtr::dcast((*it)->getCore());
						if (light != NullFC)
						{
							NodePtr node = *it;
							string name = getName(node);
							if (name.find(lightName) != string::npos)
							{
								setLightSettings(light, handler);
								lightSet = true;
							}
						}
					}

					if (!lightSet)
					{
						NodePtr rootNode = vrScenegraph::getRoot();

						TransformPtr beaconTransform = Transform::create();
						NodePtr beaconNode = Node::create();
						beginEditCP(beaconNode);
						beaconNode->setCore(beaconTransform);
						endEditCP(beaconNode);

						PointLightPtr light = PointLight::create();
						beginEditCP(light);
						light->setAttenuation(1,0,0);
						light->setBeacon(beaconNode);
						endEditCP(light);
						NodePtr lightNode = Node::create();
						beginEditCP(lightNode);
						lightNode->setCore(light);
						endEditCP(lightNode);
						OSG::setName(lightNode, lightName);

						beginEditCP(rootNode);
						rootNode->addChild(lightNode);
						rootNode->addChild(beaconNode);
						endEditCP(rootNode);

						setLightSettings(light, handler);

						vrScenegraph::update(true);
					}

				}
			}
		}
	}
	catch (std::exception const& e)
	{
		cout << "type: " << typeid(e).name() << endl;
		cout << "message: " << e.what() << endl << endl;
	}
}
void ImageImporter::slotImport()
{
    //first save all
    slotSaveSettings();

    //then init the regular expression
    QRegExp re(m_txtSourceFilename->text(), !m_chkIgnoreCase->isChecked());

    //first find all possible files
    //listdir is used as a stack containing the directories to parse
    QStringList lstDirs = m_cmbSourceFolder->currentText();

    //the list of files found in the directories
    QFileInfoList lstFiles;
    lstFiles.setAutoDelete(true);

    DlgImageImporterStatus* dlgStatus = new DlgImageImporterStatus(this, "StatusDialog");
    dlgStatus->enableImageArchive(m_groupArchive->isChecked());
    dlgStatus->show();

    dlgStatus->appendStatusMessage(i18n("Starting..."));

    dlgStatus->setCurrentMode( DlgImageImporterStatus::ModeImport,
                               i18n("Scanning for available Images..."));

    //now go thru all folders and collect all files that match the file regexp...
    while (!lstDirs.isEmpty()) {
        QDir d( lstDirs.front() );
        lstDirs.pop_front();

        dlgStatus->addFolder();

        d.setMatchAllDirs(true);

        const QFileInfoList* list = d.entryInfoList();
        if (list) {

            QFileInfoListIterator it( *list );
            QFileInfo* fi;

            for ( ; ( fi = it.current() ) != 0; ++it )
            {
                if ( fi->fileName() == "." || fi->fileName() == ".."  ) {
                    continue;
                } else if ( fi->isDir() && m_chkSrcIncludeSubfolders->isChecked())    {
                    lstDirs.append(fi->absFilePath());
                } else if( fi->isFile() ) {
                    dlgStatus->addFile();
                    if (re.exactMatch(fi->fileName())) {
                        dlgStatus->addMatch();
                        //save a copy of all FileInfos
                        lstFiles.append(new QFileInfo(*fi));
                    }
                }
                // we return here and break all importing!
                if (dlgStatus->wasCanceled()) {
                    return;
                }
            }
        }
        // we return here and break all importing!
        if (dlgStatus->wasCanceled()) {
            return;
        }
    }

    //archive the images, if requested ...
    if (m_groupArchive->isChecked())
    {
        dlgStatus->setCurrentMode(DlgImageImporterStatus::ModeArchive,
                                  i18n("Archiving found images..."));

        importFiles(&lstFiles,
                    m_txtArchiveBaseFolder->text(),
                    m_txtArchiveSubfolders->text(),
                    m_txtArchiveFilename->text(),
                    m_chkArchiveLowercase->isChecked(),
                    false,
                    dlgStatus);

        if (dlgStatus->wasCanceled()) {
            //either canceled by user or error
            return;
        }
    } else {
        dlgStatus->appendStatusMessage(i18n("Archiving found images... skipped"));
    }

    QString msg = i18n("Moving found images...");
    if (!m_chkSrcRemoveFilesFromSrc->isChecked()) {
        msg = i18n("Copying found images...");
    }
    dlgStatus->setCurrentMode(DlgImageImporterStatus::ModeDestination, msg);

    // ... then copy/ move the images to their destinaion
    importFiles(&lstFiles, m_cmbDestBasefolder->currentText(), m_txtDestSubfolders->text(),
                m_txtDestFilename->text(), m_chkDestLowercase->isChecked(),
                m_chkSrcRemoveFilesFromSrc->isChecked(), dlgStatus);

    if (dlgStatus->wasCanceled()) {
        //either canceled by user or error
        return;
    }

    //yes, we are done :)
    dlgStatus->setCurrentMode( DlgImageImporterStatus::ModeFinished, i18n("Done."));

    //now tell, that new images have arrived
    emit newImagesImported(m_cmbDestBasefolder->currentText());
}
Пример #20
0
void SpawnMonitor::saveSpawnPoints()
{
  // only save if modified
  if (!m_modified)
    return;

  if ( !m_zoneName.length() )
  {
    seqWarn("Zone name not set in 'SpawnMonitor::saveSpawnPoints'!" );
    return;
  }
  
  QString fileName;
  
  fileName = m_zoneName + ".sp";

  QFileInfo fileInfo = 
    m_dataLocMgr->findWriteFile("spawnpoints", fileName, false);

  fileName = fileInfo.absFilePath();

  QString newName = fileName + ".new";
  QFile spFile( newName );
  
  if (!spFile.open(IO_WriteOnly))
  {
    seqWarn("Failed to open %s for writing", (const char*)newName);
    return;
  }
  
  QTextStream output(&spFile);
  
  QAsciiDictIterator<SpawnPoint> it( m_points );
  SpawnPoint* sp;
  
  while ((sp = it.current()))
  {
    ++it;
    output	<< sp->x()
		<< " "
		<< sp->y()
		<< " "
		<< sp->z()
		<< " "
		<< (unsigned long)sp->diffTime()
		<< " "
		<< sp->count()
		<< " "
		<< sp->name()
		<< '\n';
  }
  
  spFile.close();
  
  QFileInfo fi( spFile );
  QFile old( fileName );
  QDir dir( fi.dir() );
  QString backupName = fileName + ".bak";
  
  if (old.exists())
  {
    if (dir.rename( fileName, backupName))
    {
      if (!dir.rename( newName, fileName))
	seqWarn( "Failed to rename %s to %s", 
		(const char*)newName, (const char*)fileName);
    }
  }
  else
  {
    if (!dir.rename(newName, fileName))
      seqWarn("Failed to rename %s to %s", 
	     (const char*)newName, (const char*)fileName);
  }
  m_modified = false;
  seqInfo("Saved spawn points: %s", (const char*)fileName);
}
Пример #21
0
void SpawnMonitor::loadSpawnPoints()
{
  QString fileName;
  
  fileName = m_zoneName + ".sp";

  QFileInfo fileInfo = 
    m_dataLocMgr->findExistingFile("spawnpoints", fileName, false);

  if (!fileInfo.exists())
  {
    seqWarn("Can't find spawn point file %s", 
	   (const char*)fileInfo.absFilePath());
    return;
  }
  
  fileName = fileInfo.absFilePath();

  QFile spFile(fileName);
  
  if (!spFile.open(IO_ReadOnly))
  {
    seqWarn( "Can't open spawn point file %s", (const char*)fileName );
    return;
  }
  
  QTextStream input( &spFile );
  
  int16_t x, y, z;
  unsigned long diffTime;
  uint32_t count;
  QString name;

  while (!input.atEnd())
  {
    input >> x;
    input >> y;
    input >> z;
    input >> diffTime;
    input >> count;
    name = input.readLine();
    name = name.stripWhiteSpace();
    
    EQPoint	loc(x, y, z);
    SpawnPoint*	p = new SpawnPoint( 0, loc, name, diffTime, count );
    if (p)
    {
      QString key = p->key();
      
      if (!m_points.find(key))
      {
	m_points.insert(key, p);
	emit newSpawnPoint(p);
      }
      else
      {
	seqWarn("Warning: spawn point key already in use!");
	delete p;
      }
    }
  }

  seqInfo("Loaded spawn points: %s", (const char*)fileName);
  m_modified = false;
}
void FileSystemScanner::addFolders(Folder* parent)
{
    tracer->sinvoked(__func__) << "with folder: " << parent->dir()->absPath() << endl;

    // get all folders in the current directory
    const QFileInfoList* subfolderlist = parent->dir()->entryInfoList(QDir::Dirs);

    if (subfolderlist) {
        QFileInfoListIterator iterator(*subfolderlist);
        QFileInfo* fileInfo = 0;
        while ((fileInfo = iterator.current()) != 0) {

            // ignore ./.. and hidden folders (beginning with .)
            // and ignore folders called 'ThumbNails'
            if (!fileInfo->fileName().startsWith(".")
                && mustHandleFolder(fileInfo->fileName())
                ) {

                QDir subfolder(fileInfo->absFilePath());

                tracer->sdebug(__func__) << "handling subfolder: " << subfolder.absPath() << endl;

                bool loopDetected = false;

                // we have to test if this folder is part of a loop or if it is the superfolder of an already added dir
                QString* alreadyAddedFolder;
                for (alreadyAddedFolder = m_loopDetectionHelper->first(); alreadyAddedFolder; alreadyAddedFolder = m_loopDetectionHelper->next()) {

                    if (*alreadyAddedFolder == subfolder.canonicalPath()) {
                        loopDetected = true;
                        tracer->swarning(__func__) << "loop detected, not adding folder again: '" << fileInfo->absFilePath()
                                << "' is pointing to '" << *alreadyAddedFolder << "'" << endl;
                        emit(progress_loopDetected(fileInfo->absFilePath(), *alreadyAddedFolder));
                        break;
                    }
                    if ((*alreadyAddedFolder).startsWith(subfolder.canonicalPath(), true)) {
                        loopDetected = true;
                        tracer->swarning(__func__) << "loop detected, not adding folder because it is a super directory ("
                                << subfolder.canonicalPath() << ") of an already added folder: '" << *alreadyAddedFolder << "'" << endl;
                        emit(progress_loopDetected(subfolder.canonicalPath(), *alreadyAddedFolder));
                        break;
                    }
                }

                if (!loopDetected) {
                    Folder* existingFolder = 0;

                    // we have to test if the folder is already processed to prevent endless loops
                    QIntDictIterator<Folder> it(*m_engine->m_sourceDirDict);
                    while (!existingFolder && it.current()) {

                        Folder* current = it.current();

                        if (current->dir()->canonicalPath() == subfolder.canonicalPath()) {
                            existingFolder = current;
                            tracer->sdebug(__func__) << "folder is already added: " << current->dir()->canonicalPath() << endl;
                            emit(progress_folderAlreadyAdded(current->dir()->canonicalPath()));
                        }

                        ++it;
                    }

                    if (existingFolder) {

                        // add the directory to the list of handled directories for detecting loops
                        m_loopDetectionHelper->append(new QString(existingFolder->dir()->canonicalPath()));

                        // make recursive call
                        addFolders(existingFolder);
                    } else {
                        tracer->sdebug(__func__) << "found new folder to add " << fileInfo->absFilePath() << endl;

                        // create the new folder
                        Folder* child = new Folder(m_engine->m_nextSourceDirId++, new QDir(fileInfo->absFilePath()), false);
                        child->setFound(true);

                        // add the current directory to the tree
                        child->setParent(parent);

                        // put the folder into the folder dictionary (id to folder map)
                        m_engine->m_sourceDirDict->insert(child->id(), child);

                        // add the directory to the list of handled directories for detcting loops
                        m_loopDetectionHelper->append(new QString(child->dir()->canonicalPath()));

                        // add all files in the current folder
                        rescanFolder(child, false);

                        emit(newFolder(child));
                        
                        if (m_cancel) {
                            return;
                        }

                        // make recursive call
                        addFolders(child);
                    }
                }
            }
            ++iterator;
        }
    }
}
void ImageImporter::importFiles(QFileInfoList* lstFiles, const QString& baseFolder,
                                const QString& subfolder, const QString& fileName,
                                bool lowercaseFileNames, bool moveFiles, DlgImageImporterStatus* dlgStatus)
{
    QRegExp re(m_txtSourceFilename->text(), !m_chkIgnoreCase->isChecked());
    if (!re.isValid()) {
        dlgStatus->appendErrorMessage(i18n("Invalid Regular Expression!"));
        dlgStatus->setCurrentMode(DlgImageImporterStatus::ModeAbort, i18n("Aborted!"));
        return;
    }


    //check if the basedir exists
    QDir bfd(baseFolder);
    if (!bfd.exists()) {
        if (!ImageImporter::mkpath(bfd.absPath())) {
            dlgStatus->appendErrorMessage(i18n("Could not create base path!"));
            dlgStatus->setCurrentMode(DlgImageImporterStatus::ModeAbort, i18n("Aborted!"));
            return;
        }
    }



    QFileInfo* fi;
    for ( fi = lstFiles->first(); fi; fi = lstFiles->next() )
    {
        dlgStatus->incProgress();

        QString sf = replaceStrings( subfolder, fi, re );
        if (sf.isEmpty()) {
            dlgStatus->appendErrorMessage(QString(i18n("Image \'%1\' does not contain exif data, skipping!"))
                                          .arg(fi->absFilePath()));
            continue;
        }
        QString fn = replaceStrings( fileName,  fi, re );

        if (lowercaseFileNames) {
            fn = fn.lower();
        }

        //now check if the directories exists ... or create them...
        QDir sfd(bfd.absPath() + "/" + sf);
        if (!sfd.exists()) {
            if (!ImageImporter::mkpath(sfd.absPath())) {
                dlgStatus->appendErrorMessage(QString(i18n("Could not create subfolder for image \'%1\'"))
                                              .arg(fi->absFilePath()));
                continue;
            }
        }

        QFileInfo toFile(sfd.absPath() + "/" + fn);
        if (toFile.exists()) {
            dlgStatus->appendErrorMessage(QString(i18n("Image \'%1\' already exists, not imported!"))
                                          .arg(fi->absFilePath()));
            continue;
        }

        if (moveFiles) {
            ImageImporter::move_file( fi->absFilePath(), toFile.absFilePath() );
        } else {
            ImageImporter::copy_file( fi->absFilePath(), toFile.absFilePath() );
        }

        if (dlgStatus->wasCanceled()) {
            return;
        }
    }
}
Пример #24
0
Session::Session(SessionManager* parent, DataSource* source)
{
	m_zoneMgr = NULL;
	m_mapMgr = NULL;
	m_groupMgr = NULL;
	m_guildMgr = NULL;
	m_guildShell = NULL;
	m_player = NULL;
	m_spawnMonitor = NULL;
	m_spawnShell = NULL;
	m_spellShell = NULL;
	m_filterMgr = NULL;
	m_messages = NULL;
	m_messageFilters = NULL;
	m_messageShell = NULL;
	
	m_parent = parent;
	m_preferences = parent->preferences();

	m_timer = new QTimer(this);
	m_delay = 1000;
	m_dataSource = 0;
	
	/***********************************************************************
	 * Create Message Objects
	 **********************************************************************/
	
	// Create message filters object
	m_messageFilters = new MessageFilters(this, "messagefilters");
	
	// Create messages storage
	m_messages = new Messages(m_parent->dateTimeMgr(), m_messageFilters, this, "messages");
	
	// Create the terminal object
	m_terminal = new Terminal(m_messages, this, "terminal");
	
	
	/***********************************************************************
	 * Create ShowEQ Objects
	 **********************************************************************/
	
	// Create the Zone Manager
	m_zoneMgr = new ZoneMgr(this, "zonemgr");
	
	// Create the Guild Manager
	QString fileName = m_preferences->getPrefString("GuildsFile", "Interface", "guilds2.dat");
	QFileInfo fileInfo = m_parent->dataLocationMgr()->findWriteFile("tmp", fileName);
	m_guildMgr = new GuildMgr(fileInfo.absFilePath(), this, "guildmgr");
	
	// Create the Player Object
	m_player = new Player(this, m_zoneMgr, m_guildMgr);
	
	// Create the filter manager
	QString filterFile = pSEQPrefs->getPrefString("FilterFile", "Interface", "global.xml");
	bool isCaseSensitive = pSEQPrefs->getPrefBool("IsCaseSensitive", "Interface", false);
	m_filterMgr = new FilterMgr(m_parent->dataLocationMgr(), filterFile, isCaseSensitive);

	// if there is a short zone name already, try to load its filters
	// (there isn't one, this should be removed)
	QString shortZoneName = m_zoneMgr->shortZoneName();
	if (!shortZoneName.isEmpty() && shortZoneName != "unknown")
		m_filterMgr->loadZone(shortZoneName);
	
	
	// Create the Guild Shell
	m_guildShell = new GuildShell(m_zoneMgr, this, "GuildShell");
	
	// Create the Spawn Shell
	m_spawnShell = new SpawnShell(*m_filterMgr, m_zoneMgr, m_player, m_guildMgr);
	
	// Create the Map Manager
	m_mapMgr = new MapMgr(m_parent->dataLocationMgr(), m_spawnShell, m_player, m_zoneMgr);
	
	// Create the Spell Shell
	m_spellShell = new SpellShell(m_player, m_spawnShell, m_parent->spells());
	
	// Create the Spawn Monitor
	m_spawnMonitor = new SpawnMonitor(m_parent->dataLocationMgr(), m_zoneMgr, m_spawnShell);
	
	// Create the Group Manager
	m_groupMgr = new GroupMgr(m_spawnShell, m_player, this, "groupmgr");
	
	// Create the message shell
	m_messageShell = new MessageShell(m_messages, m_parent->eqStrings(), m_parent->spells(),
			m_zoneMgr, m_spawnShell, m_player, this, "messageshell");
	
	// Create the Filter Notification object
	m_filterNotifications = new FilterNotifications(this, "filternotifications");

	attachSignals();

	assignSource(source);
}
Пример #25
0
int readDir(QFileInfo *fi,
            FileNameList *fnList,
            FileNameDict *fnDict,
            StringDict  *exclDict,
            QStrList *patList,
            QStrList *exclPatList,
            StringList *resultList,
            StringDict *resultDict,
            bool errorIfNotExist,
            bool recursive,
            QDict<void> *killDict,
            QDict<void> *paths
           )
{
  QCString dirName = fi->absFilePath().utf8();
  if (paths && paths->find(dirName)==0)
  {
    paths->insert(dirName,(void*)0x8);
  }
  if (fi->isSymLink())
  {
  }
  QDir dir(dirName);
  dir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden );
  int totalSize=0;
  //printf("killDict=%p count=%d\n",killDict,killDict->count());
  
  const QFileInfoList *list = dir.entryInfoList();
  if (list)
  {
    QFileInfoListIterator it( *list );
    QFileInfo *cfi;

    while ((cfi=it.current()))
    {
      if (exclDict==0 || exclDict->find(cfi->absFilePath().utf8())==0) 
      { // file should not be excluded
        //printf("killDict->find(%s)\n",cfi->absFilePath().data());
        if (!cfi->exists() || !cfi->isReadable())
        {
          if (errorIfNotExist)
          {
          }
        }
        else if (cfi->isFile() && 
            (patList==0 || patternMatch(*cfi,patList)) && 
            !patternMatch(*cfi,exclPatList) &&
            (killDict==0 || killDict->find(cfi->absFilePath().utf8())==0)
            )
        {
          totalSize+=cfi->size()+cfi->absFilePath().length()+4;
          QCString name=cfi->fileName().utf8();
          //printf("New file %s\n",name.data());
          if (fnDict)
          {
            FileDef  *fd=new FileDef(cfi->dirPath().utf8()+"/",name);
            FileName *fn=0;
            if (!name.isEmpty() && (fn=(*fnDict)[name]))
            {
              fn->append(fd);
            }
            else
            {
              fn = new FileName(cfi->absFilePath().utf8(),name);
              fn->append(fd);
              if (fnList) fnList->inSort(fn);
              fnDict->insert(name,fn);
            }
          }
          QCString *rs=0;
          if (resultList || resultDict)
          {
            rs=new QCString(cfi->absFilePath().utf8());
          }
          if (resultList) resultList->append(rs);
          if (resultDict) resultDict->insert(cfi->absFilePath().utf8(),rs);
          if (killDict) killDict->insert(cfi->absFilePath().utf8(),(void *)0x8);
        }
        else if (recursive &&
            cfi->isDir() && 
            !patternMatch(*cfi,exclPatList) &&
            cfi->fileName().at(0)!='.') // skip "." ".." and ".dir"
        {
          cfi->setFile(cfi->absFilePath());
          totalSize+=readDir(cfi,fnList,fnDict,exclDict,
              patList,exclPatList,resultList,resultDict,errorIfNotExist,
              recursive,killDict,paths);
        }
      }
      ++it;
    }
  }
  return totalSize;
}
Пример #26
0
// -------------------------------------------------------
QString SpiceFile::getSubcircuitFile()
{
  // construct full filename
  QString FileName = Props.getFirst()->Value;

  if (FileName.isEmpty())
  {
      return misc::properAbsFileName(FileName);
  }

  QFileInfo FileInfo(FileName);

  if (FileInfo.exists())
  {
      // the file must be an absolute path to a schematic file
     return FileInfo.absoluteFilePath();
  }
  else
  {
    // get the complete base name (everything except the last '.'
    // and whatever follows
    QString baseName = FileInfo.completeBaseName();

    // if only a file name is supplied, first check if it is in the
    // same directory as the schematic file it is a part of
    if (FileInfo.fileName () == FileName)
    {
        // the file has no path information, just the file name
        if (containingSchematic)
        {
            // check if a file of the same name is in the same directory
            // as the schematic file, if we have a pointer to it, in
            // which case we use this one
            QFileInfo schematicFileInfo = containingSchematic->getFileInfo ();

            for (int i = 0; i < QucsSettings.spiceExtensions.count (); i++)
            {
                QString extension = QucsSettings.spiceExtensions[i];
                extension.remove(0, 1); // take leading '*' out, issue with exits()

                QFileInfo localFileInfo (schematicFileInfo.canonicalPath ()
                                         + "/" + baseName + extension);

                if (localFileInfo.exists ())
                {
                    // return the subcircuit saved in the same directory
                    // as the schematic file
                    return localFileInfo.absoluteFilePath();
                }
                else
                {
                    /// \todo improve GUI/CLI error/warning
                    qCritical() << "Spice file not found:" << localFileInfo.absFilePath();
                }
            }
        }
    }

    // look up the hash table for the schematic file as
    // it does not seem to be an absolute path, this will also
    // search the home directory which is always hashed
    QMutex mutex;
    mutex.lock();
    QString hashsearchresult = "";
    // if GUI is running and has something in the hash
    if ( (QucsMain != 0) && !QucsMain->spiceNameHash.isEmpty() )
      hashsearchresult = QucsMain->spiceNameHash.value(baseName);
    mutex.unlock();

    if (hashsearchresult.isEmpty())
    {
        // the schematic was not found in the hash table, return
        // what would always have been returned in this case
        return misc::properAbsFileName(FileName);
    }
    else
    {
        // we found an entry in the hash table, check it actually still exists
        FileInfo.setFile(hashsearchresult);

        if (FileInfo.exists())
        {
            // it does exist so return the absolute file path
            return FileInfo.absoluteFilePath();
        }
        else
        {
            // the schematic file does not actually exist, return
            // what would always have been returned in this case
            return misc::properAbsFileName(FileName);
        }
    }

  }

}
Пример #27
0
QStringList Q3FileDialog::winGetOpenFileNames(const QString &filter,
        QString* initialDirectory,
        QWidget *parent,
        const char* /*name*/,
        const QString& caption,
        QString* selectedFilter)
{
    QStringList result;
    QFileInfo fi;
    QDir dir;
    QString isel;

    if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:"))
        initialDirectory->remove(0, 5);
    fi = QFileInfo(*initialDirectory);

    if (initialDirectory && !fi.isDir()) {
        *initialDirectory = fi.dirPath(true);
        isel = fi.fileName();
    }

    if (!fi.exists())
        *initialDirectory = QDir::homeDirPath();

    QString title = caption;
    if (title.isNull())
        title = tr("Open ");

    DWORD selFilIdx = 0;

    int idx = 0;
    if (selectedFilter && !selectedFilter->isEmpty()) {
        QStringList filterLst = makeFiltersList(filter);
        idx = filterLst.findIndex(*selectedFilter);
    }

    if (parent) {
        QEvent e(QEvent::WindowBlocked);
        QApplication::sendEvent(parent, &e);
        QApplicationPrivate::enterModal(parent);
    }

    OPENFILENAME* ofn = makeOFN(parent, isel,
                                *initialDirectory, title,
                                winFilter(filter), ExistingFiles);
    if (idx)
        ofn->nFilterIndex = idx + 1;
    if (GetOpenFileName(ofn)) {
        QString fileOrDir = QString::fromWCharArray(ofn->lpstrFile);
        selFilIdx = ofn->nFilterIndex;
        int offset = fileOrDir.length() + 1;
        if (ofn->lpstrFile[offset] == 0) {
            // Only one file selected; has full path
            fi.setFile(fileOrDir);
            QString res = fi.absFilePath();
            if (!res.isEmpty())
                result.append(res);
        }
        else {
            // Several files selected; first string is path
            dir.setPath(fileOrDir);
            QString f;
            while (!(f = QString::fromWCharArray(ofn->lpstrFile + offset)).isEmpty()) {
                fi.setFile(dir, f);
                QString res = fi.absFilePath();
                if (!res.isEmpty())
                    result.append(res);
                offset += f.length() + 1;
            }
        }
    }
    cleanUpOFN(&ofn);

    if (parent) {
        QApplicationPrivate::leaveModal(parent);
        QEvent e(QEvent::WindowUnblocked);
        QApplication::sendEvent(parent, &e);
    }

    if (!result.isEmpty()) {
        *initialDirectory = fi.dirPath();    // only save the path if there is a result
        if (selectedFilter)
            *selectedFilter = selFilter(filter, selFilIdx);
    }
    return result;
}
Пример #28
0
void HistoryPlugin::convertOldHistory()
{
	bool deleteFiles=  KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(),
		i18n( "Would you like to remove old history files?" ) , i18n( "History Converter" ), KStdGuiItem::del(), i18n("Keep") ) == KMessageBox::Yes;

	KProgressDialog *progressDlg=new KProgressDialog(Kopete::UI::Global::mainWidget() , "history_progress_dlg" , i18n( "History converter" ) ,
		 QString::null , true); //modal  to  make sure the user will not doing stupid things (we have a kapp->processEvents())
	progressDlg->setAllowCancel(false); //because i am too lazy to allow to cancel


	QString kopetedir=locateLocal( "data", QString::fromLatin1( "kopete"));
	QDir d( kopetedir ); //d should point to ~/.kde/share/apps/kopete/

	d.setFilter( QDir::Dirs  );

	const QFileInfoList_qt3 *list = d.entryInfoList_qt3();
	QFileInfoListIterator it( *list );
	QFileInfo *fi;
	while ( (fi = it.current()) != 0 )
	{
		QString protocolId;
		QString accountId;

		if( Kopete::Protocol *p = dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi->fileName() ) ) )
		{
			protocolId=p->pluginId();
			QDictIterator<Kopete::Account> it(Kopete::AccountManager::self()->accounts(p));
			Kopete::Account *a = it.current();
			if(a)
				accountId=a->accountId();
		}

		if(accountId.isNull() || protocolId.isNull())
		{
			if(fi->fileName() == "MSNProtocol" || fi->fileName() == "msn_logs" )
			{
				protocolId="MSNProtocol";
				KGlobal::config()->setGroup("MSN");
				accountId=KGlobal::config()->readEntry( "UserID" );
			}
			else if(fi->fileName() == "ICQProtocol" || fi->fileName() == "icq_logs" )
			{
				protocolId="ICQProtocol";
				KGlobal::config()->setGroup("ICQ");
				accountId=KGlobal::config()->readEntry( "UIN" );
			}
			else if(fi->fileName() == "AIMProtocol" || fi->fileName() == "aim_logs" )
			{
				protocolId="AIMProtocol";
				KGlobal::config()->setGroup("AIM");
				accountId=KGlobal::config()->readEntry( "UserID" );
			}
			else if(fi->fileName() == "OscarProtocol" )
			{
				protocolId="AIMProtocol";
				KGlobal::config()->setGroup("OSCAR");
				accountId=KGlobal::config()->readEntry( "UserID" );
			}
			else if(fi->fileName() == "JabberProtocol" || fi->fileName() == "jabber_logs")
			{
				protocolId="JabberProtocol";
				KGlobal::config()->setGroup("Jabber");
				accountId=KGlobal::config()->readEntry( "UserID" );
			}
			//TODO: gadu, wp
		}

		if(!protocolId.isEmpty() || !accountId.isEmpty())
		{
			QDir d2( fi->absFilePath() );
			d2.setFilter( QDir::Files  );
			d2.setNameFilter("*.log");
			const QFileInfoList_qt3 *list = d2.entryInfoList_qt3();
			QFileInfoListIterator it2( *list );
			QFileInfo *fi2;

			progressDlg->progressBar()->reset();
			progressDlg->progressBar()->setTotalSteps(d2.count());
			progressDlg->setLabel(i18n("Parsing old history in %1").arg(fi->fileName()));
			progressDlg->show(); //if it was not already showed...

			while ( (fi2 = it2.current()) != 0 )
			{
				//we assume that all "-" are dots.  (like in hotmail.com)
				QString contactId=fi2->fileName().replace(".log" , QString::null).replace("-" , ".");

				if(!contactId.isEmpty() )
				{
					progressDlg->setLabel(i18n("Parsing old history in %1:\n%2").arg(fi->fileName()).arg(contactId));
					kapp->processEvents(0); //make sure the text is updated in the progressDlg

					int month=0;
					int year=0;
					QDomDocument doc;
					QDomElement docElem;

					QDomElement msgelement;
					QDomNode node;
					QDomDocument xmllist;
					Kopete::Message::MessageDirection dir;
					QString body, date, nick;
					QString buffer, msgBlock;
					char cbuf[CBUFLENGTH]; // buffer for the log file

					QString logFileName = fi2->absFilePath();

					// open the file
					FILE *f = fopen(QFile::encodeName(logFileName), "r");

					// create a new <message> block
					while ( ! feof( f ) )
					{
						fgets(cbuf, CBUFLENGTH, f);
						buffer = QString::fromUtf8(cbuf);

						while ( strchr(cbuf, '\n') == NULL && !feof(f) )
						{
							fgets( cbuf, CBUFLENGTH, f );
							buffer += QString::fromUtf8(cbuf);
						}

						if( buffer.startsWith( QString::fromLatin1( "<message " ) ) )
						{
							msgBlock = buffer;

							// find the end of the message block
							while( !feof( f ) && buffer != QString::fromLatin1( "</message>\n" ) /*strcmp("</message>\n", cbuf )*/ )
							{
								fgets(cbuf, CBUFLENGTH, f);
								buffer = QString::fromUtf8(cbuf);

								while ( strchr(cbuf, '\n') == NULL && !feof(f) )
								{
									fgets( cbuf, CBUFLENGTH, f );
									buffer += QString::fromUtf8(cbuf);
								}
								msgBlock.append(buffer);
							}

							// now let's work on this new block
							xmllist.setContent(msgBlock, false);
							msgelement = xmllist.documentElement();
							node = msgelement.firstChild();

							if( msgelement.attribute( QString::fromLatin1( "direction" ) ) == QString::fromLatin1( "inbound" ) )
								dir = Kopete::Message::Inbound;
							else
								dir = Kopete::Message::Outbound;

							// Read all the elements.
							QString tagname;
							QDomElement element;

							while ( ! node.isNull() )
							{
								if ( node.isElement() )
								{
									element = node.toElement();
									tagname = element.tagName();

									if( tagname == QString::fromLatin1( "srcnick" ) )
										nick = element.text();

									else if( tagname == QString::fromLatin1( "date" ) )
										date = element.text();
									else if( tagname == QString::fromLatin1( "body" ) )
										body = element.text().stripWhiteSpace();
								}

								node = node.nextSibling();
							}
							//FIXME!! The date in logs writed with kopete running with QT 3.0 is Localised.
							// so QT can't parse it correctly.
							QDateTime dt=QDateTime::fromString(date);
							if(dt.date().month() != month || dt.date().year() != year)
							{
								if(!docElem.isNull())
								{
									QDate date(year,month,1);
									QString name = protocolId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
											QString::fromLatin1( "/" ) +
											contactId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
											date.toString(".yyyyMM");
									KSaveFile file(  locateLocal( "data", QString::fromLatin1( "kopete/logs/" ) + name+ QString::fromLatin1( ".xml" ) )  );
									if( file.status() == 0 )
									{
										QTextStream *stream = file.textStream();
										//stream->setEncoding( QTextStream::UnicodeUTF8 ); //???? oui ou non?
										doc.save( *stream , 1 );
										file.close();
									}
								}


								month=dt.date().month();
								year=dt.date().year();
								docElem=QDomElement();
							}

							if(docElem.isNull())
							{
								doc=QDomDocument("Kopete-History");
								docElem= doc.createElement( "kopete-history" );
								docElem.setAttribute ( "version" , "0.7" );
								doc.appendChild( docElem );
								QDomElement headElem = doc.createElement( "head" );
								docElem.appendChild( headElem );
								QDomElement dateElem = doc.createElement( "date" );
								dateElem.setAttribute( "year",  QString::number(year) );
								dateElem.setAttribute( "month", QString::number(month) );
								headElem.appendChild(dateElem);
								QDomElement myselfElem = doc.createElement( "contact" );
								myselfElem.setAttribute( "type",  "myself" );
								myselfElem.setAttribute( "contactId", accountId  );
								headElem.appendChild(myselfElem);
								QDomElement contactElem = doc.createElement( "contact" );
								contactElem.setAttribute( "contactId", contactId );
								headElem.appendChild(contactElem);
								QDomElement importElem = doc.createElement( "imported" );
								importElem.setAttribute( "from",  fi->fileName() );
								importElem.setAttribute( "date", QDateTime::currentDateTime().toString()  );
								headElem.appendChild(importElem);
							}
							QDomElement msgElem = doc.createElement( "msg" );
							msgElem.setAttribute( "in",  dir==Kopete::Message::Outbound ? "0" : "1" );
							msgElem.setAttribute( "from", dir==Kopete::Message::Outbound ? accountId : contactId  );
							msgElem.setAttribute( "nick",  nick ); //do we have to set this?
							msgElem.setAttribute( "time",  QString::number(dt.date().day()) + " " +  QString::number(dt.time().hour()) + ":" + QString::number(dt.time().minute())  );
							QDomText msgNode = doc.createTextNode( body.stripWhiteSpace() );
							docElem.appendChild( msgElem );
							msgElem.appendChild( msgNode );
						}
					}

					fclose( f );
					if(deleteFiles)
						d2.remove(fi2->fileName() , false);

					if(!docElem.isNull())
					{
						QDate date(year,month,1);
						QString name = protocolId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
								QString::fromLatin1( "/" ) +
								contactId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
								date.toString(".yyyyMM");
						KSaveFile file(  locateLocal( "data", QString::fromLatin1( "kopete/logs/" ) + name+ QString::fromLatin1( ".xml" ) )  );
						if( file.status() == 0 )
						{
							QTextStream *stream = file.textStream();
							//stream->setEncoding( QTextStream::UnicodeUTF8 ); //???? oui ou non?
							doc.save( *stream ,1 );
							file.close();
						}
					}

				}
				progressDlg->progressBar()->setProgress(progressDlg->progressBar()->progress()+1);
				++it2;
			}
		}
		++it;
	}
	delete progressDlg;

}
Пример #29
0
int main (int argc, char **argv)
{
   int           opt;
   int           temp_int;
   int           option_index = 0;
   
   bool          bOptionHelp = false;
        
   /* Create application instance */
   //   QApplication::setStyle( new QWindowsStyle );
   QApplication qapp (argc, argv);

   /* Print the version number */
   displayVersion();

   // create the data location manager (with user data under ~/.showeq
   DataLocationMgr dataLocMgr(".showeq");

   /* Initialize the parameters with default values */
   QFileInfo configFileDefInfo = dataLocMgr.findExistingFile(".", "seqdef.xml",
							     true, false);
   
   if (!configFileDefInfo.exists())
   {
     fprintf(stderr, 
	     "Fatal: Couldn't find seqdef.xml!\n"
	     "\tDid you remember to do 'make install'\n");
     exit(-1);
   }

   QString configFileDef = configFileDefInfo.absFilePath();

   QFileInfo configFileInfo = dataLocMgr.findWriteFile(".", "showeq.xml",
						       true, true);

   // deal with funky border case since we may be running setuid
   QString configFile;
   if (configFileInfo.dir() != QDir::root())
     configFile = configFileInfo.absFilePath();
   else
     configFile = QFileInfo(dataLocMgr.userDataDir(".").absPath(),
			    "showeq.xml").absFilePath();

   // scan command line arguments for a specified config file
   int i = 1;
   while (i < argc)
   {
      if ((argv[i][0] == '-') && (argv[i][1] == 'o'))
         configFile = argv[i + 1];

      i ++;
   }

   /* NOTE: See preferencefile.cpp for info on how to use prefrences class */
   printf("Using config file '%s'\n", (const char*)configFile);
   pSEQPrefs = new XMLPreferences(configFileDef, configFile);

   showeq_params = new ShowEQParams;

   QString section;

   section = "Interface";
   /* Allow map depth filtering */
   showeq_params->retarded_coords  = pSEQPrefs->getPrefBool("RetardedCoords", section, 0);
   showeq_params->systime_spawntime = pSEQPrefs->getPrefBool("SystimeSpawntime", section, false);
   showeq_params->pvp = pSEQPrefs->getPrefBool("PvPTeamColoring", section, false);
   showeq_params->deitypvp = pSEQPrefs->getPrefBool("DeityPvPTeamColoring", section, false);
   showeq_params->keep_selected_visible = pSEQPrefs->getPrefBool("KeepSelected", section, true);

   section = "Misc";
   showeq_params->fast_machine = pSEQPrefs->getPrefBool("FastMachine", section, true);
   showeq_params->createUnknownSpawns = pSEQPrefs->getPrefBool("CreateUnknownSpawns", section, true);

   showeq_params->walkpathrecord = pSEQPrefs->getPrefBool("WalkPathRecording", section, false);
   showeq_params->walkpathlength = pSEQPrefs->getPrefInt("WalkPathLength", section, 25);
   /* Tells SEQ whether or not to display casting messages (Turn this off if you're on a big raid) */

   section = "SpawnList";
   showeq_params->showRealName = pSEQPrefs->getPrefBool("ShowRealName", section, false);

   /* Different files for different kinds of raw data */

   section = "SaveState";
   showeq_params->saveZoneState = 
     pSEQPrefs->getPrefBool("ZoneState", section, 1);
   showeq_params->savePlayerState = 
     pSEQPrefs->getPrefBool("PlayerState", section, 1);
   showeq_params->saveSpawns = pSEQPrefs->getPrefBool("Spawns", section, false);
   showeq_params->saveSpawnsFrequency = 
     pSEQPrefs->getPrefInt("SpawnsFrequency", section, (120 * 1000));
   showeq_params->restorePlayerState = false;
   showeq_params->restoreZoneState = false;
   showeq_params->restoreSpawns = false;
   showeq_params->saveRestoreBaseFilename = dataLocMgr.findWriteFile("tmp", pSEQPrefs->getPrefString("BaseFilename", section, "last")).absFilePath();

   /* Parse the commandline for commandline parameters */
   while ((opt = getopt_long( argc,
                              argv,
                              OPTION_LIST,
                              option_list,
                              &option_index
                             ))               != -1
          )
   {
      switch (opt)
      {
         /* Set the request to use a despawn list based off the spawn alert list. */

         /* Set the interface */
         case 'i':
         {            
	   pSEQPrefs->setPrefString("Device", "Network", optarg, 
				    XMLPreferences::Runtime);
	   break;
         }


         /* Set pcap thread to realtime */
         case 'r':
         {  
	   pSEQPrefs->setPrefBool("RealTimeThread", "Network", true, 
				  XMLPreferences::Runtime);
				  
            break;
         }


         /* Set the spawn filter file */
         case 'f':
         {
	   pSEQPrefs->setPrefString("FilterFile", "Filters", optarg, 
				    XMLPreferences::Runtime);
            
	   break;
         }


         /* Packet playback mode */
         case 'j':
         {            
            if (optarg)
               pSEQPrefs->setPrefString("Filename", "VPacket", optarg, 
					XMLPreferences::Runtime);

	    pSEQPrefs->setPrefBool("Playback", "VPacket", true, 
				   XMLPreferences::Runtime);
	    pSEQPrefs->setPrefBool("Record", "VPacket", false, 
				   XMLPreferences::Runtime);
            
            break;
         }

         /* Packet record mode */
         case 'g':
         {
            if (optarg)
               pSEQPrefs->setPrefString("Filename", "VPacket", optarg, 
					XMLPreferences::Runtime);

	    pSEQPrefs->setPrefBool("Playback", "VPacket", false, 
				   XMLPreferences::Runtime);
	    pSEQPrefs->setPrefBool("Record", "VPacket", true, 
				   XMLPreferences::Runtime);
            
            break;
         }


         /* Config file was already taken care of, ignore */
         case 'o':
            break;


         /* Make filter case sensitive */
         case 'C':
         {
	   pSEQPrefs->setPrefBool("IsCaseSensitive", "Filters", true,
				  XMLPreferences::Runtime);
	   break;
         }

         /* Use retarded coordinate system yxz */
         case 'c':
         {
            showeq_params->retarded_coords = 1;
            break;
         }


         /* Fast machine updates.. framerate vs packet based */
         case 'F':
         {
            showeq_params->fast_machine = 1;
            break;
         }


         /* Show unknown spawns */
         case 'K':
         {
            showeq_params->createUnknownSpawns = 1;
            break;
         }


         /* Select spawn on 'Consider' */
         case 'S':
         {
	   pSEQPrefs->setPrefBool("SelectOnCon", "Interface", true,
				  XMLPreferences::Runtime);
	   break;
         }


         /* Select spawn on 'Target' */
         case 'e':
         {
	   pSEQPrefs->setPrefBool("SelectOnTarget", "Interface", true, 
				  XMLPreferences::Runtime);
	   break;
         }


         /* Show net info */
         case 'N':
         {
	   pSEQPrefs->getPrefBool("ShowNetStats", section, true, 
				  XMLPreferences::Runtime);
	   break;
         }


         /* 't'rack pathing for mobs */
         case 't':
         {
            showeq_params->walkpathrecord = 1;
            break;
         }


         /* Maximum spawn path tracking length  */
         case 'L':
         {
            showeq_params->walkpathlength = atoi(optarg);
            break;
         }

         
         /* Log spawns! */
         case 'x':
         {
	   pSEQPrefs->setPrefBool("LogSpawns", "Misc", true, 
				  XMLPreferences::Runtime);
	   break;
         }


         /* Display the version info... */
         case 'V':
         case 'v':
         {
  	   exit(0);
	   break;
         }

         /* Don't autodetect character settings */
         case 'W':
         {
	   pSEQPrefs->getPrefBool("AutoDetectCharSettings", "Defaults", 
				  false, XMLPreferences::Runtime);
	   break;
         }


         /* Set default player level */
         case 'X':
         {
            temp_int = atoi(optarg);
            
            if (temp_int < 1 || temp_int > 70)
            {
               printf ("Invalid default level.  Valid range is 1 - 70.\n");
               exit(0);
            }

	    pSEQPrefs->setPrefInt("DefaultLevel", "Defaults", temp_int,
				  XMLPreferences::Runtime);
            break;
         }


         /* Set default player race */
         case 'Y':
         {
            temp_int = atoi(optarg);
            
            if ((temp_int < 1 || temp_int > 12) && 
		(temp_int != 128) &&
		(temp_int != 130) &&
		(temp_int != 26) &&
		(temp_int != 330))
            {
               printf ("Invalid default race, please use showeq -h to list valid race options.\n");
               exit(0);
            }
            
	    pSEQPrefs->setPrefInt("DefaultRace", "Defaults", temp_int,
				  XMLPreferences::Runtime);

            break;
         }


         /* Set default player class */
         case 'Z':
         {
            temp_int = atoi(optarg);
            
            if (temp_int < 1 || temp_int > 16)
            {
               printf ("Invalid default class, please use showeq -h to list valid class options.\n");
               exit(0);
            }

	    pSEQPrefs->setPrefInt("DefaultClass", "Defaults", temp_int);
            break;
         }

         /* IP address to track */
         case IPADDR_OPTION:
         {
	   pSEQPrefs->setPrefString("IP", "Network", optarg, 
				    XMLPreferences::Runtime);

	   break;
         }


         /* MAC address to track for those on DHCP */
         case MACADDR_OPTION:
         {
	   pSEQPrefs->setPrefString("MAC", "Network", optarg, 
				    XMLPreferences::Runtime);

	   break;
         }


         /* Filename for logging all packets */
         case GLOBAL_LOG_FILENAME_OPTION:
         {
	   pSEQPrefs->setPrefString("GlobalLogFilename", "PacketLogging", 
				    optarg, XMLPreferences::Runtime);
	   break;
         }


         /* Filename for logging world change packets */
         case WORLD_LOG_FILENAME_OPTION:
         {
	   pSEQPrefs->setPrefString("WorldLogFilename", "PacketLogging", 
				    optarg, XMLPreferences::Runtime);
	   break;
         }

         /* Filename for logging zone change packets */
         case ZONE_LOG_FILENAME_OPTION:
         {
	   pSEQPrefs->setPrefString("ZoneLogFilename", "PacketLogging", 
				    optarg, XMLPreferences::Runtime);
	   break;
         }


         /* Filename for logging unknown zone change packets */
         case UNKNOWN_LOG_FILENAME_OPTION:
         {
	   pSEQPrefs->setPrefString("UnknownZoneLogFilename", 
				    "PacketLogging", optarg, 
				    XMLPreferences::Runtime);
	   break;
         }


         /* Log everything */
         case GLOBAL_LOG_OPTION:
         {
	   pSEQPrefs->setPrefBool("LogAllPackets", "PacketLogging", true,
				  XMLPreferences::Runtime);
	   break;
         }


         /* Log all zone change packets */
         case ZONE_LOG_OPTION:
         {
	   pSEQPrefs->setPrefBool("LogZonePackets", "PacketLogging", true,
				  XMLPreferences::Runtime);
	   break;
         }


         /* Log only unfamiliar zone change packets */
         case UNKNOWN_ZONE_LOG_OPTION:
         {
	   pSEQPrefs->setPrefBool("LogUnknownZonePackets", "PacketLogging", true,
				  XMLPreferences::Runtime);
	   break;
         }


         case PLAYBACK_SPEED_OPTION:
         {
	   pSEQPrefs->setPrefInt("PlaybackRate", "VPacket", atoi(optarg), 
				 XMLPreferences::Runtime);
            break;
         }


         /* Enable logging of raw packets... */
         case RAW_LOG_OPTION:
         {
	   pSEQPrefs->setPrefBool("LogRawPackets", "PacketLogging", true,
				  XMLPreferences::Runtime);
	   break;
         }

         /* Display spawntime in UNIX time (time_t) instead of hh:mm format */
         case SYSTIME_SPAWNTIME_OPTION:
         { 
            showeq_params->systime_spawntime = 1;
            break;
         }

         case SPAWNLOG_FILENAME_OPTION:
         {
	   pSEQPrefs->setPrefString("SpawnLogFilename", "Misc", optarg,
				  XMLPreferences::Runtime);
	   break;
         }
         
         case ITEMDB_DATA_FILENAME_OPTION:
	   {
	     pSEQPrefs->setPrefString("DataDBFilename", "ItemDB", optarg,
				      XMLPreferences::Runtime);
	     break;
         }
         
         case ITEMDB_RAW_FILENAME_OPTION:
         {
	     pSEQPrefs->setPrefString("RawDataDBFilename", "ItemDB", optarg,
				      XMLPreferences::Runtime);
            break;
         }

         case ITEMDB_DATABASES_ENABLED:
         {
	   pSEQPrefs->setPrefInt("DatabasesEnabled", "ItemDB", atoi(optarg),
				 XMLPreferences::Runtime);
	   break;
         }
	 
         case ITEMDB_DISABLE:
	 {
	   pSEQPrefs->setPrefBool("Enabled", "ItemDB", false, 
				 XMLPreferences::Runtime);
	   break;
	 }

         case ITEMDB_ENABLE:
	 {
	   pSEQPrefs->setPrefBool("Enabled", "ItemDB", true, 
				 XMLPreferences::Runtime);
	   break;
	 }

         case RESTORE_PLAYER_STATE:
	 {
	   showeq_params->restorePlayerState = true;
	   break;
	 }
         case RESTORE_ZONE_STATE:
	 {
	   showeq_params->restoreZoneState = true;
	   break;
	 }
         case RESTORE_SPAWNS:
	 {
	   showeq_params->restoreSpawns = true;
	   break;
	 }
         case RESTORE_ALL:
	 {
	   showeq_params->restorePlayerState = true;
	   showeq_params->restoreZoneState = true;
	   showeq_params->restoreSpawns = true;
	   break;
	 }


         /* Spit out the help */
         case 'h': /* Fall through */
         default:
         {
            bOptionHelp = true;
            break;
         }
      }
   }

   if (bOptionHelp)
   {
     displayOptions(argv[0]);
     exit (0);
   }

   /* Set up individual files for logging selected packet types based on
      a common filename base.   The types to log were found by following
      where pre_worked was a precondition for further analysis.
   */

   int ret;

   // just to add a scope to better control when the main interface gets 
   // destroyed
   if  (1)
   {
     /* The main interface widget */
     EQInterface intf(&dataLocMgr, 0, "interface");
     qapp.setMainWidget (&intf);
   
     /* Start the main loop */
     ret = qapp.exec ();
   }

   // delete the preferences data
   delete pSEQPrefs;

   // delete the showeq_params data
   delete showeq_params;

   return ret;
}
Пример #30
0
ExperienceWindow::ExperienceWindow(const DataLocationMgr* dataLocMgr, 
				   Player* player, GroupMgr* groupMgr,
				   ZoneMgr* zoneMgr,
				   QWidget* parent, const char* name) 
  : SEQWindow("Experience", "ShowEQ - Experience", parent, name),
    m_dataLocMgr(dataLocMgr),
    m_player(player),
    m_group(groupMgr),
    m_zoneMgr(zoneMgr)
{
  /* Hopefully this is only called once to set up the window,
     so this is a good place to initialize some things which
     otherwise won't be. */

   m_ratio = 1;
   m_timeframe = 0;
   m_calcZEM=0;
   m_ZEMviewtype = 0;

   m_view_menu = new QPopupMenu( this );
   m_view_menu->insertItem( "&All Mobs", this, SLOT(viewAll()) );
   m_view_menu->insertItem( "Previous &15 Minutes", this, SLOT(view15Minutes()) );
   m_view_menu->insertItem( "Previous &30 Minutes", this, SLOT(view30Minutes()) );
   m_view_menu->insertItem( "Previous &60 Minutes", this, SLOT(view60Minutes()) );
   m_view_menu->setItemChecked( m_view_menu->idAt(0), true );

   m_view_menu->insertSeparator();
   m_exp_rate_menu = new QPopupMenu( this );
   m_exp_rate_menu->insertItem( "per &minute", this, SLOT(viewRatePerMinute()) );
   m_exp_rate_menu->insertItem( "per &hour", this, SLOT(viewRatePerHour()) );
   m_exp_rate_menu->setItemChecked( m_exp_rate_menu->idAt(0), true );
   m_view_menu->insertItem( "Experience &Rate", m_exp_rate_menu );

   m_view_menu->insertSeparator();
   m_view_menu->insertItem( "Clear Kills", this, SLOT(viewClear()) );

   m_view_menu->insertSeparator();
   m_ZEM_menu = new QPopupMenu( this );
   m_ZEM_menu->insertItem( "Calculated Value", this, SLOT(viewZEMcalculated()) );
   m_ZEM_menu->insertItem( "Raw Value", this, SLOT(viewZEMraw()) );
   m_ZEM_menu->insertItem( "Percent Bonus", this, SLOT(viewZEMpercent()) );
   m_ZEM_menu->setItemChecked( m_ZEM_menu->idAt(0), true );
   m_view_menu->insertItem( "ZEM View Options", m_ZEM_menu );
   m_view_menu->insertItem( "Calculate ZEM on next kill", this, SLOT(calcZEMNextKill()) );

   m_layout = new QVBoxLayout(boxLayout());

   m_menu_bar = new QMenuBar( this );
   m_menu_bar->insertItem( "&View", m_view_menu );
   //m_layout->addSpacing( m_menu_bar->height() + 5 );
   m_layout->addWidget(m_menu_bar);

   QGroupBox *listGBox = new QVGroupBox( "Experience Log", this );
   m_layout->addWidget( listGBox );

   m_exp_listview = new SEQListView(preferenceName(), listGBox);
   m_exp_listview->addColumn("Time");
   m_exp_listview->addColumn("Mob");
   m_exp_listview->addColumn("Level");
   m_exp_listview->addColumn("Base Exp");
   m_exp_listview->addColumn("ZEM total");
   m_exp_listview->addColumn("Class total");
   m_exp_listview->addColumn("Group total");
   m_exp_listview->addColumn("Experience Gained");
   
   m_exp_listview->restoreColumns();

   m_exp_listview->setMinimumSize( m_exp_listview->sizeHint().width(),
      200 );

   QGroupBox *statsGBox = new QVGroupBox( "Statistics", this );
   m_layout->addWidget( statsGBox );
   
   QGrid *statsGrid = new QGrid( 4, statsGBox );

   new QLabel( "Total Experience Received:",
      statsGrid );
   m_total_received = new QLabel( statsGrid );

   new QLabel( "Play Time:", statsGrid );
   m_play_time = new QLabel( statsGrid );

   new QLabel( "Total Mobs Killed:", statsGrid );
   m_mob_count = new QLabel( statsGrid );

   m_experience_rate_label = new QLabel( "Experience Rate (per minute):", statsGrid );
   m_experience_rate = new QLabel( statsGrid );

   new QLabel( "Average Experience per Mob:",
      statsGrid );
   m_average_per_mob = new QLabel( statsGrid );

   new QLabel( "Estimated Kills To Level:",
      statsGrid );
   m_kills_to_level = new QLabel( statsGrid );

   new QLabel( "Experience Remaining:",
      statsGrid );
   m_experience_remaining = new QLabel( statsGrid );

   new QLabel( "Estimated Time To Level:",
      statsGrid );
   m_time_to_level = new QLabel( statsGrid );

   // ewww, why can't we just get it from QGrid? :(
   ((QGridLayout *)statsGrid->layout())->setColStretch( 1, 1 );
   ((QGridLayout *)statsGrid->layout())->setColStretch( 3, 1 );
   statsGrid->layout()->setSpacing( 5 );

   updateAverage( );

   // timer to update the average xp
   QTimer *timer = new QTimer( this );
   connect( timer, SIGNAL(timeout()), SLOT(updateAverage()));
   timer->start(15*1000); // calculate every 15 seconds

   QFileInfo fileInfo = m_dataLocMgr->findWriteFile("logs", "exp.log");

   m_log = fopen(fileInfo.absFilePath(), "a");
   if (m_log == 0)
   {
      m_log_exp = 0;
      seqWarn("Error opening exp.log, no exp will be logged this session");
   }

   fileInfo = m_dataLocMgr->findWriteFile("logs", "newexp.log");

   m_newExpLogFile = fileInfo.absFilePath();
}