예제 #1
0
bool ProjectFile::open(const QString &fileName)
{
    QFile file(fileName);
    file.open(QIODevice::ReadWrite | QIODevice::Text);
    if (!file.isOpen())
        return false;
    QStringList list;
    QString line;
    bool bnext = false;
    while (!file.atEnd()) {
        QByteArray ar = file.readLine().trimmed();
        if (!ar.isEmpty() && ar.right(1) == "\\") {
            bnext = true;
            ar[ar.length()-1] = ' ';
        } else {
            bnext = false;
        }
        line.push_back(ar);
        if (!bnext && !line.isEmpty()) {
            list.push_back(line);
            line.clear();
        }
    }
    file.close();

    if (!line.isEmpty()) {
        list.push_back(line);
    }
    _filePath = fileName;
    _isMakefile = QFileInfo(fileName).suffix().toLower() != "pro";

    context.clear();
    foreach (QString line, list) {
        if (line.size() >= 1 && line.at(0) == '#')
            continue;
        QStringList v = line.split(QRegExp("\\+="),QString::SkipEmptyParts);
        if (v.count() == 1) {
            v = line.split(QRegExp("="),QString::SkipEmptyParts);
            if (v.count() == 2) {
                QStringList v2 = v.at(1).split(" ",QString::SkipEmptyParts);
                if (!v2.isEmpty()) {
                    context[v.at(0).trimmed()] = v2;
                }
            }
        } else if (v.count() == 2) {
            QStringList v2 = v.at(1).split(" ",QString::SkipEmptyParts);
            if (!v2.isEmpty())
                context[v.at(0).trimmed()].append(v2);
        }
    }
    return !context.isEmpty();
    /*
    QString all = file.readAll();
    all.replace(QRegExp("\\\\[\\s]*[\n\r]+[\\s]*")," ");
    QStringList list = all.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
    context.clear();
    foreach(QString line, list) {
         line.replace("\t"," ");
        QStringList v = line.split(QRegExp("\\+="),QString::SkipEmptyParts);
        if (v.count() == 1) {
            v = line.split(QRegExp("="),QString::SkipEmptyParts);
            if (v.count() == 2) {
                QStringList v2 = v.at(1).split(" ",QString::SkipEmptyParts);
                if (!v2.isEmpty()) {
                    context[v.at(0).trimmed()] = v2;
                }
            }
        } else if (v.count() == 2) {
            QStringList v2 = v.at(1).split(" ",QString::SkipEmptyParts);
            if (!v2.isEmpty())
                context[v.at(0).trimmed()].append(v2);
        }
    }
    file.close();
    _filePath = fileName;
    return !context.isEmpty();
    */
}
예제 #2
0
파일: window.cpp 프로젝트: manikk/ekalappai
void Window::loadKeyBoard(){
    QString str1;
    QString str2;
    QString temp1;
    QString filename;
    keyboardmap.clear();

    //file handling code
    if(selected_keyboard == 1){
        filename = "keyboards/Tamil-tamil99.txt.in";
    }
    else if(selected_keyboard == 2){
        filename = "keyboards/Tamil-phonetic.txt.in";
    }
    else if(selected_keyboard == 3){
        filename = "keyboards/Tamil-typewriter.txt.in";
    }
    else if(selected_keyboard == 4){
        filename = "keyboards/Tamil-bamini.txt.in";
    }
    else if(selected_keyboard == 5){
        filename = "keyboards/Tamil-inscript.txt.in";
    }


    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;
    QTextStream in(&file);
    in.setAutoDetectUnicode(true);

    bool line_start = FALSE;
    bool line_end = FALSE;
    QString line;
    //Read the file line by line & insert into keyboardmap arrays

    while (!in.atEnd()) {
        line = in.readLine();
        str1.clear();
        str2.clear();

        //process_line(line);
        if (line == "BEGIN_TABLE"){
            line_start = true;
            line_end = false;
        }

        if (line == "END_TABLE"){
            line_end = true;
        }

        //if the line is between begin_table & end_table and not a comment, then process that line
        if ((line_start) && !(line_end) && (line.left(3) != "###")){
            QRegExp sep("\\s+");
            str1 = line.section(sep, 0, 0); // first part
            str2 = line.section(sep, 1, 1) ; // second part            
            keyboardmap.insert(str1, str2);
        }
        line.clear();
    }
}
void QScriptHighlighter::highlightBlock(const QString &text)
{
    // states
    enum {
        StateStandard,
        StateCommentStart1,
        StateCCommentStart2,
        StateCppCommentStart2,
        StateCComment,
        StateCppComment,
        StateCCommentEnd1,
        StateCCommentEnd2,
        StateStringStart,
        StateString,
        StateStringEnd,
        StateString2Start,
        StateString2,
        StateString2End,
        StateNumber,
        StatePreProcessor,
        NumStates
    };
    // tokens
    enum {
        InputAlpha,
        InputNumber,
        InputAsterix,
        InputSlash,
        InputParen,
        InputSpace,
        InputHash,
        InputQuotation,
        InputApostrophe,
        InputSep,
        NumInputs
    };

    static const uchar table[NumStates][NumInputs] = {
        { StateStandard,      StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateStandard
        { StateStandard,      StateNumber,   StateCCommentStart2, StateCppCommentStart2, StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateCommentStart1
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCComment,         StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCCommentStart2
        { StateCppComment,    StateCppComment, StateCppComment,     StateCppComment,       StateCppComment, StateCppComment, StateCppComment,   StateCppComment,  StateCppComment,   StateCppComment }, // CppCommentStart2
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCComment,         StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCComment
        { StateCppComment,    StateCppComment, StateCppComment,     StateCppComment,       StateCppComment, StateCppComment, StateCppComment,   StateCppComment,  StateCppComment,   StateCppComment }, // StateCppComment
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCCommentEnd2,     StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCCommentEnd1
        { StateStandard,      StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateCCommentEnd2
        { StateString,        StateString,     StateString,         StateString,           StateString,     StateString,     StateString,       StateStringEnd,   StateString,       StateString }, // StateStringStart
        { StateString,        StateString,     StateString,         StateString,           StateString,     StateString,     StateString,       StateStringEnd,   StateString,       StateString }, // StateString
        { StateStandard,      StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateStringEnd
        { StateString2,       StateString2,    StateString2,        StateString2,          StateString2,    StateString2,    StateString2,      StateString2,     StateString2End,   StateString2 }, // StateString2Start
        { StateString2,       StateString2,    StateString2,        StateString2,          StateString2,    StateString2,    StateString2,      StateString2,     StateString2End,   StateString2 }, // StateString2
        { StateStandard,      StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateString2End
        { StateNumber,        StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateNumber
        { StatePreProcessor,  StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard } // StatePreProcessor
    };

    QString buffer;
    buffer.reserve(text.length());
    QTextCharFormat emptyFormat;

    int state = StateStandard;
    const int previousState = previousBlockState();
    if (previousState != -1)
        state = previousState;

    if (text.isEmpty()) {
        setCurrentBlockState(previousState);
        return;
    }

    int input = -1;
    int i = 0;
    bool lastWasBackSlash = false;
    bool makeLastStandard = false;

    static const QSet<QChar> alphabeth = alphaChars();
    static const QString mathChars = QString::fromLatin1("xXeE");
    static const QString numbers = QString::fromLatin1("0123456789");
    bool questionMark = false;
    QChar lastChar;
    QString firstWord;
    forever {
        const QChar c = text.at(i);

        if (lastWasBackSlash) {
            input = InputSep;
        } else {
            switch (c.toLatin1()) {
                case '*':
                    input = InputAsterix;
                    break;
                case '/':
                    input = InputSlash;
                    break;
                case '(': case '[': case '{':
                    input = InputParen;
                    if (state == StateStandard
                        || state == StateNumber
                        || state == StatePreProcessor
                        || state == StateCCommentEnd2
                        || state == StateCCommentEnd1
                        || state == StateString2End
                        || state == StateStringEnd
                       )
                        //blockData->parentheses << Parenthesis(Parenthesis::Open, c, i);
                    break;
                case ')': case ']': case '}':
                    input = InputParen;
                    if (state == StateStandard
                        || state == StateNumber
                        || state == StatePreProcessor
                        || state == StateCCommentEnd2
                        || state == StateCCommentEnd1
                        || state == StateString2End
                        || state == StateStringEnd
                       ) {
                        //blockData->parentheses << Parenthesis(Parenthesis::Closed, c, i);
                    }
                    break;
                case '#':
                    input = InputHash;
                    break;
                case '"':
                    input = InputQuotation;
                    break;
                case '\'':
                    input = InputApostrophe;
                    break;
                case ' ':
                    input = InputSpace;
                    break;
                case '1': case '2': case '3': case '4': case '5':
                case '6': case '7': case '8': case '9': case '0':
                    if (alphabeth.contains(lastChar)
                        && (!mathChars.contains(lastChar) || !numbers.contains(text.at(i - 1)))) {
                        input = InputAlpha;
                    } else {
                        if (input == InputAlpha && numbers.contains(lastChar))
                            input = InputAlpha;
                        else
                            input = InputNumber;
                    }
                    break;
                case ':': {
                              input = InputAlpha;
                              QChar nextChar = QLatin1Char(' ');
                              if (i < text.length() - 1)
                                  nextChar = text.at(i + 1);
                              if (state == StateStandard && !questionMark &&
                                  lastChar != QLatin1Char(':') && nextChar != QLatin1Char(':')) {
                                  for (int j = 0; j < i; ++j) {
                                      if (format(j) == emptyFormat)
                                          setFormat(j, 1, m_labelFormat);
                                  }
                              }
                              break;
                          }
                default: {
                             if (!questionMark && c == QLatin1Char('?'))
                                 questionMark = true;
                             if (c.isLetter() || c == QLatin1Char('_'))
                                 input = InputAlpha;
                             else
                                 input = InputSep;
                         } break;
            }
        }

        lastWasBackSlash = !lastWasBackSlash && c == QLatin1Char('\\');

        if (input == InputAlpha)
            buffer += c;

        state = table[state][input];

        switch (state) {
            case StateStandard: {
                                    setFormat(i, 1, emptyFormat);
                                    if (makeLastStandard)
                                        setFormat(i - 1, 1, emptyFormat);
                                    makeLastStandard = false;
                                    if (!buffer.isEmpty() && input != InputAlpha ) {
                                        highlightKeyword(i, buffer);
                                        buffer.clear();
                                    }
                                } break;
            case StateCommentStart1:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = true;
                                buffer.resize(0);
                                break;
            case StateCCommentStart2:
                                setFormat(i - 1, 2, m_commentFormat);
                                makeLastStandard = false;
                                buffer.resize(0);
                                break;
            case StateCppCommentStart2:
                                setFormat(i - 1, 2, m_commentFormat);
                                makeLastStandard = false;
                                buffer.resize(0);
                                break;
            case StateCComment:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_commentFormat);
                                buffer.resize(0);
                                break;
            case StateCppComment:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_commentFormat);
                                buffer.resize(0);
                                break;
            case StateCCommentEnd1:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_commentFormat);
                                buffer.resize(0);
                                break;
            case StateCCommentEnd2:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_commentFormat);
                                buffer.resize(0);
                                break;
            case StateStringStart:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.resize(0);
                                break;
            case StateString:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_stringFormat);
                                buffer.resize(0);
                                break;
            case StateStringEnd:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.resize(0);
                                break;
            case StateString2Start:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.resize(0);
                                break;
            case StateString2:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_stringFormat);
                                buffer.resize(0);
                                break;
            case StateString2End:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.resize(0);
                                break;
            case StateNumber:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat( i, 1, m_numberFormat);
                                buffer.resize(0);
                                break;
            case StatePreProcessor:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_preProcessorFormat);
                                buffer.resize(0);
                                break;
        }

        lastChar = c;
        i++;
        if (i >= text.length())
            break;
    }

    highlightKeyword(text.length(), buffer);

    if (state == StateCComment
        || state == StateCCommentEnd1
        || state == StateCCommentStart2
       ) {
        state = StateCComment;
    } else if (state == StateString) {
        state = StateString;
    } else if (state == StateString2) {
        state =  StateString2;
    } else {
        state = StateStandard;
    }

    setCurrentBlockState(state);
}
예제 #4
0
bool DevCheck::devInfo(QString dev, QString* type, QString* label, QString* filesystem, QString* maxsize){
  //OUTPUT: bool isGoodDevice
  //INPUTS/OUTPUTS: type, label, filesystem, maxsize
  //INPUT: dev = device node (da0, not /dev/da0)
	
  //Clear the output variables
  type->clear(); label->clear(); filesystem->clear(); maxsize->clear();
  //make sure to have both the full path and just node
  QString node;
  QString fullDev;
  if(dev.startsWith(DEVICEDIR)){ fullDev = dev; node = dev.section("/",-1); }
  else{ node = dev; fullDev = DEVICEDIR + dev; }
  //Do not allow sym-links
  if(!QFile::symLinkTarget(fullDev).isEmpty()){ return FALSE; }
  
  //Double check for valid device types (just in case)
  QString detType;
  for(int i=0; i<validDevs.length(); i++){
    if(node.startsWith(validDevs[i]) && node != "mdctl"){ 
	detType = validDevTypes[i]; 
	break; 
    }
  }
  QString camctl;
  if(detType == "USB" && QFile::exists(fullDev)){
    //make sure that it is not a SCSI device
    camctl = pcbsd::Utils::runShellCommand( QString("camcontrol inquiry ")+node ).join(" ");
    if(camctl.contains(" Fixed Direct Access SCSI")){ detType = "SCSI"; } //USB devices do not have any output
    if(camctl.contains("camcontrol")){ camctl.clear(); } //error or invalid device type
  }
  //Make sure we quit before running commands on any invalid device nodes
  if(detType.isEmpty() || !QFile::exists(fullDev) ){return FALSE;}
  else{type->append(detType);}
  bool isCD=FALSE;
  if(detType == "CD9660" || detType == "ISO"){ isCD=TRUE; }
  
  //Read the Device Info using "file -s <device>"
  QString cmd = "file -s "+fullDev;
  QString output = pcbsd::Utils::runShellCommand(cmd).join(" ");
  //if(isCD){ qDebug() << "File -s output:" << output; }
  
  // ** Get the max storage size **
  int kb = 0;
  bool hasPartitions = FALSE; 
  bool isMounted = FALSE;
  if( !isCD ){
    QStringList tmp = output.split(",");
    if( !tmp.filter("partition ").isEmpty() ){
      //Check for actual sub-devices (*s[#][a/b/c/....])
      if( devChildren(node).length() > 0 ){ hasPartitions = TRUE; }
    }
    if( !tmp.filter("last mounted on /").isEmpty() && (detType == "SATA")){
      isMounted = TRUE;
    }
    //Now try to get the size of the disk
    if( !tmp.filter("number of data blocks").isEmpty() ){
      tmp = tmp.filter("number of data blocks");
      kb = tmp[0].remove("number of data blocks").simplified().toInt();
    }else if( !tmp.filter("number of blocks").isEmpty() ){
      tmp = tmp.filter("number of blocks");
      kb = tmp[0].remove("number of blocks").simplified().toInt();
    }else if( !tmp.filter("hidden sectors").isEmpty()){
      tmp = tmp.filter("hidden sectors");
      kb = tmp[0].remove("hidden sectors").simplified().toInt();
    }else if( !tmp.filter("sectors").isEmpty()){
      tmp = tmp.filter("sectors");
      //qDebug() << "Det Sectors line:"<<tmp;
      int num=0;
      for(int i=0; i<tmp.length(); i++){
        int n = tmp[i].remove("sectors").section("(",0,0).simplified().toInt();
        if(n > num){ num = n; }
      }
      kb = num;
    }else{ kb = -1; }
  } //end non-CD size and isMounted detection
  bool oksize = (kb > 0);
  //First try to get the device label using the "file -s" output
  QString dlabel;
  if(isCD){
    if( !output.contains("ERROR:") ){
      dlabel = output.section("'",-2).remove("'").simplified();
      if(dlabel.contains("(")){ dlabel = dlabel.left(dlabel.indexOf("(")+1).trimmed();}
    }
  }else{
   dlabel = output.section("label: \"",1,1).section("\"",0,0).simplified(); //device name
  }
  // - trim the label out of the output line for filesystem type detection
  QString devFSsec, devFSsec2;
  if(!isCD){
    devFSsec = output.section("label:",0,0);
    devFSsec2 = output.section("label:",1,3).section(",",1,1,QString::SectionSkipEmpty);
  }else{
    devFSsec = output.simplified();	  
  }
  // ** Find the filesystem type for the device **
  QString filesys;
  for(int i=0; i<fsDetection.length(); i++){
    if(devFSsec.contains(fsDetection[i]) || devFSsec2.contains(fsDetection[i]) ){
      filesys = fsMatch[i]; 
    }
  }
  //If the filesystem could not be detected or is not supported
  bool hasFS = TRUE;
  if(filesys.isEmpty()){ filesys = "UNKNOWN"; hasFS=FALSE; }
  
  //Now get the device label (if there is one) using glabel
  bool hasLabel = FALSE;
  QString glabel;
  if(!isCD){ glabel = devLabel(node, filesys); }
  //Check to see if we have a label, otherwise assign one
  if( !glabel.isEmpty() ){ dlabel = glabel; hasLabel = TRUE; } //glabel
  else if(!dlabel.isEmpty()){ hasLabel = TRUE; } //file -s label
  else if( !camctl.isEmpty() ){ 
    //not necessarily a "detected" label, but just an alternate fallback name
    dlabel = camctl.section(">",0,0).section("<",-1).section(" ",0,0).simplified();
  }else{
    //Assign a device label
    if(isCD){
      if(detType == "ISO"){
	dlabel = "ISO_File";
      }else{
        dlabel = "Optical_Disk";
      }
    }else{
      dlabel = detType+"-Device"; //this is not a "detected" label
    }
  }
  //make sure that a device label does not contain "(" or ")"
  if(dlabel.contains("(")){ dlabel.remove("(").simplified(); }
  if(dlabel.contains(")")){ dlabel.remove(")").simplified(); }
  dlabel = dlabel.simplified();
  //Now perform the final checks to see if it is a good device
  bool good = FALSE;
  if( isMounted ){}//Always ignore this device (local FreeBSD installation that is being used)
  else if( hasPartitions ){} //Ignore devices that have partitions accessible as seperate devices
  else if( hasFS && isCD ){ good = TRUE; } //CD/DVD data disks don't have as much info
  //Allow devices that match 2 of the 3 criteria
  else if( hasFS && oksize ){ good = TRUE; } //This will catch most good devices
  else if( hasLabel && oksize ){ good = TRUE; } //allow unknown filesystems if there is a good size reading
  else if( hasFS && hasLabel ){ good = TRUE; } // allow device if it has a known label and filesystem
  
  //Now setup the outputs as appropriate
  maxsize->append( QString::number(kb) );
  label->append(dlabel);
  filesystem->append(filesys);
  
  if(!good){
    qDebug() << "Invalid Device:" << node << detType << dlabel << filesys << kb; 
    if(DEBUG_MODE){qDebug() << " -Detected Flags:" << isMounted << hasPartitions << hasLabel << hasFS << oksize;} 
  }
  return good;
}
예제 #5
0
void PathChooser::slotBrowse()
{
    emit beforeBrowsing();

    QString predefined = path();
    if ((predefined.isEmpty() || !QFileInfo(predefined).isDir())
            && !d->m_initialBrowsePathOverride.isNull()) {
        predefined = d->m_initialBrowsePathOverride;
        if (!QFileInfo(predefined).isDir())
            predefined.clear();
    }

    // Prompt for a file/dir
    QString newPath;
    switch (d->m_acceptingKind) {
    case PathChooser::Directory:
    case PathChooser::ExistingDirectory:
        newPath = QFileDialog::getExistingDirectory(this,
                makeDialogTitle(tr("Choose Directory")), predefined);
        break;
    case PathChooser::ExistingCommand:
    case PathChooser::Command:
        newPath = QFileDialog::getOpenFileName(this,
                makeDialogTitle(tr("Choose Executable")), predefined,
                d->m_dialogFilter);
        break;
    case PathChooser::File: // fall through
        newPath = QFileDialog::getOpenFileName(this,
                makeDialogTitle(tr("Choose File")), predefined,
                d->m_dialogFilter);
        break;
    case PathChooser::SaveFile:
        newPath = QFileDialog::getSaveFileName(this,
                makeDialogTitle(tr("Choose File")), predefined,
                d->m_dialogFilter);
        break;
    case PathChooser::Any: {
        QFileDialog dialog(this);
        dialog.setFileMode(QFileDialog::AnyFile);
        dialog.setWindowTitle(makeDialogTitle(tr("Choose File")));
        QFileInfo fi(predefined);
        if (fi.exists())
            dialog.setDirectory(fi.absolutePath());
        // FIXME: fix QFileDialog so that it filters properly: lib*.a
        dialog.setNameFilter(d->m_dialogFilter);
        if (dialog.exec() == QDialog::Accepted) {
            // probably loop here until the *.framework dir match
            QStringList paths = dialog.selectedFiles();
            if (!paths.isEmpty())
                newPath = paths.at(0);
        }
        break;
        }

    default:
        break;
    }

    // Delete trailing slashes unless it is "/"|"\\", only
    if (!newPath.isEmpty()) {
        newPath = QDir::toNativeSeparators(newPath);
        if (newPath.size() > 1 && newPath.endsWith(QDir::separator()))
            newPath.truncate(newPath.size() - 1);
        setPath(newPath);
    }

    emit browsingFinished();
    d->m_lineEdit->triggerChanged();
}
예제 #6
0
int Database::FTSOpen(
    sqlite3_tokenizer* pTokenizer,
    const char* input,
    int bytes,
    sqlite3_tokenizer_cursor** cursor) {
  UnicodeTokenizerCursor* new_cursor = new UnicodeTokenizerCursor;
  new_cursor->pTokenizer = pTokenizer;
  new_cursor->position = 0;

  QString str = QString::fromUtf8(input, bytes).toLower();
  QChar* data = str.data();
  // Decompose and strip punctuation.
  QList<Token> tokens;
  QString token;
  int start_offset = 0;
  int offset = 0;
  for (int i = 0; i < str.length(); ++i) {
    QChar c = data[i];
    ushort unicode = c.unicode();
    if (unicode <= 0x007f) {
      offset += 1;
    } else if (unicode >= 0x0080 && unicode <= 0x07ff) {
      offset += 2;
    } else if (unicode >= 0x0800) {
      offset += 3;
    }
    // Unicode astral planes unsupported in Qt?
    /*else if (unicode >= 0x010000 && unicode <= 0x10ffff) {
      offset += 4;
    }*/

    if (!data[i].isLetterOrNumber()) {
      // Token finished.
      if (token.length() != 0) {
        tokens << Token(token, start_offset, offset - 1);
        start_offset = offset;
        token.clear();
      } else {
        ++start_offset;
      }
    } else {
      if (data[i].decompositionTag() != QChar::NoDecomposition) {
        token.push_back(data[i].decomposition()[0]);
      } else {
        token.push_back(data[i]);
      }
    }

    if (i == str.length() - 1) {
      if (token.length() != 0) {
        tokens << Token(token, start_offset, offset);
        token.clear();
      }
    }
  }

  new_cursor->tokens = tokens;
  *cursor = reinterpret_cast<sqlite3_tokenizer_cursor*>(new_cursor);

  return SQLITE_OK;
}
예제 #7
0
QString qt_win_get_save_file_name(const QFileDialogArgs &args,
                                  QString *initialDirectory,
                                  QString *selectedFilter)
{
    QString result;

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

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

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

    DWORD selFilIdx = 0;

    int idx = 0;
    if (selectedFilter) {
        QStringList filterLst = qt_win_make_filters_list(args.filter);
        idx = filterLst.indexOf(*selectedFilter);
    }

    QDialog modal_widget;
    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
    modal_widget.setParent(args.parent, Qt::Window);
    QApplicationPrivate::enterModal(&modal_widget);
    bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails;
    // This block is used below for the lpstrDefExt member.
    // Note that the current MSDN docs document this member wrong.
    // It should rather be documented as "the default extension if no extension was given and if the
    // current filter does not have a extension (e.g (*)). If the current filter have an extension, use
    // the extension of the current filter"
    QString defaultSaveExt;
    if (selectedFilter && !selectedFilter->isEmpty()) {
        defaultSaveExt = qt_win_extract_filter(*selectedFilter);
        // make sure we only have the extension
        int firstDot = defaultSaveExt.indexOf(QLatin1Char('.'));
        if (firstDot != -1) {
            defaultSaveExt.remove(0, firstDot + 1);
        } else {
            defaultSaveExt.clear();
        }
    }

    OPENFILENAME *ofn = qt_win_make_OFN(args.parent, args.selection,
                                        args.directory, args.caption,
                                        qt_win_filter(args.filter, hideFiltersDetails),
                                        QFileDialog::AnyFile,
                                        args.options);

    ofn->lpstrDefExt = (wchar_t*)defaultSaveExt.utf16();

    if (idx)
        ofn->nFilterIndex = idx + 1;
    if (GetSaveFileName(ofn)) {
        result = QString::fromWCharArray(ofn->lpstrFile);
        selFilIdx = ofn->nFilterIndex;
    }
    qt_win_clean_up_OFN(&ofn);

#if defined(Q_WS_WINCE)
    int semIndex = result.indexOf(QLatin1Char(';'));
    if (semIndex >= 0)
        result = result.left(semIndex);
#endif

    QApplicationPrivate::leaveModal(&modal_widget);

    qt_win_eatMouseMove();

    if (result.isEmpty())
        return result;

    fi = result;
    *initialDirectory = fi.path();
    if (selectedFilter)
        *selectedFilter = qt_win_selected_filter(args.filter, selFilIdx);
    return fi.absoluteFilePath();
}
예제 #8
0
파일: entrymodel.cpp 프로젝트: mkiol/kaktus
int EntryModel::createItems(int offset, int limit)
{
    auto s = Settings::instance();
    auto db = DatabaseManager::instance();

    QList<DatabaseManager::Entry> list;

    bool ascOrder = s->getShowOldestFirst();

    // Counting 'last' & 'daterow' rows
    if (offset > 0) {
        int dummyRowsCount = 0;
        int l = this->rowCount();
        //qDebug() << "this->rowCount():" << l;
        for (int i = 0; i < l; ++i) {
            EntryItem* item = dynamic_cast<EntryItem*>(readRow(i));
            //qDebug() << item->id();
            if (item->id()=="last" || item->id()=="daterow") {
                ++dummyRowsCount;
            }
        }
        //qDebug() << "dummyRowsCount:" << dummyRowsCount << "orig offset:" << offset;
        if (offset > dummyRowsCount)
            offset = offset - dummyRowsCount;
    }

    int mode = s->getViewMode();
    switch (mode) {
    case 0:
        // View mode: Tabs->Feeds->Entries
        if (s->getFilter() == 2)
            list = db->readEntriesUnreadByStream(_feedId,offset,limit,ascOrder);
        else if (s->getFilter() == 1)
            list = db->readEntriesUnreadAndSavedByStream(_feedId,offset,limit,ascOrder);
        else
            list = db->readEntriesByStream(_feedId,offset,limit,ascOrder);
        break;
    case 1:
        // View mode: Tabs->Entries
        if (s->getFilter() == 2)
            list = db->readEntriesUnreadByTab(_feedId,offset,limit,ascOrder);
        else if (s->getFilter() == 1)
            list = db->readEntriesUnreadAndSavedByTab(_feedId,offset,limit,ascOrder);
        else
            list = db->readEntriesByTab(_feedId,offset,limit,ascOrder);
        break;
    case 2:
        // View mode: Feeds->Entries
        if (s->getFilter() == 2)
            list = db->readEntriesUnreadByStream(_feedId,offset,limit,ascOrder);
        else if (s->getFilter() == 1)
            list = db->readEntriesUnreadAndSavedByStream(_feedId,offset,limit,ascOrder);
        else
            list = db->readEntriesByStream(_feedId,offset,limit,ascOrder);
        break;
    case 3:
        // View mode: Entries
        if (s->getFilter() == 2)
            list = db->readEntriesUnreadByDashboard(s->getDashboardInUse(),offset,limit,ascOrder);
        else if (s->getFilter() == 1)
            list = db->readEntriesUnreadAndSavedByDashboard(s->getDashboardInUse(),offset,limit,ascOrder);
        else
            list = db->readEntriesByDashboard(s->getDashboardInUse(),offset,limit,ascOrder);
        break;
    case 4:
        // View mode: Saved
        list = db->readEntriesSavedByDashboard(s->getDashboardInUse(),offset,limit,ascOrder);
        break;
    case 5:
        // View mode: Slow
        if (s->getFilter() == 2)
            list = db->readEntriesSlowUnreadByDashboard(s->getDashboardInUse(),offset,limit,ascOrder);
        else if (s->getFilter() == 1)
            list = db->readEntriesSlowUnreadAndSavedByDashboard(s->getDashboardInUse(),offset,limit,ascOrder);
        else
            list = db->readEntriesSlowByDashboard(s->getDashboardInUse(),offset,limit,ascOrder);
        break;
    case 6:
        // View mode: Liked
        list = db->readEntriesLikedByDashboard(s->getDashboardInUse(),offset,limit,ascOrder);
        break;
    case 7:
        // View mode: Broadcast
        list = db->readEntriesBroadcastByDashboard(s->getDashboardInUse(),offset,limit,ascOrder);
        break;
    }

    //qDebug() << "limit:" << limit << "Row count:" << list.count() << "new offset:" << offset;

#ifndef ANDROID
    // Remove dummy row
    if (list.count()>0) {
        int l = rowCount();
        if (l>0) {
            EntryItem* item = dynamic_cast<EntryItem*>(readRow(l-1));
            //qDebug() << "item->id()" << item->id() << "l" << l;
            if (item->id()=="last")
                removeRow(l-1);
        }
    }
#endif

    QList<DatabaseManager::Entry>::iterator i = list.begin();

    int prevDateRow = 0;
    if (rowCount()>0) {
        EntryItem* item = dynamic_cast<EntryItem*>(readRow(rowCount()-1));
        prevDateRow = getDateRowId(item->date());
        //qDebug() << "prevDateRow UID:" << item->uid();
    }

    QRegExp re("<[^>]*>");
    while (i != list.end() ) {

        // Removing html tags!
        QTextDocument doc;
        doc.setHtml((*i).content);

        QString content0 = doc.toPlainText()
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
                .replace(QChar::ObjectReplacementCharacter,QChar::Space).trimmed();
#else
                .replace(QChar::ObjectReplacementCharacter,QChar(0x0020)).trimmed();
#endif
        QString content = content0.simplified();
        if (content.length()>1000) {
            content = content.left(997)+"...";
        } else if (content.length() < 15) {
            content.clear();
        }

        doc.setHtml((*i).title);
        QString title = doc.toPlainText()
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
                .replace(QChar::ObjectReplacementCharacter,QChar::Space)
#else
                .replace(QChar::ObjectReplacementCharacter,QChar(0x0020))
#endif
                .simplified();
        if (title.length()>200)
            title = title.left(197)+QString("...");

        //qDebug() << title;

        /*QRegExp rx("(\\S*)\\s*\((\\S*)\)", Qt::CaseInsensitive);
        if (rx.indexIn((*i).author)!=-1) {
            qDebug() << "(*i).author:" << (*i).author << "cap:" << rx.cap(1).toUtf8();
            //(*i).author = rx.cap(1).toUtf8();
        }*/

        // Detecting invalid images
        bool imageOk = true;
        QUrl imageUrl((*i).image);
        //qDebug() << imageUrl.path();
        if (imageUrl.path() == "/assets/images/transparent.png")
            imageOk = false;
        if (imageUrl.host() == "rc.feedsportal.com")
            imageOk = false;

        // Adding date row
        int dateRow = getDateRowId((*i).publishedAt);
        if ((!ascOrder && dateRow>prevDateRow) || (ascOrder && dateRow<prevDateRow) || prevDateRow == 0) {
            switch (dateRow) {
            case 1:
                appendRow(new EntryItem("daterow",tr("Today"),"","","","","","","","","","",false,false,false,0,0,0,0));
                break;
            case 2:
                appendRow(new EntryItem("daterow",tr("Yesterday"),"","","","","","","","","","",false,false,false,0,0,0,0));
                break;
            case 3:
                appendRow(new EntryItem("daterow",tr("Current week"),"","","","","","","","","","",false,false,false,0,0,0,0));
                break;
            case 4:
                appendRow(new EntryItem("daterow",tr("Current month"),"","","","","","","","","","",false,false,false,0,0,0,0));
                break;
            case 5:
                appendRow(new EntryItem("daterow",tr("Previous month"),"","","","","","","","","","",false,false,false,0,0,0,0));
                break;
            case 6:
                appendRow(new EntryItem("daterow",tr("Current year"),"","","","","","","","","","",false,false,false,0,0,0,0));
                break;
            default:
                appendRow(new EntryItem("daterow",tr("Previous year & older"),"","","","","","","","","","",false,false,false,0,0,0,0));
                break;
            }
        }
        prevDateRow = dateRow;
        //qDebug() << "(*i).broadcast" << (*i).broadcast << ((*i).broadcast==1);
        //qDebug() << (*i).id << (*i).link;
        appendRow(new EntryItem((*i).id,
                                title.remove(re),
                                (*i).author,
                                content,
                                content0,
                                (*i).content,
                                (*i).link,
                                imageOk? (*i).image : "",
                                (*i).feedId,
                                (*i).feedIcon,
                                (*i).feedTitle.remove(re),
                                (*i).annotations,
                                db->isCacheExistsByEntryId((*i).id),
                                (*i).broadcast==1,
                                (*i).liked==1,
                                (*i).fresh,
                                (*i).read,
                                (*i).saved,
                                (*i).publishedAt
                                ));
        ++i;
    }
예제 #9
0
int Recognizer::nextToken()
{
  QString text;

 Lagain:
  while (ch.isSpace ())
    inp ();
  
  if (ch.isNull ())
    return EOF_SYMBOL;

  int token = ch.unicode ();

  if (token == '"')
    {
      inp(); // skip "
      text.clear ();
      while (! ch.isNull () && ch != QLatin1Char ('"'))
        {
          if (ch == QLatin1Char ('\\'))
            {
              text += ch;
              inp();
            }
          text += ch;
          inp ();
        }

      if (ch == QLatin1Char ('"'))
        inp ();
      else
        qerr << _M_input_file << ":" << _M_line << ": Warning. Expected `\"'" << endl;

      _M_current_value = text;
      return (token = STRING_LITERAL);
    }

  else if (ch.isLetterOrNumber () || ch == QLatin1Char ('_'))
    {
      text.clear ();
      do { text += ch; inp (); }
      while (ch.isLetterOrNumber () || ch == QLatin1Char ('_') || ch == QLatin1Char ('.'));
      _M_current_value = text;
      return (token = ID);
    }

  else if (token == '%')
    {
      text.clear ();

      do { inp (); }
      while (ch.isSpace ());

      do { text += ch; inp (); }
      while (ch.isLetterOrNumber () || ch == QLatin1Char ('_') || ch == QLatin1Char ('-'));

      if (text == QLatin1String("token_prefix"))
        return (token = TOKEN_PREFIX);
      else if (text == QLatin1String("merged_output"))
        return (token = MERGED_OUTPUT);
      else if (text == QLatin1String("token"))
        return (token = TOKEN);
      else if (text == QLatin1String("start"))
        return (token = START);
      else if (text == QLatin1String("parser"))
        return (token = PARSER);
      else if (text == QLatin1String("decl"))
        return (token = DECL_FILE);
      else if (text == QLatin1String("impl"))
        return (token = IMPL_FILE);
      else if (text == QLatin1String("expect"))
        return (token = EXPECT);
      else if (text == QLatin1String("expect-rr"))
        return (token = EXPECT_RR);
      else if (text == QLatin1String("left"))
        return (token = LEFT);
      else if (text == QLatin1String("right"))
        return (token = RIGHT);
      else if (text == QLatin1String("nonassoc"))
        return (token = NONASSOC);
      else if (text == QLatin1String("prec"))
        return (token = PREC);
      else
        {
          qerr << _M_input_file << ":" << _M_line << ": Unknown keyword `" << text << "'" << endl;
          exit (EXIT_FAILURE);
          return (token = ERROR);
        }
    }

  inp ();

  if (token == '-' && ch == QLatin1Char ('-'))
    {
      do { inp (); }
      while (! ch.isNull () && ch != QLatin1Char ('\n'));
      goto Lagain;
    }

  else if (token == ':' && ch == QLatin1Char (':'))
    {
      inp ();
      if (ch != QLatin1Char ('='))
        return (token = ERROR);
      inp ();
      return (token = COLON);
    }

  else if (token == '/' && ch == QLatin1Char (':'))
    {
      _M_action_line = _M_line;

      text.clear ();
      if (! _M_no_lines)
        text += QLatin1String ("\n#line ") + QString::number (_M_action_line) + " \"" + _M_input_file + "\"\n";
      inp (); // skip ':'

      forever
        {
          while (! ch.isNull ())
            {
              token = ch.unicode ();
              inp ();

              if (token == ':' && ch == QLatin1Char ('/'))
                break;

              text += QLatin1Char (token);
            }

          if (ch != QLatin1Char ('/'))
            return (token = ERROR);

          inp ();

          if (ch.isNull () || ch.isSpace ())
            {
              _M_current_value = text;
              return (token = DECL);
            }
	  else
	    text += QLatin1String (":/");
        }
    }
예제 #10
0
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice,
    const QString &fname, QString currentPath, bool ignoreErrors)
{
    Q_ASSERT(m_errorDevice);
    const QChar slash = QLatin1Char('/');
    if (!currentPath.isEmpty() && !currentPath.endsWith(slash))
        currentPath += slash;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        default:
            break;
        }
    }

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

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

    return true;
}
예제 #11
0
void Parser::parseFiles(QNetworkReply *reply, QMap<QNetworkReply*, Structureelement*> *replies, QString downloadDirectoryPath)
{
    // Holen die aktuelle Veranstaltung aus der Map
    Structureelement* aktuellerOrdner = replies->value(reply);

    // Auslesen der Antwort und Speichern in dem XmlReader
    QString replyText = reply->readAll();
    QXmlStreamReader Reader;
    Reader.addData(replyText);


    // Vorbereitung der Daten für die Elemente
    QString currentXmlTag;
    QUrl    url;
    QString name;
    QString time;
    qint32  size = 0;

    // Prüfen auf das Ende
    while(!Reader.atEnd())
    {
        // Lese nächstes Element
        Reader.readNext();

        // 1. Fall: Öffnendes Element <Element>
        if(Reader.isStartElement())
        {
            // Speichern des Namens
            currentXmlTag = Reader.name().toString();
        }

        // 2. Fall: Schließendes Element mit Namen Response </Response>
        else if (Reader.isEndElement() && Reader.name() == "response")
        {
            // Hinzufügen des Slashs bei der Url von Ordnern
            if(!size)
                url.setUrl(url.toString() % "/");

            // Wechsel in den übergeordneten Ordner des aktuellen Elements
            QString bla = url.toString();
            while(!url.toString().contains((aktuellerOrdner->data(urlRole).toUrl().toString()), Qt::CaseSensitive))//(in = RegExp.indexIn(url.toString())) == -1)
            {
                aktuellerOrdner->sortChildren(0, Qt::AscendingOrder);
                aktuellerOrdner = (Structureelement*)aktuellerOrdner->parent();
                if (aktuellerOrdner == 0)
                    qDebug() << replyText;
            }

            // Ignorieren aller Adressen, die "/Forms" enthalten
            if (!url.toString().contains("/Forms", Qt::CaseSensitive))
            {
                // Prüfe auf Elementart
                // 1. Fall: Datei (size > 0)
                if (size)
                {
                    // Erstellen einer neuen Datei
                    Structureelement* newFile = new Structureelement(name, url, time, size);

                    // Hinzufügen des endungsabhängigen Icons
                    // PDF
                    if (name.contains(QRegExp(".pdf$", Qt::CaseInsensitive)))
                        newFile->setData(QIcon(":/Icons/Icons/filetype_pdf.png"), Qt::DecorationRole);

                    // ZIP
                    else if (name.contains(QRegExp(".zip$", Qt::CaseInsensitive)))
                        newFile->setData(QIcon(":/Icons/Icons/filetype_zip.png"), Qt::DecorationRole);

                    // RAR
                    else if (name.contains(QRegExp(".rar$", Qt::CaseInsensitive)))
                        newFile->setData(QIcon(":/Icons/Icons/filetype_rar.png"), Qt::DecorationRole);

                    // Sonstige
                    else
                        newFile->setData(QIcon(":/Icons/Icons/file.png"), Qt::DecorationRole);


                    QString path;
                    path.append(Utils::getStrukturelementPfad(aktuellerOrdner, downloadDirectoryPath) %"/");
                    path.append(name);
                    path.remove(0,8);

                    if(QFile::exists(path))
                    {
                        newFile->setData(SYNCHRONISED, synchronisedRole);
                    }
                    else
                    {
                        newFile->setData(NOT_SYNCHRONISED, synchronisedRole);
                    }

                    QList<QStandardItem*> row;
                    row.append(newFile);
                    row.append(new QStandardItem(QString::number(size/1024.0/1024.0, 'f', 2) % " MB"));
                    row.append(new QStandardItem(QDateTime::fromString(time, Qt::ISODate).toString("yyyy-MM-dd hh:mm")));

                    // Hinzufügen zum aktuellen Ordner
                    aktuellerOrdner->appendRow(row);
                }
                // 2. Fall: Ordner/Veranstaltung
                // Ausschließen der Ordnernamen "documents" und "structured"
                else if (name != "documents" && name != "structured" && !url.toString().contains("exerciseCourse"))
                {
                    // Erstellen eines neuen Ordners
                    Structureelement* newDirectory = new Structureelement(name, url, directoryItem);

                    // Setzen des Zeichens
                    newDirectory->setData(QIcon(":/Icons/Icons/25_folder.png"), Qt::DecorationRole);

                    // Hinzufügen zum aktuellen Ordner
                    aktuellerOrdner->appendRow(newDirectory);

                    // NeuerOrdner wird zum aktuellen Ordner
                    aktuellerOrdner = newDirectory;
                }
            }

            // Löschen aller eingelesener Daten
            url.clear();
            name.clear();
            size = 0;
            time.clear();
        }

        // Einlesen der Elementeigenschaften
        else if (Reader.isCharacters() && !Reader.isWhitespace())
        {
            // URL
            if(currentXmlTag == "href" && url.isEmpty())
                url.setUrl(QString::fromUtf8(Reader.text().toString().toLatin1()));

            // Name
            else if (currentXmlTag == "displayname")
                name = QString::fromUtf8(Reader.text().toString().toLatin1());

            // Größe
            else if (currentXmlTag == "getcontentlength")
                size = Reader.text().toString().toInt();

            // Modifizierungsdatum
            else if (currentXmlTag == "getlastmodified")
                time = QString::fromUtf8(Reader.text().toString().toLatin1());
        }
    }

    // Leere Ordner wieder rausschmeißen.
    Structureelement* rootCourse = replies->value(reply);
    for (int i = 0; i < rootCourse->rowCount(); i++)
    {
        Structureelement *item = (Structureelement *)rootCourse->child(i);
        if (item->type() == directoryItem && item->rowCount() == 0)
        {
            rootCourse->removeRow(i);
        }
    }
    // Sortieren aller Dateien
    replies->value(reply)->sortChildren(0, Qt::AscendingOrder);
}
예제 #12
0
파일: commandexec.cpp 프로젝트: KDE/kdesvn
int CommandExec::exec(const QCommandLineParser *parser)
{
    m_pCPart->parser = const_cast<QCommandLineParser*>(parser);
    m_pCPart->args = parser->positionalArguments();
    if (m_pCPart->args.isEmpty()) {
        return -1;
    }
    m_lastMessages.clear();
    m_lastMessagesLines = 0;
    m_pCPart->m_SvnWrapper->reInitClient();
    bool dont_check_second = false;
    bool dont_check_all = false;
    bool path_only = false;
    bool no_revision = false;
    bool check_force = false;

    if (m_pCPart->args.count() >= 2) {
        m_pCPart->cmd = m_pCPart->args.at(1);
        m_pCPart->cmd = m_pCPart->cmd.toLower();
    }
    QByteArray slotCmd;
    if (!QString::compare(m_pCPart->cmd, "log")) {
        slotCmd = SLOT(slotCmd_log());
    } else if (!QString::compare(m_pCPart->cmd, "cat")) {
        slotCmd = SLOT(slotCmd_cat());
        m_pCPart->single_revision = true;
    } else if (!QString::compare(m_pCPart->cmd, "get")) {
        slotCmd = SLOT(slotCmd_get());
        m_pCPart->single_revision = true;
    } else if (!QString::compare(m_pCPart->cmd, "help")) {
        slotCmd = SLOT(slotCmd_help());
    } else if (!QString::compare(m_pCPart->cmd, "blame") ||
               !QString::compare(m_pCPart->cmd, "annotate")) {
        slotCmd = SLOT(slotCmd_blame());
    } else if (!QString::compare(m_pCPart->cmd, "update")) {
        slotCmd = SLOT(slotCmd_update());
        m_pCPart->single_revision = true;
    } else if (!QString::compare(m_pCPart->cmd, "diff")) {
        m_pCPart->start = svn::Revision::WORKING;
        slotCmd = SLOT(slotCmd_diff());
    } else if (!QString::compare(m_pCPart->cmd, "info")) {
        slotCmd = SLOT(slotCmd_info());
        m_pCPart->single_revision = true;
    } else if (!QString::compare(m_pCPart->cmd, "commit") ||
               !QString::compare(m_pCPart->cmd, "ci")) {
        slotCmd = SLOT(slotCmd_commit());
    } else if (!QString::compare(m_pCPart->cmd, "list") ||
               !QString::compare(m_pCPart->cmd, "ls")) {
        slotCmd = SLOT(slotCmd_list());
    } else if (!QString::compare(m_pCPart->cmd, "copy") ||
               !QString::compare(m_pCPart->cmd, "cp")) {
        slotCmd = SLOT(slotCmd_copy());
        dont_check_second = true;
    } else if (!QString::compare(m_pCPart->cmd, "move") ||
               !QString::compare(m_pCPart->cmd, "rename") ||
               !QString::compare(m_pCPart->cmd, "mv")) {
        slotCmd = SLOT(slotCmd_move());
        dont_check_second = true;
    } else if (!QString::compare(m_pCPart->cmd, "checkout") ||
               !QString::compare(m_pCPart->cmd, "co")) {
        slotCmd = SLOT(slotCmd_checkout());
        dont_check_second = true;
    } else if (!QString::compare(m_pCPart->cmd, "checkoutto") ||
               !QString::compare(m_pCPart->cmd, "coto")) {
        slotCmd = SLOT(slotCmd_checkoutto());
        dont_check_second = true;
    } else if (!QString::compare(m_pCPart->cmd, "export")) {
        slotCmd = SLOT(slotCmd_export());
        dont_check_second = true;
    } else if (!QString::compare(m_pCPart->cmd, "exportto")) {
        slotCmd = SLOT(slotCmd_exportto());
        dont_check_second = true;
    } else if (!QString::compare(m_pCPart->cmd, "delete") ||
               !QString::compare(m_pCPart->cmd, "del") ||
               !QString::compare(m_pCPart->cmd, "rm") ||
               !QString::compare(m_pCPart->cmd, "remove")) {
        slotCmd = SLOT(slotCmd_delete());
    } else if (!QString::compare(m_pCPart->cmd, "add")) {
        slotCmd = SLOT(slotCmd_add());
        dont_check_all = true;
        path_only = true;
    } else if (!QString::compare(m_pCPart->cmd, "undo") ||
               !QString::compare(m_pCPart->cmd, "revert")) {
        slotCmd = SLOT(slotCmd_revert());
    } else if (!QString::compare(m_pCPart->cmd, "checknew") ||
               !QString::compare(m_pCPart->cmd, "addnew")) {
        slotCmd = SLOT(slotCmd_addnew());
    } else if (!QString::compare(m_pCPart->cmd, "switch")) {
        slotCmd = SLOT(slotCmd_switch());
    } else if (!QString::compare(m_pCPart->cmd, "tree")) {
        slotCmd = SLOT(slotCmd_tree());
    } else if (!QString::compare(m_pCPart->cmd, "lock")) {
        slotCmd = SLOT(slotCmd_lock());
        no_revision = true;
        check_force = true;
    } else if (!QString::compare(m_pCPart->cmd, "unlock")) {
        slotCmd = SLOT(slotCmd_unlock());
        no_revision = true;
        check_force = true;
    }

    bool found = connect(this, SIGNAL(executeMe()), this, slotCmd.constData());
    if (!found) {
        KMessageBox::sorry(0,
                           i18n("Command \"%1\" not implemented or known", m_pCPart->cmd),
                           i18n("SVN Error"));
        return -1;
    }

    QString tmp;
    QString mainProto;
    for (int j = 2; j < m_pCPart->args.count(); ++j) {
        QUrl tmpurl = QUrl::fromUserInput(m_pCPart->args.at(j),
                                          QDir::currentPath());
        tmpurl.setScheme(svn::Url::transformProtokoll(tmpurl.scheme()));
        if (tmpurl.scheme().indexOf(QLatin1String("ssh")) != -1) {
            SshAgent ag;
            // this class itself checks if done before
            ag.addSshIdentities();
        }
        m_pCPart->extraRevisions[j - 2] = svn::Revision::HEAD;

        if (tmpurl.isLocalFile() && (j == 2 || !dont_check_second) && !dont_check_all) {
            QUrl repoUrl;
            if (m_pCPart->m_SvnWrapper->isLocalWorkingCopy(tmpurl.path(), repoUrl)) {
                tmp = tmpurl.path();
                m_pCPart->repoUrls[j - 2] = repoUrl;
                m_pCPart->extraRevisions[j - 2] = svn::Revision::WORKING;
                if (j == 2) {
                    mainProto.clear();
                }
            } else {
                tmp = tmpurl.url();
                if (j == 2) {
                    mainProto = QLatin1String("file://");
                }
            }
        } else if (path_only) {
            tmp = tmpurl.path();
        } else {
            tmp = tmpurl.url();
            if (j == 2) {
                mainProto = tmpurl.scheme();
            }
        }
        if ((j > 2 && dont_check_second) || dont_check_all) {
            if (mainProto.isEmpty()) {
                tmp = tmpurl.path();
            }
        }
        const QStringList l = tmp.split(QLatin1Char('?'), QString::SkipEmptyParts);
        if (!l.isEmpty()) {
            tmp = l[0];
        }
        while (tmp.endsWith(QLatin1Char('/'))) {
            tmp.chop(1);
        }
        m_pCPart->urls.append(tmp);
        if ((j > 2 && dont_check_second) || dont_check_all) {
            continue;
        }
        const QList<QPair<QString, QString> > q = QUrlQuery(tmpurl).queryItems();
        for(int i = 0; i < q.size(); ++i) {
            if (q.at(i).first == QLatin1String("rev")) {
                svn::Revision re = q.at(i).second;
                if (re) {
                    m_pCPart->extraRevisions[j - 2] = re;
                }
            }
        }
    }
    if (m_pCPart->urls.isEmpty()) {
        m_pCPart->urls.append(QLatin1String("."));
    }

    if (!no_revision) {
        if (m_pCPart->parser->isSet("R")) {
            m_pCPart->ask_revision = true;
            if (!askRevision()) {
                return 0;
            }
        } else if (m_pCPart->parser->isSet("r")) {
            scanRevision();
        }
    }

    m_pCPart->force = check_force && m_pCPart->parser->isSet("f");

    if (m_pCPart->parser->isSet("o")) {
        m_pCPart->outfile_set = true;
        m_pCPart->outfile = m_pCPart->parser->value("o");
    }
    if (m_pCPart->parser->isSet("l")) {
        QString s = m_pCPart->parser->value("l");
        m_pCPart->log_limit = s.toInt();
        if (m_pCPart->log_limit < 0) {
            m_pCPart->log_limit = 0;
        }
    }

    emit executeMe();
    if (Kdesvnsettings::self()->cmdline_show_logwindow() &&
            m_lastMessagesLines >= Kdesvnsettings::self()->cmdline_log_minline()) {
        QPointer<KSvnSimpleOkDialog> dlg(new KSvnSimpleOkDialog(QStringLiteral("kdesvn_cmd_log"), QApplication::activeModalWidget()));
        QTextBrowser *ptr = new QTextBrowser(dlg);
        ptr->setText(m_lastMessages);
        ptr->setReadOnly(true);
        dlg->addWidget(ptr);
        QString cmd = qApp->arguments().join(QLatin1Char(' '));
        dlg->setWindowTitle(cmd);
        dlg->exec();
        delete dlg;
    }
    return 0;
}
예제 #13
0
void PBIBackend::unlockApp(QStringList appID, QString injail){
  QHash<QString, NGApp> hash;
  if(JAILPKGS.contains(injail)){ hash = JAILPKGS[injail]; }
  for(int i=0; i<appID.length(); i++){
    NGApp app;
    if(hash.contains(appID[i])){ app = hash[appID[i]]; }
    else if(APPHASH.contains(appID[i])){ app = APPHASH[appID[i]]; }
    else if(PKGHASH.contains(appID[i])){ app = PKGHASH[appID[i]]; }
    else{ continue; }
    if(app.isInstalled && app.isLocked){
      //Run lock/unlock commands ASAP since they take no time at all, but have to be in the pkg queue
      QString cmd;
      if(injail.isEmpty() || !RUNNINGJAILS.contains(injail) ){ cmd = "pc-pkg unlock -y "+appID[i]; injail.clear();}
      else{ cmd = "pc-pkg -j "+RUNNINGJAILS[injail]+" unlock -y "+appID[i]; }
      PENDING.prepend(appID[i]+"::::"+cmd+"::::"+injail);
    }
  }
  QTimer::singleShot(0,this,SLOT(checkProcesses()) );	
}
예제 #14
0
Tellico::Data::CollPtr BibtexImporter::readCollection(const QString& text, int urlCount) {
  if(text.isEmpty()) {
    myDebug() << "no text";
    return Data::CollPtr();
  }
  Data::CollPtr ptr(new Data::BibtexCollection(true));
  Data::BibtexCollection* c = static_cast<Data::BibtexCollection*>(ptr.data());

  parseText(text); // populates m_nodes
  if(m_cancelled) {
    return Data::CollPtr();
  }

  if(m_nodes.isEmpty()) {
    return Data::CollPtr();
  }

  QString str;
  const uint count = m_nodes.count();
  const uint stepSize = qMax(s_stepSize, count/100);
  const bool showProgress = options() & ImportProgress;

  Data::CollPtr currentColl = currentCollection();
  if(!currentColl || currentColl->type() != Data::Collection::Bibtex) {
    currentColl = ptr;
  }

  uint j = 0;
  for(int i = 0; !m_cancelled && i < m_nodes.count(); ++i, ++j) {
    AST* node = m_nodes[i];
    // if we're parsing a macro string, comment or preamble, skip it for now
    if(bt_entry_metatype(node) == BTE_PREAMBLE) {
      char* preamble = bt_get_text(node);
      if(preamble) {
        c->setPreamble(QString::fromUtf8(preamble));
      }
      continue;
    }

    if(bt_entry_metatype(node) == BTE_MACRODEF) {
      char* macro;
      (void) bt_next_field(node, 0, &macro);
      // FIXME: replace macros within macro definitions!
      // lookup lowercase macro in map
      c->addMacro(m_macros[QString::fromUtf8(macro)], QString::fromUtf8(bt_macro_text(macro, 0, 0)));
      continue;
    }

    if(bt_entry_metatype(node) == BTE_COMMENT) {
      continue;
    }

    // now we're parsing a regular entry
    Data::EntryPtr entry(new Data::Entry(ptr));

    str = QString::fromUtf8(bt_entry_type(node));
//    myDebug() << "entry type: " << str;
    // text is automatically put into lower-case by btparse
    Data::BibtexCollection::setFieldValue(entry, QLatin1String("entry-type"), str, currentColl);

    str = QString::fromUtf8(bt_entry_key(node));
//    myDebug() << "entry key: " << str;
    Data::BibtexCollection::setFieldValue(entry, QLatin1String("key"), str, currentColl);

    char* name;
    AST* field = 0;
    while((field = bt_next_field(node, field, &name))) {
//      myDebug() << "\tfound: " << name;
//      str = QLatin1String(bt_get_text(field));
      str.clear();
      AST* value = 0;
      bt_nodetype type;
      char* svalue;
      bool end_macro = false;
      while((value = bt_next_value(field, value, &type, &svalue))) {
        switch(type) {
          case BTAST_STRING:
          case BTAST_NUMBER:
            str += BibtexHandler::importText(svalue).simplified();
            end_macro = false;
            break;
          case BTAST_MACRO:
            str += QString::fromUtf8(svalue) + QLatin1Char('#');
            end_macro = true;
            break;
          default:
            break;
        }
      }
      if(end_macro) {
        // remove last character '#'
        str.truncate(str.length() - 1);
      }
      QString fieldName = QString::fromUtf8(name);
      if(fieldName == QLatin1String("author") || fieldName == QLatin1String("editor")) {
        str.replace(QRegExp(QLatin1String("\\sand\\s")),FieldFormat::delimiterString());
      }
      // there's a 'key' field different from the citation key
      // http://nwalsh.com/tex/texhelp/bibtx-37.html
      // TODO account for this later
      if(fieldName == QLatin1String("key")) {
        myLog() << "skipping bibtex 'key' field for" << str;
      } else {
        Data::BibtexCollection::setFieldValue(entry, fieldName, str, currentColl);
      }
    }

    ptr->addEntries(entry);

    if(showProgress && j%stepSize == 0) {
      emit signalProgress(this, urlCount*100 + 100*j/count);
      kapp->processEvents();
    }
  }

  if(m_cancelled) {
    ptr = 0;
  }

  // clean-up
  foreach(AST* node, m_nodes) {
    bt_free_ast(node);
  }
예제 #15
0
파일: main.cpp 프로젝트: rpoyner/pcbsd
void getCMD(int argc, char ** argv, QString& binary, QString& args, QString& path){
  //Get the input file
  QString inFile;
  bool showDLG = false; //flag to bypass any default application setting
  if(argc > 1){ 
    for(int i=1; i<argc; i++){
      if(QString(argv[i]).simplified() == "-select"){
      	showDLG = true;      
      }else{
        inFile = argv[i];
        break;
      }
    }
  }else{
    printUsageInfo();
  }
  //Make sure that it is a valid file/URL
  bool isFile=false; bool isUrl=false;
  if(QFile::exists(inFile)){ isFile=true; }
  else if(QUrl(inFile).isValid()){ isUrl=true; }
  if( !isFile && !isUrl ){ qDebug() << "Error: Invalid file or URL"; return;}
  //Determing the type of file (extension)
  QString extension;
  if(isFile){ 
    QFileInfo info(inFile);
    extension=info.completeSuffix();
    if(info.isDir()){ extension="directory"; }
    else if(info.isExecutable() && extension!="desktop"){ extension="binary"; }
  }else if(isUrl){ extension = inFile.section(":",0,0); }
  //if not an application  - find the right application to open the file
  QString cmd;
  bool useInputFile = false;
  if(extension=="desktop" && !showDLG){ 
    bool ok = false;
    XDGDesktop DF = LXDG::loadDesktopFile(inFile, ok);
    if(!ok){
      qDebug() << "[ERROR] Input *.desktop file could not be read:" << inFile;
      exit(1);
    }
    switch(DF.type){
      case XDGDesktop::APP:
        if(!DF.exec.isEmpty()){ 
          cmd = LXDG::getDesktopExec(DF);
          if(!DF.path.isEmpty()){ path = DF.path; }
        }else{ 
          qDebug() << "[ERROR] Input *.desktop application file is missing the Exec line:" << inFile;
          exit(1);
        }
        break;
      case XDGDesktop::LINK:
        if(!DF.url.isEmpty()){
          //This is a URL - so adjust the input variables appropriately
          inFile = DF.url;
          cmd.clear();
          extension = inFile.section(":",0,0);
        }else{
          qDebug() << "[ERROR] Input *.desktop link file is missing the URL line:" << inFile;
          exit(1);	
        }
        break;
      case XDGDesktop::DIR:
        if(!DF.path.isEmpty()){
          //This is a directory link - adjust inputs
          inFile = DF.path;
          cmd.clear();
          extension = "directorypath";
        }else{
          qDebug() << "[ERROR] Input *.desktop directory file is missing the Path line:" << inFile;
          exit(1);        	
        }
        break;
      default:
        qDebug() << "[ERROR] Unknown *.desktop file type:" << inFile;
        exit(1);
    }
  }
  if(cmd.isEmpty()){
    if(extension=="binary"){ cmd = inFile; }
    else{
    //Find out the proper application to use this file/directory
    useInputFile=true;
    cmd = cmdFromUser(argc, argv, inFile, extension, path, showDLG);
    }
  }
  //qDebug() << "Found Command:" << cmd << "Extension:" << extension;
  //Clean up the command appropriately for output
  if(cmd.contains("%")){cmd = cmd.remove("%U").remove("%u").remove("%F").remove("%f").simplified(); }
  binary = cmd;
  if(useInputFile){ args = inFile; }
}
/*!
  Load, parse, and process a qdoc configuration file. This
  function is only called by the other load() function, but
  this one is recursive, i.e., it calls itself when it sees
  an \c{include} statement in the qdog configuration file.
 */
void Config::load(Location location, const QString& fileName)
{
    QRegExp keySyntax("\\w+(?:\\.\\w+)*");

#define SKIP_CHAR() \
    do { \
        location.advance(c); \
        ++i; \
        c = text.at(i); \
        cc = c.unicode(); \
    } while (0)

#define SKIP_SPACES() \
    while (c.isSpace() && cc != '\n') \
        SKIP_CHAR()

#define PUT_CHAR() \
    word += c; \
    SKIP_CHAR();

    if (location.depth() > 16)
        location.fatal(tr("Too many nested includes"));

    QFile fin(fileName);
    if (!fin.open(QFile::ReadOnly | QFile::Text)) {
        fin.setFileName(fileName + ".qdoc");
        if (!fin.open(QFile::ReadOnly | QFile::Text))
            location.fatal(tr("Cannot open file '%1': %2").arg(fileName).arg(fin.errorString()));
    }

    QTextStream stream(&fin);
    stream.setCodec("UTF-8");
    QString text = stream.readAll();
    text += QLatin1String("\n\n");
    text += QChar('\0');
    fin.close();

    location.push(fileName);
    location.start();

    int i = 0;
    QChar c = text.at(0);
    uint cc = c.unicode();
    while (i < (int) text.length()) {
        if (cc == 0)
            ++i;
        else if (c.isSpace()) {
            SKIP_CHAR();
        }
        else if (cc == '#') {
            do {
                SKIP_CHAR();
            } while (cc != '\n');
        }
        else if (isMetaKeyChar(c)) {
            Location keyLoc = location;
            bool plus = false;
            QString stringValue;
            QStringList stringListValue;
            QString word;
            bool inQuote = false;
            bool prevWordQuoted = true;
            bool metWord = false;

            MetaStack stack;
            do {
                stack.process(c, location);
                SKIP_CHAR();
            } while (isMetaKeyChar(c));

            QStringList keys = stack.getExpanded(location);
            SKIP_SPACES();

            if (keys.count() == 1 && keys.first() == "include") {
                QString includeFile;

                if (cc != '(')
                    location.fatal(tr("Bad include syntax"));
                SKIP_CHAR();
                SKIP_SPACES();
                while (!c.isSpace() && cc != '#' && cc != ')') {
                    includeFile += c;
                    SKIP_CHAR();
                }
                SKIP_SPACES();
                if (cc != ')')
                    location.fatal(tr("Bad include syntax"));
                SKIP_CHAR();
                SKIP_SPACES();
                if (cc != '#' && cc != '\n')
                    location.fatal(tr("Trailing garbage"));

                /*
                  Here is the recursive call.
                 */
                load(location,
                      QFileInfo(QFileInfo(fileName).dir(), includeFile)
                      .filePath());
            }
            else {
                /*
                  It wasn't an include statement, so it;s something else.
                 */
                if (cc == '+') {
                    plus = true;
                    SKIP_CHAR();
                }
                if (cc != '=')
                    location.fatal(tr("Expected '=' or '+=' after key"));
                SKIP_CHAR();
                SKIP_SPACES();

                for (;;) {
                    if (cc == '\\') {
                        int metaCharPos;

                        SKIP_CHAR();
                        if (cc == '\n') {
                            SKIP_CHAR();
                        }
                        else if (cc > '0' && cc < '8') {
                            word += QChar(c.digitValue());
                            SKIP_CHAR();
                        }
                        else if ((metaCharPos = QString::fromLatin1("abfnrtv").indexOf(c)) != -1) {
                            word += "\a\b\f\n\r\t\v"[metaCharPos];
                            SKIP_CHAR();
                        }
                        else {
                            PUT_CHAR();
                        }
                    }
                    else if (c.isSpace() || cc == '#') {
                        if (inQuote) {
                            if (cc == '\n')
                                location.fatal(tr("Unterminated string"));
                            PUT_CHAR();
                        }
                        else {
                            if (!word.isEmpty()) {
                                if (metWord)
                                    stringValue += QLatin1Char(' ');
                                stringValue += word;
                                stringListValue << word;
                                metWord = true;
                                word.clear();
                                prevWordQuoted = false;
                            }
                            if (cc == '\n' || cc == '#')
                                break;
                            SKIP_SPACES();
                        }
                    }
                    else if (cc == '"') {
                        if (inQuote) {
                            if (!prevWordQuoted)
                                stringValue += QLatin1Char(' ');
                            stringValue += word;
                            if (!word.isEmpty())
                                stringListValue << word;
                            metWord = true;
                            word.clear();
                            prevWordQuoted = true;
                        }
                        inQuote = !inQuote;
                        SKIP_CHAR();
                    }
                    else if (cc == '$') {
                        QString var;
                        SKIP_CHAR();
                        while (c.isLetterOrNumber() || cc == '_') {
                            var += c;
                            SKIP_CHAR();
                        }
                        if (!var.isEmpty()) {
                            char *val = getenv(var.toLatin1().data());
                            if (val == 0) {
                                location.fatal(tr("Environment variable '%1' undefined").arg(var));
                            }
                            else {
                                word += QString(val);
                            }
                        }
                    }
                    else {
                        if (!inQuote && cc == '=')
                            location.fatal(tr("Unexpected '='"));
                        PUT_CHAR();
                    }
                }

                QStringList::ConstIterator key = keys.begin();
                while (key != keys.end()) {
                    if (!keySyntax.exactMatch(*key))
                        keyLoc.fatal(tr("Invalid key '%1'").arg(*key));

                    if (plus) {
                        if (locMap[*key].isEmpty()) {
                            locMap[*key] = keyLoc;
                        }
                        else {
                            locMap[*key].setEtc(true);
                        }
                        if (stringValueMap[*key].isEmpty()) {
                            stringValueMap[*key] = stringValue;
                        }
                        else {
                            stringValueMap[*key] +=
                                QLatin1Char(' ') + stringValue;
                        }
                        stringListValueMap[*key] += stringListValue;
                    }
                    else {
                        locMap[*key] = keyLoc;
                        stringValueMap[*key] = stringValue;
                        stringListValueMap[*key] = stringListValue;
                    }
                    ++key;
                }
            }
        }
        else {
            location.fatal(tr("Unexpected character '%1' at beginning of line")
                            .arg(c));
        }
    }
}
예제 #17
0
/*!
    Returns a Qt version of the given \a sys_fmt Symbian locale format string.
*/
static QString s60ToQtFormat(const QString &sys_fmt)
{
    TLocale *locale = _s60Locale.GetLocale();

    QString result;
    QString other;
    QString qtformatchars = QString::fromLatin1("adhmsyzAHM");

    QChar c;
    int i = 0;
    bool open_escape = false;
    bool abbrev_next = false;
    bool abbrev_day = false;
    bool abbrev_month = false;
    bool abbrev_year = false;
    bool locale_indep_ordering = false;
    bool minus_mode = false;
    bool plus_mode = false;
    bool n_mode = false;
    TTimeFormat tf = locale->TimeFormat();

    while (i < sys_fmt.size()) {

        c = sys_fmt.at(i);

        // let formatting thru
        if (c.unicode() == '%') {
            // if we have gathered string, concat it
            if (!other.isEmpty()) {
                result += other;
                other.clear();
            }
            // if we have open escape, end it
            if (open_escape) {
                result += QLatin1Char('\'');
                open_escape = false;
            }

            ++i;
            if (i >= sys_fmt.size())
                break;

            c = sys_fmt.at(i);

            // process specials
            abbrev_next = c.unicode() == '*';
            plus_mode = c.unicode() == '+';
            minus_mode = c.unicode() == '-';

            if (abbrev_next || plus_mode || minus_mode) {
                ++i;
                if (i >= sys_fmt.size())
                    break;

                c = sys_fmt.at(i);

                if (plus_mode || minus_mode) {
                    // break on undefined plus/minus mode
                    if (c.unicode() != 'A' && c.unicode() != 'B')
                        break;
                }
            }

            switch (c.unicode()) {
                case 'F':
                {
                    // locale indep mode on
                    locale_indep_ordering = true;
                    break;
                }

                case '/':
                {
                    // date sep 0-3
                    ++i;
                    if (i >= sys_fmt.size())
                        break;

                    c = sys_fmt.at(i);
                    if (c.isDigit() && c.digitValue() <= 3) {
                        TChar s = locale->DateSeparator(c.digitValue());
                        TUint val = s;
                        // some indexes return zero for empty
                        if (val > 0)
                            result += QChar(val);
                    }
                    break;
                }

                case 'D':
                {
                    if (!locale_indep_ordering) {
                        if (abbrev_next)
                            abbrev_day = true;
                        break;
                    }

                    if (!abbrev_next)
                        result += QLatin1String("dd");
                    else
                        result += QLatin1Char('d');

                    break;
                }

                case 'M':
                {
                    if (!locale_indep_ordering) {
                        if (abbrev_next)
                            abbrev_month = true;
                        break;
                    }

                    if (!n_mode) {
                        if (!abbrev_next)
                            result += QLatin1String("MM");
                        else
                            result += QLatin1String("M");
                    } else {
                        if (!abbrev_next)
                            result += QLatin1String("MMMM");
                        else
                            result += QLatin1String("MMM");
                    }

                    break;
                }

                case 'N':
                {
                    n_mode = true;

                    if (!locale_indep_ordering) {
                        if (abbrev_next)
                            abbrev_month = true;
                        break;
                    }

                    if (!abbrev_next)
                        result += QLatin1String("MMMM");
                    else
                        result += QLatin1String("MMM");

                    break;
                }

                case 'Y':
                {
                    if (!locale_indep_ordering) {
                        if (abbrev_next)
                            abbrev_year = true;
                        break;
                    }

                    if (!abbrev_next)
                        result += QLatin1String("yyyy");
                    else
                        result += QLatin1String("yy");

                    break;
                }

                case 'E':
                {
                    if (!abbrev_next)
                        result += QLatin1String("dddd");
                    else
                        result += QLatin1String("ddd");

                    break;
                }

                case ':':
                {
                    // timesep 0-3
                    ++i;
                    if (i >= sys_fmt.size())
                        break;

                    c = sys_fmt.at(i);
                    if (c.isDigit() && c.digitValue() <= 3) {
                        TChar s = locale->TimeSeparator(c.digitValue());
                        TUint val = s;
                        // some indexes return zero for empty
                        if (val > 0)
                            result += QChar(val);
                    }

                    break;
                }

                case 'J':
                {
                    if (tf == ETime24 && !abbrev_next)
                        result += QLatin1String("hh");
                    else
                        result += QLatin1Char('h');

                    break;
                }

                case 'H':
                {
                    if (!abbrev_next)
                        result += QLatin1String("hh");
                    else
                        result += QLatin1Char('h');

                    break;
                }

                case 'I':
                {
                    result += QLatin1Char('h');
                    break;
                }

                case 'T':
                {
                    if (!abbrev_next)
                        result += QLatin1String("mm");
                    else
                        result += QLatin1Char('m');

                    break;
                }

                case 'S':
                {
                    if (!abbrev_next)
                        result += QLatin1String("ss");
                    else
                        result += QLatin1Char('s');

                    break;
                }

                case 'B':
                {
                    // only done for 12h clock
                    if (tf == ETime24)
                        break;
                }

                    // fallthru to A
                case 'A': {
                    // quickie to get capitalization, can't use s60 string as is because Qt 'hh' format's am/pm logic
                    TAmPmName ampm = TAmPmName();
                    TChar first(ampm[0]);
                    QString qtampm = QString::fromLatin1(first.IsUpper() ? "AP" : "ap");

                    int pos = locale->AmPmSymbolPosition();

                    if ((minus_mode && pos != ELocaleBefore) ||
                        (plus_mode && pos != ELocaleAfter))
                        break;

                    if (!abbrev_next && locale->AmPmSpaceBetween()) {
                        if (pos == ELocaleBefore)
                            qtampm.append(QLatin1Char(' '));
                        else
                            qtampm.prepend(QLatin1Char(' '));
                    }

                    result += qtampm;
                    }
                    break;

                case '.': {
                        // decimal sep
                        TChar s = locale->DecimalSeparator();
                        TUint val = s;
                        if (val > 0)
                            result += QChar(val);
                    }
                    break;

                case 'C':
                {
                    // six digits in s60, three digits in qt
                    if (!abbrev_next) {
                        result += QLatin1String("zzz");
                    } else {
                        // next char is number from 0-6, how many digits to display
                        ++i;
                        if (i >= sys_fmt.size())
                            break;

                        c = sys_fmt.at(i);

                        if (c.isDigit()) {
                            // try to match wanted digits
                            QChar val(c.digitValue());

                            if (val >= 3) {
                                result += QLatin1String("zzz");
                            } else if (val > 0) {
                                result += QLatin1Char('z');
                            }
                        }
                    }
                    break;
                }

                // these cases fallthru
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                {

                    // shouldn't parse these with %F
                    if (locale_indep_ordering)
                        break;

                    TDateFormat df = locale->DateFormat();

                    const char **locale_dep;
                    switch (df) {
                        default:
                            df = EDateAmerican;
                            // fallthru to american
                        case EDateAmerican:
                            locale_dep = us_locale_dep;
                            break;
                        case EDateEuropean:
                            locale_dep = eu_locale_dep;
                            break;
                        case EDateJapanese:
                            locale_dep = jp_locale_dep;
                            break;
                    }
                    int offset = 0;
                    int adjustedDigit = c.digitValue() - 1;

                    bool abbrev_this = abbrev_next;
                    // If abbreviation specified for this digit, use that.
                    // Otherwise abbreviate according to %D, %M, and %Y specified previously.
                    if (!abbrev_this) {
                        switch (digit_map[adjustedDigit + (static_cast<int>(df) * 5)]) {
                            case 0:
                                abbrev_this = abbrev_day;
                                break;
                            case 1:
                                abbrev_this = abbrev_month;
                                break;
                            case 2:
                                abbrev_this = abbrev_year;
                                break;
                            default:
                                break; // never happens
                        }
                    }

                    if (abbrev_this)
                        offset += 5;
                    if (n_mode)
                        offset += 10;

                    result += QLatin1String(locale_dep[offset + (adjustedDigit)]);
                    break;
                }

                case '%': // fallthru percent
                {
                // any junk gets copied as is
                }
                default:
                {
                    result += c;
                    break;
                }

                case 'Z': // Qt doesn't support these :(
                case 'X':
                case 'W':
                {
                    break;
                }
            }
        } else {
            // double any single quotes, don't begin escape
            if (c.unicode() == '\'') {
                // end open escape
                if (open_escape) {
                    result += other;
                    other.clear();
                    result += QLatin1Char('\'');
                    open_escape = false;
                }

                other += c;
            }

            // gather chars and escape them in one go if any format chars are found
            if (!open_escape && qtformatchars.indexOf(c) != -1) {
                result += QLatin1Char('\'');
                open_escape = true;
            }
            other += c;
        }

        ++i;
    }

    if (!other.isEmpty())
        result += other;
    if (open_escape)
        result += QLatin1Char('\'');

    return result;
}
예제 #18
0
void QNativeWifiEngine::connectToId(const QString &id)
{
    QMutexLocker locker(&mutex);

    if (!available()) {
        locker.unlock();
        emit connectionError(id, InterfaceLookupError);
        return;
    }

    WLAN_INTERFACE_INFO_LIST *interfaceList;
    DWORD result = local_WlanEnumInterfaces(handle, 0, &interfaceList);
    if (result != ERROR_SUCCESS) {
#ifdef BEARER_MANAGEMENT_DEBUG
        qDebug("%s: WlanEnumInterfaces failed with error %ld\n", __FUNCTION__, result);
#endif
        locker.unlock();
        emit connectionError(id, InterfaceLookupError);
        return;
    }

    QString profile;

    for (unsigned int i = 0; i < interfaceList->dwNumberOfItems; ++i) {
        const WLAN_INTERFACE_INFO &interface = interfaceList->InterfaceInfo[i];

        WLAN_AVAILABLE_NETWORK_LIST *networkList;
        result = local_WlanGetAvailableNetworkList(handle, &interface.InterfaceGuid,
                                                   3, 0, &networkList);
        if (result != ERROR_SUCCESS) {
#ifdef BEARER_MANAGEMENT_DEBUG
            qDebug("%s: WlanGetAvailableNetworkList failed with error %ld\n",
                   __FUNCTION__, result);
#endif
            continue;
        }

        for (unsigned int j = 0; j < networkList->dwNumberOfItems; ++j) {
            WLAN_AVAILABLE_NETWORK &network = networkList->Network[j];

            profile = QString::fromWCharArray(network.strProfileName);

            if (qHash(QLatin1String("WLAN:") + profile) == id.toUInt())
                break;
            else
                profile.clear();
        }

        local_WlanFreeMemory(networkList);

        if (!profile.isEmpty()) {
            WLAN_CONNECTION_PARAMETERS parameters;
            parameters.wlanConnectionMode = wlan_connection_mode_profile;
            parameters.strProfile = reinterpret_cast<LPCWSTR>(profile.utf16());
            parameters.pDot11Ssid = 0;
            parameters.pDesiredBssidList = 0;
            parameters.dot11BssType = dot11_BSS_type_any;
            parameters.dwFlags = 0;

            DWORD result = local_WlanConnect(handle, &interface.InterfaceGuid, &parameters, 0);
            if (result != ERROR_SUCCESS) {
#ifdef BEARER_MANAGEMENT_DEBUG
                qDebug("%s: WlanConnect failed with error %ld\n", __FUNCTION__, result);
#endif
                locker.unlock();
                emit connectionError(id, ConnectError);
                locker.relock();
                break;
            }

            break;
        }
    }

    local_WlanFreeMemory(interfaceList);

    if (profile.isEmpty()) {
        locker.unlock();
        emit connectionError(id, InterfaceLookupError);
    }
}
예제 #19
0
/*!
    Returns a SQL statement of type \a type for the table \a tableName
    with the values from \a rec. If \a preparedStatement is true, the
    string will contain placeholders instead of values.

    This method can be used to manipulate tables without having to worry
    about database-dependent SQL dialects. For non-prepared statements,
    the values will be properly escaped.
*/
QString QSqlDriver::sqlStatement(StatementType type, const QString &tableName,
                                 const QSqlRecord &rec, bool preparedStatement) const
{
    int i;
    QString s;
    s.reserve(128);
    switch (type) {
    case SelectStatement:
        for (i = 0; i < rec.count(); ++i) {
            if (rec.isGenerated(i))
                s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this)).append(QLatin1String(", "));
        }
        if (s.isEmpty())
            return s;
        s.chop(2);
        s.prepend(QLatin1String("SELECT ")).append(QLatin1String(" FROM ")).append(tableName);
        break;
    case WhereStatement:
        if (preparedStatement) {
            for (int i = 0; i < rec.count(); ++i) {
                s.append(prepareIdentifier(rec.fieldName(i), FieldName,this));
                if (rec.isNull(i))
                    s.append(QLatin1String(" IS NULL"));
                else
                    s.append(QLatin1String(" = ?"));
                s.append(QLatin1String(" AND "));
            }
        } else {
            for (i = 0; i < rec.count(); ++i) {
                s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this));
                QString val = formatValue(rec.field(i));
                if (val == QLatin1String("NULL"))
                    s.append(QLatin1String(" IS NULL"));
                else
                    s.append(QLatin1String(" = ")).append(val);
                s.append(QLatin1String(" AND "));
            }
        }
        if (!s.isEmpty()) {
            s.prepend(QLatin1String("WHERE "));
            s.chop(5); // remove tailing AND
        }
        break;
    case UpdateStatement:
        s.append(QLatin1String("UPDATE ")).append(tableName).append(
                 QLatin1String(" SET "));
        for (i = 0; i < rec.count(); ++i) {
            if (!rec.isGenerated(i) || !rec.value(i).isValid())
                continue;
            s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this)).append(QLatin1Char('='));
            if (preparedStatement)
                s.append(QLatin1Char('?'));
            else
                s.append(formatValue(rec.field(i)));
            s.append(QLatin1String(", "));
        }
        if (s.endsWith(QLatin1String(", ")))
            s.chop(2);
        else
            s.clear();
        break;
    case DeleteStatement:
        s.append(QLatin1String("DELETE FROM ")).append(tableName);
        break;
    case InsertStatement: {
        s.append(QLatin1String("INSERT INTO ")).append(tableName).append(QLatin1String(" ("));
        QString vals;
        for (i = 0; i < rec.count(); ++i) {
            if (!rec.isGenerated(i) || !rec.value(i).isValid())
                continue;
            s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this)).append(QLatin1String(", "));
            if (preparedStatement)
                vals.append(QLatin1Char('?'));
            else
                vals.append(formatValue(rec.field(i)));
            vals.append(QLatin1String(", "));
        }
        if (vals.isEmpty()) {
            s.clear();
        } else {
            vals.chop(2); // remove trailing comma
            s[s.length() - 2] = QLatin1Char(')');
            s.append(QLatin1String("VALUES (")).append(vals).append(QLatin1Char(')'));
        }
        break; }
    }
    return s;
}
예제 #20
0
static void updateTsFiles(const Translator &fetchedTor, const QStringList &tsFileNames,
    const QByteArray &codecForTr, const QString &sourceLanguage, const QString &targetLanguage,
    UpdateOptions options, bool *fail)
{
    QDir dir;
    QString err;
    foreach (const QString &fileName, tsFileNames) {
        QString fn = dir.relativeFilePath(fileName);
        ConversionData cd;
        Translator tor;
        cd.m_sortContexts = !(options & NoSort);
        if (QFile(fileName).exists()) {
            if (!tor.load(fileName, cd, QLatin1String("auto"))) {
                printOut(cd.error());
                *fail = true;
                continue;
            }
            tor.resolveDuplicates();
            cd.clearErrors();
            if (!codecForTr.isEmpty() && codecForTr != tor.codecName())
                qWarning("lupdate warning: Codec for tr() '%s' disagrees with "
                         "existing file's codec '%s'. Expect trouble.",
                         codecForTr.constData(), tor.codecName().constData());
            if (!targetLanguage.isEmpty() && targetLanguage != tor.languageCode())
                qWarning("lupdate warning: Specified target language '%s' disagrees with "
                         "existing file's language '%s'. Ignoring.",
                         qPrintable(targetLanguage), qPrintable(tor.languageCode()));
            if (!sourceLanguage.isEmpty() && sourceLanguage != tor.sourceLanguageCode())
                qWarning("lupdate warning: Specified source language '%s' disagrees with "
                         "existing file's language '%s'. Ignoring.",
                         qPrintable(sourceLanguage), qPrintable(tor.sourceLanguageCode()));
        } else {
            if (!codecForTr.isEmpty())
                tor.setCodecName(codecForTr);
            if (!targetLanguage.isEmpty())
                tor.setLanguageCode(targetLanguage);
            if (!sourceLanguage.isEmpty())
                tor.setSourceLanguageCode(sourceLanguage);
        }
        tor.makeFileNamesAbsolute(QFileInfo(fileName).absoluteDir());
        if (options & NoLocations)
            tor.setLocationsType(Translator::NoLocations);
        else if (options & RelativeLocations)
            tor.setLocationsType(Translator::RelativeLocations);
        else if (options & AbsoluteLocations)
            tor.setLocationsType(Translator::AbsoluteLocations);
        if (options & Verbose)
            printOut(QObject::tr("Updating '%1'...\n").arg(fn));

        UpdateOptions theseOptions = options;
        if (tor.locationsType() == Translator::NoLocations) // Could be set from file
            theseOptions |= NoLocations;
        Translator out = merge(tor, fetchedTor, theseOptions, err);
        if (!codecForTr.isEmpty())
            out.setCodecName(codecForTr);

        if ((options & Verbose) && !err.isEmpty()) {
            printOut(err);
            err.clear();
        }
        if (options & PluralOnly) {
            if (options & Verbose)
                printOut(QObject::tr("Stripping non plural forms in '%1'...\n").arg(fn));
            out.stripNonPluralForms();
        }
        if (options & NoObsolete)
            out.stripObsoleteMessages();
        out.stripEmptyContexts();

        out.normalizeTranslations(cd);
        if (!cd.errors().isEmpty()) {
            printOut(cd.error());
            cd.clearErrors();
        }
        if (!out.save(fileName, cd, QLatin1String("auto"))) {
            printOut(cd.error());
            *fail = true;
        }
    }
예제 #21
0
bool
StarDictDictionaryManager::lookupData(QByteArray search_word, QStringList resultList)
{
    QStringList searchWords;
    QString searchWord;
    foreach (char ch, search_word)
    {
        if (ch == '\\')
        {
            switch (ch)
            {
            case ' ':
                searchWord.append(' ');
                break;
            case '\\':
                searchWord.append('\\');
                break;
            case 't':
                searchWord.append('\t');
                break;
            case 'n':
                searchWord.append('\n');
                break;
            default:
                searchWord.append(ch);
            }
        }
        else if (ch == ' ')
        {
            if (!searchWord.isEmpty())
            {
                searchWords.append(searchWord);
                searchWord.clear();
            }
        }
        else
        {
            searchWord.append(ch);
        }
    }

    if (!searchWord.isEmpty())
    {
        searchWords.append(searchWord);
        searchWord.clear();
    }

    if (searchWords.isEmpty())
        return false;

    quint32 maximumSize = 0;
    for (QVector<Dictionary *>::size_type i = 0; i < d->dictionaryList.size(); ++i)
    {
        if (!d->dictionaryList.at(i)->containFindData())
            continue;

        if (d->progressFunction)
            d->progressFunction();

        int wordSize = articleCount(i);
        for (int j = 0; j < wordSize; ++j)
        {
            WordEntry wordEntry = d->dictionaryList.at(i)->wordEntry(j);
            if (wordEntry.dataSize() > maximumSize)
            {
                maximumSize = wordEntry.dataSize();
            }

            if (d->dictionaryList.at(i)->findData(searchWords, wordEntry.dataOffset(), wordEntry.dataSize()))
                resultList[i].append(wordEntry.data());
        }
    }

    QVector<Dictionary *>::size_type i;
    for (i = 0; i < d->dictionaryList.size(); ++i)
        if (!resultList[i].isEmpty())
            break;

    return i != d->dictionaryList.size();
}
예제 #22
0
void MainWindow::on_pushButton_3_clicked()
{
    //run programe
    IBGS *bgs;
    int i=ui->comboBox->currentIndex();
    qDebug()<<"select bgs "<<i;
    /*** Default Package ***/
    if(i==0) bgs = new FrameDifferenceBGS;
    if(i==1) bgs = new StaticFrameDifferenceBGS;
    if(i==2) bgs = new WeightedMovingMeanBGS;
    if(i==3) bgs = new WeightedMovingVarianceBGS;
    if(i==4) bgs = new MixtureOfGaussianV1BGS;
    if(i==5) bgs = new MixtureOfGaussianV2BGS;
    if(i==6) bgs = new AdaptiveBackgroundLearning;
    if(i==7) bgs = new AdaptiveSelectiveBackgroundLearning;
    if(i==8) bgs = new GMG;

    /*** DP Package (thanks to Donovan Parks) ***/
    if(i==9) bgs = new DPAdaptiveMedianBGS;
    if(i==10) bgs = new DPGrimsonGMMBGS;
    if(i==11) bgs = new DPZivkovicAGMMBGS;
    if(i==12) bgs = new DPMeanBGS;
    if(i==13) bgs = new DPWrenGABGS;
    if(i==14) bgs = new DPPratiMediodBGS;
    if(i==15) bgs = new DPEigenbackgroundBGS;
    if(i==16) bgs = new DPTextureBGS;

    /*** TB Package (thanks to Thierry Bouwmans, Fida EL BAF and Zhenjie Zhao) ***/
    if(i==17) bgs = new T2FGMM_UM;
    if(i==18) bgs = new T2FGMM_UV;
    if(i==19) bgs = new T2FMRF_UM;
    if(i==20) bgs = new T2FMRF_UV;
    if(i==21) bgs = new FuzzySugenoIntegral;
    if(i==22) bgs = new FuzzyChoquetIntegral;

    /*** JMO Package (thanks to Jean-Marc Odobez) ***/
    if(i==23) bgs = new MultiLayerBGS;

    /*** PT Package (thanks to Martin Hofmann, Philipp Tiefenbacher and Gerhard Rigoll) ***/
    //       if(i==24) bgs = new PixelBasedAdaptiveSegmenter;

    /*** LB Package (thanks to Laurence Bender) ***/
    if(i==25) bgs = new LBSimpleGaussian;
    if(i==26) bgs = new LBFuzzyGaussian;
    if(i==27) bgs = new LBMixtureOfGaussians;
    if(i==28) bgs = new LBAdaptiveSOM;
    if(i==29) bgs = new LBFuzzyAdaptiveSOM;

    /*** LBP-MRF Package (thanks to Csaba Kertész) ***/
    if(i==30) bgs = new LbpMrf;

    /*** AV Package (thanks to Lionel Robinault and Antoine Vacavant) ***/
    if(i==31) bgs = new VuMeter;

    /*** EG Package (thanks to Ahmed Elgammal) ***/
    if(i==32) bgs = new KDE;

    /*** DB Package (thanks to Domenico Daniele Bloisi) ***/
    if(i==33) bgs = new IndependentMultimodalBGS;

    /*** SJN Package (thanks to SeungJong Noh) ***/
    if(i==34) bgs = new SJN_MultiCueBGS;

    /*** BL Package (thanks to Benjamin Laugraud) ***/
    if(i==35) bgs = new SigmaDeltaBGS;

    /*** PL Package (thanks to Pierre-Luc) ***/
    if(i==36) bgs = new SuBSENSEBGS();
    if(i==37) bgs = new LOBSTERBGS();

    int temporalRoi[2];
    temporalRoi[0]=ui->spinBox->value();
    temporalRoi[1]=ui->spinBox_2->value();
    qDebug()<<"from to: "<<temporalRoi[0]<<" "<<temporalRoi[1];

    QString prefix=ui->lineEdit_3->text();
    QString suffix=ui->comboBox_2->currentText();
    int format=ui->spinBox_3->value();

    qDebug()<<"prefix "<<prefix;
    qDebug()<<"suffix "<<suffix;
    qDebug()<<"format "<<format;

    QString CDNetDir=ui->lineEdit->text();
    QString VideoPath=ui->lineEdit_2->text();

    qDebug()<<"CDNet Dir "<<CDNetDir;
    qDebug()<<"VideoPath "<<VideoPath;

    if(CDNetDir.isEmpty())   return;

    int frameNumber = temporalRoi[0];
    int key = 0;
    cvNamedWindow("input",0);
    QString fileName;
    //       QString qformat=QString("%%1d").arg(format);
    //       qDebug()<<"qformat "<<qformat;
    //       const char *cformat=qformat.toStdString().data();

    QString numstr;
    QTextStream out(&numstr);
    out.setFieldAlignment(QTextStream::AlignRight);
    out.setFieldWidth(format);
    out.setPadChar(QLatin1Char('0'));
    out<<frameNumber;

    //        QString numstr=QString::sprintf(cformat,frameNumber);
    fileName=CDNetDir+"/"+prefix+numstr+suffix;
    qDebug()<<"fileName "<<fileName;

    settings->setValue("/Folder/CDNetDir",CDNetDir);
    settings->setValue("/Folder/from",temporalRoi[0]);
    settings->setValue("/Folder/to",temporalRoi[1]);
    settings->setValue("/Folder/prefix",prefix);
    settings->setValue("/Folder/suffix",suffix);

    settings->sync();

    while(key != 'q')
    {
        if(frameNumber>temporalRoi[1])  break;

        out.flush();
        numstr.clear();
        out<<frameNumber;
        fileName=CDNetDir+"/"+prefix+numstr+suffix;
        qDebug()<<frameNumber<<" fileName "<<fileName;

        std::string filename =fileName.toStdString();
        std::cout << "reading " << filename << std::endl;

        cv::Mat img_input = cv::imread(filename, CV_LOAD_IMAGE_COLOR);

        if (img_input.empty())
            break;

        cv::imshow("input", img_input);

        cv::Mat img_mask;
        cv::Mat img_bkgmodel;
        std::cout<<" process start ..............."<<std::endl;
        bgs->process(img_input, img_mask, img_bkgmodel); // by default, it shows automatically the foreground mask image
        std::cout<<" process end ..............."<<std::endl;
        //if(!img_mask.empty())
        //  cv::imshow("Foreground", img_mask);
        //  do something

        key = cvWaitKey(33);
        frameNumber++;
    }
    delete bgs;
    cvDestroyAllWindows();

    qDebug()<<"exit ..................";
}
예제 #23
0
void synthv1widget_preset::savePreset ( const QString& sPreset )
{
	if (sPreset.isEmpty())
		return;

	synthv1_config *pConfig = synthv1_config::getInstance();
	if (pConfig == NULL)
		return;

	const QString sExt(SYNTHV1_TITLE);
	QFileInfo fi(QDir(pConfig->sPresetDir), sPreset + '.' + sExt);
	QString sFilename = fi.absoluteFilePath();
	if (!fi.exists()) {
		const QString& sTitle  = tr("Save Preset") + " - " SYNTHV1_TITLE;
		const QString& sFilter = tr("Preset files (*.%1)").arg(sExt);
	#if 1//QT_VERSION < 0x040400
		QFileDialog::Options options = 0;
		if (pConfig->bDontUseNativeDialogs)
			options |= QFileDialog::DontUseNativeDialog;
		sFilename = QFileDialog::getSaveFileName(parentWidget(),
			sTitle, sFilename, sFilter, NULL, options);
	#else
		QFileDialog fileDialog(nativeParentWidget(),
			sTitle, sFilename, sFilter);
		fileDialog.setAcceptMode(QFileDialog::AcceptSave);
		fileDialog.setFileMode(QFileDialog::AnyFile);
		fileDialog.setDefaultSuffix(sExt);
		QList<QUrl> urls(fileDialog.sidebarUrls());
		urls.append(QUrl::fromLocalFile(pConfig->sPresetDir));
		fileDialog.setSidebarUrls(urls);
		if (pConfig->bDontUseNativeDialogs)
			fileDialog.setOptions(QFileDialog::DontUseNativeDialog);
		if (fileDialog.exec())
			sFilename = fileDialog.selectedFiles().first();
	#endif
	} else {
		if (QMessageBox::warning(parentWidget(),
			tr("Warning") + " - " SYNTHV1_TITLE,
			tr("About to replace preset:\n\n"
			"\"%1\"\n\n"
			"Are you sure?")
			.arg(sPreset),
			QMessageBox::Ok | QMessageBox::Cancel)
			== QMessageBox::Cancel) {
			sFilename.clear();
		}
	}

	if (!sFilename.isEmpty()) {
		if (QFileInfo(sFilename).suffix() != sExt)
			sFilename += '.' + sExt;
		emit savePresetFile(sFilename);
		pConfig->setPresetFile(sPreset, sFilename);
		++m_iInitPreset;
		pConfig->sPreset = sPreset;
		pConfig->sPresetDir = QFileInfo(sFilename).absolutePath();
		refreshPreset();
	}

	stabilizePreset();
}
예제 #24
0
void
CLArgsPrivate::parse()
{
    {
        QStringList::iterator it = hasToken( QString::fromUtf8("version"), QString::fromUtf8("v") );
        if ( it != args.end() ) {
            QString msg = QObject::tr("%1 version %2 at commit %3 on branch %4 built on %4").arg( QString::fromUtf8(NATRON_APPLICATION_NAME) ).arg( QString::fromUtf8(NATRON_VERSION_STRING) ).arg( QString::fromUtf8(GIT_COMMIT) ).arg( QString::fromUtf8(GIT_BRANCH) ).arg( QString::fromUtf8(__DATE__) );
            std::cout << msg.toStdString() << std::endl;
            error = 1;

            return;
        }
    }

    {
        QStringList::iterator it = hasToken( QString::fromUtf8("help"), QString::fromUtf8("h") );
        if ( it != args.end() ) {
            CLArgs::printUsage( args[0].toStdString() );
            error = 1;

            return;
        }
    }

    {
        QStringList::iterator it = hasToken( QString::fromUtf8("background"), QString::fromUtf8("b") );
        if ( it != args.end() ) {
            isBackground = true;
            args.erase(it);
        }
    }

    {
        QStringList::iterator it = hasToken( QString::fromUtf8("interpreter"), QString::fromUtf8("t") );
        if ( it != args.end() ) {
            isInterpreterMode = true;
            isBackground = true;
            std::cout << QObject::tr("Note: -t argument given, loading in command-line interpreter mode, only Python commands / scripts are accepted").toStdString()
                      << std::endl;
            args.erase(it);
        }
    }

    {
        QStringList::iterator it = hasToken( QString::fromUtf8("render-stats"), QString::fromUtf8("s") );
        if ( it != args.end() ) {
            enableRenderStats = true;
            args.erase(it);
        }
    }

    {
        QStringList::iterator it = hasToken( QString::fromUtf8(NATRON_BREAKPAD_PROCESS_PID), QString() );
        if ( it != args.end() ) {
            ++it;
            if ( it != args.end() ) {
                breakpadProcessPID = it->toLongLong();
                args.erase(it);
            } else {
                std::cout << QObject::tr("You must specify the breakpad process executable file path").toStdString() << std::endl;
                error = 1;

                return;
            }
        }
    }

    {
        QStringList::iterator it = hasToken( QString::fromUtf8(NATRON_BREAKPAD_PROCESS_EXEC), QString() );
        if ( it != args.end() ) {
            ++it;
            if ( it != args.end() ) {
                breakpadProcessFilePath = *it;
                args.erase(it);
            } else {
                std::cout << QObject::tr("You must specify the breakpad process executable file path").toStdString() << std::endl;
                error = 1;

                return;
            }
        }
    }

    {
        QStringList::iterator it = hasToken( QString::fromUtf8(NATRON_BREAKPAD_CLIENT_FD_ARG), QString() );
        if ( it != args.end() ) {
            ++it;
            if ( it != args.end() ) {
                breakpadPipeClientID = it->toInt();
                args.erase(it);
            } else {
                std::cout << QObject::tr("You must specify the breakpad pipe client FD").toStdString() << std::endl;
                error = 1;

                return;
            }
        }
    }

    {
        QStringList::iterator it = hasToken( QString::fromUtf8(NATRON_BREAKPAD_PIPE_ARG), QString() );
        if ( it != args.end() ) {
            ++it;
            if ( it != args.end() ) {
                breakpadPipeFilePath = *it;
                args.erase(it);
            } else {
                std::cout << QObject::tr("You must specify the breakpad pipe path").toStdString() << std::endl;
                error = 1;

                return;
            }
        }
    }

    {
        QStringList::iterator it = hasToken( QString::fromUtf8(NATRON_BREAKPAD_COM_PIPE_ARG), QString() );
        if ( it != args.end() ) {
            ++it;
            if ( it != args.end() ) {
                breakpadComPipeFilePath = *it;
                args.erase(it);
            } else {
                std::cout << QObject::tr("You must specify the breakpad communication pipe path").toStdString() << std::endl;
                error = 1;

                return;
            }
        }
    }

    {
        QStringList::iterator it = hasToken( QString::fromUtf8("export-docs"), QString() );
        if ( it != args.end() ) {
            ++it;
            if ( it != args.end() ) {
                exportDocsPath = *it;
                args.erase(it);
            } else {
                std::cout << QObject::tr("You must specify the doc dir path").toStdString() << std::endl;
                error = 1;

                return;
            }
        }
    }

    {
        QStringList::iterator it = hasToken( QString::fromUtf8("IPCpipe"), QString() );
        if ( it != args.end() ) {
            ++it;
            if ( it != args.end() ) {
                ipcPipe = *it;
                args.erase(it);
            } else {
                std::cout << QObject::tr("You must specify the IPC pipe filename").toStdString() << std::endl;
                error = 1;

                return;
            }
        }
    }

    {
        QStringList::iterator it = hasToken( QString::fromUtf8("onload"), QString::fromUtf8("l") );
        if ( it != args.end() ) {
            ++it;
            if ( it != args.end() ) {
                defaultOnProjectLoadedScript = *it;
#ifdef __NATRON_UNIX__
                defaultOnProjectLoadedScript = AppManager::qt_tildeExpansion(defaultOnProjectLoadedScript);
#endif
                QFileInfo fi(defaultOnProjectLoadedScript);
                if ( !fi.exists() ) {
                    std::cout << QObject::tr("WARNING: --onload %1 ignored because the file does not exist.").arg(defaultOnProjectLoadedScript).toStdString() << std::endl;
                    defaultOnProjectLoadedScript.clear();
                } else {
                    defaultOnProjectLoadedScript = fi.canonicalFilePath();
                }

                args.erase(it);
                if ( !defaultOnProjectLoadedScript.endsWith( QString::fromUtf8(".py") ) ) {
                    std::cout << QObject::tr("The optional on project load script must be a Python script (.py).").toStdString() << std::endl;
                    error = 1;

                    return;
                }
            } else {
                std::cout << QObject::tr("--onload or -l specified, you must enter a script filename afterwards.").toStdString() << std::endl;
                error = 1;

                return;
            }
        }
    }

    {
        QStringList::iterator it = findFileNameWithExtension( QString::fromUtf8(NATRON_PROJECT_FILE_EXT) );
        if ( it == args.end() ) {
            it = findFileNameWithExtension( QString::fromUtf8("py") );
            if ( ( it == args.end() ) && !isInterpreterMode && isBackground ) {
                std::cout << QObject::tr("You must specify the filename of a script or %1 project. (.%2)").arg( QString::fromUtf8(NATRON_APPLICATION_NAME) ).arg( QString::fromUtf8(NATRON_PROJECT_FILE_EXT) ).toStdString() << std::endl;
                error = 1;

                return;
            }
            isPythonScript = true;
        }
        if ( it != args.end() ) {
            filename = *it;
#ifdef __NATRON_UNIX__
            filename = AppManager::qt_tildeExpansion(filename);
#endif
            QFileInfo fi(filename);
            if ( fi.exists() ) {
                filename = fi.canonicalFilePath();
            }
            args.erase(it);
        }
    }

    //Parse frame range
    for (QStringList::iterator it = args.begin(); it != args.end(); ++it) {
        if ( tryParseMultipleFrameRanges(*it, frameRanges) ) {
            args.erase(it);
            rangeSet = true;
            break;
        }
    }

    //Parse python commands
    for (;; ) {
        QStringList::iterator it = hasToken( QString::fromUtf8("cmd"), QString::fromUtf8("c") );
        if ( it == args.end() ) {
            break;
        }

        if (!isBackground) {
            std::cout << QObject::tr("You cannot use the -c option in interactive mode").toStdString() << std::endl;
            error = 1;

            return;
        }

        QStringList::iterator next = it;
        if ( next != args.end() ) {
            ++next;
        }
        if ( next == args.end() ) {
            std::cout << QObject::tr("You must specify a command when using the -c option").toStdString() << std::endl;
            error = 1;

            return;
        }

        pythonCommands.push_back( next->toStdString() );

        ++next;
        args.erase(it, next);
    } // for (;;)

    //Parse writers
    for (;; ) {
        QStringList::iterator it = hasToken( QString::fromUtf8("writer"), QString::fromUtf8("w") );
        if ( it == args.end() ) {
            break;
        }

        if (!isBackground || isInterpreterMode) {
            std::cout << QObject::tr("You cannot use the -w option in interactive or interpreter mode").toStdString() << std::endl;
            error = 1;

            return;
        }

        QStringList::iterator next = it;
        if ( next != args.end() ) {
            ++next;
        }
        if ( next == args.end() ) {
            std::cout << QObject::tr("You must specify the name of a Write node when using the -w option").toStdString() << std::endl;
            error = 1;

            return;
        }


        //Check that the name is conform to a Python acceptable script name
        std::string pythonConform = NATRON_PYTHON_NAMESPACE::makeNameScriptFriendly( next->toStdString() );
        if (next->toStdString() != pythonConform) {
            std::cout << QObject::tr("The name of the Write node specified is not valid: it cannot contain non alpha-numerical "
                                     "characters and must not start with a digit.").toStdString() << std::endl;
            error = 1;

            return;
        }

        CLArgs::WriterArg w;
        w.name = *next;

        QStringList::iterator nextNext = next;
        if ( nextNext != args.end() ) {
            ++nextNext;
        }
        if ( nextNext != args.end() ) {
            //Check for an optional filename
            if ( !nextNext->startsWith( QChar::fromLatin1('-') ) && !nextNext->startsWith( QString::fromUtf8("--") ) ) {
                w.filename = *nextNext;
#ifdef __NATRON_UNIX__
                w.filename = AppManager::qt_tildeExpansion(w.filename);
#endif
            }
        }

        writers.push_back(w);
        if ( nextNext != args.end() ) {
            ++nextNext;
        }
        args.erase(it, nextNext);
    } // for (;;)


    //Parse readers
    for (;; ) {
        QStringList::iterator it = hasToken( QString::fromUtf8("reader"), QString::fromUtf8("i") );
        if ( it == args.end() ) {
            break;
        }

        if (!isBackground || isInterpreterMode) {
            std::cout << QObject::tr("You cannot use the -i option in interactive or interpreter mode").toStdString() << std::endl;
            error = 1;

            return;
        }

        QStringList::iterator next = it;
        if ( next != args.end() ) {
            ++next;
        }
        if ( next == args.end() ) {
            std::cout << QObject::tr("You must specify the name of a Read node when using the -i option").toStdString() << std::endl;
            error = 1;

            return;
        }


        //Check that the name is conform to a Python acceptable script name
        std::string pythonConform = NATRON_PYTHON_NAMESPACE::makeNameScriptFriendly( next->toStdString() );
        if (next->toStdString() != pythonConform) {
            std::cout << QObject::tr("The name of the Read node specified is not valid: it cannot contain non alpha-numerical "
                                     "characters and must not start with a digit.").toStdString() << std::endl;
            error = 1;

            return;
        }

        CLArgs::ReaderArg r;
        r.name = *next;

        QStringList::iterator nextNext = next;
        if ( nextNext != args.end() ) {
            ++nextNext;
        }
        if ( nextNext == args.end() ) {
            std::cout << QObject::tr("You must specify the filename for the following Read node: ").toStdString()  << r.name.toStdString() << std::endl;
            error = 1;

            return;
        }


        //Check for  filename
        if ( !nextNext->startsWith( QChar::fromLatin1('-') ) && !nextNext->startsWith( QString::fromUtf8("--") ) ) {
            r.filename = *nextNext;
#ifdef __NATRON_UNIX__
            r.filename = AppManager::qt_tildeExpansion(r.filename);
#endif
        } else {
            std::cout << QObject::tr("You must specify the filename for the following Read node: ").toStdString()  << r.name.toStdString() << std::endl;
            error = 1;

            return;
        }


        readers.push_back(r);
        if ( nextNext != args.end() ) {
            ++nextNext;
        }
        args.erase(it, nextNext);
    } // for (;;)

    bool atLeastOneOutput = false;
    ///Parse outputs
    for (;; ) {
        QString indexStr;
        QStringList::iterator it  = hasOutputToken(indexStr);
        if (error > 0) {
            return;
        }
        if ( it == args.end() ) {
            break;
        }

        if (!isBackground) {
            std::cout << QObject::tr("You cannot use the -o option in interactive or interpreter mode").toStdString() << std::endl;
            error = 1;

            return;
        }

        CLArgs::WriterArg w;
        w.name = QString( QString::fromUtf8("Output%1") ).arg(indexStr);
        w.mustCreate = true;
        atLeastOneOutput = true;

        //Check for a mandatory file name
        QStringList::iterator next = it;
        if ( next != args.end() ) {
            ++next;
        }
        if ( next == args.end() ) {
            std::cout << QObject::tr("Filename is not optional with the -o option").toStdString() << std::endl;
            error = 1;

            return;
        }

        //Check for an optional filename
        if ( !next->startsWith( QChar::fromLatin1('-') ) && !next->startsWith( QString::fromUtf8("--") ) ) {
            w.filename = *next;
        }

        writers.push_back(w);

        QStringList::iterator endToErase = next;
        ++endToErase;
        args.erase(it, endToErase);
    }

    if (atLeastOneOutput && !rangeSet) {
        std::cout << QObject::tr("A frame range must be set when using the -o option").toStdString() << std::endl;
        error = 1;

        return;
    }
} // CLArgsPrivate::parse
예제 #25
0
파일: main.cpp 프로젝트: mneumann/lumina
void getCMD(int argc, char ** argv, QString& binary, QString& args, QString& path, bool& watch){
  //Get the input file
    //Make sure to load the proper system encoding first
    LUtils::LoadTranslation(0,""); //bypass application modification
  QString inFile, ActionID;
  bool showDLG = false; //flag to bypass any default application setting
  if(argc > 1){
    for(int i=1; i<argc; i++){
      if(QString(argv[i]).simplified() == "-select"){
      	showDLG = true;
      }else if(QString(argv[i]).simplified() == "-volumeup"){
	int vol = LOS::audioVolume()+5; //increase 5%
	if(vol>100){ vol=100; }
	LOS::setAudioVolume(vol);
	showOSD(argc,argv, QString(QObject::tr("Audio Volume %1%")).arg(QString::number(vol)) );
	return;
      }else if(QString(argv[i]).simplified() == "-volumedown"){
	int vol = LOS::audioVolume()-5; //decrease 5%
	if(vol<0){ vol=0; }
	LOS::setAudioVolume(vol);
	showOSD(argc,argv, QString(QObject::tr("Audio Volume %1%")).arg(QString::number(vol)) );
	return;
      }else if(QString(argv[i]).simplified() == "-brightnessup"){
	int bright = LOS::ScreenBrightness();
	if(bright > 0){ //brightness control available
	  bright = bright+5; //increase 5%
	  if(bright>100){ bright = 100; }
	  LOS::setScreenBrightness(bright);
	  showOSD(argc,argv, QString(QObject::tr("Screen Brightness %1%")).arg(QString::number(bright)) );
	}
	return;
      }else if(QString(argv[i]).simplified() == "-brightnessdown"){
	int bright = LOS::ScreenBrightness();
	if(bright > 0){ //brightness control available
	  bright = bright-5; //decrease 5%
	  if(bright<0){ bright = 0; }
	  LOS::setScreenBrightness(bright);
	  showOSD(argc,argv, QString(QObject::tr("Screen Brightness %1%")).arg(QString::number(bright)) );
	}
	return;
      }else if( (QString(argv[i]).simplified() =="-action") && (argc>(i+1)) ){
        ActionID = QString(argv[i+1]);
	i++; //skip the next input
      }else{
        inFile = QString::fromLocal8Bit(argv[i]);
        break;
      }
    }
  }else{
    printUsageInfo();
  }
  //Make sure that it is a valid file/URL
  bool isFile=false; bool isUrl=false;
  if(QFile::exists(inFile)){ isFile=true; }
  else if(QFile::exists(QDir::currentPath()+"/"+inFile)){isFile=true; inFile = QDir::currentPath()+"/"+inFile;} //account for relative paths
  else if(QUrl(inFile).isValid() && !inFile.startsWith("/") ){ isUrl=true; }
  if( !isFile && !isUrl ){ ShowErrorDialog( argc, argv, QString(QObject::tr("Invalid file or URL: %1")).arg(inFile) ); }
  //Determing the type of file (extension)
  QString extension;
  //qDebug() << "File Type:" << isFile << isUrl;
  if(isFile){
    QFileInfo info(inFile);
    extension=info.suffix();
    //qDebug() << " - Extension:" << extension;
    if(info.isDir()){ extension="directory"; }
    else if(info.isExecutable() && extension.isEmpty()){ extension="binary"; }
    else if(extension!="desktop"){ extension="mimetype"; } //flag to check for mimetype default based on file
  }
  else if(isUrl && inFile.startsWith("mailto:")){ extension = "email"; }
  else if(isUrl){ extension = "webbrowser"; }
  //qDebug() << "Input:" << inFile << isFile << isUrl << extension;
  //if not an application  - find the right application to open the file
  QString cmd;
  bool useInputFile = false;
  if(extension=="desktop" && !showDLG){
    bool ok = false;
    XDGDesktop DF = LXDG::loadDesktopFile(inFile, ok);
    if(!ok){
      ShowErrorDialog( argc, argv, QString(QObject::tr("File could not be opened: %1")).arg(inFile) );
    }
    switch(DF.type){
      case XDGDesktop::APP:
        if(!DF.exec.isEmpty()){
          cmd = LXDG::getDesktopExec(DF,ActionID);
          if(!DF.path.isEmpty()){ path = DF.path; }
	  watch = DF.startupNotify;
        }else{
	  ShowErrorDialog( argc, argv, QString(QObject::tr("Application shortcut is missing the launching information (malformed shortcut): %1")).arg(inFile) );
        }
        break;
      case XDGDesktop::LINK:
        if(!DF.url.isEmpty()){
          //This is a URL - so adjust the input variables appropriately
          inFile = DF.url;
          cmd.clear();
          extension = inFile.section(":",0,0);
	  watch = DF.startupNotify;
        }else{
	  ShowErrorDialog( argc, argv, QString(QObject::tr("URL shortcut is missing the URL: %1")).arg(inFile) );
        }
        break;
      case XDGDesktop::DIR:
        if(!DF.path.isEmpty()){
          //This is a directory link - adjust inputs
          inFile = DF.path;
          cmd.clear();
          extension = "directory";
	  watch = DF.startupNotify;
        }else{
	  ShowErrorDialog( argc, argv, QString(QObject::tr("Directory shortcut is missing the path to the directory: %1")).arg(inFile) );
        }
        break;
      default:
	qDebug() << DF.type << DF.name << DF.icon << DF.exec;
	ShowErrorDialog( argc, argv, QString(QObject::tr("Unknown type of shortcut : %1")).arg(inFile) );
    }
  }
  if(cmd.isEmpty()){
    if(extension=="binary" && !showDLG){ cmd = inFile; }
    else{
    //Find out the proper application to use this file/directory
    useInputFile=true;
    cmd = cmdFromUser(argc, argv, inFile, extension, path, showDLG);
    if(cmd.isEmpty()){ return; }
    }
  }
  //Now assemble the exec string (replace file/url field codes as necessary)
  if(useInputFile){ 
    args = inFile; //just to keep them distinct internally
    // NOTE: lumina-open is only designed for a single input file,
    //    so no need to distinguish between the list codes (uppercase) 
    //    and the single-file codes (lowercase)
    //Special "inFile" format replacements for input codes
    if( (cmd.contains("%f") || cmd.contains("%F") ) ){
      //Apply any special field replacements for the desired format
      inFile.replace("%20"," ");
      //Now replace the field codes
      cmd.replace("%f","\""+inFile+"\"");
      cmd.replace("%F","\""+inFile+"\"");
    }else if( (cmd.contains("%U") || cmd.contains("%u")) ){
      //Apply any special field replacements for the desired format
      if(!inFile.contains("://")){ inFile.prepend("file:"); } //local file - add the extra flag
      inFile.replace(" ", "%20");
      //Now replace the field codes
      cmd.replace("%u","\""+inFile+"\"");
      cmd.replace("%U","\""+inFile+"\"");
    }else{
      //No field codes (or improper field codes given in the file - which is quite common)
      // - Just tack the input file on the end and let the app handle it as necessary
      cmd.append(" \""+inFile+"\"");
    }
  }
  //qDebug() << "Found Command:" << cmd << "Extension:" << extension;
  //Clean up any leftover "Exec" field codes (should have already been replaced earlier)
  if(cmd.contains("%")){cmd = cmd.remove("%U").remove("%u").remove("%F").remove("%f").remove("%i").remove("%c").remove("%k").simplified(); }
  binary = cmd; //pass this string to the calling function

}
예제 #26
0
bool executeSqlFile(const QString &connectionName, const QString &fileName, QProgressDialog *dlg)
{
    if (!QFile::exists(fileName)) {
        LOG_ERROR_FOR("Tools", QString("ERROR: missing database schema file: %1.").arg(fileName));
        return false;
    }

    // execute all sql queries
    QString req = Utils::readTextFile(fileName);
    if (req.isEmpty()) {
        LOG_ERROR_FOR("Tools", "File is empty: " + fileName);
        return false;
    }

    req.replace("\n\n", "\n");
    req.replace("\n\n", "\n");
    req.replace("\n\n", "\n");
    req.replace("\n\n", "\n");
    req.replace("\n\n", "\n");
    req.remove("AUTO_INCREMENT"); // SQLite compatibility

    QStringList list = req.split("\n");
    QSqlDatabase DB = QSqlDatabase::database(connectionName);
    if (!DB.isOpen()) {
        if (!DB.open()) {
            LOG_ERROR_FOR("Tools", "Database not opened");
            return false;
        }
    }
    DB.transaction();

    req.clear();
    QStringList queries;
    // Reconstruct req: removes comments
    foreach(const QString &s, list) {
        if (s.startsWith("--")) {
            LOG_FOR("Tools", s);
            continue;
        }
        req += s + " \n";
        if (s.endsWith(";")) {
            queries.append(req);
            req.clear();
        }
    }

    // Execute queries
    if (dlg)
        dlg->setRange(0, queries.count());

    foreach(const QString &sql, queries) {
        QTime time;
        time.start();

        QString q = sql.simplified();
        // Do not processed empty strings
        if (q.isEmpty())
            continue;

        // No SQLite extra commands
        if (q.startsWith("."))
            continue;

        // No BEGIN, No COMMIT
        if (q.startsWith("BEGIN", Qt::CaseInsensitive) || q.startsWith("COMMIT", Qt::CaseInsensitive))
            continue;

        qWarning() << sql;

        QSqlQuery query(sql, DB);
        if (!query.isActive()) {
            LOG_ERROR_FOR("Tools", QString("SQL ERROR: %1 \"%2\"").arg(query.lastError().text(), sql));
//            DB.rollback();
            return false;
        } else {
            LOG_FOR("Tools", QString("Query correctly done (%1 ms)").arg(time.elapsed()));
        }

        if (dlg)
            dlg->setValue(dlg->value()+1);
    }
void EMBLGenbankAbstractDocument::load(const U2DbiRef& dbiRef, IOAdapter* io, QList<GObject*>& objects, QVariantMap& fs, U2OpStatus& os, QString& writeLockReason) {
    DbiOperationsBlock opBlock(dbiRef, os);
    CHECK_OP(os, );
    Q_UNUSED(opBlock);
    writeLockReason.clear();

    //get settings
    int gapSize = qBound(-1, DocumentFormatUtils::getMergeGap(fs), 1000*1000);
    bool merge = gapSize!=-1;

    QScopedPointer<AnnotationTableObject> mergedAnnotations(NULL);
    QStringList contigs;
    QVector<U2Region> mergedMapping;

    // Sequence loading is 'lazy', so, if there is no sequence, it won't be created and there is no need to remove it.
    U2SequenceImporter seqImporter(fs, true);
    const QString folder = fs.value(DBI_FOLDER_HINT, U2ObjectDbi::ROOT_FOLDER).toString();

    QSet<QString> usedNames;

    GObjectReference sequenceRef(GObjectReference(io->getURL().getURLString(), "", GObjectTypes::SEQUENCE));

    QByteArray readBuffer(ParserState::LOCAL_READ_BUFFER_SIZE, '\0');
    ParserState st(isNcbiLikeFormat() ? 12 : 5, io, NULL, os);
    st.buff = readBuffer.data();

    TmpDbiObjects dbiObjects(dbiRef, os);
    int num_sequence = 0;

    qint64 sequenceStart = 0;
    int sequenceSize = 0;
    int fullSequenceSize = 0;
    const int objectsCountLimit = fs.contains(DocumentReadingMode_MaxObjectsInDoc) ? fs[DocumentReadingMode_MaxObjectsInDoc].toInt() : -1;

    for (int i=0; !os.isCoR(); i++, ++num_sequence) {
        if (objectsCountLimit > 0 && objects.size() >= objectsCountLimit) {
            os.setError(EMBLGenbankAbstractDocument::tr("File \"%1\" contains too many sequences to be displayed. "
                "However, you can process these data using instruments from the menu <i>Tools -> NGS data analysis</i> "
                "or pipelines built with Workflow Designer.")
                .arg(io->getURL().getURLString()));
            break;
        }

        //TODO: reference to a local variable??? Such a pointer will become invalid
        EMBLGenbankDataEntry data;
        st.entry = &data;

        if (num_sequence == 0 || merge == false){
            seqImporter.startSequence(dbiRef, folder, "default sequence name", false, os); //change name and circularity after finalize method
            CHECK_OP(os, );
        }

        sequenceSize = 0;
        os.setDescription(tr("Reading entry header"));
        int offset = 0;
        if (merge && num_sequence > 0) {
            offset = gapSize;
        }
        if (!readEntry(&st,seqImporter,sequenceSize,fullSequenceSize,merge,offset, os)) {
            break;
        }

        if (merge && sequenceSize > 0 && num_sequence > 0) {
                sequenceStart = fullSequenceSize - sequenceSize;
                sequenceStart += gapSize;
                fullSequenceSize += gapSize;
        }

        // tolerate blank lines between records
        char ch;
        bool b;
        while ((b = st.io->getChar(&ch)) && (ch == '\n' || ch == '\r')){}
        if (b) {
            st.io->skip(-1);
        }

        AnnotationTableObject *annotationsObject = NULL;

        if (data.hasAnnotationObjectFlag) {
            QString annotationName = genObjectName(usedNames, data.name, data.tags, i+1, GObjectTypes::ANNOTATION_TABLE);

            QVariantMap hints;
            hints.insert(DBI_FOLDER_HINT, fs.value(DBI_FOLDER_HINT, U2ObjectDbi::ROOT_FOLDER));
            if (Q_UNLIKELY(merge && NULL == mergedAnnotations)) {
                mergedAnnotations.reset(new AnnotationTableObject(annotationName, dbiRef, hints));
            }
            annotationsObject = merge ? mergedAnnotations.data() : new AnnotationTableObject(annotationName, dbiRef, hints);

            QStringList groupNames;
            QMap<QString, QList<SharedAnnotationData> > groupName2Annotations;
            for (int i = 0, n = data.features.size(); i < n; ++i) {
                SharedAnnotationData &d = data.features[i];
                if (!d->location->regions.isEmpty()) {
                    for (int i = 0, n = d->location->regions.size(); i < n; ++i) {
                        // for some reason larger numbers cannot be stored within rtree SQLite tables
                        if (d->location->regions[i].endPos() > 9223371036854775807LL) {
                            d->location->regions[i].length = 9223371036854775807LL - d->location->regions[i].startPos;
                        }
                    }
                }
                groupNames.clear();
                d->removeAllQualifiers(GBFeatureUtils::QUALIFIER_GROUP, groupNames);
                if (groupNames.isEmpty()) {
                    groupName2Annotations[""].append(d);
                } else {
                    foreach(const QString &gName, groupNames) {
                        groupName2Annotations[gName].append(d);
                    }
                }
                CHECK_OP(os, );
            }
예제 #28
0
파일: highlighter.cpp 프로젝트: KDE/sonnet
void Highlighter::highlightBlock(const QString &text)
{
    if (text.isEmpty() || !d->active || !d->spellCheckerFound) {
        return;
    }

    if (!d->connected) {
        connect(document(), SIGNAL(contentsChange(int,int,int)),
                SLOT(contentsChange(int,int,int)));
        d->connected = true;
    }
    QTextCursor cursor;
    if (d->textEdit) {
        cursor = d->textEdit->textCursor();
    } else {
        cursor = d->plainTextEdit->textCursor();
    }
    int index = cursor.position();

    const int lengthPosition = text.length() - 1;

    if ( index != lengthPosition ||
            ( lengthPosition > 0 && !text[lengthPosition-1].isLetter() ) ) {
        d->languageFilter->setBuffer(text);

        LanguageCache* cache=dynamic_cast<LanguageCache*>(currentBlockUserData());
        if (!cache) {
            cache = new LanguageCache;
            setCurrentBlockUserData(cache);
        }

        while (d->languageFilter->hasNext()) {
            QStringRef sentence=d->languageFilter->next();
            if (d->spellchecker->testAttribute(Speller::AutoDetectLanguage)) {

                QString lang;
                QPair<int,int> spos=QPair<int,int>(sentence.position(),sentence.length());
                // try cache first
                if (cache->languages.contains(spos)) {
                    lang=cache->languages.value(spos);
                } else {
                    lang=d->languageFilter->language();
                    if (!d->languageFilter->isSpellcheckable()) lang.clear();
                    cache->languages[spos]=lang;
                }
                if (lang.isEmpty()) continue;
                d->spellchecker->setLanguage(lang);
            }


            d->tokenizer->setBuffer(sentence.toString());
            int offset=sentence.position();
            while (d->tokenizer->hasNext()) {
                QStringRef word=d->tokenizer->next();
                if (!d->tokenizer->isSpellcheckable()) continue;
                ++d->wordCount;
                if (d->spellchecker->isMisspelled(word.toString())) {
                    ++d->errorCount;
                    setMisspelled(word.position()+offset, word.length());
                } else {
                    unsetMisspelled(word.position()+offset, word.length());
                }
            }
        }
    }
    //QTimer::singleShot( 0, this, SLOT(checkWords()) );
    setCurrentBlockState(0);
}
int AnalisisSemantico::EvaluarExpresionSinVariable(QString pLinea) {
    FuncionesString mManejoFunciones;
    int mAbreParentesis = 0;
    int mVieneSiguienteSuma = 0;
    int mNumeroAnterior = 0, mNumeroResultante = 0;
    int mOperadorSuma = 0; // si es 1 es una suma y si es 2 es una resta
    int mNumeroIzquierdo = 0;
    QString mOperadorRacional;
    QString mNumeroAnalizado;
    int mIndiceInferior = -1, mIndiceSuperior = -1;
    for (int i = 0; i < pLinea.length(); i++) {
        qDebug() << "la mierda resultante" << mNumeroResultante;
        if (pLinea.at(i) == '(') {
            if (mAbreParentesis == 0) {
                mIndiceInferior = i;
            }
            mAbreParentesis++;
        } else {
            if (pLinea.at(i) == ')') {
                mAbreParentesis--;
                if (mAbreParentesis == 0) {
                    mIndiceSuperior = i;
                    char * observer = (char*) pLinea.section("", mIndiceInferior + 2, mIndiceSuperior).toStdString().c_str();
                    mNumeroAnterior = EvaluarExpresionSinVariable(pLinea.section("", mIndiceInferior + 2, mIndiceSuperior));

                }
            }
            if (mAbreParentesis == 0) {
                if (mIndiceInferior != -1 && mIndiceSuperior != -1) {
                    mIndiceInferior = -1;
                    mIndiceSuperior = -1;
                }
                if (mManejoFunciones.VerificacionEsNumero(pLinea.at(i).toAscii())) {
                    mNumeroAnalizado.append(pLinea.at(i));
                    if (i + 1 == pLinea.length()) {
                        mNumeroAnterior = mNumeroAnalizado.toInt();
                        mNumeroAnalizado.clear();
                        mVieneSiguienteSuma = 1;
                    }
                } else {
                    if (mNumeroAnterior == 0) {
                        mNumeroAnterior = mNumeroAnalizado.toInt();
                        mNumeroAnalizado.clear();
                    }
                    mVieneSiguienteSuma = 1;
                }
                if (mOperadorSuma != 0 && mVieneSiguienteSuma == 1) {

                    if (mOperadorSuma == 1) {
                        mNumeroResultante += mNumeroAnterior;
                        mNumeroAnterior = 0;
                    } else {
                        mNumeroResultante -= mNumeroAnterior;
                        mNumeroAnterior = 0;
                    }
                    mOperadorSuma = 0;
                } else {
                    if (mNumeroResultante == 0) {
                        mNumeroResultante = mNumeroAnterior;
                        mNumeroAnterior = 0;
                    }
                }
                if (pLinea.at(i) == '+') {
                    mOperadorSuma = 1;
                    mVieneSiguienteSuma = 0;
                } else {
                    if (pLinea.at(i) == '-') {
                        mOperadorSuma = 2;
                        mVieneSiguienteSuma = 0;
                    } else {
                        if (mManejoFunciones.VerificacionOperadoresRacionales(pLinea.at(i).toAscii())) {
                            mOperadorRacional.append(pLinea.at(i));
                            if (mOperadorRacional.length() >= 1 && !mManejoFunciones.VerificacionOperadoresRacionales(pLinea.at(i + 1).toAscii())) {
                                mNumeroIzquierdo = mNumeroResultante;
                                mNumeroResultante = 0;
                            }
                        }
                    }
                }
            }
        }
    }
    if (mOperadorRacional.length() >= 1) {
        if (EvaluarOperadorRacional((char*) mOperadorRacional.toStdString().c_str(), mNumeroIzquierdo, mNumeroResultante)) {
            return 1;
        } else {
            return 0;
        }
    }
    return mNumeroResultante;
}
예제 #30
0
파일: netif.cpp 프로젝트: KhuramAli/pcbsd
int NetworkInterface::enableWirelessAccessPoint(QString wdev, QString name, QString password, bool persist, QString ip, QString mode, int channel, QString netmask, QString country){
  //Return Codes: 0=success, 1=General Error, -1=Unsupported device (no AP support in driver)
	
  //Check that wlan0 is not currently in use
  QString ret = Utils::runShellCommand("ifconfig wlan0").join("\n").simplified();
  if(ret.contains( "<UP,") ){ return 1; } //wlan0 currently in use
  else if(!ret.contains("wlan0 does not exist")){ 
    //wlan0 already in use: remove it for now (not sure if associated with the device given)
    Utils::runShellCommand("ifconfig wlan0 destroy");
  }
  
  //Check that wlan0/wdev support AP mode
  Utils::runShellCommand("ifconfig wlan0 create wlandev "+wdev);
  ret = Utils::runShellCommand("ifconfig wlan0 list caps").join("\n");
  Utils::runShellCommand("ifconfig wlan0 destroy"); //clean up
  if(!ret.contains(",HOSTAP,")){
    //This device does not support access point mode
    return -1;
  }
  
  //Re-create the new wlan0 in AP mode
  Utils::runShellCommand("ifconfig wlan0 create wlandev "+wdev+" wlanmode hostap");
  QString cmd = "ifconfig wlan0 inet "+ip+" netmask "+netmask+" ssid \""+name+"\" mode "+mode+" channel "+QString::number(channel);
  if( !country.isEmpty() ){ cmd.append(" country "+country); }
  Utils::runShellCommand(cmd);
  
  //Enable WPA-PSK encryption for the Access Point (if password given)
  if( !password.isEmpty() ){
    QStringList contents;
	contents << "interface=wlan0" \
		<< "debug=1" \
		<< "ctrl_interface=/var/run/hostapd" \
		<< "ctrl_interface_group=wheel" \
		<< "ssid="+name \
		<< "wpa=1" \
		<< "wpa_passphrase="+password \
		<< "wpa_key_mgmt=WPA-PSK" \
		<< "wpa_pairwise=CCMP TKIP";
    QFile file("/etc/hostapd.conf");
    if( file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate) ){
      QTextStream out(&file);
      out << contents.join("\n");
      file.close();
      Utils::runShellCommand("service hostapd forcestart");
    }else{
      qDebug() << "[WARNING] Could not enable WPA encryption for the new Access Point - is now an open network!!";
      password.clear(); //Could not enable encryption
    }
  }
  
  //Save the AP configuration to /etc/rc.conf
  if(persist){
    Utils::setConfFileValue("/etc/rc.conf", "wlans_"+wdev, "wlans_"+wdev+"=\"wlan0\"", -1);
    Utils::setConfFileValue("/etc/rc.conf", "create_args_wlan0", "create_args_wlan0=\"wlanmode hostap\"", -1);
    Utils::setConfFileValue("/etc/rc.conf", "ifconfig_wlan0", "ifconfig_wlan0=\"inet "+ip+" netmask "+netmask+" ssid "+name+" mode "+mode+" channel "+QString::number(channel)+"\"", -1);
    if(!password.isEmpty()){
      Utils::setConfFileValue("/etc/rc.conf", "hostapd_enable", "hostapd_enable=\"YES\"", -1);
    }
  }else{
    Utils::setConfFileValue("/etc/rc.conf","wlans_"+wdev, "");
    Utils::setConfFileValue("/etc/rc.conf","create_args_wlan0", "");
    Utils::setConfFileValue("/etc/rc.conf","ifconfig_wlan0", "");
  }
  return 0;
}