void FileNameEditorWidget::buttonPressed() {
  QFileDialog *dlg = new QFileDialog(this, "Choose a file", basePath, fileFilter);
  dlg->setModal(true);
  dlg->setFileMode(QFileDialog::ExistingFile);

  if (dlg->exec() == QDialog::Accepted) {
    QString file = dlg->selectedFiles().first();

    if (!file.isNull()) {
      QStringList currentDir = QDir::currentPath().split(QDir::separator());
      QStringList filePath = QFileInfo(file).dir().absolutePath().split(QDir::separator());
      QString relativePath = "";

      while ((!currentDir.empty() && !filePath.empty()) && (currentDir.front()
             == filePath.front())) {
        currentDir.pop_front();
        filePath.pop_front();
      }

      while (!currentDir.empty()) {
        relativePath += "..";
        relativePath += QDir::separator();
        currentDir.pop_front();
      }

      if (!filePath.empty())
        relativePath += filePath.join((const QString) (QChar) QDir::separator())
                        + QDir::separator();

      setFileName(relativePath + QFileInfo(file).fileName());
    }
  }

  delete dlg;
}
示例#2
0
void AddSessionDialog::submitJobs()
{
   QSet<int> jobIds;
   foreach(const QString &r, wJobRange->text().split(',')) {
      QStringList range = r.split('-');
      if(range.size() == 2) {
         int low = range.front().toInt();
         int high = range.back().toInt();
         for(int jobId = low; jobId <= high; jobId++) {
            jobIds.insert(jobId);
         }
      }
      else if(range.size() == 1) {
         jobIds.insert(range.front().toInt());
      }
   }

   emit jobs_submitted(jobIds,
                       wImagePath->text(),
                       wNumCPUs->text().toInt(),
                       wMemory->text(),
                       wJobName->text(),
                       wStartupScript->toPlainText());
   accept();
}
示例#3
0
void Vizkit3DConfig::setCameraManipulator(QStringList const& manipulator)
{
    if (getWidget()->getCameraManipulatorName() == manipulator.front())
        return;
    
    CAMERA_MANIPULATORS id = manipulatorNameToID(manipulator.front());
    return getWidget()->setCameraManipulator(id);
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::init()
{
  log() << "initializing";

  if (firstInit && ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT
      == props[ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN])
  {
    deleteFWDir();
    firstInit = false;
  }

  // Pre-load libraries
  // This may speed up installing new plug-ins if they have dependencies on
  // one of these libraries. It prevents repeated loading and unloading of the
  // pre-loaded libraries during caching of the plug-in meta-data.
  if (props[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES].isValid())
  {
    QStringList preloadLibs = props[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES].toStringList();
    QLibrary::LoadHints loadHints;
    QVariant loadHintsVariant = props[ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS];
    if (loadHintsVariant.isValid())
    {
      loadHints = loadHintsVariant.value<QLibrary::LoadHints>();
    }

    foreach(QString preloadLib, preloadLibs)
    {
      QLibrary lib;
      QStringList nameAndVersion = preloadLib.split(":");

      QString libraryName;
      if (nameAndVersion.count() == 1)
      {
        libraryName = nameAndVersion.front();
        lib.setFileName(nameAndVersion.front());
      }
      else if (nameAndVersion.count() == 2)
      {
        libraryName = nameAndVersion.front() + "." + nameAndVersion.back();
        lib.setFileNameAndVersion(nameAndVersion.front(), nameAndVersion.back());
      }
      else
      {
        qWarning() << "Wrong syntax in" << preloadLib << ". Use <lib-name>[:version]. Skipping.";
        continue;
      }

      lib.setLoadHints(loadHints);
      log() << "Pre-loading library" << lib.fileName() << "with hints [" << static_cast<int>(loadHints) << "]";
      if (!lib.load())
      {
        qWarning() << "Pre-loading library" << lib.fileName() << "failed:" << lib.errorString() << "\nCheck your library search paths.";
      }
    }
示例#5
0
DCDCompletion QcdAssist::processCompletion(QByteArray dataArray)
{
	DCDCompletion completion;

	QString data = QString::fromUtf8(dataArray.data(),dataArray.length());
	QStringList lines = data.split(QRegExp(QLatin1String("[\r\n]")), QString::SkipEmptyParts);
	if(lines.length() == 0)
		return completion;

	QString type = lines.front();
	if(type.startsWith(QLatin1String("WARNING:")))
	{
		lines.pop_front();
		if(lines.length() == 0)
			return completion;
		type = lines.front();
	}
	if(type == QLatin1String("identifiers"))
		completion.type = Identifiers;
	else if(type == QLatin1String("calltips"))
		completion.type = Calltips;
	else
	{
		//Core::MessageManager::write(QString(QLatin1String("qcdassist error: Invalid typ=:")).arg(type));
		return completion;
	}
	lines.pop_front();

	foreach(QString line, lines)
	{
		if(line.trimmed().length() == 0)
			continue;

		QStringList kv = line.split(QRegExp(QLatin1String("\\s+")), QString::SkipEmptyParts);
		if(kv.length() != 2 && completion.type != Calltips)
		{
			//Core::MessageManager::write(QString(QLatin1String("qcdassist error: invalid completion data:")).arg(kv.length()).arg(completion.type));
			continue;
		}

		if(completion.type == Identifiers)
		{
			completion.completions.append(DCDCompletionItem(
				(DCDCompletionItemType)kv[1].at(0).toLatin1(), kv[0]));
		}
		else
		{
			completion.completions.append(DCDCompletionItem(Calltip, line));
		}
	}

	return completion;
}
示例#6
0
static QString argv0BaseName()
{
    QString result;
    const QStringList arguments = QCoreApplication::arguments();
    if (!arguments.isEmpty() && !arguments.front().isEmpty()) {
        result = arguments.front();
        const int lastSlashPos = result.lastIndexOf(QLatin1Char('/'));
        if (lastSlashPos != -1)
            result.remove(0, lastSlashPos + 1);
    }
    return result;
}
示例#7
0
void AnnotationJobs::GetAnnotationJob::slotInfoMessage(KIO::Job *, const QString &str)
{
    // Parse the result
    QStringList lst = QStringList::split("\r", str);
    while(lst.count() >= 2)    // we take items 2 by 2
    {
        QString name = lst.front();
        lst.pop_front();
        QString value = lst.front();
        lst.pop_front();
        mAnnotations.append(AnnotationAttribute(mEntry, name, value));
    }
}
示例#8
0
void MainWindow::open(QString fileName = QString("")) {
  QStringList fileNames;
  
  if (fileName.isEmpty()) {
    fileNames = QFileDialog::getOpenFileNames(this, "Select one or more files to open", (openFiles.size() > 0 && !getCurFileObj()->path.isEmpty()) ? getCurFileObj()->path : lastDir);
  } else {
    fileNames.push_front(fileName);
  }

  
  while (fileNames.count()) {
    if (!fileNames.back().isEmpty()) {
      bool alreadyOpen = false;
      QList<QsciteEditor *> openTabs = openFiles.keys();
      QList<QsciteEditor *>::iterator tab;
      for (tab = openTabs.begin(); tab != openTabs.end(); ++tab) {
        if (fileNames.front() == openFiles[*tab].fullName) {
          alreadyOpen = true;

          if (fileNames.count() == 1) {
            changeTabs(*tab);
          }

          qDebug() << "file is already open";
        }
      }
      
      if (alreadyOpen) {
        fileNames.pop_front();
        continue;
      }
      
      if ((!tabWidget->count()) || (!getCurFileObj()->baseName.isEmpty()) || getCurDoc()->isModified()) {
        createDocument();
      }

      loadFile(fileNames.front());
      setCurrentTabTitle();

      addRecentFile(fileNames.front());
    }

    fileNames.pop_front();
  }

  if (!openFiles.empty()) {
    getCurDoc()->setFocus();
    lastDir = getCurFileObj()->path;
  }
}
示例#9
0
    /// Fill the menu with plugin names and make connections
    foreach(FilterPlugin* plugin, pluginManager()->filterPlugins()){
        QAction* action = plugin->action();

        QString pluginName = plugin->name();
        QMenu * assignedMenu = mainWindow()->filterMenu;

        // Check for categories
        if(pluginName.contains("|")){
            QStringList pluginNames = pluginName.split("|");

            action->setText( pluginNames.back() );

            // Try to locate exciting submenu
            QString catName = pluginNames.front();
            QMenu * m = assignedMenu->findChild<QMenu*>( catName );
            if(!m) m = mainWindow()->filterMenu->addMenu(catName);

            assignedMenu = m;
        }

        assignedMenu->addAction(action);
        
        // Action refers to this filter, so we can retrieve it later
        // QAction* action = new QAction(plugin->name(),plugin);

        /// Does the filter have an icon? Add it to the toolbar
        /// @todo add functionality to ModelFilter
        if(!action->icon().isNull())
            mainWindow()->filterToolbar->addAction(action);

        /// Connect after it has been added        
        connect(action,SIGNAL(triggered()),this,SLOT(startFilter()));
    }
示例#10
0
void MainWindow::saveNewWorkspace()
{
    QDomDocument* config = generateWorkspaceXML();
    QStringList fileNames; //stores the entire path of the file that it attempts to open

    QStringList filters; //setting file filters
    filters << "ReViz configuration files (*.revizconfig)"
            << "Any files (*)";

    //initializing the File dialog box
    //the static QFileDialog does not seem to be working correctly in Ubuntu 12.04 with unity.
    //as per the documentation it may work correctly with gnome
    //the method used below should work correctly on all desktops and is supposedly more powerful
    QFileDialog dialog(this);
    dialog.setNameFilters(filters);
    dialog.setAcceptMode(QFileDialog::AcceptSave);
    dialog.setFileMode(QFileDialog::AnyFile);
    if (dialog.exec())
        fileNames = dialog.selectedFiles();

    if (!fileNames.isEmpty())
        saveConfigFile(config, &fileNames.front());
    else
        std::cerr << "No file was selected" << std::endl;
}
示例#11
0
void ServerObject::setClients(QStringList addys)
{
	QStringList connected_list;
	if (!threadlist.isEmpty())
	{
		threadlist.at(0);
		do
		{
			threadlist.current()->setHost(threadlist.current()->getHost());
			connected_list.push_back(threadlist.current()->getHost());
		}
		while(threadlist.next());
	}
	QString temp;
	QString hostname;
	int socket;
	if (!addys.isEmpty()) {
		while ((!addys.isEmpty())&&(threadlist.count() < 400)){
			temp=addys.front();
			addys.pop_front();
			socket = temp.section(":", 1, 1).toInt();
			hostname = temp.section(":", 0, 0);
			hostname.append(suffix);
			if (clientlist.grep(temp).isEmpty() || connected_list.grep(temp).isEmpty())
			{
				threadlist.append(new Thread(this, socket));
				threadlist.current()->setHost(hostname);
				if (clientlist.grep(temp).isEmpty()) clientlist.push_back(temp);
			}
		} 
	}
}
示例#12
0
Handle(Standard_Type) Subassembly::lookupType ( QStringList& path_components ) const
{
  // The front path component is the name of a figure with ".type" appended
  // to it.
  int dot_pos = path_components.front().lastIndexOf( '.' );
  QString name = path_components.front().left( dot_pos );
  QString type = path_components.front().right( path_components.front().length()
						- dot_pos - 1 );

  if ( subassembly_->name() == name && subassembly_->type() == type ) {
    path_components.erase( path_components.begin() );
    return subassembly_->lookupType( path_components );
  }

  return Handle(Standard_Type)();
}
示例#13
0
QString CommentFormatter::formatComment( const QString& comment ) {
  QString ret;
  int i = 0;

  if( i > 1 ) {
      ret = comment.mid( i );
  } else {
      ///remove the star in each line
      QStringList lines = comment.split( "\n", QString::KeepEmptyParts );

      if( lines.isEmpty() ) return ret;

      QStringList::iterator it = lines.begin();
      QStringList::iterator eit = lines.end();

      if( it != lines.end() ) {
 
          for( ; it != eit; ++it ) {
              strip( "//", *it );
              strip( "**", *it );
              rStrip( "/**", *it );
          }

          if( lines.front().trimmed().isEmpty() )
              lines.pop_front();

          if( !lines.isEmpty() && lines.back().trimmed().isEmpty() )
              lines.pop_back();
      }

      ret = lines.join( "\n" );
  }

  return ret;
}
示例#14
0
void CellRange::init(const QString &range)
{
    // TODO can be range from one sheet to another, ex: "Sheet1:Sheet4!A1:A5" or "Sheet1:Sheet4!A1"
    // TODO can be '!' or ':' symbol in sheet name
    QStringList sp = range.split(QLatin1Char('!'));
    QString cellRange = range;
    if (sp.size() > 1) {
        _sheet = sp.front();
        if (_sheet.startsWith(QLatin1String("'")) && _sheet.endsWith(QLatin1String("'")))
            _sheet = _sheet.mid(2, _sheet.length() - 2);
        cellRange = sp.back();
    }
    QStringList rs = cellRange.split(QLatin1Char(':'));
    if (rs.size() == 2) {
        CellReference start(rs[0]);
        CellReference end(rs[1]);
        top = start.row();
        left = start.column();
        bottom = end.row();
        right = end.column();
    } else {
        CellReference p(rs[0]);
        top = p.row();
        left = p.column();
        bottom = p.row();
        right = p.column();
    }
}
Kleo::CryptoConfigComponentGUI::CryptoConfigComponentGUI(
  CryptoConfigModule* module, Kleo::CryptoConfigComponent* component,
  QWidget* parent )
  : QWidget( parent ),
    mComponent( component )
{
  QGridLayout * glay = new QGridLayout( this );
  glay->setSpacing( KDialog::spacingHint() );
  const QStringList groups = mComponent->groupList();
  if ( groups.size() > 1 ) {
    glay->setColumnMinimumWidth( 0, KDHorizontalLine::indentHint() );
    for ( QStringList::const_iterator it = groups.begin(), end = groups.end() ; it != end; ++it ) {
      Kleo::CryptoConfigGroup* group = mComponent->group( *it );
      Q_ASSERT( group );
      if ( !group )
        continue;
      const QString title = group->description();
      KDHorizontalLine * hl = new KDHorizontalLine( title.isEmpty() ? *it : title, this );
      const int row = glay->rowCount();
      glay->addWidget( hl, row, 0, 1, 3 );
      mGroupGUIs.append( new CryptoConfigGroupGUI( module, group, glay, this ) );
    }
  } else if ( !groups.empty() ) {
    mGroupGUIs.append( new CryptoConfigGroupGUI( module, mComponent->group( groups.front() ), glay, this ) );
  }
  glay->setRowStretch( glay->rowCount(), 1 );
}
示例#16
0
static
void removeKey_( QString const & scope,
                 QString const & key,
                 QgsPropertyKey & rootProperty )
{
  QgsPropertyKey * currentProperty = &rootProperty;

  QgsProperty * nextProperty = NULL;   // link to next property down hiearchy
  QgsPropertyKey * previousQgsPropertyKey = NULL; // link to previous property up hiearchy

  QStringList keySequence = makeKeyTokens_( scope, key );

  while ( ! keySequence.isEmpty() )
  {
    // if the current head of the sequence list matches the property name,
    // then traverse down the property hierarchy
    if ( keySequence.first() == currentProperty->name() )
    {
      // remove front key since we're traversing down a level
      keySequence.pop_front();

      // if we have only one key name left, then try to remove the key
      // with that name
      if ( 1 == keySequence.count() )
      {
        currentProperty->removeKey( keySequence.front() );
      }
      // if we're out of keys then the current property is the one we
      // want to remove, but we can't delete it directly; we need to
      // delete it from the parent property key container
      else if ( keySequence.isEmpty() )
      {
        previousQgsPropertyKey->removeKey( currentProperty->name() );
      }
      else if (( nextProperty = currentProperty->find( keySequence.first() ) ) )
      {
        previousQgsPropertyKey = currentProperty;
        currentProperty = dynamic_cast<QgsPropertyKey*>( nextProperty );

        if ( currentProperty )
        {
          continue;
        }
        else            // QgsPropertyValue not Key, so return null
        {
          return;
        }
      }
      else                // if the next key down isn't found
      {                   // then the overall key sequence doesn't exist
        return;
      }
    }
    else
    {
      return;
    }
  }

} // void removeKey_
示例#17
0
文件: main.cpp 项目: RobinWuDev/Qt
int main(int argc, char *argv[])
{
    QGuiApplication a(argc, argv);

    QStringList arguments = QCoreApplication::arguments();
    arguments.pop_front();
    const bool large = !arguments.isEmpty() && arguments.front() == "-l";
    if (large)
        arguments.pop_front();
    if (arguments.size() < 1) {
        std::cout << "Usage: iconextractor [OPTIONS] FILE [IMAGE_FILE_FOLDER]\n\n"
                     "Extracts Windows icons from executables, DLL or icon files\n"
                     "and writes them out as numbered .png-files.\n\n"
                     "Options: -l    Extract large icons.\n\n"
                     "Based on Qt " << QT_VERSION_STR << "\n";
        return 1;
    }
    const QString sourceFile = arguments.at(0);
    QString imageFileRoot = arguments.size() > 1 ? arguments.at(1) : QDir::currentPath();
    const QFileInfo imageFileRootInfo(imageFileRoot);
    if (!imageFileRootInfo.isDir()) {
        std::cerr << imageFileRoot.toStdString() << " is not a directory.\n";
        return 1;
    }

    const UINT iconCount = ExtractIconEx((wchar_t *)sourceFile.utf16(), -1, 0, 0, 0);
    if (!iconCount) {
        std::cerr << sourceFile.toStdString() << " does not appear to contain icons.\n";
        return 1;
    }

    QScopedArrayPointer<HICON> icons(new HICON[iconCount]);
    const UINT extractedIconCount = large ?
        ExtractIconEx((wchar_t *)sourceFile.utf16(), 0, icons.data(), 0, iconCount) :
        ExtractIconEx((wchar_t *)sourceFile.utf16(), 0, 0, icons.data(), iconCount);
    if (!extractedIconCount) {
        qErrnoWarning("Failed to extract icons from %s", qPrintable(sourceFile));
        return 1;
    }

    std::cout << sourceFile.toStdString() << " contains " << extractedIconCount << " icon(s).\n";

    imageFileRoot = imageFileRootInfo.absoluteFilePath() + QLatin1Char('/') + QFileInfo(sourceFile).baseName();
    for (UINT i = 0; i < extractedIconCount; ++i) {
        const QPixmap pixmap = QtWin::fromHICON(icons[i]);
        if (pixmap.isNull()) {
            std::cerr << "Error converting icons.\n";
            return 1;
        }
        const QString fileName = QString::fromLatin1("%1%2.png").arg(imageFileRoot)
            .arg(i, 3, 10, QLatin1Char('0'));
        if (!pixmap.save(fileName)) {
            std::cerr << "Error writing image file " << fileName.toStdString() << ".\n";
            return 1;
        }
        std::cout << "Wrote image file "
                  << QDir::toNativeSeparators(fileName).toStdString() << ".\n";
    }
    return 0;
}
示例#18
0
void MemSpecParser::buildHelperProg(const MemSpecs& specs)
{
    QProcess proc;
    QStringList cmdlines;
    QString arch = (specs.arch & MemSpecs::ar_x86_64) ? "x86_64" : "i386";

    cmdlines += QString("make KDIR=%1 ARCH=%2 V=1")
            .arg(QDir::current().absoluteFilePath(_kernelSrcDir))
            .arg(arch);
    cmdlines += QString("make memspec");

    for (int i = 0; i < cmdlines.size(); ++i) {
        // Invoke the command
        QStringList args = cmdlines[i].split(QChar(' '));
        QString cmd = args.front();
        args.pop_front();

        proc.setWorkingDirectory(_buildDir);
        proc.start(cmd, args);
        proc.waitForFinished(-1);

        if (proc.exitCode() != 0) {
            _errorOutput = proc.readAllStandardOutput();
            _errorOutput += proc.readAllStandardError();
            memSpecParserError2(
                        QString("Command failed with exit code %3: %1 %2")
                            .arg(cmd)
                            .arg(args.join(" "))
                            .arg(proc.exitCode()),
                        _errorOutput);
        }

        proc.close();
    }
}
示例#19
0
/** Lauches a load file browser allowing a user to select multiple
*  files
*  @return the names of the selected files as a comma separated list
*/
QString MWRunFiles::openFileDialog() {
  QStringList filenames;
  QString dir = m_lastDir;

  if (m_fileFilter.isEmpty()) {
    m_fileFilter = createFileFilter();
  }

  if (m_isForDirectory) {
    QString file =
        QFileDialog::getExistingDirectory(this, "Select directory", dir);
    if (!file.isEmpty())
      filenames.append(file);
  } else if (m_allowMultipleFiles) {
    filenames = QFileDialog::getOpenFileNames(this, "Open file", dir,
                                              m_fileFilter, nullptr,
                                              QFileDialog::DontResolveSymlinks);
  } else {
    QString file =
        QFileDialog::getOpenFileName(this, "Open file", dir, m_fileFilter,
                                     nullptr, QFileDialog::DontResolveSymlinks);
    if (!file.isEmpty())
      filenames.append(file);
  }

  if (filenames.isEmpty()) {
    return "";
  }
  m_lastDir = QFileInfo(filenames.front()).absoluteDir().path();
  return filenames.join(", ");
}
示例#20
0
 void Capabilities::add( const QString & cap, bool replace ) {
   QStringList tokens = cap.toUpper().split( QLatin1Char(' ') );
   if ( tokens.empty() )
     return;
   QString name = tokens.front(); tokens.pop_front();
   add( name, tokens, replace );
 }
示例#21
0
void ImageManager::setTextureLocations(QStringList passed) {
    QImage image;
    QSize size;
    for (int loop = 0; loop < passed.size(); loop++) {
        if (image.load(passed.at(loop)) == false) {
            cerr << "Error cant load texture file: " << passed[loop].toStdString().c_str() << endl;
            return;
        };
        if (loop == 0)size = image.size();
        if (image.size().width() != size.width())
            if (image.size().width() != size.width()) {
                cerr << "Texture file at: " << passed[loop].toStdString().c_str() << " is not the same size as other images" << endl;
                return;
            }
    }
    texture_locations = passed;
    textures_ready = true;
    number_of_textures = passed.size();
    image.load(passed.front());
    texture_display->setImage(image);
    image_index = 0;
    image_display->setImage(getFirstImage());
    texture_display->setImage(getFirstTexture());
    emit selectedImage(image_index);
}
示例#22
0
void LxMQApp::start()
{
	QStringList args = QCoreApplication::arguments();
	if(args.size() < 3) 
	{
		qWarning() << "Usage: " << args.front() << " client|server <key>";
		QCoreApplication::exit();
		return;
	}

	m_byteKey = args.at(2).toLocal8Bit();

	QTimer *ndyt = new QTimer(this);
	connect(ndyt, SIGNAL(timeout()), this, SLOT(ndy()));
	ndyt->setInterval(5000);
	ndyt->start();

	if(args.at(1) == "client") 
	{
		m_pSocket = new ZmqSocket(ZMQ_SUB, this);
		connect(m_pSocket, SIGNAL(readyRead()), this, SLOT(heard()));
		m_pSocket->subscribe(m_byteKey);
		m_pSocket->connectTo("tcp://127.0.0.1:3782");
	}

	if(args.at(1) == "server") 
	{
		m_pSocket = new ZmqSocket(ZMQ_PUB, this);
		m_pSocket->bind("tcp://127.0.0.1:3782");
		QTimer *t = new QTimer(this);
		connect(t, SIGNAL(timeout()), this, SLOT(squawk()));
		t->setInterval(1000);
		t->start();
	}
}
示例#23
0
/**
 * This is a convenience static function that will return one or more existing files selected by the user.
 */
QStringList FileDialog::getOpenFileNames (QWidget * parent, const QString & caption, const QString & dir,
                                          const QString & filter, QString * selectedFilter, Options options)
{
    QString dirName = dir;
    if (dirName.isEmpty()) {
        dirName = getWorkingDirectory();
    }

    QString windowTitle = caption;
    if (windowTitle.isEmpty())
        windowTitle = FileDialog::tr("Open");

#if defined(FC_OS_LINUX)
    QList<QUrl> urls;
#if QT_VERSION >= 0x050000
    urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation));
    urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
    urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::HomeLocation));
    urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::MusicLocation));
    urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
    urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::MoviesLocation));
#else
    urls << QUrl::fromLocalFile(QDesktopServices::storageLocation(QDesktopServices::DesktopLocation));
    urls << QUrl::fromLocalFile(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation));
    urls << QUrl::fromLocalFile(QDesktopServices::storageLocation(QDesktopServices::HomeLocation));
    urls << QUrl::fromLocalFile(QDesktopServices::storageLocation(QDesktopServices::MusicLocation));
    urls << QUrl::fromLocalFile(QDesktopServices::storageLocation(QDesktopServices::PicturesLocation));
    urls << QUrl::fromLocalFile(QDesktopServices::storageLocation(QDesktopServices::MoviesLocation));
#endif
    urls << QUrl::fromLocalFile(getWorkingDirectory());

    QStringList files;
    FileDialog dlg(parent);
    dlg.setWindowTitle(windowTitle);
    dlg.setSidebarUrls(urls);
    dlg.setIconProvider(new FileIconProvider());
    dlg.setFileMode(QFileDialog::ExistingFiles);
    dlg.setAcceptMode(QFileDialog::AcceptOpen);
    dlg.setDirectory(dirName);
    dlg.setOptions(options);
    dlg.setNameFilters(filter.split(QLatin1String(";;")));
    dlg.setNameFilterDetailsVisible(true);
    if (dlg.exec() == QDialog::Accepted) {
        if (selectedFilter)
            *selectedFilter = dlg.selectedNameFilter();
        files = dlg.selectedFiles();
    }
#else
    QStringList files = QFileDialog::getOpenFileNames(parent, windowTitle, dirName, filter, selectedFilter, options);
    for (QStringList::iterator it = files.begin(); it != files.end(); ++it) {
        *it = QDir::fromNativeSeparators(*it);
    }
#endif
    if (!files.isEmpty()) {
        setWorkingDirectory(files.front());
    }
    
    return files;
}
示例#24
0
unsigned int Kleo::classify( const QStringList & fileNames ) {
    if ( fileNames.empty() )
        return 0;
    unsigned int result = classify( fileNames.front() );
    Q_FOREACH( const QString & fileName, fileNames )
        result &= classify( fileName );
    return result;
}
示例#25
0
static QString longestCommonPrefix( const QStringList & sl ) {
    if ( sl.empty() )
        return QString();
    QString result = sl.front();
    Q_FOREACH( const QString & s, sl )
        result = commonPrefix( s, result );
    return result;
}
示例#26
0
void MainWindow::loadWorkspace(std::string workspaceFile)
{
    QStringList fileNames; //stores the entire path of the file that it attempts to open

    if (workspaceFile.empty()) {
        QStringList filters; //setting file filters
        filters << "ReViz configuration files (*.revizconfig)"
                << "Any files (*)";

        //initializing the File dialog box
        //the static QFileDialog does not seem to be working correctly in Ubuntu 12.04 with unity.
        //as per the documentation it may work correctly with gnome
        //the method used below should work correctly on all desktops and is supposedly more powerful
        QFileDialog dialog(this);
        dialog.setNameFilters(filters);
        dialog.setAcceptMode(QFileDialog::AcceptOpen);
        dialog.setFileMode(QFileDialog::ExistingFile);
        if (dialog.exec())
            fileNames = dialog.selectedFiles();
    } else {
        fileNames.append(QString::fromStdString(workspaceFile));
    }

    if (!fileNames.isEmpty()){
        std::cerr << "Attempting to load the following configuration file: "<< fileNames.front().toStdString() << std::endl;
        try {
            QFile file(fileNames.front());
            if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                std::cerr << "Unable to open file." << std::endl;
                return;
            }

            QDomDocument config;
            QString errorMsg;
            int errorLine, errorColumn;
            if(config.setContent(&file, &errorMsg, &errorLine, &errorColumn)) {
                parseConfig(config);
                *configFilePath = fileNames.front();
            }
        }
        catch(const std::exception& e){
            std::cerr << e.what() << std::endl;
        }
    }
}
示例#27
0
EventModel::EventModel(QStringList initStringList):
    repeatPeriod(0),
    repeatEvery(1)
{
    dateTimeFormatString = initStringList.front();
    initStringList.pop_front();
    dateTime = QDateTime::fromString(initStringList.front(),dateTimeFormatString);
    initStringList.pop_front();
    type = initStringList.front();
    initStringList.pop_front();
    title = initStringList.front();
    initStringList.pop_front();
    room = initStringList.front().replace('=',' ');
    initStringList.pop_front();
    description = initStringList.front();
    initStringList.pop_front();
    //description += initStringList.front();
    QString tmpRrule = initStringList.front().split(';').front().split('=').back();
    if (tmpRrule == "MONTHLY") {
        repeatPeriod=30;
    } else if (tmpRrule == "WEEKLY") {
        repeatPeriod=7;
    }

    initStringList.pop_front();
}
/**
 * Add column for a log to the table for the case of multiple fits.
 * Have to check multiple values are not returned
 * @param table :: [input, output] Table to write to
 * @param paramsByLabel :: [input] Map of <label name, <workspace name,
 * <parameter, value>>>
 * @param log :: [input] the log we are going to add to the table
 */
void MuonAnalysisResultTableCreator::addColumnToResultsTable(
    ITableWorkspace_sptr &table,
    const QMap<QString, WSParameterList> &paramsByLabel,
    const QString &log) const {
  // if its a single fit we know its a double
  if (!m_multiple) {
    addColumnToTable(table, "double", log.toStdString(), PLOT_TYPE_X);
    return;
  }
  const auto &labelName = m_items[0];

  QStringList valuesPerWorkspace;
  for (const auto &wsName : paramsByLabel[labelName].keys()) {
    const auto &logValues = m_logValues->value(wsName);
    const auto &val = logValues[log];
    // Special case: if log is time in sec, subtract the first start time
    if (log.endsWith(" (s)")) {
      auto seconds =
          val.toDouble() - static_cast<double>(m_firstStart_ns) * 1.e-9;
      valuesPerWorkspace.append(QString::number(seconds));
    } else if (MuonAnalysisHelper::isNumber(val.toString()) &&
               !log.endsWith(" (text)")) {

      valuesPerWorkspace.append(QString::number(val.toDouble()));

    } else {
      valuesPerWorkspace.append(logValues[log].toString());
    }
  }
  valuesPerWorkspace.sort();

  auto dashIndex = valuesPerWorkspace.front().toStdString().find_first_of("-");
  if (dashIndex != std::string::npos && dashIndex != 0) {

    addColumnToTable(table, "str", log.toStdString(), PLOT_TYPE_X);
    return;
  }
  const auto &min = valuesPerWorkspace.front().toDouble();
  const auto &max = valuesPerWorkspace.back().toDouble();
  if (min == max) {
    addColumnToTable(table, "double", log.toStdString(), PLOT_TYPE_X);
    return;
  }
  addColumnToTable(table, "str", log.toStdString(), PLOT_TYPE_X);
}
void FileUploader::upload(QStringList files)
{
	_model->moveToThread(&_workerThread);
	_total = 0;

	mtp::ObjectId currentParentId = _model->parentObjectId();
	QList<Command *> commands;
	while(!files.empty())
	{
		QString currentFile = files.front();
		files.pop_front();
		QFileInfo currentFileInfo(currentFile);
		if (currentFileInfo.isDir())
		{
			qDebug() << "adding subdirectory" << currentFile;
			commands.push_back(new MakeDirectory(currentFile, true));
			QDirIterator it(currentFile, QDirIterator::Subdirectories);
			while(it.hasNext())
			{
				QString next = it.next();
				QFileInfo fi(next);
				QString filename = fi.fileName();
				if (filename == "." || filename == "..")
					continue;

				if (fi.isFile())
				{
					commands.push_back(new UploadFile(next));
					_total += fi.size();
				}
				else if (fi.isDir())
				{
					commands.push_back(new MakeDirectory(next));
				}
			}
		}
		else if (currentFileInfo.isFile())
		{
			commands.push_back(new UploadFile(currentFile));
			_total += currentFileInfo.size();
		}
	}
	qDebug() << "uploading" << _total << "bytes";
	if (_total < 1)
		_total = 1;

	_startedAt = QDateTime::currentDateTime();
	_aborted = false;

	for(auto command: commands)
	{
		if (_aborted)
			break;
		emit executeCommand(command);
	}
	emit executeCommand(new FinishQueue(currentParentId));
}
示例#30
0
QString defaultDownloadDir() {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    static QStringList list = QStandardPaths::standardLocations(QStandardPaths::DownloadLocation);
    if (!list.empty())
        return list.front();
#endif
    // qt4 don't have QStandardPaths, use glib's as fallback
    return QString::fromUtf8(g_get_user_special_dir(G_USER_DIRECTORY_DOWNLOAD));
}