void
AnimPacket::parseWifi(std::string metaInfo)
{
    QRegExp rxCTL_ACK("ns3::WifiMacHeader \\(CTL_ACK .*RA=(..:..:..:..:..:..)");
    int pos = 0;
    if ((pos = rxCTL_ACK.indexIn(metaInfo.c_str())) != -1)
    {
        m_wifiMacInfo = new WifiMacInfo;
        m_wifiMacInfo->type = "CTL_ACK";
        m_wifiMacInfo->Ra = rxCTL_ACK.cap(1).toAscii().data();
       return;

    }
    QRegExp rxCTL_RTS("ns3::WifiMacHeader \\(CTL_RTS .*RA=(..:..:..:..:..:..), TA=(..:..:..:..:..:..)");
    pos = 0;
    if ((pos = rxCTL_RTS.indexIn(metaInfo.c_str())) != -1)
    {
        m_wifiMacInfo = new WifiMacInfo;
        m_wifiMacInfo->type = "CTL_RTS";
        m_wifiMacInfo->Ra = rxCTL_RTS.cap(1).toAscii().data();
        m_wifiMacInfo->Sa = rxCTL_RTS.cap(2).toAscii().data();

       return;

    }

    QRegExp rxCTL_CTS("ns3::WifiMacHeader \\(CTL_CTS .*RA=(..:..:..:..:..:..)");
    pos = 0;
    if ((pos = rxCTL_CTS.indexIn(metaInfo.c_str())) != -1)
    {
        m_wifiMacInfo = new WifiMacInfo;
        m_wifiMacInfo->type = "CTL_CTS";
        m_wifiMacInfo->Ra = rxCTL_CTS.cap(1).toAscii().data();
        return;

    }

    QRegExp rx("ns3::WifiMacHeader \\((\\S+) ToDS=(0|1), FromDS=(0|1), .*DA=(..:..:..:..:..:..), SA=(..:..:..:..:..:..), BSSID=(..:..:..:..:..:..)");
    pos = 0;
    if ((pos = rx.indexIn(metaInfo.c_str())) == -1)
        return;
    m_wifiMacInfo = new WifiMacInfo;
    m_wifiMacInfo->type = rx.cap(1).toAscii().data();
    m_wifiMacInfo->toDs = rx.cap(2).toAscii().data();
    m_wifiMacInfo->fromDs = rx.cap(3).toAscii().data();
    m_wifiMacInfo->Da = rx.cap(4).toAscii().data();
    m_wifiMacInfo->Sa = rx.cap(5).toAscii().data();
    m_wifiMacInfo->Bssid = rx.cap(6).toAscii().data();

    if(m_wifiMacInfo->type == "MGT_ASSOCIATION_REQUEST")
    {
        QRegExp rx("ns3::MgtAssocRequestHeader \\(ssid=(\\S+),");
        int pos = 0;
        if ((pos = rx.indexIn(metaInfo.c_str())) == -1)
            return;
        m_wifiMacInfo->SSid = rx.cap(1).toAscii().data();
    }
    if(m_wifiMacInfo->type == "MGT_ASSOCIATION_RESPONSE")
    {
        QRegExp rx("ns3::MgtAssocResponseHeader \\(status code=(\\S+), rates");
        int pos = 0;
        if ((pos = rx.indexIn(metaInfo.c_str())) == -1)
            return;
        m_wifiMacInfo->assocResponseStatus = rx.cap(1).toAscii().data();
    }


}
DialogSpectrumTemplate::DialogSpectrumTemplate(Qpx::Spectrum::Template newTemplate,
                                               std::vector<Qpx::Detector> current_dets,
                                               bool edit, QWidget *parent) :
  QDialog(parent),
  current_dets_(current_dets),
  ui(new Ui::DialogSpectrumTemplate)
{
  ui->setupUi(this);
  for (auto &q : Qpx::Spectrum::Factory::getInstance().types())
    ui->comboType->addItem(QString::fromStdString(q));
  ui->colPicker->setStandardColors();
  connect(ui->colPicker, SIGNAL(colorChanged(QColor)), this, SLOT(colorChanged(QColor)));

  QRegExp rx("^\\w*$");
  QValidator *validator = new QRegExpValidator(rx, this);
  ui->lineName->setValidator(validator);

  if (edit) {
    myTemplate = newTemplate;
    ui->lineName->setEnabled(false);
    ui->comboType->setEnabled(false);
    Qpx::Spectrum::Template *newtemp = Qpx::Spectrum::Factory::getInstance().create_template(newTemplate.type);
    if (newtemp != nullptr) {
      myTemplate.description = newtemp->description;
      myTemplate.input_types = newtemp->input_types;
      myTemplate.output_types = newtemp->output_types;
    } else
      PL_WARN << "Problem with spectrum type. Factory cannot make template for " << newTemplate.type;
  } else {
    Qpx::Spectrum::Template *newtemp = Qpx::Spectrum::Factory::getInstance().create_template(ui->comboType->currentText().toStdString());
    if (newtemp != nullptr) {
      myTemplate = *newtemp;
      size_t sz = current_dets_.size();

      Qpx::Setting pattern;

      pattern = myTemplate.generic_attributes.get(Qpx::Setting("pattern_coinc"));
      pattern.value_pattern.resize(sz);
      myTemplate.generic_attributes.replace(pattern);

      pattern = myTemplate.generic_attributes.get(Qpx::Setting("pattern_anti"));
      pattern.value_pattern.resize(sz);
      myTemplate.generic_attributes.replace(pattern);

      pattern = myTemplate.generic_attributes.get(Qpx::Setting("pattern_add"));
      pattern.value_pattern.resize(sz);
      myTemplate.generic_attributes.replace(pattern);

      myTemplate.match_pattern.resize(sz);
      myTemplate.add_pattern.resize(sz);
    } else
      PL_WARN << "Problem with spectrum type. Factory cannot make template for " << ui->comboType->currentText().toStdString();
    myTemplate.appearance = generateColor().rgba();
  }

  table_model_.eat(&myTemplate.generic_attributes);
  ui->tableGenericAttrs->setModel(&table_model_);
  ui->tableGenericAttrs->setItemDelegate(&special_delegate_);
  ui->tableGenericAttrs->verticalHeader()->hide();
  ui->tableGenericAttrs->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
  ui->tableGenericAttrs->horizontalHeader()->setStretchLastSection(true);
  ui->tableGenericAttrs->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
  ui->tableGenericAttrs->setSelectionMode(QAbstractItemView::SingleSelection);
  ui->tableGenericAttrs->show();

  updateData();

  ui->tableGenericAttrs->resizeColumnsToContents();

}
Example #3
0
QUrl QgsHelp::helpUrl( const QString &key )
{
  QUrl helpNotFound = QUrl::fromLocalFile( QgsApplication::pkgDataPath() + "/doc/nohelp.html" );

  QgsSettings settings;
  QStringList paths = settings.value( QStringLiteral( "help/helpSearchPath" ) ).toStringList();
  if ( paths.isEmpty() )
  {
    return helpNotFound;
  }

  std::unique_ptr<QgsExpressionContextScope> scope( QgsExpressionContextUtils::globalScope() );

  QUrl helpUrl;
  QString helpPath, fullPath;
  bool helpFound = false;

  Q_FOREACH ( const QString &path, paths )
  {
    if ( path.endsWith( "\\" ) || path.endsWith( "/" ) )
    {
      fullPath = path.left( path.size() - 1 );
    }
    else
    {
      fullPath = path;
    }

    Q_FOREACH ( const QString &var, scope->variableNames() )
    {
      QRegularExpression rx( QStringLiteral( "(<!\\$\\$)*(\\$%1)" ).arg( var ) );
      fullPath.replace( rx, scope->variable( var ).toString() );
    }
    fullPath.replace( QRegularExpression( "(\\$\\$)" ), "$" );

    helpPath = QStringLiteral( "%1/%2" ).arg( fullPath, key );

    if ( helpPath.startsWith( QStringLiteral( "http" ) ) )
    {
      if ( !QgsHelp::urlExists( helpPath ) )
      {
        continue;
      }
      helpUrl = QUrl( helpPath );
    }
    else
    {
      QString filePath = helpPath.mid( 0, helpPath.lastIndexOf( "#" ) );
      if ( !QFileInfo::exists( filePath ) )
      {
        continue;
      }
      helpUrl = QUrl::fromLocalFile( filePath );
      int pos = helpPath.lastIndexOf( "#" );
      if ( pos != -1 )
      {
        helpUrl.setFragment( helpPath.mid( helpPath.lastIndexOf( "#" ) + 1, -1 ) );
      }
    }

    helpFound = true;
    break;
  }

  return helpFound ? helpUrl : helpNotFound;
}
Example #4
0
/*
 * gibt den ermittelten Buchstaben zurück einschließliech Umlaute
 */
QString QvkShowkeyGetkey::getKey( QStringList list, int code )
{
  QString keyFromList;
  QStringList splitValuesList;
  QString key;
  
  QRegExp rx( "^" + QString::number( code ) + " " );
  QStringList keyList = list.filter( rx );
  QString keyValues = keyList[0];
  splitValuesList = keyValues.split( " " );
  keyFromList = splitValuesList[ 1 ];
  
  int integer = keyFromList.toInt( 0, 16 );
  key = (QString)integer;
  
  // Bei folgen Tasten Flag setzen und kein Wert zurückgeben
  keyFromList = splitValuesList[ 2 ];
  if ( keyFromList == "Caps_Lock")
  {
     key = "";
     caps_set.insert(code);
  }
  else if ( keyFromList == "Shift_L"   || keyFromList == "Shift_R")
  {
     key = "";
     shift_set.insert(code);
  }
  else if ( keyFromList == "Control_L" || keyFromList == "Control_R")
  {
     key = "";
     ctrl_set.insert(code);
  }
  else if ( keyFromList == "Alt_L"     || keyFromList == "Alt_R")
  {
     key = "";
     alt_set.insert(code);
  }
  else if ( keyFromList == "Meta_L"    || keyFromList == "Meta_R")
  {
     key = "";
     meta_set.insert(code);
  }
  else if ( keyFromList == "Super_L"    || keyFromList == "Super_R")
  {
     key = "";
     meta_set.insert(code);
  }

  // Mit "xset q" kann der status abgefragt werden
  // http://www.qtcentre.org/threads/30180-how-to-determine-if-CapsLock-is-on-crossplatform
  // http://stackoverflow.com/questions/24822505/how-to-tell-if-shift-is-pressed-on-numpad-input-with-numlock-on-or-at-least-get
  
  if ( keyFromList == "F1" ) key = "F1";
  if ( keyFromList == "F2" ) key = "F2";
  if ( keyFromList == "F3" ) key = "F3";
  if ( keyFromList == "F4" ) key = "F4";
  if ( keyFromList == "F5" ) key = "F5";
  if ( keyFromList == "F6" ) key = "F6";
  if ( keyFromList == "F7" ) key = "F7";
  if ( keyFromList == "F8" ) key = "F8";
  if ( keyFromList == "F9" ) key = "F9";
  if ( keyFromList == "F10" ) key = "F10";
  if ( keyFromList == "F11" ) key = "F11";
  if ( keyFromList == "F12" ) key = "F12";
  if ( keyFromList == "Escape" ) key = "Esc";
  if ( keyFromList == "BackSpace" ) key = "Bsp";
  if ( keyFromList == "Tab" ) key = "Tab";
  if ( keyFromList == "Num_Lock" ) key = "";
  if ( keyFromList == "Return" ) key = "Return";
  
  if ( isNumLockOn() == true )
  {
    keyFromList = splitValuesList[ 4 ];
    if ( keyFromList == "KP_0" ) key = "0";
    if ( keyFromList == "KP_1" ) key = "1";
    if ( keyFromList == "KP_2" ) key = "2";
    if ( keyFromList == "KP_3" ) key = "3";
    if ( keyFromList == "KP_4" ) key = "4";
    if ( keyFromList == "KP_5" ) key = "5";
    if ( keyFromList == "KP_6" ) key = "6";
    if ( keyFromList == "KP_7" ) key = "7";
    if ( keyFromList == "KP_8" ) key = "8";
    if ( keyFromList == "KP_9" ) key = "9";
    if ( keyFromList == "KP_Multiply" ) key = "*";
    if ( keyFromList == "KP_Subtract" ) key = "-";
    if ( keyFromList == "KP_Add" ) key = "+";
    if ( keyFromList == "KP_Decimal" ) key = ".";
    if ( keyFromList == "KP_Divide" ) key = "/";
    if ( keyFromList == "KP_Separator" ) key = ",";
  }

  if ( isNumLockOn() == false )
  {
    keyFromList = splitValuesList[ 2 ];
    if ( keyFromList == "KP_Home" )      key = "Home";
    if ( keyFromList == "KP_Up" )        key = "Up";
    if ( keyFromList == "KP_Prior" )     key = "Prior";
    if ( keyFromList == "KP_Left" )      key = "Left";
    if ( keyFromList == "KP_Begin" )     key = "Begin";
    if ( keyFromList == "KP_Right" )     key = "Right";
    if ( keyFromList == "KP_End" )       key = "End";
    if ( keyFromList == "KP_Down" )      key = "Down";
    if ( keyFromList == "KP_Next" )      key = "Next";
    if ( keyFromList == "KP_Insert" )    key = "insert";
    if ( keyFromList == "KP_Delete" )    key = "Delete";
    if ( keyFromList == "KP_Enter" )     key = "Enter";
    if ( keyFromList == "KP_Add" )       key = "+";
    if ( keyFromList == "KP_Subtract" )  key = "-";
    if ( keyFromList == "KP_Multiply" )  key = "*";
    if ( keyFromList == "KP_Divide" )    key = "/";
  }
  
  qDebug() << "Numlook" << isNumLockOn() << "|" << "keycode" << code << "|" << "Keysym" << keyFromList << "|" << "Print key:" << key;
  
  return key;
}
void QParseSite::parse_page(QString content)
{
    if(!siteurl.isEmpty())
    {

        QRegExp rx("<a[^>]+href=\"([^\"]+)\"[^>]*>(.*)</a>");
        rx.setMinimal(true);
        QStringList list;
        int pos = 0;
        while((pos = rx.indexIn(content, pos)) != -1)
        {
            list << rx.cap(1);
            pos += rx.matchedLength();

        }
        list.removeDuplicates();
        media=list.filter(".mp3");
        links.clear();
        links=list.replaceInStrings(QRegExp(".*.mp3"),"_");
        links=list.replaceInStrings(QRegExp(".*.m3u"),"_");
        links=list.replaceInStrings(QRegExp("javascript:;"),"_");

        links.removeDuplicates();
        QUrl link("");
        int iternal ;
        QString url;
        for( int n = 0; n < links.size(); n++)
        {
            link.setUrl(links.at( n));
            iternal =links.at(n).indexOf("/");
            if(siteurl.host() != link.host())
            {
                if(iternal==1 || iternal==0)
                {
                    url = links.at(n);
                    if(iternal == 1)
                    {
                        url=url.replace("./","/");
                    }

                    /*
                    if(link.host()=="")
                    {
                        ///url = links.at(n);
                        if(url_current.toString().lastIndexOf("/") == url_current.toString().size()-1 &&  url.at(0)=='/')
                        {
                            url.replace(0,1,"");
                        }
                        url=url_current.toString()+url;
                    }
                    else
                          {
                              */
                              url = siteurl.scheme()+"://"+siteurl.host()+url;



                    links.replace(n,url);
                }
                else
                {
                    links.removeAt(n);
                }

            }



        }
        emit page_parsed(links.filter(siteurl.host()),media,"","");
    }


}
Example #6
0
bool ImageThread::addImage(_IMAGE img) {
    int i,k;
    bool alreadyInList;
    bool fileExists;

    fileExists = false;

    if (_blackList->contains(img.largeURI)) {
        alreadyInList = true;
    }
    else {
        alreadyInList = false;
        k = 2;
        for (i=0; i<images.length(); i++) {
            if (images.at(i).largeURI == img.largeURI) {
                alreadyInList = true;
                break;
            }

            if (images.at(i).originalFilename == img.originalFilename) {
                QStringList tmp;

                tmp = img.originalFilename.split(QRegExp("\\(\\d+\\)"));
                if  (tmp.count() > 1) // Already has a number in brackets in filename
                    img.originalFilename = QString("%1(%2)%3").arg(tmp.at(0)).
                                           arg(k++).
                                           arg(tmp.at(1));
                else
                    img.originalFilename = img.originalFilename.replace("."," (1).");
            }
        }

        if (!alreadyInList) {
            // Check if already downloaded
            QFile f;
            if (_saveWithOriginalFilename)
                f.setFileName(getSavepath()+"/"+img.originalFilename);
            else {
                QRegExp rx(__IMAGEFILE_REGEXP__, Qt::CaseInsensitive, QRegExp::RegExp2);
                QStringList res;
                int pos;

                pos = 0;

                pos = rx.indexIn(img.largeURI);
                res = rx.capturedTexts();

                if (pos != -1) {
                    f.setFileName(getSavepath()+"/"+res.at(1)+res.at(2));
                }
            }

            if (f.exists()) {
                img.downloaded = true;
                fileExists = true;
                img.savedAs = f.fileName();
            }

            images.append(img);
        }
    }

    return (!alreadyInList && !fileExists);
}
Example #7
0
void CodeSnippet::insertAt(QEditor* editor, QDocumentCursor* cursor, bool usePlaceholders, bool byCompleter) const{
	if (lines.empty()||!editor||!cursor) return;
	
	//find filechooser escape %(   %)
	QString line=lines.join("\n");
	QRegExp rx("%\\((.+)%\\)");
	int pos=rx.indexIn(line,0);
	if(pos>-1){
		FileChooser sfDlg(0,QApplication::tr("Select a File"));
		sfDlg.setFilter(rx.cap(1));
		LatexDocument *doc=qobject_cast<LatexDocument*>(cursor->document());
		QString path=doc->parent->getCompileFileName();
		path=getPathfromFilename(path);
		QString directory;
		if(path.isEmpty()) directory=QDir::homePath();
		else directory=path;
		sfDlg.setDir(directory);
		if (sfDlg.exec()) {
			QString fn=sfDlg.fileName();
			line.replace(rx,getRelativeBaseNameToPath(fn,path));
		} else return;
	}


	QString savedSelection;
	bool alwaysSelect = false;
	bool editBlockOpened = false;
	if (cursor->hasSelection()) {
		savedSelection=cursor->selectedText();
		editBlockOpened = true;
		cursor->beginEditBlock();
		cursor->removeSelectedText();
	}else if(!editor->cutBuffer.isEmpty()){
		savedSelection=editor->cutBuffer;
		editor->cutBuffer.clear();
		alwaysSelect = true;
	}
	bool multiLineSavedSelection = savedSelection.contains("\n");
	QDocumentCursor selector=*cursor;
	QDocumentLine curLine=cursor->line();

	// on multi line commands, replace environments only
	if(autoReplaceCommands && lines.size()>1 && line.contains("\\begin{")){
		QString curLine=cursor->line().text();
		int wordBreak=curLine.indexOf(QRegExp("\\W"),cursor->columnNumber());
		int closeCurl=curLine.indexOf("}",cursor->columnNumber());
		int openCurl=curLine.indexOf("{",cursor->columnNumber());
		int openBracket=curLine.indexOf("[",cursor->columnNumber());
		if(closeCurl>0){
			if(openBracket<0) openBracket=1e9;
			if(openCurl<0) openCurl=1e9;
			if(wordBreak<0) wordBreak=1e9;
			if(closeCurl<openBracket && (closeCurl<=wordBreak || openCurl<=wordBreak)){
				QString oldEnv;
				if(closeCurl<openCurl)
					oldEnv=curLine.mid(cursor->columnNumber(),closeCurl-cursor->columnNumber());
				else
					oldEnv=curLine.mid(openCurl+1,closeCurl-openCurl-1);
				QRegExp rx("\\\\begin\\{(.+)\\}");
				rx.setMinimal(true);
				rx.indexIn(line);
				QString newEnv=rx.cap(1);
				// remove curly brakets as well
				QDocument* doc=cursor->document();
				QString searchWord="\\end{"+oldEnv+"}";
				QString inhibitor="\\begin{"+oldEnv+"}";
				bool backward=false;
				int step=1;
				int startLine=cursor->lineNumber();
				//int startCol=cursor.columnNumber();
				int endLine=doc->findLineContaining(searchWord,startLine+step,Qt::CaseSensitive,backward);
				int inhibitLine=doc->findLineContaining(inhibitor,startLine+step,Qt::CaseSensitive,backward); // not perfect (same line end/start ...)
				while (inhibitLine>0 && endLine>0 && inhibitLine*step<endLine*step) {
					endLine=doc->findLineContaining(searchWord,endLine+step,Qt::CaseSensitive,backward); // not perfect (same line end/start ...)
					inhibitLine=doc->findLineContaining(inhibitor,inhibitLine+step,Qt::CaseSensitive,backward);
				}
				QString endText=doc->line(endLine).text();
				int start=endText.indexOf(searchWord);
				int offset=searchWord.indexOf("{");
				int length=searchWord.length()-offset-1;
				selector.moveTo(endLine,start+1+offset);
				selector.movePosition(length-1,QDocumentCursor::Right,QDocumentCursor::KeepAnchor);
				selector.replaceSelectedText(newEnv);
				cursor->movePosition(closeCurl-cursor->columnNumber()+1,QDocumentCursor::Right,QDocumentCursor::KeepAnchor);
				QString first=lines.first();
				int pos=first.indexOf('{');
				pos=first.indexOf('{',pos+1); //pos of second {
				if(pos>-1)
				    first.remove(pos,first.length()-pos);
				editor->insertText(*cursor,first);
				if (editBlockOpened) cursor->endEditBlock();
				return;
			}
		}
	}

	int baseLine=cursor->lineNumber();
	int baseLineIndent = cursor->columnNumber(); //text before inserted word moves placeholders to the right
	int lastLineRemainingLength = curLine.text().length()-baseLineIndent; //last line will has length: indentation + codesnippet + lastLineRemainingLength
	editor->insertText(*cursor,line); //don't use cursor->insertText to keep autoindentation working

	if (editBlockOpened) cursor->endEditBlock();

	// on single line commands only: replace command
	if(byCompleter && autoReplaceCommands && lines.size()==1 && line.startsWith('\\')){
		if(cursor->nextChar().isLetterOrNumber()||cursor->nextChar()==QChar('{')){
			QString curLine=cursor->line().text();
			int wordBreak=curLine.indexOf(QRegExp("\\W"),cursor->columnNumber());
			int closeCurl=curLine.indexOf("}",cursor->columnNumber());
			int openCurl=curLine.indexOf("{",cursor->columnNumber());
			int openBracket=curLine.indexOf("[",cursor->columnNumber());
			if(!line.contains("{")){
				if(openBracket<0) openBracket=1e9;
				if(closeCurl<0) closeCurl=1e9;
				if(openCurl<0) openCurl=1e9;
				if(wordBreak<openBracket && wordBreak<closeCurl &&wordBreak<openCurl){
					if(wordBreak<0)
						cursor->movePosition(wordBreak-cursor->columnNumber(),QDocumentCursor::EndOfLine,QDocumentCursor::KeepAnchor);
					else
						cursor->movePosition(wordBreak-cursor->columnNumber(),QDocumentCursor::Right,QDocumentCursor::KeepAnchor);
					cursor->removeSelectedText();
					return;
				}
			}else{
				if(openCurl>-1){
					if(openBracket<0) openBracket=1e9;
					if(closeCurl<0) closeCurl=1e9;
					if(openCurl<openBracket && openCurl<closeCurl &&openCurl<=wordBreak){
						cursor->movePosition(openCurl-cursor->columnNumber(),QDocumentCursor::Right,QDocumentCursor::KeepAnchor);
						cursor->removeSelectedText();
						int curl=line.length()-line.indexOf("{");
						cursor->movePosition(curl,QDocumentCursor::Left,QDocumentCursor::KeepAnchor);
						cursor->removeSelectedText();
						return;
					}
				}
			}
		}
	}


	Q_ASSERT(placeHolders.size()==lines.count());
	if (usePlaceholders) {
		//check if there actually are placeholders to insert
		usePlaceholders=false;
		for (int l=0;l< lines.count();l++)
			usePlaceholders|=placeHolders[l].size();
	}
	int autoSelectPlaceholder = -1;
	if (usePlaceholders) {
		if (editor->currentPlaceHolder()!=-1 && 
			editor->getPlaceHolder(editor->currentPlaceHolder()).cursor.isWithinSelection(*cursor))
			editor->removePlaceHolder(editor->currentPlaceHolder()); //remove currentplaceholder to prevent nesting
		for (int l=0;l< lines.count();l++){
			//if (l<mLines.count()-1) cursor->insertLine();
			for (int i=0; i<placeHolders[l].size(); i++) {
				if (placeHolders[l][i].flags & CodeSnippetPlaceHolder::Mirror) continue;
				PlaceHolder ph;
				ph.length=placeHolders[l][i].length;
				ph.cursor = getCursor(editor, placeHolders[l][i], l, baseLine, baseLineIndent, lastLineRemainingLength);
				ph.autoRemove = !(placeHolders[l][i].flags & CodeSnippetPlaceHolder::Persistent);
				if (!ph.cursor.isValid()) continue;
				editor->addPlaceHolder(ph);
				if (placeHolders[l][i].flags & CodeSnippetPlaceHolder::Mirrored) {
					int phId = editor->placeHolderCount()-1;
					for (int lm=0; lm<placeHolders.size(); lm++)
						for (int im=0; im < placeHolders[lm].size(); im++)
							if (placeHolders[lm][im].flags & CodeSnippetPlaceHolder::Mirror &&
							    placeHolders[lm][im].id == placeHolders[l][i].id)
							editor->addPlaceHolderMirror(phId, getCursor(editor, placeHolders[lm][im], lm, baseLine, baseLineIndent, lastLineRemainingLength));
				}
				if ((placeHolders[l][i].flags & CodeSnippetPlaceHolder::AutoSelect) &&
				      ((autoSelectPlaceholder == -1) ||
					(multiLineSavedSelection && (placeHolders[l][i].flags & CodeSnippetPlaceHolder::PreferredMultilineAutoSelect))))
					autoSelectPlaceholder = editor->placeHolderCount()-1;

			}
		}
	}
	//place cursor/add \end
	if (cursorOffset!=-1) {
		int realAnchorOffset=anchorOffset; //will be moved to the right if text is already inserted on this line
		if (cursorLine>0) {
			if (cursorLine>=lines.size()) return;
			if (!selector.movePosition(cursorLine,QDocumentCursor::Down,QDocumentCursor::MoveAnchor))
				return;
			//if (editor->flag(QEditor::AutoIndent))
			realAnchorOffset += selector.line().length()-lines[cursorLine].length();
			if (cursorLine + 1 == lines.size())
				realAnchorOffset-=lastLineRemainingLength;
		} else realAnchorOffset += baseLineIndent;
		selector.setColumnNumber(realAnchorOffset);
		bool ok=true;
		if (cursorOffset>anchorOffset) 
			ok=selector.movePosition(cursorOffset-anchorOffset,QDocumentCursor::Right,QDocumentCursor::KeepAnchor);
		else if (cursorOffset<anchorOffset)
			ok=selector.movePosition(anchorOffset-cursorOffset,QDocumentCursor::Left,QDocumentCursor::KeepAnchor);
		if (!ok) return;
		editor->setCursor(selector);
	} else if (autoSelectPlaceholder!=-1) editor->setPlaceHolder(autoSelectPlaceholder, true); //this moves the cursor to that placeholder
	else {
		editor->setCursor(*cursor); //place after insertion
		return;
	}
	if (!savedSelection.isEmpty()) {
		QDocumentCursor oldCursor = editor->cursor();
		editor->cursor().insertText(savedSelection,true);
		if (!editor->cursor().hasSelection() && alwaysSelect) {
			oldCursor.movePosition(savedSelection.length(), QDocumentCursor::Right, QDocumentCursor::KeepAnchor);
			editor->setCursor(oldCursor);
		}
		if (autoSelectPlaceholder!=-1) editor->setPlaceHolder(autoSelectPlaceholder, true); //this synchronizes the placeholder mirrors with the current placeholder text
	}
}
Example #8
0
QString TimeZone::TimeZone::readAllCities()
{
    // get translation list
    QString lines = cityTranslations();

    QSettings settings;
    int sortOrder = settings.value("sortorder_completeList", "").toInt();
    QList<QByteArray> ids =  QTimeZone::availableTimeZoneIds();
    QString output;
    QString sign;
    QString timeoffset;
    QMultiMap<int, QString> map;
    QMultiMap<QString, QString> sorted_map;
    // QMultiMap is sorted by key by default
    // We use QMultiMap (not QMap) so we can have duplicates
    int dummy_counter_for_sort = 0; // to inverse reverted sorting
    foreach (QByteArray id, ids) {
        QTimeZone zone = QTimeZone(id);
        QDateTime zoneTime = QDateTime(QDate::currentDate(), QTime::currentTime(), zone).toLocalTime();
        int offset = zone.offsetFromUtc(QDateTime::currentDateTime());
        QString countryName = QLocale::countryToString(zone.country());
        QString countryNameOrg = countryName;
        // insert space where appropriate. Can't be done in one regex replace?
        QRegularExpression rx("([a-z])([A-Z])");
        QRegularExpressionMatch match = rx.match(countryName);
        for (int i = 1; i <= 6; i++) {
            match = rx.match(countryName);
            if (match.hasMatch()) {
                QString lowerChar1 = match.captured(1);
                QString upperChar1 = match.captured(2);
                countryName.replace(lowerChar1+upperChar1,lowerChar1 + " " + upperChar1);
            }
        }
        int index = lines.indexOf('\n'+countryName+';', 0, Qt::CaseInsensitive);
        if (index != -1) {
            index++;
            // Replace countryName with translation
            countryName = lines.mid(index+countryName.length()+1, lines.indexOf('\n',index) - lines.indexOf(';',index)-1);
        }
        if ( countryName == "Default") {
            // UTC name
            countryName = "";
        } else {
            countryName = " [" + countryName + "]";
        }
        if (offset < 0)
            sign = "-";
        else
            sign = "+";
        if((offset % 3600)==0)
            // offset equals to whole hour
            timeoffset = QString("UTC %3").arg(sign+QString::number(abs(offset)/3600));
        else
        {
            int minutes = offset/60 %60;
            timeoffset = QString("UTC %3:%4").arg(sign+QString::number(abs(offset)/3600)).arg(abs(minutes));
        }

        const int delimiter = id.lastIndexOf('/');
        int nbrSlashes = id.count("/");
        QString cityNameTr = id.mid(delimiter + 1).replace("_"," ");
        QString continentTr = id.mid(0, delimiter);
        QString stateTr = "";
        if ( nbrSlashes == 2) {
            // eg (America/North Dakota/Beulah)
            continentTr = id.mid(0, id.indexOf('/')); //first part
            stateTr = id.mid(id.indexOf('/')+1, delimiter - continentTr.length() - 1 ); //second part
        }
        if (!lines.isEmpty()) {
            int index = lines.indexOf(cityNameTr+';', 0, Qt::CaseInsensitive);
            if (index != -1) {
                cityNameTr = lines.mid(index+cityNameTr.length()+1, lines.indexOf('\n',index) - lines.indexOf(';',index)-1);
            }
            index = lines.indexOf(continentTr+';', 0, Qt::CaseInsensitive);
            if (index != -1) {
                continentTr = lines.mid(index+continentTr.length()+1, lines.indexOf('\n',index) - lines.indexOf(';',index)-1);
            }
            if (!stateTr.isEmpty()) {
                index = lines.indexOf(stateTr+';', 0, Qt::CaseInsensitive);
                if (index != -1) {
                    stateTr =  lines.mid(index+stateTr.length()+1, lines.indexOf('\n',index) - lines.indexOf(';',index)-1);
                }
                continentTr = continentTr + "/" + stateTr;
            }
        }
        if (sortOrder == 1) {
            dummy_counter_for_sort ++;
            map.insert(offset + dummy_counter_for_sort,timeoffset + " (" + continentTr + "/" + cityNameTr + ")" + countryName + ";" + id + ";" + countryNameOrg);
        } else if (sortOrder == 2) {
            sorted_map.insert(cityNameTr, timeoffset + " (" + continentTr + "/" + cityNameTr + ")" + countryName + ";" + id + ";" + countryNameOrg);
        } else if (sortOrder == 3) {
            sorted_map.insert(countryName, timeoffset + " (" + continentTr + "/" + cityNameTr + ")" + countryName + ";" + id + ";" + countryNameOrg);
        } else {
            output += timeoffset + " (" + continentTr + "/" + cityNameTr + ")" + countryName + ";" + id +  + ";" + countryNameOrg + "\n";
        }

    }
Example #9
0
// Constructor.
qtractorAudioFileFactory::qtractorAudioFileFactory (void)
{
	// Default file format/type (for capture/record)
	m_pDefaultFormat  = NULL;
	m_iDefaultFormat  = SF_FORMAT_PCM_16;
	m_iDefaultQuality = 4;

	// Second for libsndfile stuff...
	FileFormat *pFormat;
	const QString sExtMask("*.%1");
	const QString sFilterMask("%1 (%2)");
	SF_FORMAT_INFO sffinfo;
	int iCount = 0;
	::sf_command(NULL, SFC_GET_FORMAT_MAJOR_COUNT, &iCount, sizeof(int));
	for (int i = 0 ; i < iCount; ++i) {
		sffinfo.format = i;
		::sf_command(NULL, SFC_GET_FORMAT_MAJOR, &sffinfo, sizeof(sffinfo));
		pFormat = new FileFormat;
		pFormat->type = SndFile;
		pFormat->name = QString(sffinfo.name)
			.replace('/', '-')	// Replace some illegal characters.
			.replace('(', QString::null)
			.replace(')', QString::null);
		pFormat->ext  = sffinfo.extension;
		pFormat->data = sffinfo.format;
		m_formats.append(pFormat);
		// Add for the extension map (should be unique)...
		QString sExt = pFormat->ext;
		QString sExts(sExtMask.arg(sExt));
		if (m_types.find(sExt) == m_types.end()) {
			m_types[sExt] = pFormat;
			// Take care of some old 8.3 convention,
			// specially regarding filename extensions...
			if (sExt.length() > 3) {
				sExt = sExt.left(3);
				if (m_types.find(sExt) == m_types.end()) {
					sExts = sExtMask.arg(sExt) + ' ' + sExts;
					m_types[sExt] = pFormat;
				}
			}
			// Make a stance on the default format...
			if (sExt == "wav") m_pDefaultFormat = pFormat;
		}
		// What we see on dialog is some excerpt...
		m_filters.append(
			sFilterMask.arg(pFormat->name).arg(sExts));
	}

#ifdef CONFIG_LIBVORBIS
	// Add for libvorbis...
	pFormat = new FileFormat;
	pFormat->type = VorbisFile;
	pFormat->name = "OGG Vorbis";
	pFormat->ext  = "ogg";
	pFormat->data = 0;
	m_formats.append(pFormat);
	m_types[pFormat->ext] = pFormat;
	m_filters.append(
		sFilterMask.arg(pFormat->name).arg(sExtMask.arg(pFormat->ext)));
	// Oh yeah, this will be the official default format...
	m_pDefaultFormat = pFormat;
#endif

#ifdef CONFIG_LIBMAD
	// Add for libmad (mp3 read-only)...
	pFormat = new FileFormat;
	pFormat->type = MadFile;
	pFormat->name = "MP3 MPEG-1 Audio Layer 3";
	pFormat->ext  = "mp3";
	pFormat->data = 0;
	m_formats.append(pFormat);
	m_types[pFormat->ext] = pFormat;
	m_filters.append(
		sFilterMask.arg(pFormat->name).arg(sExtMask.arg(pFormat->ext)));
#endif

	// Finally, simply build the all (most commonly) supported files entry.
	QRegExp rx("^(aif(|f)|fla(|c)|mp3|ogg|w(av|64))", Qt::CaseInsensitive);
	QStringList exts;
	FileTypes::ConstIterator iter = m_types.constBegin();
	const FileTypes::ConstIterator& iter_end = m_types.constEnd();
	for ( ; iter != iter_end; ++iter) {
		const QString& sExt = iter.key();
		if (rx.exactMatch(sExt))
			exts.append(sExtMask.arg(sExt));
	}
	m_filters.prepend(QObject::tr("Audio files (%1)").arg(exts.join(" ")));
	m_filters.append(QObject::tr("All files (*.*)"));
}
  void CollocationIntegratorInternal::setupFG() {

    // Interpolation order
    deg_ = getOption("interpolation_order");

    // All collocation time points
    std::vector<long double> tau_root = collocationPointsL(deg_, getOption("collocation_scheme"));

    // Coefficients of the collocation equation
    vector<vector<double> > C(deg_+1, vector<double>(deg_+1, 0));

    // Coefficients of the continuity equation
    vector<double> D(deg_+1, 0);

    // Coefficients of the quadratures
    vector<double> B(deg_+1, 0);

    // For all collocation points
    for (int j=0; j<deg_+1; ++j) {

      // Construct Lagrange polynomials to get the polynomial basis at the collocation point
      Polynomial p = 1;
      for (int r=0; r<deg_+1; ++r) {
        if (r!=j) {
          p *= Polynomial(-tau_root[r], 1)/(tau_root[j]-tau_root[r]);
        }
      }

      // Evaluate the polynomial at the final time to get the
      // coefficients of the continuity equation
      D[j] = zeroIfSmall(p(1.0L));

      // Evaluate the time derivative of the polynomial at all collocation points to
      // get the coefficients of the continuity equation
      Polynomial dp = p.derivative();
      for (int r=0; r<deg_+1; ++r) {
        C[j][r] = zeroIfSmall(dp(tau_root[r]));
      }

      // Integrate polynomial to get the coefficients of the quadratures
      Polynomial ip = p.anti_derivative();
      B[j] = zeroIfSmall(ip(1.0L));
    }

    // Symbolic inputs
    MX x0 = MX::sym("x0", f_.input(DAE_X).sparsity());
    MX p = MX::sym("p", f_.input(DAE_P).sparsity());
    MX t = MX::sym("t", f_.input(DAE_T).sparsity());

    // Implicitly defined variables (z and x)
    MX v = MX::sym("v", deg_*(nx_+nz_));
    vector<int> v_offset(1, 0);
    for (int d=0; d<deg_; ++d) {
      v_offset.push_back(v_offset.back()+nx_);
      v_offset.push_back(v_offset.back()+nz_);
    }
    vector<MX> vv = vertsplit(v, v_offset);
    vector<MX>::const_iterator vv_it = vv.begin();

    // Collocated states
    vector<MX> x(deg_+1), z(deg_+1);
    for (int d=1; d<=deg_; ++d) {
      x[d] = reshape(*vv_it++, this->x0().shape());
      z[d] = reshape(*vv_it++, this->z0().shape());
    }
    casadi_assert(vv_it==vv.end());

    // Collocation time points
    vector<MX> tt(deg_+1);
    for (int d=0; d<=deg_; ++d) {
      tt[d] = t + h_*tau_root[d];
    }

    // Equations that implicitly define v
    vector<MX> eq;

    // Quadratures
    MX qf = MX::zeros(f_.output(DAE_QUAD).sparsity());

    // End state
    MX xf = D[0]*x0;

    // For all collocation points
    for (int j=1; j<deg_+1; ++j) {
      //for (int j=deg_; j>=1; --j) {

      // Evaluate the DAE
      vector<MX> f_arg(DAE_NUM_IN);
      f_arg[DAE_T] = tt[j];
      f_arg[DAE_P] = p;
      f_arg[DAE_X] = x[j];
      f_arg[DAE_Z] = z[j];
      vector<MX> f_res = f_.call(f_arg);

      // Get an expression for the state derivative at the collocation point
      MX xp_j = C[0][j] * x0;
      for (int r=1; r<deg_+1; ++r) {
        xp_j += C[r][j] * x[r];
      }

      // Add collocation equation
      eq.push_back(vec(h_*f_res[DAE_ODE] - xp_j));

      // Add the algebraic conditions
      eq.push_back(vec(f_res[DAE_ALG]));

      // Add contribution to the final state
      xf += D[j]*x[j];

      // Add contribution to quadratures
      qf += (B[j]*h_)*f_res[DAE_QUAD];
    }

    // Form forward discrete time dynamics
    vector<MX> F_in(DAE_NUM_IN);
    F_in[DAE_T] = t;
    F_in[DAE_X] = x0;
    F_in[DAE_P] = p;
    F_in[DAE_Z] = v;
    vector<MX> F_out(DAE_NUM_OUT);
    F_out[DAE_ODE] = xf;
    F_out[DAE_ALG] = vertcat(eq);
    F_out[DAE_QUAD] = qf;
    F_ = MXFunction(F_in, F_out);
    F_.init();

    // Backwards dynamics
    // NOTE: The following is derived so that it will give the exact adjoint
    // sensitivities whenever g is the reverse mode derivative of f.
    if (!g_.isNull()) {

      // Symbolic inputs
      MX rx0 = MX::sym("x0", g_.input(RDAE_RX).sparsity());
      MX rp = MX::sym("p", g_.input(RDAE_RP).sparsity());

      // Implicitly defined variables (rz and rx)
      MX rv = MX::sym("v", deg_*(nrx_+nrz_));
      vector<int> rv_offset(1, 0);
      for (int d=0; d<deg_; ++d) {
        rv_offset.push_back(rv_offset.back()+nrx_);
        rv_offset.push_back(rv_offset.back()+nrz_);
      }
      vector<MX> rvv = vertsplit(rv, rv_offset);
      vector<MX>::const_iterator rvv_it = rvv.begin();

      // Collocated states
      vector<MX> rx(deg_+1), rz(deg_+1);
      for (int d=1; d<=deg_; ++d) {
        rx[d] = reshape(*rvv_it++, this->rx0().shape());
        rz[d] = reshape(*rvv_it++, this->rz0().shape());
      }
      casadi_assert(rvv_it==rvv.end());

      // Equations that implicitly define v
      eq.clear();

      // Quadratures
      MX rqf = MX::zeros(g_.output(RDAE_QUAD).sparsity());

      // End state
      MX rxf = D[0]*rx0;

      // For all collocation points
      for (int j=1; j<deg_+1; ++j) {

        // Evaluate the backward DAE
        vector<MX> g_arg(RDAE_NUM_IN);
        g_arg[RDAE_T] = tt[j];
        g_arg[RDAE_P] = p;
        g_arg[RDAE_X] = x[j];
        g_arg[RDAE_Z] = z[j];
        g_arg[RDAE_RX] = rx[j];
        g_arg[RDAE_RZ] = rz[j];
        g_arg[RDAE_RP] = rp;
        vector<MX> g_res = g_.call(g_arg);

        // Get an expression for the state derivative at the collocation point
        MX rxp_j = -D[j]*rx0;
        for (int r=1; r<deg_+1; ++r) {
          rxp_j += (B[r]*C[j][r]) * rx[r];
        }

        // Add collocation equation
        eq.push_back(vec(h_*B[j]*g_res[RDAE_ODE] - rxp_j));

        // Add the algebraic conditions
        eq.push_back(vec(g_res[RDAE_ALG]));

        // Add contribution to the final state
        rxf += -B[j]*C[0][j]*rx[j];

        // Add contribution to quadratures
        rqf += h_*B[j]*g_res[RDAE_QUAD];
      }

      // Form backward discrete time dynamics
      vector<MX> G_in(RDAE_NUM_IN);
      G_in[RDAE_T] = t;
      G_in[RDAE_X] = x0;
      G_in[RDAE_P] = p;
      G_in[RDAE_Z] = v;
      G_in[RDAE_RX] = rx0;
      G_in[RDAE_RP] = rp;
      G_in[RDAE_RZ] = rv;
      vector<MX> G_out(RDAE_NUM_OUT);
      G_out[RDAE_ODE] = rxf;
      G_out[RDAE_ALG] = vertcat(eq);
      G_out[RDAE_QUAD] = rqf;
      G_ = MXFunction(G_in, G_out);
      G_.init();
    }
  }
Example #11
0
    SshTunnelTab::SshTunnelTab(ConnectionSettings *settings) :
        _settings(settings)
    {
        SshSettings *info = settings->sshSettings();
        _sshSupport = new QCheckBox("Use SSH tunnel");
        _sshSupport->setStyleSheet("margin-bottom: 7px");
        _sshSupport->setChecked(info->enabled());

        _askForPassword = new QCheckBox(askPasswordText);
        _askForPassword->setChecked(info->askPassword());
        VERIFY(connect(_askForPassword, SIGNAL(stateChanged(int)), this, SLOT(askForPasswordStateChanged(int))));

        _sshHostName = new QLineEdit(QtUtils::toQString(info->host()));
        _userName = new QLineEdit(QtUtils::toQString(info->userName()));

        _sshPort = new QLineEdit(QString::number(info->port()));
        _sshPort->setFixedWidth(40);
        QRegExp rx("\\d+"); //(0-65554)
        _sshPort->setValidator(new QRegExpValidator(rx, this));        

        _security = new QComboBox();
        _security->addItems(QStringList() << "Password" << "Private Key");
        VERIFY(connect(_security, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(securityChange(const QString&))));

        _passwordBox = new QLineEdit(QtUtils::toQString(info->userPassword()));
        _passwordBox->setEchoMode(QLineEdit::Password);
        _passwordEchoModeButton = new QPushButton;
        VERIFY(connect(_passwordEchoModeButton, SIGNAL(clicked()), this, SLOT(togglePasswordEchoMode())));
        togglePasswordEchoMode();

        _privateKeyBox = new QLineEdit(QtUtils::toQString(info->privateKeyFile()));
        
        _passphraseBox = new QLineEdit(QtUtils::toQString(info->passphrase()));
        _passphraseBox->setEchoMode(QLineEdit::Password);
        _passphraseEchoModeButton = new QPushButton;
        VERIFY(connect(_passphraseEchoModeButton, SIGNAL(clicked()), this, SLOT(togglePassphraseEchoMode())));
        togglePassphraseEchoMode();

        _passwordLabel = new QLabel("User Password:"******"Private key:");
        _sshPassphraseLabel = new QLabel("Passphrase:");
        _sshAddressLabel = new QLabel("SSH Address:");
        _sshUserNameLabel = new QLabel("SSH User Name:");
        _sshAuthMethodLabel = new QLabel("SSH Auth Method:");

/*
// Commented because of this:
// https://github.com/paralect/robomongo/issues/391

#ifdef Q_OS_WIN
        QRegExp pathx("([a-zA-Z]:)?([\\\\/][a-zA-Z0-9_.-]+)+[\\\\/]?");
#else
        QRegExp pathx("^\\/?([\\d\\w\\.]+)(/([\\d\\w\\.]+))*\\/?$");
#endif // Q_OS_WIN
        _publicKeyBox->setValidator(new QRegExpValidator(pathx, this));
        _privateKeyBox->setValidator(new QRegExpValidator(pathx, this));
*/

        QHBoxLayout *hostAndPasswordLayout = new QHBoxLayout;
        hostAndPasswordLayout->addWidget(_sshHostName);
        hostAndPasswordLayout->addWidget(new QLabel(":"));
        hostAndPasswordLayout->addWidget(_sshPort);

        QGridLayout *connectionLayout = new QGridLayout;
        connectionLayout->setAlignment(Qt::AlignTop);
        connectionLayout->setColumnStretch(1, 1);
        connectionLayout->setColumnMinimumWidth(0, _passwordLabel->sizeHint().width() + 5);

        connectionLayout->addWidget(_sshAddressLabel ,             1, 0);
        connectionLayout->addLayout(hostAndPasswordLayout,         1, 1, 1, 2);

        connectionLayout->addWidget(_sshUserNameLabel,             2, 0);
        connectionLayout->addWidget(_userName,                     2, 1, 1, 2);

        connectionLayout->addWidget(_sshAuthMethodLabel,           4, 0);
        connectionLayout->addWidget(_security,                     4, 1, 1, 2);

        connectionLayout->addWidget(_passwordLabel,                5, 0);
        connectionLayout->addWidget(_passwordBox,                  5, 1);
        connectionLayout->addWidget(_passwordEchoModeButton,       5, 2);

        _selectPrivateFileButton = new QPushButton("...");
        _selectPrivateFileButton->setMaximumWidth(50);

        connectionLayout->addWidget(_sshPrivateKeyLabel,           7, 0);
        connectionLayout->addWidget(_privateKeyBox,                7, 1);
        connectionLayout->addWidget(_selectPrivateFileButton,      7, 2);

        connectionLayout->addWidget(_sshPassphraseLabel,           8, 0);
        connectionLayout->addWidget(_passphraseBox,                8, 1);
        connectionLayout->addWidget(_passphraseEchoModeButton,     8, 2);
        connectionLayout->addWidget(_askForPassword,               9, 1, 1, 2);

        QVBoxLayout *mainLayout = new QVBoxLayout;
        mainLayout->addWidget(_sshSupport);
        mainLayout->addLayout(connectionLayout);
        setLayout(mainLayout);

        if (info->authMethod() == "publickey") {
            utils::setCurrentText(_security, "Private Key");
        } else {
            utils::setCurrentText(_security, "Password");
        }

        securityChange(_security->currentText());
        VERIFY(connect(_selectPrivateFileButton, SIGNAL(clicked()), this, SLOT(setPrivateFile())));

        sshSupportStateChange(_sshSupport->checkState());
        VERIFY(connect(_sshSupport, SIGNAL(stateChanged(int)), this, SLOT(sshSupportStateChange(int))));

        _sshHostName->setFocus();

#ifdef Q_OS_MAC
        _passwordEchoModeButton->setMaximumWidth(_selectPrivateFileButton->width());
        _passphraseEchoModeButton->setMaximumWidth(_selectPrivateFileButton->width());
#else
        _passwordEchoModeButton->setMinimumWidth(_selectPrivateFileButton->width());
        _passphraseEchoModeButton->setMinimumWidth(_selectPrivateFileButton->width());
#endif
        // Attempt to fix the issue for Windows High DPI button height is slightly taller than other widgets 
#ifdef Q_OS_WIN
        _passwordEchoModeButton->setMaximumHeight(HighDpiContants::WIN_HIGH_DPI_BUTTON_HEIGHT);
        _passphraseEchoModeButton->setMaximumHeight(HighDpiContants::WIN_HIGH_DPI_BUTTON_HEIGHT);
        _selectPrivateFileButton->setMaximumHeight(HighDpiContants::WIN_HIGH_DPI_BUTTON_HEIGHT);
#endif

    }
Example #12
0
bool SVNDiff::DiffProps(const CTSVNPath& filePath, const SVNRev& rev1, const SVNRev& rev2, svn_revnum_t &baseRev) const
{
    bool retvalue = false;
    // diff the properties
    SVNProperties propswc(filePath, rev1, false, false);
    SVNProperties propsbase(filePath, rev2, false, false);

#define MAX_PATH_LENGTH 80
    WCHAR pathbuf1[MAX_PATH] = {0};
    if (filePath.GetWinPathString().GetLength() >= MAX_PATH)
    {
        std::wstring str = filePath.GetWinPath();
        std::wregex rx(L"^(\\w+:|(?:\\\\|/+))((?:\\\\|/+)[^\\\\/]+(?:\\\\|/)[^\\\\/]+(?:\\\\|/)).*((?:\\\\|/)[^\\\\/]+(?:\\\\|/)[^\\\\/]+)$");
        std::wstring replacement = L"$1$2...$3";
        std::wstring str2 = std::regex_replace(str, rx, replacement);
        if (str2.size() >= MAX_PATH)
            str2 = str2.substr(0, MAX_PATH-2);
        PathCompactPathEx(pathbuf1, str2.c_str(), MAX_PATH_LENGTH, 0);
    }
    else
        PathCompactPathEx(pathbuf1, filePath.GetWinPath(), MAX_PATH_LENGTH, 0);

    if ((baseRev == 0) && (!filePath.IsUrl()) && (rev1.IsBase() || rev2.IsBase()))
    {
        SVNStatus stat;
        CTSVNPath dummy;
        svn_client_status_t * s = stat.GetFirstFileStatus(filePath, dummy);
        if (s)
            baseRev = s->revision;
    }
    // check for properties that got removed
    for (int baseindex = 0; baseindex < propsbase.GetCount(); ++baseindex)
    {
        std::string basename = propsbase.GetItemName(baseindex);
        tstring basenameU = CUnicodeUtils::StdGetUnicode(basename);
        tstring basevalue = (LPCTSTR)CUnicodeUtils::GetUnicode(propsbase.GetItemValue(baseindex).c_str());
        bool bFound = false;
        for (int wcindex = 0; wcindex < propswc.GetCount(); ++wcindex)
        {
            if (basename.compare (propswc.GetItemName(wcindex))==0)
            {
                bFound = true;
                break;
            }
        }
        if (!bFound)
        {
            // write the old property value to temporary file
            CTSVNPath wcpropfile = CTempFiles::Instance().GetTempFilePath(false);
            CTSVNPath basepropfile = CTempFiles::Instance().GetTempFilePath(false);
            FILE * pFile;
            _tfopen_s(&pFile, wcpropfile.GetWinPath(), L"wb");
            if (pFile)
            {
                fclose(pFile);
                FILE * pFile2;
                _tfopen_s(&pFile2, basepropfile.GetWinPath(), L"wb");
                if (pFile2)
                {
                    fputs(CUnicodeUtils::StdGetUTF8(basevalue).c_str(), pFile2);
                    fclose(pFile2);
                }
                else
                    return false;
            }
            else
                return false;
            SetFileAttributes(wcpropfile.GetWinPath(), FILE_ATTRIBUTE_READONLY);
            SetFileAttributes(basepropfile.GetWinPath(), FILE_ATTRIBUTE_READONLY);
            CString n1, n2;
            bool bSwitch = false;
            if (rev1.IsWorking())
                n1.Format(IDS_DIFF_PROP_WCNAME, basenameU.c_str());
            if (rev1.IsBase())
            {
                if (baseRev)
                    n1.FormatMessage(IDS_DIFF_PROP_BASENAMEREV, basenameU.c_str(), baseRev);
                else
                    n1.Format(IDS_DIFF_PROP_BASENAME, basenameU.c_str());
            }
            if (rev1.IsHead())
                n1.Format(IDS_DIFF_PROP_REMOTENAME, basenameU.c_str());
            if (n1.IsEmpty())
            {
                CString temp;
                temp.Format(IDS_DIFF_REVISIONPATCHED, (LONG)rev1);
                n1 = basenameU.c_str();
                n1 += L" " + temp;
                bSwitch = true;
            }
            else
            {
                n1 = CString(pathbuf1) + L" - " + n1;
            }
            if (rev2.IsWorking())
                n2.Format(IDS_DIFF_PROP_WCNAME, basenameU.c_str());
            if (rev2.IsBase())
            {
                if (baseRev)
                    n2.FormatMessage(IDS_DIFF_PROP_BASENAMEREV, basenameU.c_str(), baseRev);
                else
                    n2.Format(IDS_DIFF_PROP_BASENAME, basenameU.c_str());
            }
            if (rev2.IsHead())
                n2.Format(IDS_DIFF_PROP_REMOTENAME, basenameU.c_str());
            if (n2.IsEmpty())
            {
                CString temp;
                temp.Format(IDS_DIFF_REVISIONPATCHED, (LONG)rev2);
                n2 = basenameU.c_str();
                n2 += L" " + temp;
                bSwitch = true;
            }
            else
            {
                n2 = CString(pathbuf1) + L" - " + n2;
            }
            if (bSwitch)
            {
                retvalue = !!CAppUtils::StartExtDiffProps(wcpropfile, basepropfile, n1, n2, TRUE, TRUE);
            }
            else
            {
                retvalue = !!CAppUtils::StartExtDiffProps(basepropfile, wcpropfile, n2, n1, TRUE, TRUE);
            }
        }
    }

    for (int wcindex = 0; wcindex < propswc.GetCount(); ++wcindex)
    {
        std::string wcname = propswc.GetItemName(wcindex);
        tstring wcnameU = CUnicodeUtils::StdGetUnicode(wcname);
        tstring wcvalue = (LPCTSTR)CUnicodeUtils::GetUnicode(propswc.GetItemValue(wcindex).c_str());
        tstring basevalue;
        bool bDiffRequired = true;
        for (int baseindex = 0; baseindex < propsbase.GetCount(); ++baseindex)
        {
            if (propsbase.GetItemName(baseindex).compare(wcname)==0)
            {
                basevalue = CUnicodeUtils::GetUnicode(propsbase.GetItemValue(baseindex).c_str());
                if (basevalue.compare(wcvalue)==0)
                {
                    // name and value are identical
                    bDiffRequired = false;
                    break;
                }
            }
        }
        if (bDiffRequired)
        {
            // write both property values to temporary files
            CTSVNPath wcpropfile = CTempFiles::Instance().GetTempFilePath(false);
            CTSVNPath basepropfile = CTempFiles::Instance().GetTempFilePath(false);
            FILE * pFile;
            _tfopen_s(&pFile, wcpropfile.GetWinPath(), L"wb");
            if (pFile)
            {
                fputs(CUnicodeUtils::StdGetUTF8(wcvalue).c_str(), pFile);
                fclose(pFile);
                FILE * pFile2;
                _tfopen_s(&pFile2, basepropfile.GetWinPath(), L"wb");
                if (pFile2)
                {
                    fputs(CUnicodeUtils::StdGetUTF8(basevalue).c_str(), pFile2);
                    fclose(pFile2);
                }
                else
                    return false;
            }
            else
                return false;
            SetFileAttributes(wcpropfile.GetWinPath(), FILE_ATTRIBUTE_READONLY);
            SetFileAttributes(basepropfile.GetWinPath(), FILE_ATTRIBUTE_READONLY);
            CString n1, n2;
            if (rev1.IsWorking())
                n1.Format(IDS_DIFF_WCNAME, wcnameU.c_str());
            if (rev1.IsBase())
                n1.Format(IDS_DIFF_BASENAME, wcnameU.c_str());
            if (rev1.IsHead())
                n1.Format(IDS_DIFF_REMOTENAME, wcnameU.c_str());
            if (n1.IsEmpty())
                n1.FormatMessage(IDS_DIFF_PROP_REVISIONNAME, wcnameU.c_str(), (LPCTSTR)rev1.ToString());
            else
                n1 = CString(pathbuf1) + L" - " + n1;
            if (rev2.IsWorking())
                n2.Format(IDS_DIFF_WCNAME, wcnameU.c_str());
            if (rev2.IsBase())
                n2.Format(IDS_DIFF_BASENAME, wcnameU.c_str());
            if (rev2.IsHead())
                n2.Format(IDS_DIFF_REMOTENAME, wcnameU.c_str());
            if (n2.IsEmpty())
                n2.FormatMessage(IDS_DIFF_PROP_REVISIONNAME, wcnameU.c_str(), (LPCTSTR)rev2.ToString());
            else
                n2 = CString(pathbuf1) + L" - " + n2;
            retvalue = !!CAppUtils::StartExtDiffProps(basepropfile, wcpropfile, n2, n1, TRUE, TRUE);
        }
    }
    return retvalue;
}
Example #13
0
/****************************************************************************
**
** Author: Marc Bowes
**
** Replaces emoticon img tags with the shorthand text
**
****************************************************************************/
void Emoticon::HtmlToShorthand(QString &message)
{
  QRegExp rx("<img alt=\"(.*)\" src=\"(.*)\" class=\"emoticon\" />");
  rx.setMinimal(true);
  message.replace(rx, "\\1");
}
Example #14
0
void creditCard::sSave()
{
  bool everythingOK;
  everythingOK = true;

  QString ccname	= _name->text().stripWhiteSpace();
  QString ccAddress1	= _address->line1().stripWhiteSpace();
  QString ccCity	= _address->city().stripWhiteSpace();
  QString ccState	= _address->state().stripWhiteSpace();
  QString ccZip		= _address->postalCode().stripWhiteSpace();
  QString ccCountry	= _address->country().stripWhiteSpace();
  QString ccExpireMonth	= _expireMonth->text().stripWhiteSpace();
  QString ccExpireYear	= _expireYear->text().stripWhiteSpace();

  if (ccExpireMonth.length() == 1)
      ccExpireMonth = "0" + ccExpireMonth;

  int mymonth = ccExpireMonth.toInt();
  int myyear = ccExpireYear.toInt();

  struct {
    bool	condition;
    QString	msg;
    QWidget*	widget;
  } error[] = {
    { ccname.length() == 0 || ccname.isEmpty(),
      tr("The name of the card holder must be entered"), _name },
    { ccAddress1.length() == 0 || ccAddress1.isEmpty(),
      tr("The first address line must be entered"), _address },
    { ccCity.length() == 0 || ccCity.isEmpty(),
      tr("The city must be entered"), _address },
    { ccState.length() == 0 || ccState.isEmpty(),
      tr("The state must be entered"), _address },
    { ccZip.length() == 0 || ccZip.isEmpty(),
      tr("The zip code must be entered"), _address },
    { ccCountry.length() == 0 || ccCountry.isEmpty(),
      tr("The country must be entered"), _address },
    { ccExpireMonth.length() == 0 || ccExpireMonth.isEmpty() || ccExpireMonth.length() > 2,
      tr("The Expiration Month must be entered"), _expireMonth },
    { mymonth < 1 || mymonth > 12,
      tr("Valid Expiration Months are 01 through 12"), _expireMonth },
    { ccExpireYear.length() != 4,
      tr("Valid Expiration Years are CCYY in format"), _expireYear },
    { myyear < 1970 || myyear > 2100,
      tr("Valid Expiration Years are 1970 through 2100"), _expireYear },
    { true, "", NULL }
  };

  int errIndex;
  for (errIndex = 0; ! error[errIndex].condition; errIndex++)
    ;
  if (! error[errIndex].msg.isEmpty())
  {
    QMessageBox::critical(this, tr("Cannot Save Credit Card Information"),
			  error[errIndex].msg);
    error[errIndex].widget->setFocus();
    return;
  }

  if (! _address->line3().isEmpty())
  {
    int answer = QMessageBox::question(this, tr("Third Address Line Ignored"),
				       tr("<p>The third line of the street "
				          "address will not be saved as part "
					  "of the credit card address. The "
					  "OpenMFG credit card interface "
					  "supports only 2 lines of street "
					  "address.</p><p>Continue processing?"),
					QMessageBox::Yes,
					QMessageBox::No | QMessageBox::Default);
    if (answer == QMessageBox::No)
    {
      _address->setFocus();
      return;
    }
  }

  QString key;
  key = omfgThis->_key;

  if (_mode == cNew)
  {
    QString ccnum;
    QString cctype;
    int cceditreturn = 0;
    ccnum = _creditCardNumber->text().stripWhiteSpace();
    cctype = QString(*(_fundsTypes2 + _fundsType2->currentItem()));

// We need to check the validity of the credit card number
    QRegExp rx( "[0-9]{13,16}" );
    bool returnMatch = rx.exactMatch(ccnum);

    if (!returnMatch)
    {
      QMessageBox::warning( this, tr("Invalid Credit Card Number"),
                          tr("The credit card number must be all numeric (no spaces or hyphens) and must be 13, 15 or 16 characters in length") );
      _creditCardNumber->setFocus();
      return;
    }

    if(ccnum.length() == 14)
    {
      QMessageBox::warning( this, tr("Invalid Credit Card Number"),
                          tr("The credit card number must be all numeric (no spaces or hyphens) and must be 13, 15 or 16 characters in length") );
      _creditCardNumber->setFocus();
      return;
    }

    q.prepare("SELECT editccnumber(text(:ccnum), text(:cctype)) AS cc_back;");
    q.bindValue(":ccnum", ccnum);
    q.bindValue(":cctype", cctype);
    q.exec();
    if (q.first())
      cceditreturn = q.value("cc_back").toInt();
    else if (q.lastError().type() != QSqlError::None)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }

    if (cceditreturn == -10)
    { // don't combine into (-10 && !CCtest): continue on -10 if not strict
      if (!_metrics->boolean("CCTest"))
      {
       QMessageBox::warning( this, tr("Invalid Credit Card Number"),
			   storedProcErrorLookup("editccnumber", cceditreturn));
       _creditCardNumber->setFocus();
       return;
      }
    }
    else if (cceditreturn < 0)
    {
      QMessageBox::warning(this, tr("Invalid Credit Card Information"),
			   storedProcErrorLookup("editccnumber", cceditreturn));
      _creditCardNumber->setFocus();
      return;
    }

    q.exec("SELECT NEXTVAL('ccard_ccard_id_seq') AS ccard_id;");
    if (q.first())
      _ccardid = q.value("ccard_id").toInt();
    else if (q.lastError().type() != QSqlError::None)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }

     q.prepare("SELECT COALESCE(MAX(ccard_seq), 0) + 10 AS ccard_seq FROM ccard WHERE ccard_cust_id =:ccard_cust_id;");
    q.bindValue(":ccard_cust_id", _custid);
    q.exec();
    if (q.first())
      _seq = q.value("ccard_seq").toInt();
    else if (q.lastError().type() != QSqlError::None)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }

    q.prepare( "INSERT INTO ccard "
               "( ccard_id, ccard_seq, ccard_cust_id, "
               "  ccard_active, ccard_name, ccard_address1,"
               "  ccard_address2,"
               "  ccard_city, ccard_state, ccard_zip,"
               "  ccard_country, ccard_number,"
               "  ccard_month_expired, ccard_year_expired, ccard_type)"
               "VALUES "
               "( :ccard_id,"
	  "  :ccard_seq,"
	  "  :ccard_cust_id,"
               "  :ccard_active, "
               "  encrypt(setbytea(:ccard_name), setbytea(:key), 'bf'),"
	  " encrypt(setbytea(:ccard_address1), setbytea(:key), 'bf'),"
               "  encrypt(setbytea(:ccard_address2), setbytea(:key), 'bf'),"
               "  encrypt(setbytea(:ccard_city), setbytea(:key), 'bf'),"
	  "  encrypt(setbytea(:ccard_state), setbytea(:key), 'bf'),"
               "  encrypt(setbytea(:ccard_zip), setbytea(:key), 'bf'),"
               "  encrypt(setbytea(:ccard_country), setbytea(:key), 'bf'),"
               "  encrypt(setbytea(:ccard_number), setbytea(:key), 'bf'),"
               "  encrypt(setbytea(:ccard_month_expired), setbytea(:key), 'bf'),"
               "  encrypt(setbytea(:ccard_year_expired), setbytea(:key), 'bf'),"
               "  :ccard_type );" );
  }
  else if (_mode == cEdit)
    q.prepare( "UPDATE ccard "
               "SET ccard_active=:ccard_active, "
               "    ccard_name=encrypt(setbytea(:ccard_name), setbytea(:key), 'bf'),"
	  "    ccard_address1=encrypt(setbytea(:ccard_address1), setbytea(:key), 'bf'),"
               "    ccard_address2=encrypt(setbytea(:ccard_address2), setbytea(:key), 'bf'), "
               "    ccard_city=encrypt(setbytea(:ccard_city), setbytea(:key), 'bf'),"
	  "    ccard_state=encrypt(setbytea(:ccard_state), setbytea(:key), 'bf'),"
	  "    ccard_zip=encrypt(setbytea(:ccard_zip), setbytea(:key), 'bf'),"
               "    ccard_country=encrypt(setbytea(:ccard_country), setbytea(:key), 'bf'),"
               "    ccard_month_expired=encrypt(setbytea(:ccard_month_expired), setbytea(:key), 'bf'),"
               "    ccard_year_expired=encrypt(setbytea(:ccard_year_expired), setbytea(:key), 'bf'),"
	  "    ccard_type=:ccard_type "
               "WHERE (ccard_id=:ccard_id);" );

  q.bindValue(":ccard_id", _ccardid);
  q.bindValue(":ccard_seq", _seq);
  q.bindValue(":ccard_cust_id", _custid);
  q.bindValue(":ccard_active", QVariant(_active->isChecked(), 0));
  q.bindValue(":ccard_number", _creditCardNumber->text().stripWhiteSpace());
  q.bindValue(":ccard_name", _name->text());
  q.bindValue(":ccard_address1", _address->line1());
  q.bindValue(":ccard_address2", _address->line2());
  q.bindValue(":ccard_city",	 _address->city());
  q.bindValue(":ccard_state",	 _address->state());
  q.bindValue(":ccard_zip",	 _address->postalCode());
  q.bindValue(":ccard_country",	 _address->country());
  q.bindValue(":ccard_month_expired",_expireMonth->text());
  q.bindValue(":ccard_year_expired",_expireYear->text());
  q.bindValue(":key", key);
  q.bindValue(":ccard_type", QString(*(_fundsTypes2 + _fundsType2->currentItem())));
  q.exec();
  if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  done(_ccardid);
}
Example #15
0
bool TextItem::isNeedExpandContent() const
{
    QRegExp rx("$*\\{[^{]*\\}");
    return content().contains(rx);
}
Example #16
0
  QByteArray parseAssembly(QTextStream &assembly)
  {
    QByteArray result;

    while (!assembly.atEnd())
    {
        unsigned int instruction = 0;

        QString line1 = assembly.readLine();
        QStringList words = line1.split(' ');


        // parse the instruction name
        if (words[0] == "ADD")
         {
            instruction |= ADD_OP << OP_SHIFT;
            instruction |= ADD_FUNC << FUNC_SHIFT;
         }

        else if (words[0] == "SUB")
         {
             instruction |= SUB_OP << OP_SHIFT;
             instruction |= SUB_FUNC << FUNC_SHIFT;
         }

        else if (words[0] == "ORI")
         {
             instruction |= ORI_OP << OP_SHIFT;
         }

         else if (words[0] == "JUMP")
         {
             instruction |= JMP_OP << OP_SHIFT;
         }

         else if (words[0] == "LW")
         {
             instruction |= LW_OP << OP_SHIFT;
         }

         else if (words[0] == "SW")
         {
             instruction |= SW_OP << OP_SHIFT;
         }

         else if (words[0] == "BEQ_OP")
         {
             instruction |= BEQ_OP << OP_SHIFT;
         }

         else
         {
             Q_ASSERT(false);  // TODO: throw an exception
             return QByteArray();
         }


    switch((instruction & OP_MASK) >> OP_SHIFT)
    {
      case ADD_OP:
//      case SUB_OP:
        {
          // parse the register numbers
          QRegExp rx("^\\s.\\$(\\d+)\\s.,\\s.\\$(\\d+)\\s.,\\s.\\$(\\d+)\\s.$");
          int pos = rx.indexIn(words[1]);

          if(pos < 0)
          {
            Q_ASSERT(false);  // TODO: throw an exception
            return QByteArray();
          }

          QStringList registers = rx.capturedTexts();

          if(registers.length() != 3)
          {
            Q_ASSERT(false);  // TODO: throw an exception
            return QByteArray();
          }

          unsigned int rd = QVariant(registers[0]).toInt();

          if(rd >= NUM_REGISTERS)
          {
            Q_ASSERT(false);  // TODO: throw an exception
            return QByteArray();
          }

          unsigned int rs = QVariant(registers[1]).toInt();

          if(rs >= NUM_REGISTERS)
          {
            Q_ASSERT(false);  // TODO: throw an exception
            return QByteArray();
          }

          unsigned int rt = QVariant(registers[2]).toInt();

          if(rt >= NUM_REGISTERS)
          {
            Q_ASSERT(false);  // TODO: throw an exception
            return QByteArray();
          }

          instruction |= rd << RD_SHIFT;
          instruction |= rs << RS_SHIFT;
          instruction |= rt << RT_SHIFT;
        }

    case ORI_OP:
        //Also for LW,SW,BEQ
    {
          // parse the register numbers
          QRegExp rx("^\\s.\\$(\\d+)\\s.,\\s.\\$(\\d+)\\s.,\\s.\\$(\\d+)\\s.$");
          int pos = rx.indexIn(words[1]);

          if(pos < 0)
          {
            Q_ASSERT(false);  // TODO: throw an exception
            return QByteArray();
          }

          QStringList registers = rx.capturedTexts();

          if(registers.length() != 3)
          {
            Q_ASSERT(false);  // TODO: throw an exception
            return QByteArray();
          }

          unsigned int rs = QVariant(registers[0]).toInt();

          if(rs >= NUM_REGISTERS)
          {
            Q_ASSERT(false);  // TODO: throw an exception
            return QByteArray();
          }

          unsigned int rt = QVariant(registers[1]).toInt();

          if(rt >= NUM_REGISTERS)
          {
            Q_ASSERT(false);  // TODO: throw an exception
            return QByteArray();
          }

          unsigned int IMM16 = QVariant(registers[2]).toInt();

          rs |= IMM16;

          instruction |= rs << RS_SHIFT;
          instruction |= rt << RT_SHIFT;
      }

    case JMP_OP:
      {
          // Parse the target value
          QRegExp rx("^\\s.\\$(\\d+)\\s.,\\s.\\$(\\d+)\\s.,\\s.\\$(\\d+)\\s.$");

          int pos = rx.indexIn(words[1]);

          QStringList target = rx.capturedTexts();

          if(pos < 0)
          {
              Q_ASSERT(false); // TODO: throw an exception
              return QByteArray();
          }

          unsigned int jmp = QVariant(target[0]).toInt();

          if(target.length() > ((1 << 25) - 1))
          {
              Q_ASSERT(false);
              return QByteArray();
          }

          instruction |= jmp << FUNC_SHIFT; // Jump function in our case takes the target value and points to
                                            // an arbitrary value that we will set in a register.
      }



      default:
        Q_ASSERT(false);  // TODO: throw an exception
        return QByteArray();



      }
      result.append(qToLittleEndian(instruction));

    }

    return result;
  }
Example #17
0
bool RClient::parse(int &argc, char **argv)
{
    Rct::findExecutablePath(*argv);
    mSocketFile = Path::home() + ".rdm";

    List<option> options;
    options.reserve(sizeof(opts) / sizeof(Option));
    List<std::shared_ptr<QueryCommand> > projectCommands;

    String shortOptionString;
    Hash<int, Option*> shortOptions, longOptions;
    for (int i=0; opts[i].description; ++i) {
        if (opts[i].option != None) {
            const option opt = { opts[i].longOpt, opts[i].argument, 0, opts[i].shortOpt };
            if (opts[i].shortOpt) {
                shortOptionString.append(opts[i].shortOpt);
                switch (opts[i].argument) {
                case no_argument:
                    break;
                case required_argument:
                    shortOptionString.append(':');
                    break;
                case optional_argument:
                    shortOptionString.append("::");
                    break;
                }
                assert(!shortOptions.contains(opts[i].shortOpt));
                shortOptions[opts[i].shortOpt] = &opts[i];
            }
            if (opts[i].longOpt)
                longOptions[options.size()] = &opts[i];
            options.push_back(opt);
        }
    }

    if (getenv("RTAGS_DUMP_UNUSED")) {
        String unused;
        for (int i=0; i<26; ++i) {
            if (!shortOptionString.contains('a' + i))
                unused.append('a' + i);
            if (!shortOptionString.contains('A' + i))
                unused.append('A' + i);
        }
        printf("Unused: %s\n", unused.constData());
        for (int i=0; opts[i].description; ++i) {
            if (opts[i].longOpt) {
                if (!opts[i].shortOpt) {
                    printf("No shortoption for %s\n", opts[i].longOpt);
                } else if (opts[i].longOpt[0] != opts[i].shortOpt) {
                    printf("Not ideal option for %s|%c\n", opts[i].longOpt, opts[i].shortOpt);
                }
            }
        }
        return 0;
    }

    {
        const option opt = { 0, 0, 0, 0 };
        options.push_back(opt);
    }

    Path logFile;
    unsigned logFlags = 0;

    enum State {
        Parsing,
        Done,
        Error
    } state = Parsing;
    while (true) {
        int idx = -1;
        const int c = getopt_long(argc, argv, shortOptionString.constData(), options.data(), &idx);
        switch (c) {
        case -1:
            state = Done;
            break;
        case '?':
        case ':':
            state = Error;
            break;
        default:
            break;
        }
        if (state != Parsing)
            break;

        const Option *opt = (idx == -1 ? shortOptions.value(c) : longOptions.value(idx));
        assert(opt);

        switch (opt->option) {
        case None:
            assert(0);
            break;
        case Help:
            help(stdout, argv[0]);
            return 0;
        case Man:
            man();
            return 0;
        case SocketFile:
            mSocketFile = optarg;
            break;
        case IMenu:
            mQueryFlags |= QueryMessage::IMenu;
            break;
        case ContainingFunction:
            mQueryFlags |= QueryMessage::ContainingFunction;
            break;
        case DeclarationOnly:
            mQueryFlags |= QueryMessage::DeclarationOnly;
            break;
        case FindVirtuals:
            mQueryFlags |= QueryMessage::FindVirtuals;
            break;
        case FindFilePreferExact:
            mQueryFlags |= QueryMessage::FindFilePreferExact;
            break;
        case CursorInfoIncludeParents:
            mQueryFlags |= QueryMessage::CursorInfoIncludeParents;
            break;
        case CursorInfoIncludeTargets:
            mQueryFlags |= QueryMessage::CursorInfoIncludeTargets;
            break;
        case CursorInfoIncludeReferences:
            mQueryFlags |= QueryMessage::CursorInfoIncludeReferences;
            break;
        case CursorKind:
            mQueryFlags |= QueryMessage::CursorKind;
            break;
        case CodeComplete:
            // logFile = "/tmp/rc.log";
            mCommands.append(std::shared_ptr<RCCommand>(new CompletionCommand));
            break;
        case Context:
            mContext = optarg;
            break;
        case CodeCompleteAt: {
            const String arg = optarg;
            List<RegExp::Capture> caps;
            RegExp rx("^\\(.*\\):\\([0-9][0-9]*\\):\\([0-9][0-9]*\\)$");
            if (rx.indexIn(arg, 0, &caps) != 0 || caps.size() != 4) {
                fprintf(stderr, "Can't decode argument for --code-complete-at [%s]\n", optarg);
                return false;
            }
            const Path path = Path::resolved(caps[1].capture, Path::MakeAbsolute);
            if (!path.exists()) {
                fprintf(stderr, "Can't decode argument for --code-complete-at [%s]\n", optarg);
                return false;
            }

            String out;
            {
                Serializer serializer(out);
                serializer << path << atoi(caps[2].capture.constData()) << atoi(caps[3].capture.constData());
            }
            CompletionCommand *cmd = new CompletionCommand(path, atoi(caps[2].capture.constData()), atoi(caps[3].capture.constData()));
            mCommands.append(std::shared_ptr<RCCommand>(cmd));
            break; }
        case DisplayName:
            mQueryFlags |= QueryMessage::DisplayName;
            break;
        case AllReferences:
            mQueryFlags |= QueryMessage::AllReferences;
            break;
        case MatchCaseInsensitive:
            mQueryFlags |= QueryMessage::MatchCaseInsensitive;
            break;
        case MatchRegexp:
            mQueryFlags |= QueryMessage::MatchRegexp;
            break;
        case AbsolutePath:
            mQueryFlags |= QueryMessage::AbsolutePath;
            break;
        case ReverseSort:
            mQueryFlags |= QueryMessage::ReverseSort;
            break;
        case ElispList:
            mQueryFlags |= QueryMessage::ElispList;
            break;
        case FilterSystemHeaders:
            mQueryFlags |= QueryMessage::FilterSystemIncludes;
            break;
        case NoContext:
            mQueryFlags |= QueryMessage::NoContext;
            break;
        case PathFilter: {
            Path p = optarg;
            p.resolve();
            mPathFilters.insert(p);
            break; }
        case RangeFilter: {
            List<RegExp::Capture> caps;
            RegExp rx("^\\([0-9][0-9]*\\)-\\([0-9][0-9]*\\)$");
            if (rx.indexIn(optarg, 0, &caps) != 0 || caps.size() != 3) {
                fprintf(stderr, "Can't parse range, must be uint-uint. E.g. 1-123\n");
                return false;
            } else {
                mMinOffset = atoi(caps.at(1).capture.constData());
                mMaxOffset = atoi(caps.at(2).capture.constData());
                if (mMaxOffset <= mMinOffset || mMinOffset < 0) {
                    fprintf(stderr, "Invalid range (%d-%d), must be uint-uint. E.g. 1-123\n", mMinOffset, mMaxOffset);
                    return false;
                }
            }
            break; }
        case LineNumbers:
            mQueryFlags |= QueryMessage::LineNumbers;
            break;
        case Verbose:
            ++mLogLevel;
            break;
        case Silent:
            mLogLevel = -1;
            break;
        case LogFile:
            logFile = optarg;
            break;
        case StripParen:
            mQueryFlags |= QueryMessage::StripParentheses;
            break;
        case ConnectTimeout:
            mConnectTimeout = atoi(optarg);
            if (mConnectTimeout < 0) {
                fprintf(stderr, "--connect-timeout [arg] must be >= 0\n");
                return false;
            }
            break;
        case Max:
            mMax = atoi(optarg);
            if (mMax <= 0) {
                fprintf(stderr, "-M [arg] must be positive integer\n");
                return false;
            }
            break;
        case Timeout:
            mTimeout = atoi(optarg);
            if (mTimeout <= 0) {
                fprintf(stderr, "-y [arg] must be positive integer\n");
                return false;
            }
            break;
        case UnsavedFile: {
            const String arg(optarg);
            const int colon = arg.lastIndexOf(':');
            if (colon == -1) {
                fprintf(stderr, "Can't parse -u [%s]\n", optarg);
                return false;
            }
            const int bytes = atoi(arg.constData() + colon + 1);
            if (!bytes) {
                fprintf(stderr, "Can't parse -u [%s]\n", optarg);
                return false;
            }
            const Path path = Path::resolved(arg.left(colon), Path::MakeAbsolute);
            if (!path.isFile()) {
                fprintf(stderr, "Can't open [%s] for reading\n", arg.left(colon).nullTerminated());
                return false;
            }

            String contents(bytes, '\0');
            const int r = fread(contents.data(), 1, bytes, stdin);
            if (r != bytes) {
                fprintf(stderr, "Read error %d (%s). Got %d, expected %d\n",
                        errno, strerror(errno), r, bytes);
                return false;
            }
            mUnsavedFiles[path] = contents;
            break; }
        case FollowLocation:
        case CursorInfo:
        case ReferenceLocation: {
            const String encoded = Location::encodeClientLocation(optarg);
            if (encoded.isEmpty()) {
                fprintf(stderr, "Can't resolve argument %s\n", optarg);
                return false;
            }
            QueryMessage::Type type = QueryMessage::Invalid;
            switch (opt->option) {
            case FollowLocation: type = QueryMessage::FollowLocation; break;
            case CursorInfo: type = QueryMessage::CursorInfo; break;
            case ReferenceLocation: type = QueryMessage::ReferencesLocation; break;
            default: assert(0); break;
            }
            addQuery(type, encoded);
            break; }
        case WithProject:
            mProjects.append(optarg);
            break;
        case ReloadFileManager:
            addQuery(QueryMessage::ReloadFileManager);
            break;
        case ReloadProjects:
            addQuery(QueryMessage::ReloadProjects);
            break;
        case Clear:
            addQuery(QueryMessage::ClearProjects);
            break;
        case RdmLog:
            addLog(RdmLogCommand::Default);
            break;
        case Diagnostics:
            addLog(RTags::CompilationError);
            break;
        case XmlDiagnostics:
            addLog(RTags::CompilationErrorXml);
            break;
        case QuitRdm:
            addQuery(QueryMessage::Shutdown);
            break;
        case DeleteProject:
            addQuery(QueryMessage::DeleteProject, optarg);
            break;
        case CodeCompletionEnabled:
            addQuery(QueryMessage::CodeCompletionEnabled);
            break;
        case UnloadProject:
            addQuery(QueryMessage::UnloadProject, optarg);
            break;
        case FindProjectRoot: {
            const Path p = Path::resolved(optarg);
            printf("findProjectRoot [%s] => [%s]\n", p.constData(),
                   RTags::findProjectRoot(p).constData());
            return 0; }
        case Reindex:
        case Project:
        case FindFile:
        case ListSymbols:
        case FindSymbols:
        case JSON:
        case Builds:
        case JobCount:
        case Status: {
            QueryMessage::Type type = QueryMessage::Invalid;
            switch (opt->option) {
            case Reindex: type = QueryMessage::Reindex; break;
            case Project: type = QueryMessage::Project; break;
            case FindFile: type = QueryMessage::FindFile; break;
            case Builds: type = QueryMessage::Builds; break;
            case Status: type = QueryMessage::Status; break;
            case JSON: type = QueryMessage::JSON; break;
            case ListSymbols: type = QueryMessage::ListSymbols; break;
            case FindSymbols: type = QueryMessage::FindSymbols; break;
            case JobCount: type = QueryMessage::JobCount; break;
            default: assert(0); break;
            }

            if (optarg) {
                addQuery(type, optarg);
            } else if (optind < argc && argv[optind][0] != '-') {
                addQuery(type, argv[optind++]);
            } else {
                addQuery(type);
            }
            assert(!mCommands.isEmpty());
            if (type == QueryMessage::Project)
                projectCommands.append(std::static_pointer_cast<QueryCommand>(mCommands.back()));
            break; }
        case LoadCompilationDatabase: {
            Path dir;
            if (optarg) {
                dir = optarg;
            } else if (optind < argc && argv[optind][0] != '-') {
                dir = argv[optind++];
            } else {
                dir = Path::pwd();
            }
            dir.resolve(Path::MakeAbsolute);
            if (!dir.exists()) {
                fprintf(stderr, "%s does not seem to exist\n", dir.constData());
                return false;
            }
            if (!dir.isDir()) {
                fprintf(stderr, "%s is not a directory\n", dir.constData());
                return false;
            }
            if (!dir.endsWith('/'))
                dir += '/';
            const Path file = dir + "compile_commands.json";
            if (!file.isFile()) {
                fprintf(stderr, "no compile_commands.json file in %s\n", dir.constData());
                return false;
            }
            addQuery(QueryMessage::LoadCompilationDatabase, dir);
            break; }
        case HasFileManager: {
            Path p;
            if (optarg) {
                p = optarg;
            } else if (optind < argc && argv[optind][0] != '-') {
                p = argv[optind++];
            } else {
                p = ".";
            }
            p.resolve(Path::MakeAbsolute);
            if (!p.exists()) {
                fprintf(stderr, "%s does not seem to exist\n", optarg);
                return false;
            }
            if (p.isDir())
                p.append('/');
            addQuery(QueryMessage::HasFileManager, p);
            break; }
        case SuspendFile: {
            Path p;
            if (optarg) {
                p = optarg;
            } else if (optind < argc && argv[optind][0] != '-') {
                p = argv[optind++];
            }
            if (!p.isEmpty()) {
                if (p == "clear" && !p.exists()) {

                } else {
                    p.resolve(Path::MakeAbsolute);
                    if (!p.isFile() && p != "clear") {
                        fprintf(stderr, "%s is not a file\n", optarg);
                        return false;
                    }
                }
            }
            addQuery(QueryMessage::SuspendFile, p);
            break; }
        case Compile: {
            String args = optarg;
            while (optind < argc) {
                args.append(' ');
                args.append(argv[optind++]);
            }
            addCompile(Path::pwd(), args);
            break; }
        case IsIndexing:
            addQuery(QueryMessage::IsIndexing);
            break;
        case IsIndexed:
        case DumpFile:
        case Dependencies:
        case FixIts: {
            Path p = optarg;
            if (!p.exists()) {
                fprintf(stderr, "%s does not exist\n", optarg);
                return false;
            }

            if (!p.isAbsolute())
                p.prepend(Path::pwd());

            if (p.isDir()) {
                if (opt->option != IsIndexed) {
                    fprintf(stderr, "%s is not a file\n", optarg);
                    return false;
                } else if (!p.endsWith('/')) {
                    p.append('/');
                }
            }
            QueryMessage::Type type = QueryMessage::Invalid;
            switch (opt->option) {
            case Dependencies: type = QueryMessage::Dependencies; break;
            case FixIts: type = QueryMessage::FixIts; break;
            case IsIndexed: type = QueryMessage::IsIndexed; break;
            case DumpFile: type = QueryMessage::DumpFile; break;
            default: assert(0); break;
            }

            addQuery(type, p);
            break; }
        case PreprocessFile: {
            Path p = optarg;
            p.resolve(Path::MakeAbsolute);
            if (!p.isFile()) {
                fprintf(stderr, "%s is not a file\n", optarg);
                return false;
            }
            addQuery(QueryMessage::PreprocessFile, p);
            break; }

        case RemoveFile: {
            const Path p = Path::resolved(optarg, Path::MakeAbsolute);
            if (!p.exists()) {
                addQuery(QueryMessage::RemoveFile, p);
            } else {
                addQuery(QueryMessage::RemoveFile, optarg);
            }
            break; }
        case ReferenceName:
            addQuery(QueryMessage::ReferencesName, optarg);
            break;
        }
    }
    if (state == Error) {
        help(stderr, argv[0]);
        return false;
    }

    if (optind < argc) {
        fprintf(stderr, "rc: unexpected option -- '%s'\n", argv[optind]);
        return false;
    }

    if (!initLogging(argv[0], LogStderr, mLogLevel, logFile, logFlags)) {
        fprintf(stderr, "Can't initialize logging with %s %d %d %s 0x%0x\n",
                argv[0], LogStderr, mLogLevel, logFile.constData(), logFlags);
        return false;
    }


    if (mCommands.isEmpty()) {
        help(stderr, argv[0]);
        return false;
    }
    if (mCommands.size() > projectCommands.size()) {
        // If there's more than one command one likely does not want output from
        // the queryCommand (unless there's no arg specified for it). This is so
        // we don't have to pass a different flag for auto-updating project
        // using the current buffer but rather piggy-back on --project
        const int count = projectCommands.size();
        for (int i=0; i<count; ++i) {
            std::shared_ptr<QueryCommand> &cmd = projectCommands[i];
            if (!cmd->query.isEmpty()) {
                cmd->extraQueryFlags |= QueryMessage::Silent;
            }
        }
    }

    if (!logFile.isEmpty() || mLogLevel > 0) {
        Log l(1);
        l << argc;
        for (int i = 0; i < argc; ++i)
            l << " " << argv[i];
    }
    mArgc = argc;
    mArgv = argv;

    return true;
}
Example #18
0
Service::Result ArtistInfo::processData(const std::string &data)
{
	size_t a, b;
	Service::Result result;
	result.first = false;
	
	boost::regex rx("<content>(.*?)</content>");
	boost::smatch what;
	if (boost::regex_search(data, what, rx))
	{
		std::string desc = what[1];
		// if there is a description...
		if (desc.length() > 0)
		{
			// ...locate the link to wiki on last.fm...
			rx.assign("<link rel=\"original\" href=\"(.*?)\"");
			if (boost::regex_search(data, what, rx))
			{
				// ...try to get the content of it...
				std::string wiki;
				CURLcode code = Curl::perform(wiki, what[1]);
				
				if (code != CURLE_OK)
				{
					result.second = curl_easy_strerror(code);
					return result;
				}
				else
				{
					// ...and filter it to get the whole description.
					rx.assign("<div id=\"wiki\">(.*?)</div>");
					if (boost::regex_search(wiki, what, rx))
						desc = unescapeHtmlUtf8(what[1]);
				}
			}
			else
			{
				// otherwise, get rid of CDATA wrapper.
				rx.assign("<!\\[CDATA\\[(.*)\\]\\]>");
				desc = boost::regex_replace(desc, rx, "\\1");
			}
			stripHtmlTags(desc);
			boost::trim(desc);
			result.second += desc;
		}
		else
			result.second += "No description available for this artist.";
	}
	else
	{
		result.second = msgInvalidResponse;
		return result;
	}
	
	auto add_similars = [&result](boost::sregex_iterator &it, const boost::sregex_iterator &last) {
		for (; it != last; ++it)
		{
			std::string value = it->str(1);
			std::string url = it->str(2);
			stripHtmlTags(value);
			stripHtmlTags(url);
			result.second += "\n * ";
			result.second += value;
			result.second += " (";
			result.second += url;
			result.second += ")";
		}
	};
	
	a = data.find("<similar>");
	b = data.find("</similar>");
	if (a != std::string::npos && b != std::string::npos)
	{
		rx.assign("<artist>.*?<name>(.*?)</name>.*?<url>(.*?)</url>.*?</artist>");
		auto it = boost::sregex_iterator(data.begin()+a, data.begin()+b, rx);
		auto last = boost::sregex_iterator();
		if (it != last)
			result.second += "\n\nSimilar artists:\n";
		add_similars(it, last);
	}
	
	a = data.find("<tags>");
	b = data.find("</tags>");
	if (a != std::string::npos && b != std::string::npos)
	{
		rx.assign("<tag>.*?<name>(.*?)</name>.*?<url>(.*?)</url>.*?</tag>");
		auto it = boost::sregex_iterator(data.begin()+a, data.begin()+b, rx);
		auto last = boost::sregex_iterator();
		if (it != last)
			result.second += "\n\nSimilar tags:\n";
		add_similars(it, last);
	}
	
	// get artist we look for, it's the one before similar artists
	rx.assign("<name>.*?</name>.*?<url>(.*?)</url>.*?<similar>");
	
	if (boost::regex_search(data, what, rx))
	{
		std::string url = what[1];
		stripHtmlTags(url);
		result.second += "\n\n";
		// add only url
		result.second += url;
	}
	
	result.first = true;
	return result;
}
Example #19
0
void ImageThread::processRequestResponse(QUrl url, QByteArray ba, bool cached) {
    QString requestURI;
    QList<_IMAGE>   imageList;
    QList<QUrl>     threadList;
    ParsingStatus   status;
    QString         path;
    qint64 bytesWritten;

    QLOG_TRACE() << "ImageThread :: processRequestResponse (" << url.toString() << ", " << QString(ba);

    requestURI = url.toString();
    path = url.path();

    if (isImage(url)) {
        QFile f;
        QRegExp rx(__IMAGEFILE_REGEXP__, Qt::CaseInsensitive, QRegExp::RegExp2);
        QStringList res;
        int pos;

        pos = 0;

        pos = rx.indexIn(requestURI);
        res = rx.capturedTexts();

        if (pos != -1) {
            f.setFileName(getSavepath()+"/"+res.at(1)+res.at(2));

            if (_saveWithOriginalFilename) {
                _IMAGE tmp;

                for (int i=0; i<images.count(); i++) {
                    if (images.at(i).largeURI.endsWith("/"+res.at(1)+res.at(2))) {
                        tmp = images.at(i);

                        f.setFileName(getSavepath()+"/"+tmp.originalFilename);
                        break;
                    }
                }
            }

            f.open(QIODevice::ReadWrite);
            bytesWritten = f.write(ba);
            f.close();

            if (bytesWritten == ba.size()) {
                setCompleted(requestURI, f.fileName());
            }
            else {
                QLOG_ERROR() << "UIImageOverview :: Couldn't save file from URI " << url.toString();
            }
        }

    }
    else {
        iParser->setURL(url);
        status = iParser->parseHTML(ba);

        if (status.hasErrors) {
            QLOG_ERROR() << "ImageOverview :: Parser error " << iParser->getErrorCode();
            switch (iParser->getErrorCode()) {
            case 404:
                stopDownload();
                processCloseRequest();
                break;

            default:
                break;
            }
        }
        else {
            if (status.isFrontpage) {
                QStringList newTab;
                QString v;

                v = getValues();
                newTab = v.split(";;");
                threadList = iParser->getUrlList();

                foreach (QUrl u, threadList) {
                    newTab.replace(0, u.toString());
                    emit createThreadRequest(newTab.join(";;"));
                }

                if (settings->value("options/close_overview_threads", true).toBool()) {
                    emit closeRequest(this, 0);
                }
            }
            else {
                if (status.hasImages) {
Example #20
0
BarcodeGenerator::BarcodeGenerator(QWidget* parent, const char* name)
	: QDialog(parent),
	  paintBarcodeTimer(NULL)
{
	ui.setupUi(this);
	setObjectName(name);
	setModal(true);

	connect(&thread, SIGNAL(renderedImage(QString)),this, SLOT(updatePreview(QString)));

	/*
	 *  We extract the barcode information from the BWIPP metadata which looks like this:
	 *
	 *  % --BEGIN ENCODER gs1-128--
	 *  % --REQUIRES preamble raiseerror renlinear code128--
	 *  % --DESC: GS1-128
	 *  % --EXAM: (01)95012345678903(3103)000123
	 *  % --EXOP: includetext
	 *  % --RNDR: renlinear
	 *
	 */

	QFile f(ScPaths::instance().shareDir() + QString("/plugins/barcode.ps"));
	if(!f.open(QIODevice::ReadOnly))
	{
		qDebug()<<"Barcodegenerator unable to open "<<f.fileName();
		return;
	}
	QTextStream ts(&f);
	QString bwipp = ts.readAll();
	f.close();

	QRegExp rx(
		"[\\r\\n]+% --BEGIN (RESOURCE|RENDERER|ENCODER) ([\\w-]+)--[\\r\\n]+"
		"(.*[\\r\\n]+)?"
		"(%%BeginResource.*[\\r\\n]+)"
		"% --END \\1 \\2--[\\r\\n]+");
	rx.setMinimal(true);
	int pos = 0;
	while ( (pos = rx.indexIn(bwipp, pos)) != -1 )
	{
		int len=rx.matchedLength();
		QString restype=rx.cap(1);
	 	QString resname=rx.cap(2);
	 	QString reshead=rx.cap(3);
	 	QString resbody=rx.cap(4);

	 	resbodys[resname]=resbody;

	 	if (restype=="ENCODER")
		{
			QRegExp rxhead(
				"% --REQUIRES (.*)--[\\r\\n]+"
				"% --DESC:(.*)[\\r\\n]+"
				"% --EXAM:(.*)[\\r\\n]+"
				"% --EXOP:(.*)[\\r\\n]+"
				"% --RNDR:(.*)[\\r\\n]+"
			);
			rxhead.indexIn(reshead);
			resreqs[resname]=rxhead.cap(1).trimmed();
			resdescs[resname]=rxhead.cap(2).trimmed();
			resexams[resname]=rxhead.cap(3).trimmed();
			resexops[resname]=rxhead.cap(4).trimmed();
			resrndrs[resname]=rxhead.cap(5).trimmed();
			encoderlist.append(resname);
	 	}
		pos+=len;
	}

	foreach (const QString& enc, encoderlist)
		map[resdescs[enc]] = BarcodeType(enc, resexams[enc], resexops[enc]);

	/*
	 *  Ultimately all of this static data about the capabilities of each barcode
	 *  encoder will be replaced by data read from the barcode.ps metadata, when 
	 *  such data exists...
	 *
	 */ 

	// Content for the version and ecc combos
	resvers["qrcode"]="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40";
	resecls["qrcode"]="L,Q,M,H";
	resvers["gs1qrcode"]=resvers["qrcode"];
	resecls["gs1qrcode"]=resecls["qrcode"];
	resvers["hibcqrcode"]=resvers["qrcode"];
	resecls["hibcqrcode"]=resecls["qrcode"];
	resvers["microqrcode"]="M1,M2,M3,M4";
	resecls["microqrcode"]="L,Q,M,H";
	resvers["datamatrix"]="10x10,12x12,14x14,16x16,18x18,20x20,22x22,24x24,26x26,32x32,36x36,40x40,44x44,48x48,52x52,64x64,72x72,80x80,88x88,96x96,104x104,120x120,132x132,144x144,8x18,8x32,12x26,12x36,16x36,16x48";
	resecls["datamatrix"]="";
	resvers["gs1datamatrix"]=resvers["datamatrix"];
	resecls["gs1datamatrix"]=resvers["datamatrix"];
	resvers["hibcdatamatrix"]=resvers["datamatrix"];
	resecls["hibcdatamatrix"]=resecls["datamatrix"];
	resvers["azteccode"]="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32";
	resvlbl["azteccode"]="Layers";
	resecls["azteccode"]="5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95";
	resvers["azteccodecompact"]="1,2,3,4";
	resvlbl["azteccodecompact"]=resvlbl["azteccode"];
	resecls["azteccodecompact"]=resecls["azteccode"];
	resvers["pdf417"]="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30";
	resvlbl["pdf417"]="Columns";
	resecls["pdf417"]="1,2,3,4,5";
	resvers["pdf417compact"]=resvers["pdf417"];
	resvlbl["pdf417compact"]=resvlbl["pdf417"];
	resecls["pdf417compact"]=resecls["pdf417"];
	resvers["hibcpdf417"]=resvers["pdf417"];
	resvlbl["hibcpdf417"]=resvlbl["pdf417"];
	resecls["hibcpdf417"]=resecls["pdf417"];
	resvers["micropdf417"]="1x11,1x14,1x17,1x20,1x24,1x28,2x8,2x11,2x14,2x17,2x20,2x23,2x26,3x6,3x8,3x10,3x12,3x15,3x20,3x26,3x32,3x38,3x44,4x4,4x6,4x8,4x10,4x12,4x15,4x20,4x26,4x32,4x38,4x44";
	resecls["micropdf417"]="";
	resvers["hibcmicropdf417"]=resvers["micropdf417"];
	resecls["hibcmicropdf417"]=resecls["micropdf417"];
	resvers["hanxin"]="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84";
	resecls["hanxin"]="L1,L2,L3,L4";


	// Which options checkboxes are enabled for each encoder
	QStringList includetextAvail=encoderlist;
	foreach (const QString& enc, includetextAvail)
		resincludetextAvail[enc]=true; 

	QStringList guardwhitespaceAvail;
	guardwhitespaceAvail << "ean13" << "ean8" << "isbn" << "ismn" << "issn" << "ean13composite" << "ean8composite";
	foreach (const QString& enc, guardwhitespaceAvail)
		resguardwhitespaceAvail[enc]=true; 

	QStringList includecheckAvail;
	includecheckAvail << "bc412" << "channelcode" << "code11" << "code2of5" << "coop2of5" << "datalogic2of5"
					  << "iata2of5" << "industrial2of5" << "matrix2of5" << "code39" << "code39ext"
					  << "code93" << "code93ext" << "interleaved2of5" << "msi" << "rationalizedCodabar";
	foreach (const QString& enc, includecheckAvail)
		resincludecheckAvail[enc]=true; 

	QStringList includecheckintextAvail;
	includecheckintextAvail << "bc412" << "code11" << "code2of5" << "coop2of5" << "datalogic2of5" << "iata2of5"
							<< "industrial2of5" << "matrix2of5" << "code39" << "code39ext" << "interleaved2of5"
							<< "japanpost" << "msi" << "planet" << "plessey" << "postnet" << "rationalizedCodabar" << "royalmail";
	foreach (const QString& enc, includecheckintextAvail)
		resincludecheckintextAvail[enc]=true; 

	QStringList parseAvail;
	parseAvail << "azteccode" << "azteccodecompact" << "codablockf" << "hibccodablockf" << "code128" << "hibccode128" << "code16k" << "code39ext" << "code49"
			   << "code93ext" << "codeone" << "datamatrix" << "hibcdatamatrix" << "maxicode" << "micropdf417" << "hibcmicropdf417" << "pdf417" << "hibcpdf417"
			   << "pdf417compact" << "posicode" << "qrcode" << "hibcqrcode" << "microqrcode" << "telepen" << "hanxin";
	foreach (const QString& enc, parseAvail)
		resparseAvail[enc]=true; 

	QStringList parsefncAvail;
	parsefncAvail << "codablockf" << "code128" << "code16k" << "code49" << "code93" << "codeone"
				  << "datamatrix" << "posicode" << "qrcode" << "microqrcode";
	foreach (const QString& enc, parsefncAvail)
		resparsefncAvail[enc]=true; 

	// Building up the bcFamilyCombo grouping the formats for readablity
	ui.bcFamilyCombo->addItem(tr("Select a barcode family")); // to prevent 1st gs call
	ui.bcFamilyCombo->insertSeparator(999);

	// Building up the bcCombo grouping the formats for readablity
	ui.bcCombo->addItem(tr("Select a barcode format")); // to prevent 1st gs call
	ui.bcCombo->insertSeparator(999);

	QString familyName;
	QStringList bcNames;
	bcNames << "EAN-13" << "EAN-8" << "UPC-A" << "UPC-E" << "ISBN" << "ISMN" << "ISSN";
	familyName = tr("Point of Sale");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "GS1-14" << "GS1 Data Matrix" << "GS1 QR Code" << "GS1-128" << "ITF-14" << "SSCC-18";
	familyName = tr("Supply Chain");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "QR Code" << "Micro QR Code" << "Data Matrix" << "Aztec Code" << "Compact Aztec Code"
			<< "Aztec Runes" << "PDF417" << "Compact PDF417" << "MicroPDF417" << "Han Xin Code";
	familyName = tr("Two-dimensional symbols");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "Code 128" << "Code 39" << "Code 39 Extended" << "Code 93" << "Code 93 Extended"
			<< "Interleaved 2 of 5 (ITF)";
	familyName = tr("One-dimensional symbols");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "GS1 DataBar Omnidirectional" << "GS1 DataBar Stacked Omnidirectional"
			<< "GS1 DataBar Expanded" << "GS1 DataBar Expanded Stacked" << "GS1 DataBar Truncated"
			<< "GS1 DataBar Stacked" << "GS1 DataBar Limited";
	familyName = tr("GS1 DataBar family");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "AusPost 4 State Customer Code" << "Deutsche Post Identcode" << "Deutsche Post Leitcode"
			<< "Japan Post 4 State Customer Code" << "Royal Dutch TPG Post KIX"
			<< "Royal Mail 4 State Customer Code" << "USPS Intelligent Mail" << "USPS PLANET" << "USPS POSTNET";
	familyName = tr("Postal symbols");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "Italian Pharmacode" << "Pharmaceutical Binary Code" << "Two-track Pharmacode"
			<< "Pharmazentralnummer (PZN)" << "HIBC Codablock F" << "HIBC Code 128" << "HIBC Code 39"
			<< "HIBC Data Matrix" << "HIBC MicroPDF417" << "HIBC PDF417" << "HIBC QR Code";
	familyName = tr("Pharmaceutical symbols");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "Code 11" << "Codabar" << "Code 25" << "COOP 2 of 5" << "Datalogic 2 of 5" << "IATA 2 of 5"
			<< "Industrial 2 of 5" << "Matrix 2 of 5" << "MSI Modified Plessey" << "Plessey UK"
			<< "PosiCode" << "Telepen" << "Telepen Numeric"<< "Code 16K" << "Codablock F" << "Code 49"
			<< "Code One";
	familyName = tr("Less-used symbols");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "EAN-13 Composite" << "EAN-8 Composite" << "UPC-A Composite" << "UPC-E Composite"
			<< "GS1 DataBar Omnidirectional Composite" << "GS1 DataBar Stacked Omnidirectional Composite"
			<< "GS1 DataBar Expanded Composite" << "GS1 DataBar Expanded Stacked Composite"
			<< "GS1 DataBar Truncated Composite" << "GS1 DataBar Stacked Composite"
			<< "GS1 DataBar Limited Composite" << "GS1-128 Composite";
	familyName = tr("GS1 Composite symbols");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	ui.bcFamilyCombo->addItems(familyList);

	/*
	 *  End of the hard-coded data 
	 *
	 */

	guiColor = ui.codeEdit->palette().color(QPalette::Window);

	ui.okButton->setText(CommonStrings::tr_OK);
	ui.cancelButton->setText(CommonStrings::tr_Cancel);
	ui.resetButton->setIcon(IconManager::instance()->loadIcon("u_undo16.png"));

	if (ScCore->primaryMainWindow()->doc->PageColors.contains("Black"))
	{
		lnColor = ScCore->primaryMainWindow()->doc->PageColors["Black"];
		txtColor = ScCore->primaryMainWindow()->doc->PageColors["Black"];
		ui.linesLabel->setToolTip("Black");
		ui.txtLabel->setToolTip("Black");
	}
	else
	{
		ui.linesLabel->setToolTip("n.a.");
		ui.txtLabel->setToolTip("n.a.");
	}
	if (ScCore->primaryMainWindow()->doc->PageColors.contains("White"))
	{
		bgColor = ScCore->primaryMainWindow()->doc->PageColors["White"];
		ui.bgLabel->setToolTip("White");
	}
	else
		ui.bgLabel->setToolTip("n.a.");

	paintColorSample(ui.linesLabel, lnColor);
	paintColorSample(ui.txtLabel, txtColor);
	paintColorSample(ui.bgLabel, bgColor);

	paintBarcodeTimer=new QTimer(this);
	paintBarcodeTimer->setSingleShot(true);
	connect(paintBarcodeTimer, SIGNAL(timeout()), this, SLOT(paintBarcode()));

	connect(ui.bcFamilyCombo, SIGNAL(activated(QString)), this, SLOT(bcFamilyComboChanged()));
	connect(ui.bcCombo, SIGNAL(activated(QString)), this, SLOT(bcComboChanged()));
	connect(ui.bgColorButton, SIGNAL(clicked()), this, SLOT(bgColorButton_pressed()));
	connect(ui.lnColorButton, SIGNAL(clicked()), this, SLOT(lnColorButton_pressed()));
	connect(ui.txtColorButton, SIGNAL(clicked()), this, SLOT(txtColorButton_pressed()));
	connect(ui.okButton, SIGNAL(clicked()), this, SLOT(okButton_pressed()));
	connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(cancelButton_pressed()));
	connect(ui.codeEdit, SIGNAL(textChanged(QString)), this, SLOT(codeEdit_textChanged(QString)));
	connect(ui.resetButton, SIGNAL(clicked()), this, SLOT(resetButton_clicked()));
	bcComboChanged();

}
Example #21
0
void CRootItem::patch(std::string diff) throw(ExMalformedPatch) {
	istringstream iss(diff);

	CCategoryItem* parent = 0;

	bool new_category = true;
    boost::regex rx("^@@ -(\\d+),(\\d+)\\s+\\+(\\d+),(\\d+)\\s*@@$");
    int oldStart(0);
	int oldLen(0);
	int newStart(0);
	int newLen(0);

	int lineNr = 0;
	int patchLineNr = 0;
	int chunkSizeSum = 0;

	string line;

	while(!iss.eof()) {
		getline(iss, line);
		if(iss.bad()) {
			cerr << "CRootItem::patch: Error reading lines." << endl;
		}
		patchLineNr++;

		if( line.find("+++ ") == 0 ) {
			// new or modified category
			string path = line.substr(4, line.size() - 4);
			parent = getCategoryPtr(path);
			if(parent == 0) {
				parent = mkPath(path);
			}
			new_category = true;
			chunkSizeSum = 0;
		}
		else if(line.find("--- ") == 0) {
			// remove a complete category
			string path = line.substr(4, line.size() - 4);
			CCategoryItem *categoryToRemove = getCategoryPtr(path);
			if(categoryToRemove == 0) {
				ostringstream oss;
				oss << "CRootItem::patch (__FILE__:__LINE__): the category item to be removed was not be found in current collection(" << path << ").";
				throw ExMalformedPatch(oss.str(), patchLineNr);
			}
			CCategoryItem* parent = categoryToRemove->getParent();
			parent->delCategory(categoryToRemove);
			/// TODO really remove category here
			chunkSizeSum = 0;
			new_category = true;
		} else if( line.find("@@") == 0 ) {
			// diff chunk header
			boost::cmatch res;
			boost::regex_search(line.c_str(), res, rx);

			string oldStartStr = res[1];
			string oldLenStr = res[2];
			string newStartStr = res[3];
			string newLenStr = res[4];

			try
			{
				oldStart = CUtils::str2long( oldStartStr );
				oldLen = CUtils::str2long( oldLenStr );
				newStart = CUtils::str2long( newStartStr );
				newLen = CUtils::str2long( newLenStr );
			}
			catch(std::invalid_argument& ex)
			{
				throw ExMalformedPatch(ex.what(), lineNr);
			}

			if(oldLen == 0) oldStart++;
			lineNr = oldStart + chunkSizeSum;

			chunkSizeSum += newLen - oldLen;

			new_category = false;
			// cerr << "- << oldStart << "," << oldLen << " + " << newStart << "," << newLen << endl;

		}
		else if( line.size() > 0 ) {
			char sign = line[0];
			string content = line.substr(1, line.size() - 1);
			assert(new_category == false);

			switch(sign){
				case '+': //insert
				{
					//cerr << "adding line : << lineNr << endl;;
					//cerr << "from diff : "<< content << endl;
					IContentItem* newItem = addContentItem(content, lineNr - 1);
					break;
				}
				case '-': //remove
				{
					string path = stripFirstSection(content);
					parent = getCategoryPtr(path);
					if(parent == 0) {
						ostringstream oss;
						oss << "error removing item: unknown parent category '" << path << "'";
						throw ExMalformedPatch(oss.str(), patchLineNr);
					}
                    if((lineNr - 1) < 0 || (lineNr - 1) > parent->getNumContentItems() ) {
                        ostringstream oss;
                        oss << "error: request to remove item at " << lineNr - 1 << " in category '" << path << "' outside valid range [0, " << parent->getNumContentItems() << "].";
                        throw ExMalformedPatch(oss.str(), patchLineNr);
                    }

					IContentItem *contItem = parent->getContentItem(lineNr - 1);
					string itemText = contItem->getText();
					if(itemText.compare(0, itemText.size() - 1, content) != 0 )	// possible error:
					{
						cerr << "Error when removing line " << lineNr << " :" << endl;
						cerr << "line expected from diff : "<< content << endl;
						cerr << "differs form collection : " << contItem->getText();
					}
					parent->delContentItem(lineNr - 1);
					lineNr--;
					break;
				}
				case ' ': //check
				{
					IContentItem *contItem = parent->getContentItem(lineNr - 1);
					string itemText = contItem->getText();
					if(itemText.compare(0, itemText.size() - 1, content) != 0 )	// possible error:
					{
						cerr << "Error when keeping line " << lineNr << " :" << endl;
						cerr << "line expected from diff : "<< content << endl;
						cerr << "differs form collection : " << contItem->getText();
					}
					break;
				}
				default:
					break;
			}
			lineNr++;
		}
	}
}
void ImageExporterOutputWidget::checkFilename()
{
    const QString emp("");
    QString filename(m_ui->fileNameTextEdit->toPlainText());
    QString errorMessage{ "" };

    for (auto it = m_supportedTags.begin(); it != m_supportedTags.end(); it++)
    {
        if (filename.contains(it->second) && it->first != "enum_num")
            filename.replace(filename.indexOf(it->second), it->second.length(), emp);
    }

    if (filename.indexOf(m_supportedTags["enum_num"]) != static_cast<int>(std::string::npos))
    {
        int position = filename.indexOf(m_supportedTags["enum_num"]);
        filename.replace(position, static_cast<int>(m_supportedTags["enum_num"].length()), "");

        std::set<QString> numbers{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        bool numberFound{ false }, endFound{ false };

        while (position < filename.length())
        {
            if (numbers.find(filename.at(position)) != numbers.end())
            {
                filename.replace(position, 1, "");
                numberFound = true;
            }
            else if (numberFound && filename.at(position) == '>')
            {
                filename.replace(position, 1, "");
                endFound = true;
                break;
            }
            else
                break;
        }

        if (!endFound)
            errorMessage = "includes an incomplete <enum#> tag";
    }

    if (errorMessage == "")
    {
        QRegExp rx("[A-Za-z0-9_\\-\\!\\§\\$\\%\\&\\(\\)\\=\\`\\´\\+\\'\\#\\-\\.\\,\\;\\_\\^\\°\\}\\{\\[\\]\\@\\x00C4\\x00E4\\x00D6\\x00F6\\x00DC\\x00FC\\x00DF\\s]{1,100}");

        if (!rx.exactMatch(filename))
            errorMessage = "includes invalid symbols";
    }

    if (errorMessage != "")
    {
        if (m_ui->saveButton->isEnabled())
            m_ui->saveButton->setDisabled(true);

        m_ui->fileNameTextEdit->setStyleSheet("background-color:rgb(255,170,127);");
        m_ui->filenamePeviewLabel->setText( filename + ".png " + errorMessage);
    }
    else
    {
        if (!m_ui->saveButton->isEnabled())
            m_ui->saveButton->setDisabled(false);

        m_ui->fileNameTextEdit->setStyleSheet(emp);

        emit filenameChanged();
    }
}
Example #23
0
void md5Fix::on_buttonStart_clicked()
{
	ui->buttonStart->setEnabled(false);

	// Check that directory exists
	QDir dir(ui->lineFolder->text());
	if (!dir.exists())
	{
		error(this, tr("This folder does not exist."));
		ui->buttonStart->setEnabled(true);
		return;
	}

	// Make sure the input is valid
	if (!ui->radioForce->isChecked() && !ui->lineFilename->text().contains("%md5%"))
	{
		error(this, tr("If you want to get the MD5 from the filename, you have to include the %md5% token in it."));
		ui->buttonStart->setEnabled(true);
		return;
	}

	// Suffixes
	QStringList suffixes = ui->lineSuffixes->text().split(',');
	for (QString &suffix : suffixes)
		suffix = suffix.trimmed();

	// Get all files from the destination directory
	auto files = listFilesFromDirectory(dir, suffixes);

	int count = 0;
	if (files.count() > 0)
	{
		// Show progress bar
		ui->progressBar->setValue(0);
		ui->progressBar->setMaximum(files.size());
		ui->progressBar->show();

		// Parse all files
		for (const auto &file : files)
		{
			QString fileName = file.first;
			QString path = dir.absoluteFilePath(fileName);

			QString md5;
			if (ui->radioForce->isChecked())
			{
				QFile fle(path);
				fle.open(QFile::ReadOnly);
				md5 = QCryptographicHash::hash(fle.readAll(), QCryptographicHash::Md5).toHex();
			}
			else
			{
				QRegExp regx("%([^%]*)%");
				QString reg = QRegExp::escape(ui->lineFilename->text());
				int pos = 0, cur = 0, id = -1;
				while ((pos = regx.indexIn(reg, pos)) != -1)
				{
					pos += 4;
					reg.replace(regx.cap(0), "(.+)");
					if (regx.cap(1) == QLatin1String("md5"))
					{ id = cur; }
					cur++;
				}
				QRegExp rx(reg);
				rx.setMinimal(true);
				pos = 0;
				while ((pos = rx.indexIn(fileName, pos)) != -1)
				{
					pos += rx.matchedLength();
					md5 = rx.cap(id + 1);
				}
			}

			if (!md5.isEmpty())
			{
				m_profile->addMd5(md5, path);
				count++;
			}

			ui->progressBar->setValue(ui->progressBar->value() + 1);
		}
	}

	// Hide progress bar
	ui->progressBar->hide();
	ui->progressBar->setValue(0);
	ui->progressBar->setMaximum(0);

	ui->buttonStart->setEnabled(true);

	QMessageBox::information(this, tr("Finished"), tr("%n MD5(s) loaded", "", count));
}
void servercontroller::do_autoconnect()
{
    static int stime = 0;
    static int ctime = 0;
    int loop;

    kdDebug(5008) << "Doing AUTOCONNECT" << endl;

    KConfig *conf = kapp->config();
    conf->setGroup("AutoConnect");
    QStringList servers = conf->readListEntry("Servers");
    servers.sort();
    QStringList::ConstIterator ser = servers.begin();

    loop = 0;

    for( ; ser != servers.end(); ser++){
        if(loop++ == stime){
		stime++;
		QString server = *ser;
		QString port = "6667";
		bool usessl = false;
		QString pass = QString::null;

		QRegExp rx("(.+) \\(SSL\\)(.*)");
		if(rx.search(server) >= 0){
		    server = rx.cap(1) + rx.cap(3);
                    usessl = true;
		}
		rx.setPattern("(.+) \\(pass: (\\S+)\\)(.*)");
		if(rx.search(server) >= 0){
		    server = rx.cap(1) + rx.cap(3);
		    pass = rx.cap(2);
		}
		rx.setPattern("([^: ]+):(\\d+)");
		if(rx.search(server) >= 0){
		    server = rx.cap(1);
		    port = rx.cap(2);
		}
		kdDebug(5008) << server << ": Done " << port << " " << usessl << " " << pass << endl;
                KSircServer kss(server, port, "", pass, usessl);
		new_ksircprocess(kss);
                return;
        }
    }

    loop = 0;

    ser = servers.begin();
    for( ; ser != servers.end(); ser++){
        QStringList channels = conf->readListEntry(*ser);
        if(channels.empty() == FALSE){
            channels.sort();
            QStringList::ConstIterator chan = channels.begin();
            for(; chan != channels.end(); chan++){
                if(loop++ == ctime){
		    ctime++;
		    QString channel = *chan;
		    QString key = QString::null;
		    QRegExp crx("(.+) \\(key: (\\S+)\\)");
		    if(crx.search(channel) >= 0){
			channel = crx.cap(1);
			key = crx.cap(2);
		    }
		    QString server = *ser;

		    QRegExp rx("^([^ :]+)");
		    if(rx.search(server) >= 0){
			server = rx.cap(1);
		    }
		    kdDebug(5008) << server << ": Channed: " << channel << " key: " << key << endl;
		    new_toplevel(KSircChannel(server, channel, key), true);
		    return;
		}
            }
        }
    }

    ctime = 0;
    stime = 0;
    at->stop();
    delete at;

}
TimeSigProperties::TimeSigProperties(TimeSig* t, QWidget* parent)
    : QDialog(parent)
{
    setupUi(this);
    setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);
    timesig = t;

    zText->setText(timesig->numeratorString());
    nText->setText(timesig->denominatorString());
    // set validators for numerator and denominator strings
    // which only accept '+', '(', ')', digits and some time symb conventional representations
    QRegExp rx("[0-9+CO()\\x00A2\\x00D8]*");
    QValidator *validator = new QRegExpValidator(rx, this);
    zText->setValidator(validator);
    nText->setValidator(validator);

    Fraction nominal = timesig->sig() / timesig->stretch();
    nominal.reduce();
    zNominal->setValue(nominal.numerator());
    nNominal->setValue(nominal.denominator());
    Fraction sig(timesig->sig());
    zActual->setValue(sig.numerator());
    nActual->setValue(sig.denominator());
    zNominal->setEnabled(false);
    nNominal->setEnabled(false);

    // TODO: fix http://musescore.org/en/node/42341
    // for now, editing of actual (local) time sig is disabled in dialog
    // but more importantly, the dialog should make it clear that this is "local" change only
    // and not normally the right way to add 7/4 to a score
    zActual->setEnabled(false);
    nActual->setEnabled(false);
    switch (timesig->timeSigType()) {
    case TimeSigType::NORMAL:
        textButton->setChecked(true);
        break;
    case TimeSigType::FOUR_FOUR:
        fourfourButton->setChecked(true);
        break;
    case TimeSigType::ALLA_BREVE:
        allaBreveButton->setChecked(true);
        break;
    }

    // set ID's of other symbols
    static const SymId prolatioSymbols[] = {
        SymId::mensuralProlation1,          // tempus perfectum, prol. perfecta
        SymId::mensuralProlation2,          // tempus perfectum, prol. imperfecta
        SymId::mensuralProlation3,          // tempus perfectum, prol. imperfecta, dimin.
        SymId::mensuralProlation4,          // tempus perfectum, prol. perfecta, dimin.
        SymId::mensuralProlation5,          // tempus imperf. prol. perfecta
//            SymId::mensuralProlation6,              // same shape as common time
        SymId::mensuralProlation7,          // tempus imperf., prol. imperfecta, reversed
        SymId::mensuralProlation8,          // tempus imperf., prol. perfecta, dimin.
//            SymId::mensuralProlation9,              // same shape as alla breve
        SymId::mensuralProlation10,         // tempus imperf., prol imperfecta, dimin., reversed
        SymId::mensuralProlation11,         // tempus inperf., prol. perfecta, reversed
    };

    ScoreFont* scoreFont = t->score()->scoreFont();
    int idx = 0;
    for (SymId symId : prolatioSymbols) {
        const QString& str = scoreFont->toString(symId);
        if (str.size() > 0) {
            otherCombo->setItemData(idx, (int)symId);
            // if time sig matches this symbol string, set as selected
            if (timesig->timeSigType() == TimeSigType::NORMAL && timesig->denominatorString().isEmpty()
                    && timesig->numeratorString() == str) {
                textButton->setChecked(false);
                otherButton->setChecked(true);
                otherCombo->setCurrentIndex(idx);
            }
        }
        idx++;
    }

    Groups g = t->groups();
    if (g.empty())
        g = Groups::endings(timesig->sig());     // initialize with default
    groups->setSig(timesig->sig(), g);
}
Example #26
0
File: ppplog.cpp Project: KDE/kppp
void PPPL_AnalyseLog(QStringList &list, QStringList &result) {
  QString msg;
  const char *rmsg = "Remote message: ";

  result.clear();

  // setup the analysis database
  struct {
    const char *regexp;
    const char *answer;
  } hints[] = {
    {"Receive serial link is not 8-bit clean",
     I18N_NOOP("You have launched pppd before the remote server " \
	  "was ready to establish a PPP connection.\n"
	  "Please use the terminal-based login to verify") },

    {"Serial line is looped back",
     I18N_NOOP("You have not started the PPP software on the peer system.") },

    {"AP authentication failed",
     I18N_NOOP("Check that you supplied the correct username and password.")} ,

    {"is locked by pid",
     I18N_NOOP("You should not pass 'lock' as an argument to pppd. "
	  "Check /etc/ppp/options and ~/.ppprc") },

    {"CP: timeout sending",
     I18N_NOOP("The remote system does not seem to answer to\n"
	  "configuration request. Contact your provider.") },

    {"unrecognized option",
     I18N_NOOP("You have passed an invalid option to pppd. See 'man pppd' "
          "for a complete list of valid arguments.") },

    // terminator
    {0,0}
  };


  // scan the log for keywords and try to offer any help
  for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it )
  {
    // look for remote message
    int pos = (*it).indexOf(rmsg);
    if (pos != -1)
    {
      QString str = (*it);
      str.remove(0, pos + strlen(rmsg));
      if(!str.isEmpty()) {
        msg = i18n("Notice that the remote system has sent the following"
                         " message:\n\"%1\"\nThis may give you a hint why the"
                         " connection has failed.", str);
        result.append(msg);
      }
    }

    // check in the hint database
    for(uint k = 0; hints[k].regexp != 0; k++) {
      QRegExp rx(hints[k].regexp);
      QString l(*it);
      if(l.contains(rx)) {
	result.append(i18n(hints[k].answer));
	break;
      }
    }
  }

  if (result.isEmpty())
    result.append(i18n("Unable to provide help."));
}
// Tokenize file to search for keywords
void CountKeywords::tokenizeSearchFile()
{
	regex rx ("[^_A-Za-z]"); // Match any character that isn't a letter or underscore

	string currentLine;
	int findBlockComment, findLineComment; //, stringStart, stringEnd;

	set<string>::iterator keywordsIterator; // string iterator for sourceKeywords set
	string rxMatchesRemoved; // store string remaining after regex_replace match(s) is processed
	string singleToken; // store individual tokens passed by stringstream
	string fmt = " "; // replace regex matches with a blank space

	while( !fileSearch.eof() ) // while not at the end of the user-specified file to process, find keyword tokens
	{
		getline(fileSearch, currentLine); // get first line of ifstream fileSearch

		findBlockComment = currentLine.find("/*"); // Detect block comment
		findLineComment = currentLine.find("//"); // Detect line comment
		if (findBlockComment != string::npos ) 
		{
			while( currentLine.find("*/") == string::npos) // Ignore all lines until end of block comment
			{
				fileSearch.ignore(80, '\n');
				getline(fileSearch, currentLine);
			}
		}
		else if( findLineComment != string::npos )
		{
			currentLine.erase(findLineComment, (80 - findLineComment) ); // Erase line comment
		} // end if...else detect and remove comments from document

		//while( (stringStart = currentLine.find('"')) != string::npos )
		//{
		//	if( (stringEnd = currentLine.find('\\"')) != string::npos)
		//	{
		//		currentLine.erase( stringStart, (currentLine.find('"', stringEnd) - stringStart) );
		//	}
		//	else
		//		currentLine.erase( stringStart, (currentLine.find('"') - stringStart) );
		//}

		//cout << currentLine << endl;

		rxMatchesRemoved = regex_replace ( currentLine, rx, fmt); // string after regex_replace match
		// for each singleToken, search set of keywords; and, on match insert keyword into map
		for( keywordsIterator = sourceKeywords.begin(); keywordsIterator != sourceKeywords.end(); keywordsIterator++)
		{
			stringstream ss(rxMatchesRemoved);
			while( ss >> singleToken ) // while read input has valid return
			{	
				if( singleToken.compare( (*keywordsIterator) ) == 0 )
				{
					if( foundKeywords.find(singleToken) == foundKeywords.end() )
						foundKeywords[singleToken] = 1;
					else
						foundKeywords[singleToken]++;
				}
			}
		}
	} // end while !fileSearch.eof() loop
	fileSearch.close(); // close fileSearch ifstream
} // end tokenizeSearchFile() function
Example #28
0
void MythSqueezeDisplay::PaintSqueezeDisplay(DisplayBuffer *buf)
{
    DEBUGF("Colors" << m_displayBackgroundColor << m_textcolorGeneral );
    int playedCount = 0;
    int totalCount = 1; // this way we never get a divide by zero error
    QString timeText = "";


    QPainter p( displayImage );
    QBrush b( m_displayBackgroundColor );
    m_textcolorGeneral.setAlpha( m_Brightness );
    textcolorLine1.setAlpha( m_Brightness - line1Alpha );

    QBrush c( m_textcolorGeneral );
    QBrush e( c ); // non-filling brush
    e.setStyle( Qt::NoBrush );
    p.setBackground( b );
    p.setBrush( c );
    p.setPen( m_textcolorGeneral );
    p.setFont( large );
    p.eraseRect( displayImage->rect() );

    DEBUGF("LINE 0: " << line0Bounds << " LINE 1:" << line1Bounds);

    // draw Line 0  NOTE: Only transitions left or right, but NOT up and down
    if( buf->line0.length() > 0 ) {
        p.setFont( small );
        if( isTransition && ( transitionDirection == transLEFT || transitionDirection == transRIGHT)) {
            p.drawText(line0Bounds.left()+xOffsetOld, line0Bounds.bottom(), transBuffer.line0);
            p.drawText(line0Bounds.left()+xOffsetNew, line0Bounds.bottom(), buf->line0);
        }
        else
            p.drawText(line0Bounds.x(), line0Bounds.bottom(), buf->line0);
    }

    // draw Line 1
    if( buf->line1.length() > 0 ) {
        if( buf->line0.left( 8 ) == "Volume (" ) {   // it's the volume, so emulate a progress bar
            qreal volume = buf->line0.mid( 8, buf->line0.indexOf( ')' ) - 8 ).toInt();
            volFillRect.setWidth( (qreal)volRect.width() * ( volume / (qreal)100 ) );
            p.setBrush( e );  // non-filling brush so we end up with an outline of a rounded rectangle
            p.drawRoundedRect( volRect, radius, radius );
            p.setBrush( c );
            if( volume > 1 ) // if it's too small, we get a funny line at the start of the progress bar
                p.drawRoundedRect( volFillRect, radius, radius );
        }
        else {
            QBrush cLine1( textcolorLine1 );
            p.setBrush( cLine1 );
            p.setPen( textcolorLine1 );
            p.setFont( large );
            p.setClipRegion( line1Clipping );
            if( isTransition ) {
                p.drawText( line1Bounds.x() + xOffsetOld, line1Bounds.bottom() + yOffsetOld, transBuffer.line1);
                p.drawText( line1Bounds.x() + xOffsetNew, line1Bounds.bottom() + yOffsetNew, buf->line1 );
            } else {
                //                p.drawText( line1Bounds.x(), line1Bounds.bottom(), buf->line1 );
                p.drawText( line1Bounds.x() - ScrollOffset, line1Bounds.bottom(), buf->line1 );
                if( scrollState != NOSCROLL )
                    p.drawText(pointLine1_2.x() - ScrollOffset, line1Bounds.bottom(), buf->line1 );
            }
            p.setClipRegion( fullDisplayClipping );
            p.setBrush( c );
            p.setPen( m_textcolorGeneral );
        }
    }

    // deal with "overlay0" (the right-hand portion of the display) this can be time (e.g., "-3:08") or number of items (e.g., "(2 of 7)")
    if( buf->overlay0.length() > 0 ) {
        if( Slimp3Display( buf->overlay0 ) ) {
            QRegExp rx( "\\W(\\w+)\\W");
            //            QRegExp rx( "\037(\\w+)\037" );
            QStringList el;
            int pos = 0;

            while ((pos = rx.indexIn(buf->overlay0, pos)) != -1) {
                el << rx.cap(1);
                pos += rx.matchedLength();
            }

            rx.indexIn( buf->overlay0 );
            QStringList::iterator it = el.begin();
            while( it != el.end() ) {
                QString s = *it;
                if( s.left( 12 ) == "leftprogress" ) { // first element
                    int inc = s.at( 12 ).digitValue();
                    playedCount += inc;
                    totalCount += 4;
                }
                else if( s.left( 14 ) == "middleprogress" ) { // standard element
                    int inc = s.at( 14 ).digitValue();
                    playedCount += inc;
                    totalCount += 4;
                }
                else if( s.left( 10 ) == "solidblock" ) { // full block
                    playedCount += 4;
                    totalCount += 4;
                }
                else if( s.left( 13 ) == "rightprogress" ) { // end element
                    int inc = s.at( 13 ).digitValue();
                    playedCount += inc;
                    totalCount += 4;
                }
                ++it;
            }
            QChar *data = buf->overlay0.data();
            for( int i = ( buf->overlay0.length() - 8 ); i < buf->overlay0.length(); i++ ) {
                if( *( data + i ) == ' ' ) {
                    timeText = buf->overlay0.mid( i + 1 );
                }
            }
        }
        else if( buf->overlay0.contains( QChar( 8 ) ) ) {
            QChar elapsed = QChar(8);
            QChar remaining = QChar(5);
            QChar *data = buf->overlay0.data();
            for( int i = 0; i < buf->overlay0.length(); i++, data++ ) {
                if( *data == elapsed ) {
                    playedCount++;
                    totalCount++;
                }
                else if( *data == remaining )
                    totalCount++;
                else if( *data == ' ' ) {
                    timeText = buf->overlay0.mid( i + 1 );
                }
            }
        }
        else {
            timeText = buf->overlay0;
        }
        p.setFont( small );
        QFontMetrics fm = p.fontMetrics();
        //        p.setClipping(false);
        p.setClipRegion(line0Clipping );
        if( isTransition ) {
            p.drawText( ( line0Bounds.right() + xOffsetNew ) - fm.width(timeText), line0Bounds.bottom(), timeText );
        }
        else {
            p.drawText( line0Bounds.right() - fm.width(timeText), line0Bounds.bottom(), timeText );
        }
        if( totalCount > 1 ) {  // make sure we received data on a progress bar, otherwise, don't draw
            progRect.setLeft( ( qreal )( line0Bounds.x() + fm.width( buf->line0.toUpper() ) + xOffsetOld ) );
            progRect.setRight( ( qreal )( line0Bounds.right() + xOffsetOld - ( qreal )( 3 * fm.width( timeText ) / 2 ) ) );
            progFillRect.setLeft( progRect.left() );
            progFillRect.setWidth( ( playedCount * progRect.width() ) / totalCount );
            p.setBrush( e );  // non-filling brush so we end up with an outline of a rounded rectangle
            p.drawRoundedRect( progRect, radius, radius );
            p.setBrush( c );
            if( playedCount > 1 ) // if it's too small, we get a funny line at the start of the progress bar
                p.drawRoundedRect( progFillRect, radius, radius );
        }
    }

    // deal with "overlay1" (the right-hand portion of the display)
//    if( buf->overlay1.length() > 0 ) {
//        DEBUGF( "Don't know what to do with overlay1 yet" );
//    }
//     if we've received a "center" display, it means we're powered down, so draw them
        if( buf->center0.length() > 0 ) {
            p.setFont( medium );
            QFontMetrics fm = p.fontMetrics();
            QPoint start = QPoint( center0Bounds.x() + (center0Bounds.width()/2) - (fm.width( buf->center0 )/2 ), center0Bounds.bottom() );
            p.drawText( start, buf->center0 );
        }

        if( buf->center1.length() > 0 ) {
            p.setFont( medium );
            QFontMetrics fm = p.fontMetrics();
            QPoint start = QPoint( center1Bounds.x() + (center1Bounds.width()/2)- ( fm.width( buf->center1 )/2 ), center1Bounds.bottom() );
            p.drawText( start, buf->center1 );
        }
//    displayLabel.setPixmap(QPixmap::fromImage( *displayImage) );
        QPixmap pix = QPixmap::fromImage(*displayImage);
        m_squeezeDisplay->UpdateFrame(&pix);
}
Example #29
0
void measurepulse::on_pushButton_5_clicked()
{
	publiccaution.addevent("摩擦系数测试页面","第三次开始","用户第三次开始",1);

	//校验上次的测试
	QRegExp rx("^\\d+\\.?\\d*$");
	if ( rx.indexIn(lineEdit[1]->text()) == -1)
	{
		QMessageBox msgBox;
		msgBox.setText("输入格式不对,请重新输入");
		msgBox.setWindowTitle("输入错误");
		msgBox.setStandardButtons(QMessageBox::Yes );
		QAbstractButton* tb = msgBox.button(QMessageBox::Yes);
		tb->setText("确定");
		return;
	}
	bool ok;

	if (lineEdit[1]->text().toDouble(&ok) == 0)
	{
		QMessageBox msgBox;
		msgBox.setText("输入数据为0,请重新输入");
		msgBox.setWindowTitle("输入错误");
		msgBox.setStandardButtons(QMessageBox::Yes );
		QAbstractButton* tb = msgBox.button(QMessageBox::Yes);
		tb->setText("确定");
		msgBox.exec();
		return;
	}

	//记录脉冲数
	double count = 0;
	ksmc->GetEncoderCount(count);

	//新值小于小于旧值,说明可能翻转了
	if (count < encoder[1])
	{
		//真正翻转,而不是编码器回退,回退脉冲不可能超过3000000000
		if (count < 1000000000 && encoder[1] > 4000000000)
		{
			encoder[1] = 4294967295 - encoder[1] + count;
		} 
		else
		{
			encoder[1] = count - encoder[1];
		}
	}
	else
	{
		encoder[1] = count - encoder[1];
	}

	//校验编码计数
	if (encoder[1] == 0)
	{
		QMessageBox msgBox;
		msgBox.setText("编码器计数没有变化,请重新测试");
		msgBox.setWindowTitle("错误");
		msgBox.setStandardButtons(QMessageBox::Yes );
		QAbstractButton* tb = msgBox.button(QMessageBox::Yes);
		tb->setText("确定");
		msgBox.exec();

		ui.pushButton->setEnabled(false);
		ui.pushButton_2->setEnabled(true);
		ui.pushButton_3->setEnabled(true);
		ui.pushButton_4->setEnabled(true);
		ui.pushButton_5->setEnabled(false);
		ui.pushButton_6->setEnabled(true);
		ui.pushButton_7->setEnabled(false);
		lineEdit[0]->setEnabled(false);
		lineEdit[1]->setEnabled(false);
		lineEdit[2]->setEnabled(false);
		lineEdit[1]->clear();

		//返回
		return;
	}
	//记录脉冲数目
	count = 0;
	ksmc->GetEncoderCount(count);
	encoder[2] = count;

	step = 3;

	interfaceevent* ptempevent = new interfaceevent();
	ptempevent->cmd = 0x0a;//橡毯开始运动
	ptempevent->status = 0x00;//命令状态

	//发送一个事件给后台线程
	QCoreApplication::postEvent(backendobject, ptempevent);

	//启动
	ui.pushButton_5->setEnabled(false);
	lineEdit[1]->setEnabled(false);
	ui.pushButton_8->setEnabled(false);

}
Example #30
0
void PkInstallCatalogs::search()
{
    QString distroId = Daemon::global()->distroID();
    QStringList parts = distroId.split(';');
    if (parts.size() != 3) {
        sendErrorFinished(Failed, "invalid distribution id, please fill a bug against you distribution backend");
        return;
    }
    QString distro = parts.at(0);
    QString version = parts.at(1);
    QString arch = parts.at(2);

    QStringList rxActions;
    Transaction::Roles roles = Daemon::global()->roles();
    if (roles & Transaction::RoleResolve) {
        rxActions << "InstallPackages";
    }

    if (roles & Transaction::RoleWhatProvides) {
        rxActions << "InstallProvides";
    }

    if (roles & Transaction::RoleSearchFile) {
        rxActions << "InstallFiles";
    }

    if (rxActions.isEmpty()) {
        if (showWarning()) {
            // TODO display a nicer message informing of already installed ones
            setInfo(i18n("Not supported"),
                    i18n("Your backend does not support any of the needed "
                         "methods to install a catalog"));
        }
        sendErrorFinished(Failed, "not supported by backend");
        return;
    }

    // matches at the beginning of line installPackages or InstallProvides or installFiles and capture it
    // matches an optional set of parenthesis
    // matches *%1* and or *%2* and or *%3*
    // matches after '=' but ';' at the end
    QString pattern;
    pattern = QString(
                "^(%1)(?:\\((?:.*%2[^;]*(?:;(?:.*%3[^;]*(?:;(?:.*%4[^;]*)?)?)?)?)?\\))?=(.*[^;$])").arg(rxActions.join("|")).arg(distro).arg(version).arg(arch);
    QRegExp rx(pattern, Qt::CaseInsensitive);

    QStringList filesFailedToOpen;
    QStringList files = m_model->files();
    if (!files.isEmpty()) {
        foreach (const QString &file, files) {
            QFile catalog(file);
            if (catalog.open(QIODevice::ReadOnly | QIODevice::Text)) {
                QTextStream in(&catalog);
                while (!in.atEnd()) {
                    if (rx.indexIn(in.readLine()) != -1) {
                        if (rx.cap(1).compare("InstallPackages", Qt::CaseInsensitive) == 0) {
                            m_installPackages.append(rx.cap(2).split(';'));
                        } else if (rx.cap(1).compare("InstallProvides", Qt::CaseInsensitive) == 0) {
                            m_installProvides.append(rx.cap(2).split(';'));
                        } else if (rx.cap(1).compare("InstallFiles", Qt::CaseInsensitive) == 0) {
                            m_installFiles.append(rx.cap(2).split(';'));
                        }
                    }
                }
            } else {
                filesFailedToOpen << file;
            }
        }