Ejemplo n.º 1
0
QMap<QString, shared_ptr<ChatUser> >
ConnectorOld::parseChatUsers(QStringList recvMessage)
{
  QMap<QString, shared_ptr<ChatUser> > users;
  QString channelId = recvMessage.at(0);
  recvMessage.pop_front(); // Remove channelId
  QStringList usersList = recvMessage.join("\t").split("\r");
  usersList.pop_back();   // Remove empty string

  QStringList::const_iterator it;
  for (it = usersList.constBegin(); it != usersList.constEnd(); ++it)
  {
    QStringList user = (*it).split('\t');
    shared_ptr<ChatUser> us(
          new ChatUser(
            this,
            channelId,
            user.at(0),
            user.at(1),
            user.at(2),
            user.at(3)));
    users.insert(us->id(), us);
  }
  return users;
}
Ejemplo n.º 2
0
void MainWindow::loadFile()
{

    QString fullFilePath = QFileDialog::getOpenFileName(this,
       tr("Open Material Script"), "./", tr("Material scripts (*.material )"));

    if ( fullFilePath.isEmpty() ) { // If no file is loaded
        return ;
    }

    QString fileName = fullFilePath.section('/', -1);

    ui->textEdit->openFile(fullFilePath);
    this->ui->wMat->setWindowTitle("Material Editor: " + fileName);

    QStringList places = fullFilePath.split("/");
    places.pop_back();
    QString pathOnly = places.join("/");

    Ogre::ResourceGroupManager::getSingleton().addResourceLocation( pathOnly.toStdString() ,"FileSystem","mm");
    Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("mm");

    ui->listWidget->clear();
   // QStringList materials = ui->OgreWidget->manager->getMaterialList();
    //ui->listWidget->addItems(materials);

}
Ejemplo n.º 3
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;
}
void CelereMonitor::update_listView()
{
	std::ifstream input("temp.txt",std::ios::in);
	std::string output;
	mioParser::parse(input,output,lineEditCode->text().toStdString(),3);
	QString finalOut;
	finalOut += QString::fromStdString(output);
	
	input.close();

	if(finalOut.contains("Attenzione!",	Qt::CaseInsensitive)>0)
	{
		QMessageBox::information(this,tr("Attenzione"),tr("Informazione non ancora disponibile o codice inserito errato.<br>Controllare l'esattezza dei dati ed eventualmente riprovare pi&ugrave; tardi."));
		//.arg(finalOut));
		//this->groupBoxResponse->setEnabled(false);
	}
	else if(finalOut.contains("momento",	Qt::CaseInsensitive)>0)
		QMessageBox::information(this,tr("Attenzione"),tr("Il servizio non &egrave; al momento disponibile.<BR>Riprovare nuovamente pi&ugrave; tardi."));
	else
	{
		//this->groupBoxResponse->setEnabled(true);
		QStringList rows = finalOut.split("\n");
		rows.pop_back();
		rows.pop_front();
		
		for (QStringList::Iterator it = rows.begin(); it != rows.end(); ++it )
		{
			QStringList cols = (*it).split("\t");
			new QTreeWidgetItem(listViewResponse,cols);
    		}
		
	}
	QFile fi("temp.txt");
	if(fi.exists()) fi.remove();
}	
bool DubProjectNode::addFilePath(const QString &path)
{
#if QTCREATOR_MINOR_VERSION < 4
    QString relativePath = QDir(QFileInfo(this->path()).path()).relativeFilePath(path);
#else
    QString relativePath = QDir(QFileInfo(this->path().toString()).path()).relativeFilePath(path);
#endif
    QStringList subpaths = relativePath.split(QLatin1Char('/'), QString::SkipEmptyParts);
    subpaths.pop_back();

    // simply add all structure to node
    ProjectExplorer::FolderNode* node = this;
    typedef QList<ProjectExplorer::FolderNode *> SubFolders;
    foreach (const QString& s, subpaths) {
        SubFolders nodes = node->subFolderNodes();
        NodeEqualPred pred(s);
        SubFolders::iterator it = std::find_if(nodes.begin(), nodes.end(), pred);
        if (it == nodes.end()) {
            SubFolders list;
#if QTCREATOR_MINOR_VERSION < 4
            ProjectExplorer::FolderNode* added = new ProjectExplorer::FolderNode(s);
#else
            ProjectExplorer::FolderNode* added = new ProjectExplorer::FolderNode(Utils::FileName::fromString(s));
#endif
            list.push_back(added);
            node->addFolderNodes(list);
            node = added;
        } else {
            node = *it;
        }
    }
Ejemplo n.º 6
0
void TreeItemModel::createShowColumnsProperty()
{
	QStringList range = QStringList() << "color" << "vg0" << "vg1" << "vg2" << "vg3";
	QStringList defvals = range;
	defvals.pop_back();
	defvals.pop_back();

	std::map<QString, QString> names;
	names["color"] = "Color";
	for (unsigned i=0; i<4; ++i)
		names[QString("vg%1").arg(i)] = QString("View Group %1").arg(i);

//	QStringList range = QStringList() << "Color"
//									  << "View Group 0"
//									  << "View Group 1"
//									  << "View Group 2"
//									  << "View Group 3";
	mShowColumnsProperty = StringListProperty::initialize("visible_columns",
														"Columns",
														"Select visible columns",
														range,
														range,
														 mOptions.getElement());
	mShowColumnsProperty->setDisplayNames(names);
	connect(mShowColumnsProperty.get(), &Property::changed, this, &TreeItemModel::onShowColumnsChanged);
}
Ejemplo n.º 7
0
static QString findExecutableFromName(const QString &fileNameFromCore, const QString &coreFile)
{
    if (QFileInfo(fileNameFromCore).isFile())
        return fileNameFromCore;
    if (fileNameFromCore.isEmpty())
        return QString();

    // turn the filename into an absolute path, using the location of the core as a hint
    QString absPath;
    QFileInfo fi(fileNameFromCore);
    if (fi.isAbsolute()) {
        absPath = fileNameFromCore;
    } else {
        QFileInfo coreInfo(coreFile);
        QDir coreDir = coreInfo.dir();
        absPath = FileUtils::resolvePath(coreDir.absolutePath(), fileNameFromCore);
    }
    if (QFileInfo(absPath).isFile() || absPath.isEmpty())
        return absPath;

    // remove possible trailing arguments
    QLatin1Char sep(' ');
    QStringList pathFragments = absPath.split(sep);
    while (pathFragments.size() > 0) {
        QString joined_path = pathFragments.join(sep);
        if (QFileInfo(joined_path).isFile()) {
            return joined_path;
        }
        pathFragments.pop_back();
    }

    return QString();
}
Ejemplo n.º 8
0
QVariant RequestManager::requestVideoList(QTcpSocket *caller, QVariant params)
{
    QStringList videos;
    int max_return = -1;
    if(!params.isNull())
    {
        // Get the packed max_return value
        QJsonObject max_return_obj(params.toJsonObject());
        QJsonValue max_ret_val( max_return_obj["max_return"]);
        QVariant max_ret_var(max_ret_val.toVariant());
        if(max_ret_var.type() == QVariant::Int)
            max_return = max_ret_var.toInt();
    }
    videos = VideoLocator::findVideos(mVideoDirectory);
    if(max_return != -1)
    {
        int amount_to_remove = videos.length()-max_return;
        //only return the amount passed in
        for(int i = 0; i < amount_to_remove; ++i)
        {
            videos.pop_back();
        }
    }

    QJsonObject ret_object;
    ret_object["VideoList"] = QJsonValue::fromVariant(QVariant::fromValue(videos));
    QVariant ret_var(QVariant::fromValue(ret_object));
    //qDebug() << "Sending back" << ret_var;
    return ret_var;

}
Ejemplo n.º 9
0
bool PackageJobThread::uninstallPackage(const QString &packagePath)
{
    if (!QFile::exists(packagePath)) {
        d->errorMessage = i18n("%1 does not exist", packagePath);
        d->errorCode = Package::JobError::PackageFileNotFoundError;
        return false;
    }
    QString pkg;
    QString root;
    {
        // FIXME: remove, pass in packageroot, type and pluginName separately?
        QStringList ps = packagePath.split('/');
        int ix = ps.count() - 1;
        if (packagePath.endsWith('/')) {
            ix = ps.count() - 2;
        }
        pkg = ps[ix];
        ps.pop_back();
        root = ps.join('/');
    }

    bool ok = removeFolder(packagePath);
    if (!ok) {
        d->errorMessage = i18n("Could not delete package from: %1", packagePath);
        d->errorCode = Package::JobError::PackageUninstallError;
        return false;
    }

    indexDirectory(root, QStringLiteral("kpluginindex.json"));

    return true;
}
Ejemplo n.º 10
0
QStringList UserManagement::userSort()
{
    //sorts the usernames by timestamp
    int totalSize=userPlayer.size();
    QStringList sortedTimes=userTimestamp;
    if(userPlayer.size()>0)
    {
        sortedTimes.sort();
        QStringList sortedNames;
        for(int n=totalSize;n>0;n--)
        {
            for(int i=0;i<userPlayer.size();i++)
            {
                if(sortedTimes[n-1]==userTimestamp[i])
                    if(userPlayer[i]!="NULL")
                    {
                        sortedNames.append(userPlayer[i]);

                    }
                else
                        break;
            }
        }
        while(sortedNames.size()>5)//only takes the top 5 for the combobox
        {
            sortedNames.pop_back();
        }
        return sortedNames;
    }
}
Ejemplo n.º 11
0
void 
pcl::modeler::MainWindow::updateRecentActions(std::vector<boost::shared_ptr<QAction> >& recent_actions, QStringList& recent_items)
{
  QMutableStringListIterator recent_items_it(recent_items);
  while (recent_items_it.hasNext())
  {
    if (!QFile::exists(recent_items_it.next()))
      recent_items_it.remove();
  }

  recent_items.removeDuplicates();
  int recent_number = std::min((int)MAX_RECENT_NUMBER, recent_items.size());
  for (int i = 0; i < recent_number; ++ i)
  {
    QString text = tr("%1 %2").arg(i+1).arg(recent_items[i]);
    recent_actions[i]->setText(text);
    recent_actions[i]->setData(recent_items[i]);
    recent_actions[i]->setVisible(true);
  }

  for (size_t i = recent_number, i_end = recent_actions.size(); i < i_end; ++ i)
  {
    recent_actions[i]->setVisible(false);
  }

  while (recent_items.size() > recent_number) {
    recent_items.pop_back();
  }

  return;
}
Ejemplo n.º 12
0
QMap<int, shared_ptr<BoardChannel> >
ConnectorOld::parseBoardChannels(QString recvMessage)
{
  QMap<int, shared_ptr<BoardChannel> > channels;
//  Thanks Assaron
//
//  CHANNEL_PROPERTIES = (("id", int_decoder),
//                        ("name", unicode_decoder),
//                        ("description", unicode_decoder))
  QStringList channelsList = recvMessage.split('\r');
  channelsList.pop_back(); // Remove empty string
  QStringList::const_iterator it;
  for (it = channelsList.constBegin(); it != channelsList.constEnd(); ++it)
  {
    QStringList channel = (*it).split('\t');
    shared_ptr<BoardChannel> ch(
          new BoardChannel(
            this,
            channel.at(0).toInt(),
            channel.at(1).mid(1),
            channel.at(2)));
    channels.insert(ch->id(), ch);
  }
  return channels;
}
Ejemplo n.º 13
0
void Shell::saveShellHistory()
{
#ifdef CONFIG_READLINE
	// Only save history for interactive sessions
	if (_listenOnSocket)
		return;

	// Construct the path name of the history file
	QStringList pathList = QString(mt_history_file).split("/", QString::SkipEmptyParts);
	pathList.pop_back();
	QString path = pathList.join("/");

    // Create history path, if it does not exist
    if (!QDir::home().exists(path) && !QDir::home().mkpath(path))
        debugerr("Error creating path for saving the history");

    // Save the history for the next launch
    QString histFile = QDir::home().absoluteFilePath(mt_history_file);
    QByteArray ba = histFile.toLocal8Bit();
    int ret = write_history(ba.constData());
    if (ret)
        debugerr("Error #" << ret << " occured when trying to save the "
                 "history data to \"" << histFile << "\"");
#endif
}
Ejemplo n.º 14
0
void djvFileInfoUtil::recent(
    const QString & fileName,
    QStringList &   list,
    int             max)
{
    const int index = list.indexOf(fileName);
    
    if (-1 == index)
    {
        // Insert new item at front of list.

        list.push_front(fileName);    
        
        while (list.count() > max)
        {
            list.pop_back();
        }
    }
    else
    {
        // Move existing item to front of list.

        list.removeAt(list.indexOf(fileName));
        
        list.push_front(fileName);
    }
}
Ejemplo n.º 15
0
bool XmlLookupTable::readFile(QIODevice &file)
{
    if (!file.isOpen())
        return false;
    int depth = 0;
    QXmlStreamReader reader(&file);
    QStringList path;

    m_data.clear();
    while (!reader.atEnd() && !reader.hasError()) {
        QXmlStreamReader::TokenType token = reader.readNext();
        if (token == QXmlStreamReader::StartElement) {
            path.push_back(reader.name().toString());
            Entry& entry = m_data[path.join("/")];
            QXmlStreamAttributes attributes = reader.attributes();
            entry.attributes.clear();
            foreach (QXmlStreamAttribute attr, attributes)
                entry.attributes[attr.name().toString()]
                        = attr.value().toString();
            ++depth;
        } else if (token == QXmlStreamReader::Characters) {
            Entry& entry = m_data[path.join("/")];
            entry.data += reader.text().toString().trimmed();
        } else if (token == QXmlStreamReader::EndElement) {
            if (depth <= 0)
                return false; // malformed xml
            --depth;
            path.pop_back();
        }
    }

    return !reader.hasError();
}
Ejemplo n.º 16
0
/**
 * Check for closing of one or more scopes.
 */
bool checkClosing(QStringList& tokens)
{
    if (tokens.count() == 0)
        return false;
    if (tokens.last() == QLatin1String(")")) {
        // For a single closing parenthesis, we just return true.
        // But if there are more closing parentheses, we need to increment
        // nClosures for each scope.
        tokens.pop_back();
        while (tokens.count() && tokens.last() == QLatin1String(")")) {
            nClosures++;
            tokens.pop_back();
        }
        return true;
    }
    return false;
}
void QuickOpenFunctionDialog::slotTextChangedDelayed() {
    QString text = nameEdit->text();
    QString txt = text;
    QStringList parts = QStringList::split("::", text);
    if(text.endsWith("::") || parts.isEmpty()) {
        txt = "";
    }else{
        txt = parts.back();
        parts.pop_back();
    }
    QValueList<QRegExp> regExpParts;
    for( QStringList::const_iterator it = parts.begin(); it != parts.end(); ++it ) {
      regExpParts << QRegExp( *it, false, true );
    }

    QString scope = parts.join("::");

    if( m_scope != scope ) {
        if( !scope.startsWith(m_scope) ) { ///Not a specialization, so reload all function-definitions
          fillItemList();
        }

        if(!parts.isEmpty()) {
            FunctionList accepted;
            QStringList acceptedItems;
            FunctionList::iterator it = m_functionDefList.begin();
            while(it != m_functionDefList.end()) {
                QStringList scope = (*it)->scope();
                QValueList<QRegExp>::iterator mit = regExpParts.begin();
                QStringList::iterator sit = scope.begin();
                bool fail = false;
                while(mit != regExpParts.end()) {
                    while(sit != scope.end() && !(*mit).exactMatch( *sit ) ) ++sit;
                    if(sit == scope.end()) {
                        fail = true;
                        break;
                    }
                    ++mit;
                }
                if(!fail) {
                  accepted.append(*it);
                  acceptedItems << (*it)->name();
                }
                ++it;
            }
            m_functionDefList = accepted;
            m_items = acceptedItems;
            QStringList_unique( m_items );
        }

        m_scope = scope;
    }
    
    itemList->clear();
    itemList->insertStringList( wildCardCompletion( txt ) );
    itemList->setCurrentItem(0);
}
void QuickOpenFunctionDialog::itemSelectionChanged() {
      QString text = nameEdit->text();
      QString txt = text;
      QStringList parts = QStringList::split("::", text);
      if( !text.endsWith( "::" ) && !parts.isEmpty() )
        parts.pop_back();
      parts << itemList->currentText();
      nameEdit->setText(parts.join("::"));
}
Ejemplo n.º 19
0
ObjectTag ObjectTag::fromString(const QString& str) {
  QStringList l = str.split(tagSeparator);
  if (l.isEmpty()) {
    return invalidTag;
  }

  QString t = l.last();
  l.pop_back();
  return ObjectTag(t, l);
}
Ejemplo n.º 20
0
QStringList byteArrayToStringList(const QByteArray& r) {
    QStringList items;
    foreach ( const QByteArray& item, r.split('\n') ) {
        items << item.data();
    }
    if ( r.endsWith('\n') ) {
        items.pop_back();
    }
    return items;
}
Ejemplo n.º 21
0
void NimProject::addNodes(const QSet<QString> &nodes)
{
    QStringList path;
    foreach (const QString &node, nodes) {
        path = m_projectDir.relativeFilePath(node).split(QDir::separator());
        path.pop_back();
        FolderNode *folder = findFolderFor(path);
        auto fileNode = new FileNode(FileName::fromString(node), SourceType, false);
        folder->addFileNodes({fileNode});
    }
Ejemplo n.º 22
0
void QgsGrassEdit::closeEdit( void )
{
  QgsDebugMsg( "entered." );

  // Disconnect signals
  // Warning: it seems that slots (postRender) can be called even
  //          after disconnect (is it a queue?)
  disconnect( this, SLOT( postRender( QPainter * ) ) );

  mValid = false; // important for postRender

  if ( mAttributes )
  {
    delete mAttributes;
  }

  mProvider->closeEdit( mNewMap );

  hide();

  // Add new layers
  if ( mNewMap )
  {
    QString uri = QDir::cleanPath( mProvider->dataSourceUri() );
    QgsDebugMsg( QString( "uri = %1" ).arg( uri ) );
    // Note: QDir::cleanPath is using '/' also on Windows
    //QChar sep = QDir::separator();
    QChar sep = '/';

    QStringList split = uri.split( sep, QString::SkipEmptyParts );
    split.pop_back(); // layer
    QString map = split.last();
    split.pop_back(); // map
    QString mapset = split.last();

    QgsGrassUtils::addVectorLayers( mIface, QgsGrass::getDefaultGisdbase(),
                                    QgsGrass::getDefaultLocation(),
                                    mapset, map );
  }
  emit finished();
  delete this;
}
Ejemplo n.º 23
0
bool DynamicObjectImp::setAttributeByPath(QStringList pathComponents, DataVariant& value, bool swap)
{
   if (!value.isValid())
   {
      return false;
   }

   QString finalName = pathComponents.back();
   pathComponents.pop_back();

   string loopType = "DynamicObject";
   DynamicObject* pLoopObj = dynamic_cast<DynamicObject*>(this);
   DynamicObject* pCurObj = pLoopObj;
   for (QStringList::const_iterator iter = pathComponents.begin();
      iter != pathComponents.end(); ++iter)
   {
      if (pLoopObj == NULL || loopType != "DynamicObject")
      {
         return false;
      }

      pCurObj = pLoopObj;
      DataVariant& attrValue = pCurObj->getAttribute(iter->toStdString());
      loopType = attrValue.getTypeName();
      pLoopObj = attrValue.getPointerToValue<DynamicObject>();

      if ((pLoopObj != NULL) && (loopType != "DynamicObject"))
      {
         return false;
      }

      if (pLoopObj == NULL)
      {
         FactoryResource<DynamicObject> pNewObj;
         if (pCurObj != NULL)
         {
            pCurObj->setAttribute(iter->toStdString(), *pNewObj.get());
            DataVariant& currentValue = pCurObj->getAttribute(iter->toStdString());
            loopType = currentValue.getTypeName();
            pLoopObj = currentValue.getPointerToValue<DynamicObject>();
         }
      }
   }

   if (pLoopObj == NULL || loopType != "DynamicObject")
   {
      return false;
   }

   pCurObj = pLoopObj;
   DynamicObjectImp* const pCurObjImp = dynamic_cast<DynamicObjectImp*>(pCurObj);
   VERIFY(pCurObjImp != NULL);
   return pCurObjImp->setAttribute(finalName.toStdString(), value, swap);
}
Ejemplo n.º 24
0
static void typeNameList( QStringList & path, QStringList & lst, ClassDom klass )
{
	path.push_back( klass->name() );
	
	lst << path.join( "::" );
	
	const ClassList classList = klass->classList();
	for( ClassList::ConstIterator it=classList.begin(); it!=classList.end(); ++it )
		typeNameList( path, lst, *it );
	
	path.pop_back();
}
Ejemplo n.º 25
0
ObjectTag::ObjectTag(const QStringList &fullTag)
  : _minDisplayComponents(1), _uniqueDisplayComponents(UINT_MAX) {

  if (fullTag.isEmpty()) {
    _minDisplayComponents = 0;
  } else {
    QStringList context = fullTag;
    _name = cleanTagComponent(context.last());
    context.pop_back();
    _context = context;
  }
}
Ejemplo n.º 26
0
//====================================
// splitImport...
//------------------------------------
void SaXImportProfile::splitImport (void) {
	// .../
	//! Split the data from the profile into the appropriate
	//! ISAX sections. If the section does not exist a new one
	//! will be created. Each section can be obtained using the
	//! getImport() method. For the profile to take effect it is
	//! normally needed to merge this SaXImport objects into the
	//! basic imports which are the base for the configuration
	//! export: For example
	//! \code
	//!   SaXImport* profile = this->getImport (SAX_CARD);
	//!   baseImport->merge (profile->getTablePointerDATA());
	//! \endcode
	// ----
	for (int n=0;n < getCount();n++) {
		Q3Dict<QString>* table = getTablePointer ( n );
		Q3DictIterator<QString> it (*table);
		for (; it.current(); ++it) {
			QStringList tokens = QStringList::split ( ":", *it.current() );
			QString section = tokens.last();
			tokens.pop_back();
			QString value   = tokens.join(":");
			if (section == "Layout") {
				if (! mLayout) {
					mLayout  = new SaXImport (SAX_LAYOUT);
				}
				mLayout -> addID (n);
				mLayout -> setItem (it.currentKey(),value);
			}
			if (section == "Desktop") {
				if (! mDesktop) {
					mDesktop = new SaXImport (SAX_DESKTOP);
				}
				mDesktop -> addID (n);
				mDesktop -> setItem (it.currentKey(),value);
			}
			if (section == "Card") {
				if (! mCard) {
					mCard = new SaXImport (SAX_CARD);
				}
				mCard -> addID (n);
				mCard -> setItem (it.currentKey(),value);
			}
			if (section == "Mouse") {
				if (! mPointers) {
					mPointers = new SaXImport (SAX_POINTERS);
				 }
				mPointers -> addID (n);
				mPointers -> setItem (it.currentKey(),value);
			}
		}
	}
}
Ejemplo n.º 27
0
void LegendWidget::restore(Graph *g, const QStringList& lst)
{
	QColor backgroundColor = Qt::white;
	double x = 0.0, y = 0.0;
	QStringList::const_iterator line;
	LegendWidget *l = new LegendWidget(g);
	for (line = lst.begin(); line != lst.end(); line++){
        QString s = *line;
        if (s.contains("<Frame>"))
			l->setFrameStyle((s.remove("<Frame>").remove("</Frame>").toInt()));
		else if (s.contains("<Color>"))
			l->setFrameColor(QColor(s.remove("<Color>").remove("</Color>")));
		else if (s.contains("<FrameWidth>"))
			l->setFrameWidth(s.remove("<FrameWidth>").remove("</FrameWidth>").toInt());
		else if (s.contains("<LineStyle>"))
			l->setFrameLineStyle(PenStyleBox::penStyle(s.remove("<LineStyle>").remove("</LineStyle>").toInt()));
		else if (s.contains("<x>"))
			x = s.remove("<x>").remove("</x>").toDouble();
		else if (s.contains("<y>"))
			y = s.remove("<y>").remove("</y>").toDouble();
		else if (s.contains("<Text>")){
			QStringList txt;
			while ( s != "</Text>" ){
				s = *(++line);
				txt << s;
			}
			txt.pop_back();
			l->setText(txt.join("\n"));
		} else if (s.contains("<Font>")){
			QStringList lst = s.remove("<Font>").remove("</Font>").split("\t");
			QFont f = QFont(lst[0], lst[1].toInt(), lst[2].toInt(), lst[3].toInt());
			f.setUnderline(lst[4].toInt());
			f.setStrikeOut(lst[5].toInt());
			l->setFont(f);
		} else if (s.contains("<TextColor>"))
			l->setTextColor(QColor(s.remove("<TextColor>").remove("</TextColor>")));
		else if (s.contains("<Background>"))
			backgroundColor = QColor(s.remove("<Background>").remove("</Background>"));
		else if (s.contains("<Alpha>"))
			backgroundColor.setAlpha(s.remove("<Alpha>").remove("</Alpha>").toInt());
		else if (s.contains("<Angle>"))
			l->setAngle(s.remove("<Angle>").remove("</Angle>").toInt());
		else if (s.contains("<AutoUpdate>"))
			l->setAutoUpdate(s.remove("<AutoUpdate>").remove("</AutoUpdate>").toInt());
	}
	if (l){
		l->setBackgroundColor(backgroundColor);
		l->setOriginCoord(x, y);
		g->add(l, false);
	}
}
Ejemplo n.º 28
0
void DropLabel::dropEvent( QDropEvent* event )
{
	QFileInfo fileInfo(event->mimeData()->text());

	//A little sting manuipulation to remove the "file:///"-prefix on the file path if dragged from asset browser
	QString filePath;
	if (fileInfo.filePath().startsWith(QLatin1String("file:///")))
	{
		filePath =  fileInfo.filePath().mid(8);
	}
	else
	{
		filePath =  fileInfo.filePath();	
	}

	QDir dirInfo(filePath);
	//Check if there is a name to begin with
	if(fileInfo.baseName() != 0)
	{
		QStringList dirPaths;
		//Collect all dirs up to Assets
		while(dirInfo.dirName() != "Assets")
		{
			dirPaths << dirInfo.dirName();

			if(!dirInfo.cdUp())
				break;
		}

		//Remove and store the file name without suffix
		dirPaths.pop_front();
		//Remove category folder from path list
		dirPaths.pop_back();

		QString relativePath;

		//Construct the relative path
		while (!dirPaths.isEmpty())
		{
			relativePath += dirPaths.takeLast() + "/";
		}

		//Finally add file name to path
		relativePath += fileInfo.completeBaseName();

		emit dropped(relativePath);
	}

	setStyleSheet("");

}
static QStringList split( const QString & newLine, QString & old ) {
  // when done right, this would need to use QTextCodec...
  const QString str = old + newLine;
  QStringList l = str.split( '\n' );
  if ( l.empty() )
    return l;
  if ( str.endsWith( '\n' ) ) {
    old.clear();
  } else {
    old = l.back();
    l.pop_back();
  }
  return l;
}
Ejemplo n.º 30
0
int CodeEditer::format()
{
	const QString code = this->toPlainText();
	//const QString code = this->textCursor().selectedText();
	if (code == QString::null)
		return 1;

	QStringList program = code.split(QLatin1Char('\n'), QString::KeepEmptyParts);
	while (!program.isEmpty()) {
		if (!program.back().trimmed().isEmpty())
			break;
		program.pop_back();
	}

	QStringList p;
	QString out;

	const QChar colon = QLatin1Char(':');
	const QChar blank = QLatin1Char(' ');
	const QChar newLine = QLatin1Char('\n');

	QStringList::const_iterator cend = program.constEnd();
	for (QStringList::const_iterator it = program.constBegin(); it != cend; ++it) {
		p.push_back(*it);
		QString &line = p.back();

		QChar typedIn = Indenter::instance().firstNonWhiteSpace(line);
		if (p.last().endsWith(colon))
			typedIn = colon;

		const int indent = Indenter::instance().indentForBottomLine(it, p.constBegin(), p.constEnd(), typedIn);

		const QString trimmed = line.trimmed();
		// Indent the line in the list so that the formatter code sees the indented line.
		if (!trimmed.isEmpty()) {
			line = QString(indent, blank);
			line += trimmed;
		}
		out += line;
		out += newLine ;
	}

	while (out.endsWith(newLine))
		out.truncate(out.length() - 1 );

	//fputs(out.toUtf8().constData(), stdout);
	this->setPlainText(out);
	return 0;
}