Example #1
0
ProFileEditorWidget::Link ProFileEditorWidget::findLinkAt(const QTextCursor &cursor,
                                                          bool /*resolveTarget*/,
                                                          bool /*inNextSplit*/)
{
    Link link;

    int lineNumber = 0, positionInBlock = 0;
    convertPosition(cursor.position(), &lineNumber, &positionInBlock);

    const QString block = cursor.block().text();

    // check if the current position is commented out
    const int hashPos = block.indexOf(QLatin1Char('#'));
    if (hashPos >= 0 && hashPos < positionInBlock)
        return link;

    // find the beginning of a filename
    QString buffer;
    int beginPos = positionInBlock - 1;
    while (beginPos >= 0) {
        QChar c = block.at(beginPos);
        if (isValidFileNameChar(c)) {
            buffer.prepend(c);
            beginPos--;
        } else {
            break;
        }
    }

    // find the end of a filename
    int endPos = positionInBlock;
    while (endPos < block.count()) {
        QChar c = block.at(endPos);
        if (isValidFileNameChar(c)) {
            buffer.append(c);
            endPos++;
        } else {
            break;
        }
    }

    if (buffer.isEmpty())
        return link;

    // remove trailing '\' since it can be line continuation char
    if (buffer.at(buffer.size() - 1) == QLatin1Char('\\')) {
        buffer.chop(1);
        endPos--;
    }

    // if the buffer starts with $$PWD accept it
    if (buffer.startsWith(QLatin1String("PWD/")) ||
            buffer.startsWith(QLatin1String("PWD\\"))) {
        if (beginPos > 0 && block.mid(beginPos - 1, 2) == QLatin1String("$$")) {
            beginPos -=2;
            buffer = buffer.mid(4);
        }
    }

    QDir dir(textDocument()->filePath().toFileInfo().absolutePath());
    QString fileName = dir.filePath(buffer);
    QFileInfo fi(fileName);
    if (fi.exists()) {
        if (fi.isDir()) {
            QDir subDir(fi.absoluteFilePath());
            QString subProject = subDir.filePath(subDir.dirName() + QLatin1String(".pro"));
            if (QFileInfo::exists(subProject))
                fileName = subProject;
            else
                return link;
        }
        link.targetFileName = QDir::cleanPath(fileName);
        link.linkTextStart = cursor.position() - positionInBlock + beginPos + 1;
        link.linkTextEnd = cursor.position() - positionInBlock + endPos;
    }
    return link;
}
Example #2
0
	void Plugin::hookMessageWillCreated (LeechCraft::IHookProxy_ptr proxy,
			QObject*, QObject *entry, int, QString)
	{
		ICLEntry *other = qobject_cast<ICLEntry*> (entry);
		if (!other)
		{
			qWarning () << Q_FUNC_INFO
				<< "unable to cast"
				<< entry
				<< "to ICLEntry";
			return;
		}

		QString text = proxy->GetValue ("text").toString ();

		const int maxLines = XmlSettingsManager::Instance ()
				.property ("LineCount").toInt ();
		const int maxSymbols = XmlSettingsManager::Instance ()
				.property ("SymbolCount").toInt ();
		if (text.size () < maxSymbols &&
				text.count ('\n') + 1 < maxLines)
			return;

		QByteArray propName;
		switch (other->GetEntryType ())
		{
		case ICLEntry::ETChat:
			propName = "EnableForNormalChats";
			break;
		case ICLEntry::ETMUC:
			propName = "EnableForMUCChats";
			break;
		case ICLEntry::ETPrivateChat:
			propName = "EnableForPrivateChats";
			break;
		default:
			return;
		}

		if (!XmlSettingsManager::Instance ().property (propName).toBool ())
			return;

		QSettings settings (QCoreApplication::organizationName (),
				QCoreApplication::applicationName () + "_Azoth_Autopaste");
		settings.beginGroup ("SavedChoices");
		settings.beginGroup (other->GetEntryID ());
		auto guard = std::shared_ptr<void> (nullptr,
				[&settings] (void*) -> void
				{
					settings.endGroup ();
					settings.endGroup ();
				});

		PasteDialog dia;

		dia.SetCreatorName (settings.value ("Service").toString ());
		dia.SetHighlight (static_cast<Highlight> (settings.value ("Highlight").toInt ()));

		dia.exec ();

		switch (dia.GetChoice ())
		{
		case PasteDialog::Cancel:
			proxy->CancelDefault ();
		case PasteDialog::No:
			return;
		case PasteDialog::Yes:
		{
			auto service = dia.GetCreator () (entry);
			service->Paste ({ Proxy_->GetNetworkAccessManager (), text, dia.GetHighlight () });
			proxy->CancelDefault ();

			settings.setValue ("Service", dia.GetCreatorName ());
			settings.setValue ("Highlight", static_cast<int> (dia.GetHighlight ()));
		}
		}
	}
Example #3
0
QStringList Parse::parseFile(const QString& buf, int strt, int end)
{
  QStringList outBuffer;
  outBuffer.clear();
  int lineCount = 0;
  QString tmpBuffer;
  tmpBuffer.clear();
  bool inQuotes = false;
  int charCount = buf.count();
  QString::const_iterator constIterator;

  for (constIterator = buf.constBegin(); constIterator != buf.constEnd();
       ++constIterator) {
    QString chr = (*constIterator);
    charCount -= 1;
    if (chr == m_textDelimiterCharacter) {
      tmpBuffer += chr;
      if (inQuotes == true) {      //               if already in quoted field..
        inQuotes = false;//                    ..end it
      } else {//                               if not..
        inQuotes = true;//                     ..start it
      }
      continue;

      //  find carriage return and line feed chars

    } else if ((chr == "\r") || (chr == "\n")) {
      if (inQuotes == true) {      //               embedded '\n'  or '\r' in quoted field
        chr = '~';//                           replace it with ~ for now
        tmpBuffer += chr;
        if (charCount > 0)      //                      more chars yet
          continue;//                          more chars yet
      }
      //                                       true EOL (not in quotes)
      if (tmpBuffer.isEmpty()) {
        continue;
      }
      lineCount ++;
      if (lineCount < strt) {      //   startLine      not yet reached first wanted line
        tmpBuffer.clear();
        continue;
      }
      outBuffer << tmpBuffer;
      tmpBuffer.clear();
      //                                       look for start of wanted data
      //  if first pass or if not at last line, proceed
      if ((!end == 0) && (lineCount >= end)) {      //  m_endLine is set from UI after first pass
        m_lastLine = lineCount;
        break;
      }
    }

    //  end of 'EOL detected' loop

    else {//                                   must be data char
      tmpBuffer += chr;

      if (charCount > 0) {    //                      more chars yet
        continue;
      } else {//                                      else eoFile = true;
        //  last char in file is data char
        //  meaning no return on last line
        //  so bump line count
        lineCount ++;
      }
    }
    if (!tmpBuffer.isEmpty()) {
      outBuffer << tmpBuffer;
    }
  }
  m_lastLine = lineCount;
  return outBuffer;
}
Example #4
0
/* Generic open file */
void DialogsProvider::openFileGenericDialog( intf_dialog_args_t *p_arg )
{
    if( p_arg == NULL )
    {
        msg_Warn( p_intf, "openFileGenericDialog() called with NULL arg" );
        return;
    }

    /* Replace the extensions to a Qt format */
    int i = 0;
    QString extensions = qfu( p_arg->psz_extensions );
    while ( ( i = extensions.indexOf( "|", i ) ) != -1 )
    {
        if( ( extensions.count( "|" ) % 2 ) == 0 )
            extensions.replace( i, 1, ");;" );
        else
            extensions.replace( i, 1, "(" );
    }
    extensions.replace( ";*", " *" );
    extensions.append( ")" );

    /* Save */
    if( p_arg->b_save )
    {
        QString file = QFileDialog::getSaveFileName( NULL, p_arg->psz_title,
                                        p_intf->p_sys->filepath, extensions );
        if( !file.isEmpty() )
        {
            p_arg->i_results = 1;
            p_arg->psz_results = (char **)malloc( p_arg->i_results * sizeof( char * ) );
            p_arg->psz_results[0] = strdup( qtu( toNativeSepNoSlash( file ) ) );
        }
        else
            p_arg->i_results = 0;
    }
    else /* non-save mode */
    {
        QStringList files = QFileDialog::getOpenFileNames( NULL,
                p_arg->psz_title, p_intf->p_sys->filepath,
                extensions );
        p_arg->i_results = files.count();
        p_arg->psz_results = (char **)malloc( p_arg->i_results * sizeof( char * ) );
        i = 0;
        foreach( const QString &file, files )
            p_arg->psz_results[i++] = strdup( qtu( toNativeSepNoSlash( file ) ) );
        if(i == 0)
            p_intf->p_sys->filepath = QString::fromAscii("");
        else
            p_intf->p_sys->filepath = qfu( p_arg->psz_results[i-1] );
    }

    /* Callback */
    if( p_arg->pf_callback )
        p_arg->pf_callback( p_arg );

    /* Clean afterwards */
    if( p_arg->psz_results )
    {
        for( i = 0; i < p_arg->i_results; i++ )
            free( p_arg->psz_results[i] );
        free( p_arg->psz_results );
    }
    free( p_arg->psz_title );
    free( p_arg->psz_extensions );
    free( p_arg );
}
bool KeyboardTranslatorReader::decodeSequence(const QString& text,
                                              int& keyCode,
                                              Qt::KeyboardModifiers& modifiers,
                                              Qt::KeyboardModifiers& modifierMask,
                                              KeyboardTranslator::States& flags,
                                              KeyboardTranslator::States& flagMask)
{
    bool isWanted = true; 
    bool endOfItem = false;
    QString buffer;

    Qt::KeyboardModifiers tempModifiers = modifiers;
    Qt::KeyboardModifiers tempModifierMask = modifierMask;
    KeyboardTranslator::States tempFlags = flags;
    KeyboardTranslator::States tempFlagMask = flagMask;

    for ( int i = 0 ; i < text.count() ; i++ )
    {
        const QChar& ch = text[i];
        bool isLastLetter = ( i == text.count()-1 );

        endOfItem = true;
        if ( ch.isLetterOrNumber() )
        {
            endOfItem = false;
            buffer.append(ch);
        }

        if ( (endOfItem || isLastLetter) && !buffer.isEmpty() )
        {
            Qt::KeyboardModifier itemModifier = Qt::NoModifier;
            int itemKeyCode = 0;
            KeyboardTranslator::State itemFlag = KeyboardTranslator::NoState;

            if ( parseAsModifier(buffer,itemModifier) )
            {
                tempModifierMask |= itemModifier;

                if ( isWanted )
                    tempModifiers |= itemModifier;
            }
            else if ( parseAsStateFlag(buffer,itemFlag) )
            {
                tempFlagMask |= itemFlag;

                if ( isWanted )
                    tempFlags |= itemFlag;
            }
            else if ( parseAsKeyCode(buffer,itemKeyCode) )
                keyCode = itemKeyCode;
            else
                qDebug() << "Unable to parse key binding item:" << buffer;

            buffer.clear();
        }

        // check if this is a wanted / not-wanted flag and update the 
        // state ready for the next item
        if ( ch == '+' )
           isWanted = true;
        else if ( ch == '-' )
           isWanted = false; 
    } 

    modifiers = tempModifiers;
    modifierMask = tempModifierMask;
    flags = tempFlags;
    flagMask = tempFlagMask;

    return true;
}
//--------------------------------------------------------------------------------------------
void MEkranoplan::InitGeometry()
{

    QString fileNameIn(":/Ekranoplan_3dsMax.obj");
    QList<QVector3D> listPositions;
    QList<QVector3D> listTextures;
    QList<QVector3D> listNormals;
    QList<int> listFacePositionIndices;
    QList<int> listFaceTextureIndices;
    QList<int> listFaceNormalIndices;

    QFile fileIn(fileNameIn);
    if(!fileIn.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox msgBox;
        msgBox.setText("Problem file \""+fileNameIn+"\"");
        msgBox.exec();
        return;
    }

    QMessageBox msgBox;
    QTextStream in(&fileIn);
    QString line;
    QChar qc;
    char c;
    int pos1,pos2;
    QString s;
    QVector3D v3D;
    while(!in.atEnd())
    {
        line = in.readLine();
        if(line.length() == 0)  continue;
        qc = line.at(0);
        switch(qc.toLatin1())
        {
        case 'v':
            c = line.at(1).toLatin1();
            if(c == ' ' || c == 't' || c == 'n')
            {   // vertices || textures || normals
                pos1 = 3;
                pos2 = line.indexOf(' ', pos1);
                v3D.setX(line.mid(pos1, pos2-pos1).toFloat());
                pos1 = pos2+1;
                pos2 = line.indexOf(' ', pos1);
                v3D.setY(line.mid(pos1, pos2-pos1).toFloat());
                v3D.setZ(line.mid(pos2+1).toFloat());
                if(c == ' ')       listPositions << v3D;
                else if(c == 't')  listTextures << v3D;
                else               listNormals  << v3D;   //  c == 'n'
            }
            break;
        case 'f':
            if(line.at(1).toLatin1() == ' ')
            {   // indices
                pos1 = 2;
                if(listFaceTextureIndices.count() == 0 && listNormals.count() == 0)
                {
//:  f 5 34 85
                    pos2 = line.indexOf(' ', pos1);
                    listFacePositionIndices << line.mid(pos1, pos2-pos1).toInt();
                    pos1 = pos2 + 1;
                    pos2 = line.indexOf(' ', pos1);
                    listFacePositionIndices << line.mid(pos1, pos2-pos1).toInt();
                    pos1 = pos2 + 1;
                    pos2 = line.count();
                    listFacePositionIndices << line.mid(pos1, pos2-pos1).toInt();
                }
                if((listTextures.count() > 0 && listNormals.count() == 0) || (listTextures.count() == 0 && listNormals.count() > 0))
                {
//:  f 5/6 34/67 85/2
                    pos2 = line.indexOf('/', pos1);
                    listFacePositionIndices << line.mid(pos1, pos2-pos1).toInt();
                    pos1 = pos2 + 1;
                    pos2 = line.indexOf(' ', pos1);
                    if(listTextures.count() > 0)  listFaceTextureIndices << line.mid(pos1, pos2-pos1).toInt();
                    else                          listFaceNormalIndices  << line.mid(pos1, pos2-pos1).toInt();

                    pos1 = pos2 + 1;
                    pos2 = line.indexOf('/', pos1);
                    listFacePositionIndices << line.mid(pos1, pos2-pos1).toInt();
                    pos1 = pos2 + 1;
                    pos2 = line.indexOf(' ', pos1);
                    if(listTextures.count() > 0)  listFaceTextureIndices << line.mid(pos1, pos2-pos1).toInt();
                    else                          listFaceNormalIndices  << line.mid(pos1, pos2-pos1).toInt();

                    pos1 = pos2 + 1;
                    pos2 = line.indexOf('/', pos1);
                    listFacePositionIndices << line.mid(pos1, pos2-pos1).toInt();
                    pos1 = pos2 + 1;
                    pos2 = line.count();
                    if(listTextures.count() > 0)  listFaceTextureIndices << line.mid(pos1, pos2-pos1).toInt();
                    else                          listFaceNormalIndices  << line.mid(pos1, pos2-pos1).toInt();
                }
                else
                {
//:  f 5/6/4 34/67/18 85/2/16

                    int  p1,p2,p3, t1,t2,t3, n1,n2,n3;
                    pos2 = line.indexOf('/', pos1);
                    p1 = line.mid(pos1, pos2-pos1).toInt();
                    pos1 = pos2 + 1;
                    pos2 = line.indexOf('/', pos1);
                    t1 = line.mid(pos1, pos2-pos1).toInt();
                    pos1 = pos2 + 1;
                    pos2 = line.indexOf(' ', pos1);
                    n1 = line.mid(pos1, pos2-pos1).toInt();

                    pos1 = pos2 + 1;
                    pos2 = line.indexOf('/', pos1);
                    p2 = line.mid(pos1, pos2-pos1).toInt();
                    pos1 = pos2 + 1;
                    pos2 = line.indexOf('/', pos1);
                    t2 = line.mid(pos1, pos2-pos1).toInt();
                    pos1 = pos2 + 1;
                    pos2 = line.indexOf(' ', pos1);
                    n2 = line.mid(pos1, pos2-pos1).toInt();

                    pos1 = pos2 + 1;
                    pos2 = line.indexOf('/', pos1);
                    p3 = line.mid(pos1, pos2-pos1).toInt();
                    pos1 = pos2 + 1;
                    pos2 = line.indexOf('/', pos1);
                    t3 = line.mid(pos1, pos2-pos1).toInt();
                    pos1 = pos2 + 1;
                    pos2 = line.count();
                    n3 = line.mid(pos1, pos2-pos1).toInt();

                    listFacePositionIndices << p1;
                    listFacePositionIndices << p2;
                    listFacePositionIndices << p3;
                    listFaceTextureIndices  << t1;
                    listFaceTextureIndices <<  t2;
                    listFaceTextureIndices  << t3;
                    listFaceNormalIndices   << n1;
                    listFaceNormalIndices <<   n2;
                    listFaceNormalIndices   << n3;
                }
            }
            break;
        default:
            ;
        }
    }
    fileIn.close();
    float fm = 0.0;
    for(int i=0; i < listPositions.count(); i++)
    {   //         fm = 359.85657
        fm = qMax(fm, qAbs(listPositions.at(i).x()));
        fm = qMax(fm, qAbs(listPositions.at(i).y()));
        fm = qMax(fm, qAbs(listPositions.at(i).z()));
    }
//openGL counts from 1; C++ from 0, therefore replace
    for(int i = 0; i < listFacePositionIndices.count(); i++) {
        listFacePositionIndices.replace(i, listFacePositionIndices.at(i)-1);
        listFaceTextureIndices.replace(i, listFaceTextureIndices.at(i)-1);
        listFaceNormalIndices.replace(i, listFaceNormalIndices.at(i)-1);
    }

    QList<int> listFacePositionIndicesDiff;
    QList<int> listFaceTextureIndicesDiff;
    QList<int> listFaceNormalIndicesDiff;
    listFacePositionIndicesDiff << listFacePositionIndices.at(0);
    listFaceTextureIndicesDiff << listFaceTextureIndices.at(0);
    listFaceNormalIndicesDiff << listFaceNormalIndices.at(0);

    QList<int> listVertexIndices;
    listVertexIndices << 0;
    int j;
    bool isHas;
    for(int i = 1; i < listFacePositionIndices.count(); i++)
    {
        isHas = false;
        for(j = 0; j < listFacePositionIndicesDiff.count(); j++)
        {
            if(listFacePositionIndices.at(i) == listFacePositionIndicesDiff.at(j) &&
                    listFaceTextureIndices.at(i) == listFaceTextureIndicesDiff.at(j) &&
                    listFaceNormalIndices.at(i) == listFaceNormalIndicesDiff.at(j)) {
                isHas = true;
                break;
            }
        }
        if(!isHas)
        {
            listFacePositionIndicesDiff << listFacePositionIndices.at(i);
            listFaceTextureIndicesDiff << listFaceTextureIndices.at(i);
            listFaceNormalIndicesDiff << listFaceNormalIndices.at(i);
        }
        listVertexIndices << j;
    }
    CountVertexIndices = listVertexIndices.count();
    VertexData* vertices = new VertexData[listFacePositionIndicesDiff.count()]; //  countIndicesDiff == listFacePositionIndicesDiff.count()

    for(int i = 0; i < listFacePositionIndicesDiff.count(); i++)
    {
        vertices[i].position = listPositions.at(listFacePositionIndicesDiff.at(i)); //-1)
        vertices[i].position /= fm;
        vertices[i].normal = listNormals.at(listFaceNormalIndicesDiff.at(i)); //-1);
        vertices[i].texCoord.setX(qMin(listTextures.at(listFaceTextureIndicesDiff.at(i)).x(), 1.0f));
        vertices[i].texCoord.setY(qMin(listTextures.at(listFaceTextureIndicesDiff.at(i)).y(), 1.0f));
    }

    GLushort* indices = new GLushort[CountVertexIndices];
    for(int i=0; i < CountVertexIndices; i++) {
        indices[i] = listVertexIndices.at(i);
    }

    // Transfer vertex data to VBO 0
    glBindBuffer(GL_ARRAY_BUFFER, vboIds[0]);
    glBufferData(GL_ARRAY_BUFFER, listFacePositionIndicesDiff.count()*sizeof(VertexData), vertices, GL_STATIC_DRAW);

    delete[] vertices;


    // Transfer index data to VBO 1
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboIds[1]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, CountVertexIndices*sizeof(GLushort), indices, GL_STATIC_DRAW);

    delete[] indices;
}
Example #7
0
CMakeEditorWidget::Link CMakeEditorWidget::findLinkAt(const QTextCursor &cursor,
                                                      bool/* resolveTarget*/, bool /*inNextSplit*/)
{
    Link link;

    int lineNumber = 0, positionInBlock = 0;
    convertPosition(cursor.position(), &lineNumber, &positionInBlock);

    const QString block = cursor.block().text();

    // check if the current position is commented out
    const int hashPos = block.indexOf(QLatin1Char('#'));
    if (hashPos >= 0 && hashPos < positionInBlock)
        return link;

    // find the beginning of a filename
    QString buffer;
    int beginPos = positionInBlock - 1;
    while (beginPos >= 0) {
        QChar c = block.at(beginPos);
        if (isValidFileNameChar(c)) {
            buffer.prepend(c);
            beginPos--;
        } else {
            break;
        }
    }

    // find the end of a filename
    int endPos = positionInBlock;
    while (endPos < block.count()) {
        QChar c = block.at(endPos);
        if (isValidFileNameChar(c)) {
            buffer.append(c);
            endPos++;
        } else {
            break;
        }
    }

    if (buffer.isEmpty())
        return link;

    // TODO: Resolve variables

    QDir dir(textDocument()->filePath().toFileInfo().absolutePath());
    QString fileName = dir.filePath(buffer);
    QFileInfo fi(fileName);
    if (fi.exists()) {
        if (fi.isDir()) {
            QDir subDir(fi.absoluteFilePath());
            QString subProject = subDir.filePath(QLatin1String("CMakeLists.txt"));
            if (QFileInfo::exists(subProject))
                fileName = subProject;
            else
                return link;
        }
        link.targetFileName = fileName;
        link.linkTextStart = cursor.position() - positionInBlock + beginPos + 1;
        link.linkTextEnd = cursor.position() - positionInBlock + endPos;
    }
    return link;
}
double FontScalingWidget::calculateFontPointSizeF(const QString& text, const QSize &size)
{
    QFontMetrics fmint = d_widget->fontMetrics();
    QFontMetricsF fm(fmint);
    QFont f = d_widget->font();
    QString longestLine;
    double txtWidth;
    double txtHeight;
    int linecnt = text.count("\n") + 1;

    if(linecnt > 1) {
        QStringList lines = text.split("\n");
        qSort(lines.begin(), lines.end(), FontScalingWidget::longerThan);
        qslisttoc(lines);
        longestLine = lines.first();
        txtHeight = fm.lineSpacing() * linecnt;
    } else {
        longestLine = text; /* no newline */
        txtHeight = fm.height();
    }

    double borderH1 = size.height() - d_botTopBorderWidth;
    double borderH2 = borderH1 - d_botTopBorderWidth;

     /* scale according to width and height */
    if(d_scaleMode == 2) {

        txtWidth = fm.width(longestLine);
        double borderW1 = size.width() - d_lateralBorderWidth;
        double borderW2 = borderW1 - d_lateralBorderWidth;

         /* first scale according to height (same algorithme as below) and then verify width */
        borderH2 = borderH1;
        if(txtHeight == (borderH1 + 1) || txtHeight == (borderH1)) {
            //printf("good: text for <%s> :text \"%s\" %.2f\e[0m | borderH1: %.2f borderH2: %.2f pointSizeF %.2f, h: %.2f\n",
            //widget()->objectName().toAscii().constData(), text.toAscii().constData(), txtHeight, borderH1,borderH2, f.pointSizeF(), borderH1 );

        } else {
            while((txtHeight > borderH1) && f.pointSizeF() > MIN_FONT_SIZE) {
                if(f.pointSizeF() <= 0.0) f.setPointSizeF(1.0);
                f.setPointSizeF(f.pointSizeF() - 0.5);
                //printf(" \e[1;36m -- DECREASING font size for object \"%s\" :text \"%s\"  height %.1f - point size %.2f - h: %.2f\e[0m\n",
                //         d_widget->objectName().toAscii().constData(), text.toAscii().constData(),  txtHeight, f.pointSizeF(), borderH1);
                QFontMetricsF tmpFm(f);
                txtHeight = linecnt * tmpFm.lineSpacing();
            }

            while(txtHeight < borderH2) {
                if(f.pointSizeF() <= 0.0) f.setPointSizeF(0.5);
                f.setPointSizeF(f.pointSizeF() + 0.5);
                //printf(" \e[1;35m ++ INCREASING font size for object\"%s\" :text \"%s\" height %.1f - point size %.2f - h: %.2f\e[0m\n",
                //         d_widget->objectName().toAscii().constData(), text.toAscii().constData(), txtHeight, f.pointSizeF(), borderH2);
                QFontMetricsF tmpFm(f);
                txtHeight = linecnt * tmpFm.lineSpacing();
            }
        }

        // check if width does not go outside
        QFontMetricsF tmpFm(f);
        txtWidth = tmpFm.width(longestLine);
        while((txtWidth > borderW2) && f.pointSizeF() > MIN_FONT_SIZE) {
            if(f.pointSizeF() <= 0.0) f.setPointSizeF(1.0);
            f.setPointSizeF(f.pointSizeF() - 0.5);
            //printf(" \e[1;36m -- next DECREASING font size \"%s\" :text \"%s\" width %.1f height %.1f - point size %.2f - w: %.2f\e[0m\n",
            //         d_widget->objectName().toAscii().constData(), text.toAscii().constData(),  txtWidth, txtHeight, f.pointSizeF(), borderW2);
            QFontMetricsF tmpFm(f);
            txtWidth = tmpFm.width(longestLine);
            txtHeight = linecnt * tmpFm.lineSpacing();
        }

    /* scale according to height only */
    } else {

        borderH2 = borderH1;
        if(txtHeight == (borderH1 + 1) || txtHeight == (borderH1)) {
        //if(txtHeight == borderH1) {
            //printf("good: text h %.2f\e[0m | borderH1: %.2f borderH2: %.2f pointSizeF %.2f, h: %.2f\n",
            //   txtHeight, borderH1,borderH2, f.pointSizeF(), borderH1 );

        } else {
            while((txtHeight > borderH1) && f.pointSizeF() > MIN_FONT_SIZE) {
                if(f.pointSizeF() <= 0.0) f.setPointSizeF(1.0);
                f.setPointSizeF(f.pointSizeF() - 0.5);
                //printf(" \e[1;36m -- DECREASING font size \"%s\" :text \"%s\"  height %.1f - point size %.2f - h: %.2f\e[0m\n",
                //         widget()->objectName().toAscii().constData(), text.toAscii().constData(),  txtHeight, f.pointSizeF(), borderH1);
                QFontMetricsF tmpFm(f);
                txtHeight = linecnt * tmpFm.lineSpacing();
            }

            while(txtHeight < borderH2) {
                if(f.pointSizeF() <= 0.0) f.setPointSizeF(0.5);
                f.setPointSizeF(f.pointSizeF() + 0.5);
                //printf(" \e[1;35m ++ INCREASING font size \"%s\" :text \"%s\" height %.1f - point size %.2f - h: %.2f\e[0m\n",
                //         widget()->objectName().toAscii().constData(), text.toAscii().constData(), txtHeight, f.pointSizeF(), borderH2);
                QFontMetricsF tmpFm(f);
                txtHeight = linecnt * tmpFm.lineSpacing();
            }
        }

    }
    return f.pointSizeF();
}
Example #9
0
void EventSenderProxy::keyDown(WKStringRef keyRef, WKEventModifiers modifiersRef, unsigned location)
{
    const QString key = WKStringCopyQString(keyRef);
    QString keyText = key;

    Qt::KeyboardModifiers modifiers = getModifiers(modifiersRef);

    if (location == 3)
        modifiers |= Qt::KeypadModifier;
    int code = 0;
    if (key.length() == 1) {
        code = key.unicode()->unicode();
        // map special keycodes used by the tests to something that works for Qt/X11
        if (code == '\r') {
            code = Qt::Key_Return;
        } else if (code == '\t') {
            code = Qt::Key_Tab;
            if (modifiers == Qt::ShiftModifier)
                code = Qt::Key_Backtab;
            keyText = QString();
        } else if (code == KEYCODE_DEL || code == KEYCODE_BACKSPACE) {
            code = Qt::Key_Backspace;
            if (modifiers == Qt::AltModifier)
                modifiers = Qt::ControlModifier;
            keyText = QString();
        } else if (code == 'o' && modifiers == Qt::ControlModifier) {
            // Mimic the emacs ctrl-o binding on Mac by inserting a paragraph
            // separator and then putting the cursor back to its original
            // position. Allows us to pass emacs-ctrl-o.html
            keyText = QLatin1String("\n");
            code = '\n';
            modifiers = 0;
            QKeyEvent event(QEvent::KeyPress, code, modifiers, keyText);
            m_testController->mainWebView()->sendEvent(&event);
            QKeyEvent event2(QEvent::KeyRelease, code, modifiers, keyText);
            m_testController->mainWebView()->sendEvent(&event2);
            keyText = QString();
            code = Qt::Key_Left;
        } else if (code == 'y' && modifiers == Qt::ControlModifier) {
            keyText = QLatin1String("c");
            code = 'c';
        } else if (code == 'k' && modifiers == Qt::ControlModifier) {
            keyText = QLatin1String("x");
            code = 'x';
        } else if (code == 'a' && modifiers == Qt::ControlModifier) {
            keyText = QString();
            code = Qt::Key_Home;
            modifiers = 0;
        } else if (code == KEYCODE_LEFTARROW) {
            keyText = QString();
            code = Qt::Key_Left;
            if (modifiers & Qt::MetaModifier) {
                code = Qt::Key_Home;
                modifiers &= ~Qt::MetaModifier;
            }
        } else if (code == KEYCODE_RIGHTARROW) {
            keyText = QString();
            code = Qt::Key_Right;
            if (modifiers & Qt::MetaModifier) {
                code = Qt::Key_End;
                modifiers &= ~Qt::MetaModifier;
            }
        } else if (code == KEYCODE_UPARROW) {
            keyText = QString();
            code = Qt::Key_Up;
            if (modifiers & Qt::MetaModifier) {
                code = Qt::Key_PageUp;
                modifiers &= ~Qt::MetaModifier;
            }
        } else if (code == KEYCODE_DOWNARROW) {
            keyText = QString();
            code = Qt::Key_Down;
            if (modifiers & Qt::MetaModifier) {
                code = Qt::Key_PageDown;
                modifiers &= ~Qt::MetaModifier;
            }
        } else if (code == 'a' && modifiers == Qt::ControlModifier) {
            keyText = QString();
            code = Qt::Key_Home;
            modifiers = 0;
        } else
            code = key.unicode()->toUpper().unicode();
    } else {
        if (key.startsWith(QLatin1Char('F')) && key.count() <= 3) {
            keyText = keyText.mid(1);
            int functionKey = keyText.toInt();
            Q_ASSERT(functionKey >= 1 && functionKey <= 35);
            code = Qt::Key_F1 + (functionKey - 1);
        // map special keycode strings used by the tests to something that works for Qt/X11
        } else if (key == QLatin1String("leftArrow")) {
            keyText = QString();
            code = Qt::Key_Left;
        } else if (key == QLatin1String("rightArrow")) {
            keyText = QString();
            code = Qt::Key_Right;
        } else if (key == QLatin1String("upArrow")) {
            keyText = QString();
            code = Qt::Key_Up;
        } else if (key == QLatin1String("downArrow")) {
            keyText = QString();
            code = Qt::Key_Down;
        } else if (key == QLatin1String("pageUp")) {
            keyText = QString();
            code = Qt::Key_PageUp;
        } else if (key == QLatin1String("pageDown")) {
            keyText = QString();
            code = Qt::Key_PageDown;
        } else if (key == QLatin1String("home")) {
            keyText = QString();
            code = Qt::Key_Home;
        } else if (key == QLatin1String("end")) {
            keyText = QString();
            code = Qt::Key_End;
        } else if (key == QLatin1String("insert")) {
            keyText = QString();
            code = Qt::Key_Insert;
        } else if (key == QLatin1String("delete")) {
            keyText = QString();
            code = Qt::Key_Delete;
        } else if (key == QLatin1String("printScreen")) {
            keyText = QString();
            code = Qt::Key_Print;
        } else if (key == QLatin1String("menu")) {
            keyText = QString();
            code = Qt::Key_Menu;
        }
    }

    QKeyEvent* pressEvent = new QKeyEvent(QEvent::KeyPress, code, modifiers, keyText);
    sendOrQueueEvent(pressEvent);
    QKeyEvent* releaseEvent = new QKeyEvent(QEvent::KeyRelease, code, modifiers, keyText);
    sendOrQueueEvent(releaseEvent);

}
bool WidgetRegistrationS60::registerAppL(const QString& appId,
                                         const QString& appTitle,
                                         const QString& appPath,
                                         const QString& dataPath,
                                         const QString& iconPath,
                                         const AttributeMap& attr,
                                         const QString& type,
                                         unsigned long size,
                                         const QString& startPath,
                                         int& widgetUid,
                                         QString& convertedIconPath, 
                                         bool hideIcon)
{
      (void)attr;
      (void)type;
      (void)size;
      (void)startPath;
      (void)hideIcon;
    LOG("WidgetRegistrationS60::registerAppL()" << " appId : " << appId << " appTitle : " << 
            appTitle << " appPath : " << appPath << " iconPath : " << iconPath << " startPath : " << 
            startPath << " hideIcon : " << hideIcon);

    if (appId.isEmpty() || appTitle.isEmpty() || appPath.isEmpty())
        return false;

    RFs rfs;
    User::LeaveIfError(rfs.Connect());
    CleanupClosePushL(rfs); // pushed 1
    User::LeaveIfError(rfs.ShareProtected());

    SwiUI::CWidgetRegistrationS60Apparc* appArc = SwiUI::CWidgetRegistrationS60Apparc::NewL(rfs);
    CleanupStack::PushL(appArc); // pushed 2

    // Generate our UID based on UIDs in the Qt WidgetRegistry
    int iUid = WebAppRegistry::instance()->nextAvailableUid();
    widgetUid = iUid;

    if (iUid == 0) {
        LOG("WidgetRegistrationS60::registerAppL() - netAvailableUid() failed");
        CleanupStack::PopAndDestroy(2);
        return false;
    }

    // convert icon to required format and sizes
    QString newIconPath = "";
    if (!processIconL(iUid, newIconPath, iconPath, QDir::toNativeSeparators(dataPath))) {
        LOG("WidgetRegistrationS60::registerAppL() - processIconL() failed");
        CleanupStack::PopAndDestroy(2);
        return false;
    }

    // FIXME this translation doesn't cover all cases, if generalized
    // must cover S60 WRT names and W3C names
    QString appPathNative = QDir::toNativeSeparators(appPath);
    // FIXME enforce canonicalization in caller
    // must end in QDir::separator()
    if (QDir::separator() != appPathNative.at(appPathNative.count()-1)) {
        appPathNative.append(QDir::separator());
    }

    convertedIconPath = newIconPath;

    // Record the used UID in the qt registry
    WebAppRegistry::instance()->setUid(appId, iUid);

    CleanupStack::PopAndDestroy(2); // appArc, rfs

    //Notify widget altered
    NotifyW3cWidgetAltered();

    return true;
}
bool WidgetRegistrationS60::registerAppL(const QString& appId,
                                         const QString& appTitle,
                                         const QString& appPath,
                                         const QString& dataPath,
                                         const QString& iconPath,
                                         const AttributeMap& attr,
                                         const QString& type,
                                         unsigned long size,
                                         const QString& startPath,
                                         int& widgetUid,
                                         QString& convertedIconPath,
                                         bool hideIcon)
{
    LOG("WidgetRegistrationS60::registerAppL()" << " appId : " << appId << " appTitle : " << 
            appTitle << " appPath : " << appPath << " iconPath : " << iconPath << " startPath : " << 
            startPath);

    if (appId.isEmpty() || appTitle.isEmpty() || appPath.isEmpty())
        return false;

    // S60 requires widgetProps as CWidgetPropertyValue
    RPointerArray<CWidgetPropertyValue> propertyValues(EWidgetPropertyIdCount);
    CleanupStack::PushL(TCleanupItem(PointerArrayCleanup, &propertyValues)); // pushed 1

    RWidgetRegistryClientSession registryClient;
    User::LeaveIfError(registryClient.Connect());
    CleanupClosePushL( registryClient ); // pushed 2

    RFs rfs;
    User::LeaveIfError(rfs.Connect());
    CleanupClosePushL(rfs); // pushed 3
    User::LeaveIfError(rfs.ShareProtected());

    // empty values
    for (TInt i = 0; i < EWidgetPropertyIdCount; ++i) {
        CWidgetPropertyValue* value = CWidgetPropertyValue::NewL();
        CleanupStack::PushL(value); // pushed 4
        propertyValues.AppendL(value);
        CleanupStack::Pop(value); // pushed 3
    }

    *(propertyValues[EWidgetPropertyListVersion]) = KWidgetPropertyListVersion71CWRT;
    *(propertyValues[EFileSize]) = size;

    SwiUI::CWidgetRegistrationS60Apparc* appArc = SwiUI::CWidgetRegistrationS60Apparc::NewL(rfs);
    CleanupStack::PushL(appArc); // pushed 4

    // get drive letter from appPath
    TUint driveLetter = appPath[0].unicode();

    // Generate our UID based on UIDs in the Qt WidgetRegistry
    int iUid = WebAppRegistry::instance()->nextAvailableUid();
    widgetUid = iUid;

    if (iUid == 0) {
        LOG("WidgetRegistrationS60::registerAppL() - registryClient.GetAvailableUidL() failed");
        CleanupStack::PopAndDestroy( 4, &propertyValues );
        return false;
    }

    // convert icon to required format and sizes
    QString newIconPath = "";
    if (!processIconL(iUid, newIconPath, iconPath, QDir::toNativeSeparators(dataPath))) {
        LOG("WidgetRegistrationS60::registerAppL() - processIconL() failed");
        CleanupStack::PopAndDestroy( 4, &propertyValues );
        return false;
        }

    // FIXME this translation doesn't cover all cases, if generalized
    // must cover S60 WRT names and W3C names
    QString appPathNative = QDir::toNativeSeparators(appPath);
    // FIXME enforce canonicalization in caller
    // must end in QDir::separator()
    if (QDir::separator() != appPathNative.at(appPathNative.count()-1)) {
        appPathNative.append(QDir::separator());
    }
    TPtrC16 basePathSymbian(reinterpret_cast<const TUint16*>
                            (appPathNative.constData()));
    *(propertyValues[EBasePath]) = basePathSymbian;

    QString driveName = appPathNative.left(2);
    TPtrC16 driveNameSymbian(reinterpret_cast<const TUint16*>
                             (driveName.constData()));
    *(propertyValues[EDriveName]) = driveNameSymbian;

    TPtrC16 mainHtmlSymbian(reinterpret_cast<const TUint16*>
                            (startPath.constData()));
    *(propertyValues[EMainHTML]) = mainHtmlSymbian;

    TPtrC16 identifierSymbian(reinterpret_cast<const TUint16*>
                              (appId.constData()));
    *(propertyValues[EBundleIdentifier]) = identifierSymbian;

    if (attr.contains(W3CSettingsKey::WIDGET_VERSION)) {
        QString ver = attr.value(W3CSettingsKey::WIDGET_VERSION).toString();
        if(!(ver.isEmpty())) {
            TPtrC16 version(reinterpret_cast<const TUint16*>
                            (attr.value(W3CSettingsKey::WIDGET_VERSION).toString().constData()));
            *(propertyValues[EBundleVersion]) = version;
        }
    }

    if (appTitle.isEmpty()) {
        // FIXME this probably should cause registration failure
        *(propertyValues[EBundleDisplayName]) = identifierSymbian;
    } else {
        TPtrC16 titleSymbian(reinterpret_cast<const TUint16*>
                             (appTitle.constData()));
        *(propertyValues[EBundleDisplayName]) = titleSymbian;
    }

    // TODO: We decided to drop BundleName and just use
    // DisplayName but the registry code has errors in it and uses
    // BundleName when it should use DisplayName so as a workaround,
    // set BundleName to DisplayName.  Should eventually remove
    // BundleName from set of registry values.
    const TDesC& name = *(propertyValues[EBundleDisplayName]);
    *(propertyValues[EBundleName]) = name;

    convertedIconPath = newIconPath;

    if (!newIconPath.isEmpty()) {
        // FIXME enforce canonicalization in caller
        // strangely icon path doesn't include icon file name
        int li = newIconPath.lastIndexOf(QDir::separator());
        if (li > 0) {
            newIconPath = newIconPath.left(li+1);
            TPtrC16 iconPathSymbian(reinterpret_cast<const TUint16*>
                                    (newIconPath.constData()));
            *(propertyValues[EIconPath]) = iconPathSymbian;
        }
    }

    *(propertyValues[EUid]) = iUid;

    *(propertyValues[EMiniViewEnable]) = 0;
    if (attr.contains(W3CSettingsKey::WIDGET_VIEWMODES)) {
        QStringList viewModeList = attr.value(W3CSettingsKey::WIDGET_VIEWMODES).toString().split(" ");
        foreach (const QString &str, viewModeList) {
            if (str.contains("minimized", Qt::CaseInsensitive)) {
                *(propertyValues[EMiniViewEnable]) = 1;
                break;
            }
        }
    }
void FontDocument::setFontCharacters(const QString &chars,
                                     const Data::Containers::FontParameters &parameters)
{
  QFontDatabase fonts;

  bool regenerateAll = false;

  this->mContainer->blockSignals(true);

  if (this->mContainer->count() > 1) {
    if (this->usedFont().family() != parameters.family ||
        this->usedStyle() != parameters.style ||
        this->usedFont().pixelSize() != parameters.size ||
        this->monospaced() != parameters.monospaced ||
        this->antialiasing() != parameters.antiAliasing ||
        this->foreground() != parameters.foreground ||
        this->background() != parameters.background ||
        this->ascent() != parameters.ascent ||
        this->descent() != parameters.descent ||
        this->multiplicityHeight() != parameters.multiplicityHeight ||
        this->multiplicityWidth() != parameters.multiplicityWidth
       ) {
      AppUI::Fonts::DialogFontChanged dialog(qobject_cast<QWidget *>(this->parent()));

      if (dialog.exec() == QDialog::Accepted) {
        regenerateAll = dialog.regenerateAll();
      } else {
        return;
      }
    }
  } else { // for newly created fonts
    regenerateAll = true;
  }

  this->beginChanges();

  // create font with specified parameters
  QFont fontNew = fonts.font(parameters.family, parameters.style, parameters.size);
  fontNew.setPixelSize(parameters.size);

  if (parameters.antiAliasing) {
    fontNew.setStyleStrategy(QFont::PreferAntialias);
  } else {
    fontNew.setStyleStrategy(QFont::NoAntialias);
  }

  // remove old characters
  if (regenerateAll) {
    this->mContainer->clear();

    // save new font
    this->setUsedFont(fontNew);
    this->setUsedStyle(parameters.style);
    this->setMonospaced(parameters.monospaced);
    this->setAntialiasing(parameters.antiAliasing);
    this->setAscent(parameters.ascent);
    this->setDescent(parameters.descent);
    this->setForeground(parameters.foreground);
    this->setBackground(parameters.background);
    this->setMultiplicityHeight(parameters.multiplicityHeight);
    this->setMultiplicityWidth(parameters.multiplicityWidth);
  } else {
    // remove characters, which not present in new characters list
    QStringList keys = this->mContainer->keys();
    QListIterator<QString> it(keys);
    it.toFront();

    while (it.hasNext()) {
      QString a = it.next();

      if (!chars.contains(a)) {
        this->mContainer->removeImage(a);
      }
    }
  }

  // find max size
  int width = 0, height = 0;
  QFontMetrics metrics(fontNew);

  if (parameters.monospaced) {
    for (int i = 0; i < chars.count(); i++) {
      width = qMax(width, metrics.width(chars.at(i)));
    }

    height = metrics.height();
  }

  // generate new characters
  QStringList keys = this->mContainer->keys();
  QStringList userOrdered;

  for (int i = 0; i < chars.count(); i++) {
    QString key = QString(chars.at(i));
    userOrdered.append(key);

    // if character not exists, create it
    if (!keys.contains(key)) {
      keys.append(key);
      QImage image = Parsing::Conversion::FontHelper::drawCharacter(chars.at(i),
                     fontNew,
                     parameters.foreground,
                     parameters.background,
                     width,
                     height,
                     parameters.antiAliasing,
                     parameters.multiplicityHeight,
                     parameters.multiplicityWidth);
      this->mContainer->setImage(key, new QImage(image));
    }
  }

  this->mContainer->reorderTo(&userOrdered);

  this->mContainer->blockSignals(false);

  this->endChanges(false);
}
Example #13
0
void HelpWindow::startSearch()
{
	QString str = m_pTermsEdit->text();
	str = str.replace( "\'", "\"" );
	str = str.replace( "`", "\"" );
	QString buf = str;
	str = str.replace( "-", " " );
	str = str.replace( QRegExp( "\\s[\\S]?\\s" ), " " );
	m_terms = str.split(" ",QString::SkipEmptyParts);
	QStringList termSeq;
	QStringList seqWords;
	QStringList::iterator it = m_terms.begin();
	for ( ; it != m_terms.end(); ++it ) {
		(*it) = (*it).simplified();
		(*it) = (*it).toLower();
		(*it) = (*it).replace( "\"", "" );
	}
	if ( str.contains( '\"' ) ) {
		if ( (str.count( '\"' ))%2 == 0 ) {
			int beg = 0;
			int end = 0;
			QString s;
			beg = str.indexOf( '\"', beg );
			while ( beg != -1 ) {
				beg++;
				end = str.indexOf( '\"', beg );
				s = str.mid( beg, end - beg );
				s = s.toLower();
				s = s.simplified();
				if ( s.contains( '*' ) ) {
				QMessageBox::warning( this, tr( "Full Text Search" ),
					tr( "Using a wildcard within phrases is not allowed." ) );
				return;
				}
				seqWords += s.split( ' ', QString::SkipEmptyParts );
				termSeq << s;
				beg = str.indexOf( '\"', end + 1);
			}
		} else {
			QMessageBox::warning( this, tr( "Full Text Search" ),
				tr( "The closing quotation mark is missing." ) );
			return;
		}
	}
	setCursor( Qt::WaitCursor );
	m_foundDocs.clear();
	m_foundDocs = g_pDocIndex->query( m_terms, termSeq, seqWords );

	m_pResultBox->clear();
	for ( it = m_foundDocs.begin(); it != m_foundDocs.end(); ++it )
		m_pResultBox->addItem( g_pDocIndex->getDocumentTitle( *it ) );

	m_terms.clear();
	bool isPhrase = false;
	QString s = "";
	for ( int i = 0; i < (int)buf.length(); ++i ) {
		if ( buf[i] == '\"' ) {
			isPhrase = !isPhrase;
			s = s.simplified();
			if ( !s.isEmpty() )
				m_terms << s;
			s = "";
		} else if ( buf[i] == ' ' && !isPhrase ) {
			s = s.simplified();
			if ( !s.isEmpty() )
				m_terms << s;
			s = "";
		} else
		s += buf[i];
	}
	if ( !s.isEmpty() ) m_terms << s;

	setCursor( Qt::ArrowCursor );
}
Example #14
0
KeyValuesTable::KeyValuesTable(HaveKeyValueData * hv, QWidget * parent, bool visit)
    : StringTable(((hv == 0) ? 0 : hv->get_n_keys()) + ((visit) ? 0 : 1),
		  (visit) ? 2 : 3, parent, visit) {
  horizontalHeader()->setLabel(0, TR("Key"));
  horizontalHeader()->setLabel(1, TR("Value"));
  if (! visit)
    horizontalHeader()->setLabel(2, TR("do"));
  
  int index;
  int sup = (hv == 0) ? 0 : hv->get_n_keys();
  
  if (visit) {
    for (index = 0; index < sup; index += 1) {
      TableItem * ti;
      
      ti = new TableItem(this, Q3TableItem::Never,
			 toUnicode(hv->get_key(index)));
      ti->setReplaceable(FALSE);
      setItem(index, 0, ti);
      
      QString s = toUnicode(hv->get_value(index));
      int n = s.count('\n');
    
      ti = new TableItem(this, Q3TableItem::Never, s);
      ti->setReplaceable(FALSE);
      setItem(index, 1, ti);
      if (n != 0) {
	// note : adjustRow(index) does nothing
	setRowHeight(index, rowHeight(index)*(n+1));
      }
    }
  }
  else {
    props.setAutoDelete(TRUE);
    
    QStringList items;
    
    for (index = 0; index < sup; index += 1){
      QString k = toUnicode(hv->get_key(index));
      QString v = toUnicode(hv->get_value(index));
      QStringList * psl = props[k];
      
      setText(index, 0, k);
      
      if (psl != 0)
	setItem(index, 1, new ComboItem(this, v, *psl, FALSE));
      if ((k.contains(':') == 2) &&
	  ProfiledStereotypes::enumerated(k, items)) {
	psl = new QStringList(items);
	props.insert(k, psl);
	setItem(index, 1, new ComboItem(this, v, *psl, FALSE));
      }
      else
	setItem(index, 1, new MLinesItem(this, v));

      setText(index, 2, QString::null);
      setRowStretchable(index, TRUE);
    }
    
    setText(index, 0, QString::null);
    setItem(index, 1, new MLinesItem(this, QString::null));
    setText(index, 2, QString::null);
    setRowStretchable(index, TRUE);
  }
  
  horizontalHeader()->setResizeEnabled(TRUE, 0);  //setColumnStretchable (0, TRUE);
  setColumnStretchable (1, TRUE);
  if (! visit) {
    adjustColumn(2);
    setColumnStretchable (2, FALSE);
  }
}
Example #15
0
void EventSender::keyDown(const QString& string, const QStringList& modifiers, unsigned int location)
{
    QString s = string;
    Qt::KeyboardModifiers modifs = getModifiers(modifiers);
    if (location == 3)
        modifs |= Qt::KeypadModifier;
    int code = 0;
    if (string.length() == 1) {
        code = string.unicode()->unicode();
        //qDebug() << ">>>>>>>>> keyDown" << code << (char)code;
        // map special keycodes used by the tests to something that works for Qt/X11
        if (code == '\r') {
            code = Qt::Key_Return;
        } else if (code == '\t') {
            code = Qt::Key_Tab;
            if (modifs == Qt::ShiftModifier)
                code = Qt::Key_Backtab;
            s = QString();
        } else if (code == KEYCODE_DEL || code == KEYCODE_BACKSPACE) {
            code = Qt::Key_Backspace;
            if (modifs == Qt::AltModifier)
                modifs = Qt::ControlModifier;
            s = QString();
        } else if (code == 'o' && modifs == Qt::ControlModifier) {
            // Mimic the emacs ctrl-o binding on Mac by inserting a paragraph
            // separator and then putting the cursor back to its original
            // position. Allows us to pass emacs-ctrl-o.html
            s = QLatin1String("\n");
            code = '\n';
            modifs = 0;
            QKeyEvent event(QEvent::KeyPress, code, modifs, s);
            sendEvent(m_page, &event);
            QKeyEvent event2(QEvent::KeyRelease, code, modifs, s);
            sendEvent(m_page, &event2);
            s = QString();
            code = Qt::Key_Left;
        } else if (code == 'y' && modifs == Qt::ControlModifier) {
            s = QLatin1String("c");
            code = 'c';
        } else if (code == 'k' && modifs == Qt::ControlModifier) {
            s = QLatin1String("x");
            code = 'x';
        } else if (code == 'a' && modifs == Qt::ControlModifier) {
            s = QString();
            code = Qt::Key_Home;
            modifs = 0;
        } else if (code == KEYCODE_LEFTARROW) {
            s = QString();
            code = Qt::Key_Left;
            if (modifs & Qt::MetaModifier) {
                code = Qt::Key_Home;
                modifs &= ~Qt::MetaModifier;
            }
        } else if (code == KEYCODE_RIGHTARROW) {
            s = QString();
            code = Qt::Key_Right;
            if (modifs & Qt::MetaModifier) {
                code = Qt::Key_End;
                modifs &= ~Qt::MetaModifier;
            }
        } else if (code == KEYCODE_UPARROW) {
            s = QString();
            code = Qt::Key_Up;
            if (modifs & Qt::MetaModifier) {
                code = Qt::Key_PageUp;
                modifs &= ~Qt::MetaModifier;
            }
        } else if (code == KEYCODE_DOWNARROW) {
            s = QString();
            code = Qt::Key_Down;
            if (modifs & Qt::MetaModifier) {
                code = Qt::Key_PageDown;
                modifs &= ~Qt::MetaModifier;
            }
        } else if (code == 'a' && modifs == Qt::ControlModifier) {
            s = QString();
            code = Qt::Key_Home;
            modifs = 0;
        } else
            code = string.unicode()->toUpper().unicode();
    } else {
        //qDebug() << ">>>>>>>>> keyDown" << string;

        if (string.startsWith(QLatin1Char('F')) && string.count() <= 3) {
            s = s.mid(1);
            int functionKey = s.toInt();
            Q_ASSERT(functionKey >= 1 && functionKey <= 35);
            code = Qt::Key_F1 + (functionKey - 1);
        // map special keycode strings used by the tests to something that works for Qt/X11
        } else if (string == QLatin1String("leftArrow")) {
            s = QString();
            code = Qt::Key_Left;
        } else if (string == QLatin1String("rightArrow")) {
            s = QString();
            code = Qt::Key_Right;
        } else if (string == QLatin1String("upArrow")) {
            s = QString();
            code = Qt::Key_Up;
        } else if (string == QLatin1String("downArrow")) {
            s = QString();
            code = Qt::Key_Down;
        } else if (string == QLatin1String("pageUp")) {
            s = QString();
            code = Qt::Key_PageUp;
        } else if (string == QLatin1String("pageDown")) {
            s = QString();
            code = Qt::Key_PageDown;
        } else if (string == QLatin1String("home")) {
            s = QString();
            code = Qt::Key_Home;
        } else if (string == QLatin1String("end")) {
            s = QString();
            code = Qt::Key_End;
        } else if (string == QLatin1String("insert")) {
            s = QString();
            code = Qt::Key_Insert;
        } else if (string == QLatin1String("delete")) {
            s = QString();
            code = Qt::Key_Delete;
        } else if (string == QLatin1String("printScreen")) {
            s = QString();
            code = Qt::Key_Print;
        } else if (string == QLatin1String("menu")) {
            s = QString();
            code = Qt::Key_Menu;
        }
    }
    QKeyEvent event(QEvent::KeyPress, code, modifs, s);
    sendEvent(m_page, &event);
    QKeyEvent event2(QEvent::KeyRelease, code, modifs, s);
    sendEvent(m_page, &event2);
}
Example #16
0
void AghPhoneDialog::menuTriggered(QAction *action) {
	cout << action->text().toLocal8Bit().data() << endl;
	QString operation = action->text();

	if (operation == "Preferences") {
		prefDialog->exec();
		prefDialog->updateConfiguration();
		configuration->saveConf();
	} else if (operation == "Close") {
		terminateApplication();
	} else if (operation == "Search in directory") {
		searchDir->exec();
		TerminalAddress *foundTerminal = searchDir->getSelectedTerminal();

		// check whether terminal was selected
		if (foundTerminal == NULL) {
			return;
		}

		QString foundTermName = foundTerminal->name.c_str();
		foundTermName += ":";
		foundTermName += foundTerminal->port.c_str();
		if (foundTerminal != 0) {
			this->putTerminalIntoList(foundTerminal, foundTermName);
		}
	} else if (operation == "Log in") {
		registeredAddress = new TerminalAddress;

		if (isRegistered) {
			QMessageBox::critical( this, this->windowTitle(),
					"User already registered");
			return;
		}

		if (this->configuration->directoryAlias->size() <= 0) {
			QMessageBox::critical( this, this->windowTitle(),
					"User alias not specified! Check your configuration.");
			return;
		}

		if (this->configuration->localPort->size() <= 0) {
			QMessageBox::critical( this, this->windowTitle(),
					"Local port not specified! Check your configuration.");
			return;
		}

		registeredAddress->name = *(this->configuration->directoryAlias);
		registeredAddress->port = *(this->configuration->localPort);

		// Get directory reference
		QString errorMessage = this->configuration->validateDirectory().c_str();

		if (errorMessage.count() > 0) {
			QMessageBox::critical( this, this->windowTitle(),
					errorMessage);

		} else {
			// search for directory
			try {
				Ice::CommunicatorPtr ic = Ice::initialize();
				stringstream a;
				a << *(configuration->directoryName)
				<< ":default -h " << *(configuration->directoryAddress)
				<< " -p " << *(configuration->directoryPort);
				Ice::ObjectPrx base = ic->stringToProxy ( a.str() );
				DirectoryPrx directory = DirectoryPrx::checkedCast ( base );

				if ( !directory ) {
					QMessageBox::critical( this, this->windowTitle(),
							"Connection to directory failed, please check your configuration!");
				} else {
					directory->registerTerminal(*registeredAddress);
					isRegistered = true;


					QString message("Terminal ");
					message += registeredAddress->name.c_str();
					message += " successfully registered.";
					statusbar->showMessage(message, 5000);
				}

				ic->destroy();

			} catch (TerminalExistsException ex) {
				QMessageBox::critical( this, this->windowTitle(),
						"User already registered, change your alias!");
				return;
			}  catch (...) {
				QMessageBox::critical( this, this->windowTitle(),
						"Connection to directory failed, please check your configuration!");
				return;
			}
		}

	} else if (operation == "Log out") {

		if (!isRegistered) {
			QMessageBox::critical( this, this->windowTitle(),
					"User not registered");
			return;
		}

		// Get directory reference
		QString errorMessage = this->configuration->validateDirectory().c_str();

		if (errorMessage.count() > 0) {
			QMessageBox::critical( this, this->windowTitle(),
					errorMessage);

		} else {
			// search for directory
			try {
				Ice::CommunicatorPtr ic = Ice::initialize();
				stringstream a;
				a << *(configuration->directoryName)
				<< ":default -h " << *(configuration->directoryAddress)
				<< " -p " << *(configuration->directoryPort);
				Ice::ObjectPrx base = ic->stringToProxy ( a.str() );
				DirectoryPrx directory = DirectoryPrx::checkedCast ( base );

				if ( !directory ) {
					QMessageBox::critical( this, this->windowTitle(),
							"Connection to directory failed, please check your configuration!");
				} else {
					directory->removeTerminal(registeredAddress->name);

					QString message("Terminal ");
					message += registeredAddress->name.c_str();
					message += " successfully unregistered.";
					statusbar->showMessage(message, 5000);

					delete registeredAddress;
					isRegistered = false;
				}

				ic->destroy();

			} catch (NoSuchTerminalException ex) {
				QMessageBox::critical( this, this->windowTitle(),
						"Such user does not exists in directory!");
			}  catch (...) {
				QMessageBox::critical( this, this->windowTitle(),
						"Connection to directory failed, please check your configuration!");
				return;
			}
		}
	} else if (operation == "About") {
		QString about;
		QDate curDate = QDate::currentDate();
		about += "AGHPhone VoIP application\n";
		about += "\n\nVersion 0.9.0.2b from ";
		about += curDate.toString();
		about += "\n\nCopyright (C) 2008  Mateusz Kramarczyk <*****@*****.**>\n";
		about += "Copyright (C) 2008  Tomasz Kijas <*****@*****.**>\n";
		about += "Copyright (C) 2008  Tomir Kryza <*****@*****.**>\n";
		about += "Copyright (C) 2008  Maciej Kluczny <*****@*****.**>\n";
		about += "Copyright (C) 2008  AGH University of Science and Technology <www.agh.edu.pl>\n";
		QMessageBox::about(this, "About AGHPhone", about);
	} else if (operation == "About Qt") {
		QMessageBox::aboutQt(this, "About Qt");
	} else if (operation == "License") {
		QString msg;
		msg += "This program is free software: you can redistribute it and/or modify\n";
		msg += "it under the terms of the GNU General Public License as published by\n";
		msg += "the Free Software Foundation, either version 3 of the License, or\n";
		msg += "(at your option) any later version.\n";
		msg += "\n";
		msg += "This program is distributed in the hope that it will be useful,\n";
		msg += "but WITHOUT ANY WARRANTY; without even the implied warranty of\n";
		msg += "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n";
		msg += "GNU General Public License for more details.\n";
		msg += "\n";
		msg += "You should have received a copy of the GNU General Public License\n";
		msg += "along with this program.  If not, see <http://www.gnu.org/licenses/>.\n";

		QMessageBox::about(this, "AGHPhone license regulations", msg);
	}
}
Example #17
0
//-------------------------------------------------------------------------
void DcMidiData::setText( const char* data )
{
    clear();

    QString str = QString(QByteArray(data));

    str = str.trimmed();
    int len = str.length();

    if(len < 2)
        return;

    QStringList strList;

    if( str.count(" ") || str.count(","))
    {
        strList = str.split(QRegExp("[ ,]+"));
    }
    else
    {
        // At this point, 'str' holds a string like this: 0x1234 or F06677AA
        // Check for the '0x' string, then the non-delim/non-0x string.
        // Assume all strings passed in as char* must be hex

        if(is0xHexStr(str))
        {
            strList.append(str);
        }
        else
        {
            // For a legal hex midi string without spaces, it must be
            // divisible by 2
            if((str.length()%2) != 0)
            {
                qDebug() << "DcMidiData::DcMidiData(const char*,int) - invalid hex string format: " << str;
            }
            else
            {
                for (int idx = 0; idx < str.length() ; idx++)
                {
                    QString tstr;
                    tstr.append(str[idx++]);
                    tstr.append(str[idx]);
                    strList.append(tstr);
                }
            }
        }
    }
    // Convert the string to hex
    foreach(QString s, strList)
    {
        if(s.isEmpty())
            continue;

        bool ok = true;
        int x = s.toInt(&ok,16);
        if(!ok)
        {
            qDebug() << "DcMidiData::DcMidiData(const char*,int) - error converting hex string: " << str;
        }
        else
        {
            if(!appendNum(x))
                break;
        }
    }
}
Example #18
0
void QTextOdfWriter::writeBlock(QXmlStreamWriter &writer, const QTextBlock &block)
{
    if (block.textList()) { // its a list-item
        const int listLevel = block.textList()->format().indent();
        if (m_listStack.isEmpty() || m_listStack.top() != block.textList()) {
            // not the same list we were in.
            while (m_listStack.count() >= listLevel && !m_listStack.isEmpty() && m_listStack.top() != block.textList() ) { // we need to close tags
                m_listStack.pop();
                writer.writeEndElement(); // list
                if (m_listStack.count())
                    writer.writeEndElement(); // list-item
            }
            while (m_listStack.count() < listLevel) {
                if (m_listStack.count())
                    writer.writeStartElement(textNS, QString::fromLatin1("list-item"));
                writer.writeStartElement(textNS, QString::fromLatin1("list"));
                if (m_listStack.count() == listLevel - 1) {
                    m_listStack.push(block.textList());
                    writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("L%1")
                            .arg(block.textList()->formatIndex()));
                }
                else {
                    m_listStack.push(0);
                }
            }
        }
        writer.writeStartElement(textNS, QString::fromLatin1("list-item"));
    }
    else {
        while (! m_listStack.isEmpty()) {
            m_listStack.pop();
            writer.writeEndElement(); // list
            if (m_listStack.count())
                writer.writeEndElement(); // list-item
        }
    }

    if (block.length() == 1) { // only a linefeed
        writer.writeEmptyElement(textNS, QString::fromLatin1("p"));
        writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("p%1")
            .arg(block.blockFormatIndex()));
        if (block.textList())
            writer.writeEndElement(); // numbered-paragraph
        return;
    }
    writer.writeStartElement(textNS, QString::fromLatin1("p"));
    writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("p%1")
        .arg(block.blockFormatIndex()));
    for (QTextBlock::Iterator frag= block.begin(); !frag.atEnd(); frag++) {
        writer.writeCharacters(QString()); // Trick to make sure that the span gets no linefeed in front of it.
        writer.writeStartElement(textNS, QString::fromLatin1("span"));

        QString fragmentText = frag.fragment().text();
        if (fragmentText.length() == 1 && fragmentText[0] == 0xFFFC) { // its an inline character.
            writeInlineCharacter(writer, frag.fragment());
            writer.writeEndElement(); // span
            continue;
        }

        writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("c%1")
            .arg(frag.fragment().charFormatIndex()));
        bool escapeNextSpace = true;
        int precedingSpaces = 0;
        int exportedIndex = 0;
        for (int i=0; i <= fragmentText.count(); ++i) {
            bool isSpace = false;
                QChar character = fragmentText[i];
                isSpace = character.unicode() == ' ';

            // find more than one space. -> <text:s text:c="2" />
            if (!isSpace && escapeNextSpace && precedingSpaces > 1) {
                const bool startParag = exportedIndex == 0 && i == precedingSpaces;
                if (!startParag)
                    writer.writeCharacters(fragmentText.mid(exportedIndex, i - precedingSpaces + 1 - exportedIndex));
                writer.writeEmptyElement(textNS, QString::fromLatin1("s"));
                const int count = precedingSpaces - (startParag?0:1);
                if (count > 1)
                    writer.writeAttribute(textNS, QString::fromLatin1("c"), QString::number(count));
                precedingSpaces = 0;
                exportedIndex = i;
            }

            if (i < fragmentText.count()) {
                if (character.unicode() == 0x2028) { // soft-return
                    //if (exportedIndex < i)
                        writer.writeCharacters(fragmentText.mid(exportedIndex, i - exportedIndex));
                    writer.writeEmptyElement(textNS, QString::fromLatin1("line-break"));
                    exportedIndex = i+1;
                    continue;
                } else if (character.unicode() == '\t') { // Tab
                    //if (exportedIndex < i)
                        writer.writeCharacters(fragmentText.mid(exportedIndex, i - exportedIndex));
                    writer.writeEmptyElement(textNS, QString::fromLatin1("tab"));
                    exportedIndex = i+1;
                    precedingSpaces = 0;
                } else if (isSpace) {
                    ++precedingSpaces;
                    escapeNextSpace = true;
                } else if (!isSpace) {
                    precedingSpaces = 0;
                }
            }
        }

        writer.writeCharacters(fragmentText.mid(exportedIndex));
        writer.writeEndElement(); // span
    }
    writer.writeCharacters(QString()); // Trick to make sure that the span gets no linefeed behind it.
    writer.writeEndElement(); // p
    if (block.textList())
        writer.writeEndElement(); // list-item
}
QgsProviderRegistry::QgsProviderRegistry( QString pluginPath )
{
  // At startup, examine the libs in the qgis/lib dir and store those that
  // are a provider shared lib
  // check all libs in the current plugin directory and get name and descriptions
  //TODO figure out how to register and identify data source plugin for a specific
  //TODO layer type
#if 0
  char **argv = qApp->argv();
  QString appDir = argv[0];
  int bin = appDir.findRev( "/bin", -1, false );
  QString baseDir = appDir.left( bin );
  QString mLibraryDirectory = baseDir + "/lib";
#endif
  mLibraryDirectory = pluginPath;
  mLibraryDirectory.setSorting( QDir::Name | QDir::IgnoreCase );
  mLibraryDirectory.setFilter( QDir::Files | QDir::NoSymLinks );

#if defined(WIN32) || defined(__CYGWIN__)
  mLibraryDirectory.setNameFilters( QStringList( "*.dll" ) );
#elif ANDROID
  mLibraryDirectory.setNameFilters( QStringList( "*provider.so" ) );
#else
  mLibraryDirectory.setNameFilters( QStringList( "*.so" ) );
#endif

  QgsDebugMsg( QString( "Checking %1 for provider plugins" ).arg( mLibraryDirectory.path() ) );

  if ( mLibraryDirectory.count() == 0 )
  {
    QString msg = QObject::tr( "No QGIS data provider plugins found in:\n%1\n" ).arg( mLibraryDirectory.path() );
    msg += QObject::tr( "No vector layers can be loaded. Check your QGIS installation" );

    QgsMessageOutput* output = QgsMessageOutput::createMessageOutput();
    output->setTitle( QObject::tr( "No Data Providers" ) );
    output->setMessage( msg, QgsMessageOutput::MessageText );
    output->showMessage();
    return;
  }

  QListIterator<QFileInfo> it( mLibraryDirectory.entryInfoList() );
  while ( it.hasNext() )
  {
    QFileInfo fi( it.next() );

    QLibrary myLib( fi.filePath() );
    if ( !myLib.load() )
    {
      QgsDebugMsg( QString( "Checking %1: ...invalid (lib not loadable): %2" ).arg( myLib.fileName() ).arg( myLib.errorString() ) );
      continue;
    }

    //MH: Added a further test to detect non-provider plugins linked to provider plugins.
    //Only pure provider plugins have 'type' not defined
    isprovider_t *hasType = ( isprovider_t * ) cast_to_fptr( myLib.resolve( "type" ) );
    if ( hasType )
    {
      QgsDebugMsg( QString( "Checking %1: ...invalid (has type method)" ).arg( myLib.fileName() ) );
      continue;
    }

    // get the description and the key for the provider plugin
    isprovider_t *isProvider = ( isprovider_t * ) cast_to_fptr( myLib.resolve( "isProvider" ) );
    if ( !isProvider )
    {
      QgsDebugMsg( QString( "Checking %1: ...invalid (no isProvider method)" ).arg( myLib.fileName() ) );
      continue;
    }

    // check to see if this is a provider plugin
    if ( !isProvider() )
    {
      QgsDebugMsg( QString( "Checking %1: ...invalid (not a provider)" ).arg( myLib.fileName() ) );
      continue;
    }

    // looks like a provider. get the key and description
    description_t *pDesc = ( description_t * ) cast_to_fptr( myLib.resolve( "description" ) );
    if ( !pDesc )
    {
      QgsDebugMsg( QString( "Checking %1: ...invalid (no description method)" ).arg( myLib.fileName() ) );
      continue;
    }

    providerkey_t *pKey = ( providerkey_t * ) cast_to_fptr( myLib.resolve( "providerKey" ) );
    if ( !pKey )
    {
      QgsDebugMsg( QString( "Checking %1: ...invalid (no providerKey method)" ).arg( myLib.fileName() ) );
      continue;
    }

    // add this provider to the provider map
    mProviders[pKey()] = new QgsProviderMetadata( pKey(), pDesc(), myLib.fileName() );

    // load database drivers
    databaseDrivers_t *pDatabaseDrivers = ( databaseDrivers_t * ) cast_to_fptr( myLib.resolve( "databaseDrivers" ) );
    if ( pDatabaseDrivers )
    {
      mDatabaseDrivers = pDatabaseDrivers();
    }

    // load directory drivers
    directoryDrivers_t *pDirectoryDrivers = ( directoryDrivers_t * ) cast_to_fptr( myLib.resolve( "directoryDrivers" ) );
    if ( pDirectoryDrivers )
    {
      mDirectoryDrivers = pDirectoryDrivers();
    }

    // load protocol drivers
    protocolDrivers_t *pProtocolDrivers = ( protocolDrivers_t * ) cast_to_fptr( myLib.resolve( "protocolDrivers" ) );
    if ( pProtocolDrivers )
    {
      mProtocolDrivers = pProtocolDrivers();
    }

    // now get vector file filters, if any
    fileVectorFilters_t *pFileVectorFilters = ( fileVectorFilters_t * ) cast_to_fptr( myLib.resolve( "fileVectorFilters" ) );
    if ( pFileVectorFilters )
    {
      QString fileVectorFilters = pFileVectorFilters();

      if ( !fileVectorFilters.isEmpty() )
        mVectorFileFilters += fileVectorFilters;

      QgsDebugMsg( QString( "Checking %1: ...loaded ok (%2 file filters)" ).arg( myLib.fileName() ).arg( fileVectorFilters.split( ";;" ).count() ) );
    }

    // now get raster file filters, if any
    // this replaces deprecated QgsRasterLayer::buildSupportedRasterFileFilter
    buildsupportedrasterfilefilter_t *pBuild =
      ( buildsupportedrasterfilefilter_t * ) cast_to_fptr( myLib.resolve( "buildSupportedRasterFileFilter" ) );
    if ( pBuild )
    {
      QString fileRasterFilters;
      pBuild( fileRasterFilters );

      QgsDebugMsg( "raster filters: " + fileRasterFilters );
      if ( !fileRasterFilters.isEmpty() )
        mRasterFileFilters += fileRasterFilters;

      QgsDebugMsg( QString( "Checking %1: ...loaded ok (%2 file filters)" ).arg( myLib.fileName() ).arg( fileRasterFilters.split( ";;" ).count() ) );
    }
  }
} // QgsProviderRegistry ctor
Example #20
0
bool DDZ::enregistre(QString fichier, QString contenu, QString langue, QStringList annexes, QStringList ignore){
    //Paramètres de fonction
    ErrorManager instance_erreur;

    QZipWriter ddz_global(fichier, QIODevice::WriteOnly);

    //Création d'un XML global pour les préférences
    QDomDocument preferences;
    QDomElement xmlConfig = preferences.createElement("config");
    QDomElement xmlLangue = preferences.createElement("langue");
    QDomText xmlLangueTexte = preferences.createTextNode(langue);
    xmlLangue.appendChild(xmlLangueTexte);
    xmlConfig.appendChild(xmlLangue);

    //On remplit le fichier avec le contenu
    QString nom_fichier = fichier.split("/").last();
    //Le nom du fichier est le même que le nom de l'archive globale si ce n'est que l'extention change
    nom_fichier.remove(nom_fichier.size()-4, nom_fichier.size()).append(".ddw");


    QByteArray array_contenu;
    array_contenu.append(contenu);
    ddz_global.addFile(nom_fichier, array_contenu);

    //On regarde s'il y avait des images
    int nb_images = contenu.count("<img src=");

    //Il y a des images, on rentre dans la boucle
    if(nb_images > 0){
        //Définition de la RegExp
        QRegExp regexp_images("<img[^>]*src=\"([^\"]*)");

        //Récupération des images
        int pos = 0; QStringList list;
        while ((pos = regexp_images.indexIn(contenu, pos)) != -1){
            list << regexp_images.cap(1);
            pos += regexp_images.matchedLength();
        }

        if(nb_images != list.size()){
            //On a pas trouvé toutes les images (ou on en a trouvé trop, ce qui est pire)
            instance_erreur.Erreur_msg(QObject::tr("Problème lors de la détection d'images -> annulation de la sauvegarde"), QMessageBox::Ignore);
            return false;
        }

        //Si on est ici, c'est que tout roule
        //On ajoute les images détectées au zip
        //ddz_global.addDirectory("images");
        for(int i=0; i<list.size(); i++){
            QString liste_temp = list.at(i);
            QString nom_fichier = liste_temp.split("/").last();
            //nom_fichier.prepend("images/");
            //On récupère l'extention
            QString extention = list.at(i).section('.', -1);
            QImageReader image(list.at(i), extention.toUpper().toStdString().c_str());
            ddz_global.addFile(nom_fichier, image.device());
        }
    }

    //Traitement des annexes
    if(annexes.size() > 0){
        QDomNode xmlAnnexe = preferences.createElement("annexes");
        for(int i=0; i<annexes.size(); i++){
            QFile fichier(annexes.at(i));
            fichier.open(QFile::ReadOnly);
            ddz_global.addFile(annexes.at(i).split("/").last(), fichier.readAll());
            fichier.close();
            //Ajout des annexes au XML global
            QDomElement thisAnnexe = preferences.createElement("annexe");
            QDomText thisText = preferences.createTextNode(annexes.at(i).split("/").last());
            thisAnnexe.appendChild(thisText);
            xmlAnnexe.appendChild(thisAnnexe);
            xmlConfig.appendChild(xmlAnnexe);
        }
    }

    //Traitement des mots à ignorer définitivement (ajout dans le XML de config)
    if(ignore.size() >= 1){
        QDomNode xmlIgnore = preferences.createElement("orthographe");
        for(int i=0; i<ignore.count(); i++){
            QDomElement motIgnore = preferences.createElement("mot");
            QDomText motTexte = preferences.createTextNode(ignore.at(i));
            motIgnore.appendChild(motTexte);
            xmlIgnore.appendChild(motIgnore);
            xmlConfig.appendChild(xmlIgnore);
        }
    }

    //Enregistrement des préférences
    preferences.appendChild(xmlConfig);
    QDomNode noeud = preferences.createProcessingInstruction("xml","version=\"1.0\"");
    preferences.insertBefore(noeud, preferences.firstChild());
    QByteArray array_prefs;
    array_prefs.append(preferences.toString());
    ddz_global.addFile("config.xml", array_prefs);

    //On ferme tout
    ddz_global.close();


    return true;
}
Example #21
0
void ScriptingWidget::insertFromMimeData(const QMimeData* pSource)
{
   QString filePath;
   QString text;
   if (mDropOccurring && pSource->hasUrls())
   {
      QList<QUrl> urls = pSource->urls();
      if (!urls.empty())
      {
         filePath = urls.front().toLocalFile();
      }
   }
   if (pSource->hasText())
   {
      text = pSource->text();
      int numNewlines = text.count("\n");
      QString trimmedText = text.trimmed();
      bool haveFile = false;
      if (mDropOccurring && numNewlines <= 1 && QFile::exists(trimmedText))
      {
         filePath = trimmedText;
      }
   }
   if (!filePath.isEmpty())
   {
      //don't get here if mDropOccurring == false
      InterpreterManager* pInterMgr = dynamic_cast<InterpreterManager*>(mInterpreter.get());
      bool bMatch = false;
      if (pInterMgr != NULL)
      {
         QString strInterpreterExtensions = QString::fromStdString(pInterMgr->getFileExtensions());
         if (!strInterpreterExtensions.isEmpty())
         {
            QStringList filterListCandidates = strInterpreterExtensions.split(";;", QString::SkipEmptyParts);
            QStringList filterList;
            for (int i = 0; i < filterListCandidates.count(); i++)
            {
               QString strExtensions = filterListCandidates[i];
               if (strExtensions.isEmpty() == false)
               {
                  int iOpenPos = strExtensions.indexOf("(");
                  int iClosePos = strExtensions.lastIndexOf(")");
                  strExtensions = strExtensions.mid(iOpenPos + 1, iClosePos - iOpenPos - 1);

                  QStringList globPatterns = strExtensions.split(QString(" "), QString::SkipEmptyParts);
                  QString catchAll = QString::fromStdString("*");
                  QString catchAll2 = QString::fromStdString("*.*");
                  for (int globCount = 0; globCount < globPatterns.count(); ++globCount)
                  {
                     QString pattern = globPatterns[globCount];
                     if ((pattern != catchAll) && (pattern != catchAll2))
                     {
                        filterList << pattern;
                     }
                  }
               }
            }

            bMatch = QDir::match(filterList, filePath);
         }
      }

      QFile file(filePath);
      if (bMatch && file.open(QIODevice::ReadOnly | QIODevice::Text))
      {
         QTextStream reader(&file);
         QString fileContent = reader.readAll();
         QTextCursor cursor = textCursor();
         cursor.movePosition(QTextCursor::End);
         cursor.insertText("\n");
         executeCommand(fileContent);
         return;
      }
   }
   if (!text.isEmpty())
   {
      bool insertText = true;
      if (mDropOccurring)
      {
         if (getCommandText().isEmpty())
         {
            insertText = false;
            QTextCursor cursor = textCursor();
            cursor.movePosition(QTextCursor::End);
            cursor.insertText("\n");
            executeCommand(text);
         }
      }
      if (insertText)
      {
         QTextCursor cursor = textCursor();
         cursor.insertText(text, currentCharFormat());
      }
   }
}
Example #22
0
void EventSender::keyDown(const QString& string, const QStringList& modifiers, unsigned int location)
{
    QString s = string;
    Qt::KeyboardModifiers modifs = 0;
    for (int i = 0; i < modifiers.size(); ++i) {
        const QString& m = modifiers.at(i);
        if (m == "ctrlKey")
            modifs |= Qt::ControlModifier;
        else if (m == "shiftKey")
            modifs |= Qt::ShiftModifier;
        else if (m == "altKey")
            modifs |= Qt::AltModifier;
        else if (m == "metaKey")
            modifs |= Qt::MetaModifier;
    }
    if (location == 3)
        modifs |= Qt::KeypadModifier;
    int code = 0;
    if (string.length() == 1) {
        code = string.unicode()->unicode();
        //qDebug() << ">>>>>>>>> keyDown" << code << (char)code;
        // map special keycodes used by the tests to something that works for Qt/X11
        if (code == '\r') {
            code = Qt::Key_Return;
        } else if (code == '\t') {
            code = Qt::Key_Tab;
            if (modifs == Qt::ShiftModifier)
                code = Qt::Key_Backtab;
            s = QString();
        } else if (code == KEYCODE_DEL || code == KEYCODE_BACKSPACE) {
            code = Qt::Key_Backspace;
            if (modifs == Qt::AltModifier)
                modifs = Qt::ControlModifier;
            s = QString();
        } else if (code == 'o' && modifs == Qt::ControlModifier) {
            s = QLatin1String("\n");
            code = '\n';
            modifs = 0;
        } else if (code == 'y' && modifs == Qt::ControlModifier) {
            s = QLatin1String("c");
            code = 'c';
        } else if (code == 'k' && modifs == Qt::ControlModifier) {
            s = QLatin1String("x");
            code = 'x';
        } else if (code == 'a' && modifs == Qt::ControlModifier) {
            s = QString();
            code = Qt::Key_Home;
            modifs = 0;
        } else if (code == KEYCODE_LEFTARROW) {
            s = QString();
            code = Qt::Key_Left;
            if (modifs & Qt::MetaModifier) {
                code = Qt::Key_Home;
                modifs &= ~Qt::MetaModifier;
            }
        } else if (code == KEYCODE_RIGHTARROW) {
            s = QString();
            code = Qt::Key_Right;
            if (modifs & Qt::MetaModifier) {
                code = Qt::Key_End;
                modifs &= ~Qt::MetaModifier;
            }
        } else if (code == KEYCODE_UPARROW) {
            s = QString();
            code = Qt::Key_Up;
            if (modifs & Qt::MetaModifier) {
                code = Qt::Key_PageUp;
                modifs &= ~Qt::MetaModifier;
            }
        } else if (code == KEYCODE_DOWNARROW) {
            s = QString();
            code = Qt::Key_Down;
            if (modifs & Qt::MetaModifier) {
                code = Qt::Key_PageDown;
                modifs &= ~Qt::MetaModifier;
            }
        } else if (code == 'a' && modifs == Qt::ControlModifier) {
            s = QString();
            code = Qt::Key_Home;
            modifs = 0;
        } else
            code = string.unicode()->toUpper().unicode();
    } else {
        //qDebug() << ">>>>>>>>> keyDown" << string;

        if (string.startsWith(QLatin1Char('F')) && string.count() <= 3) {
            s = s.mid(1);
            int functionKey = s.toInt();
            Q_ASSERT(functionKey >= 1 && functionKey <= 35);
            code = Qt::Key_F1 + (functionKey - 1);
        // map special keycode strings used by the tests to something that works for Qt/X11
        } else if (string == QLatin1String("leftArrow")) {
            s = QString();
            code = Qt::Key_Left;
        } else if (string == QLatin1String("rightArrow")) {
            s = QString();
            code = Qt::Key_Right;
        } else if (string == QLatin1String("upArrow")) {
            s = QString();
            code = Qt::Key_Up;
        } else if (string == QLatin1String("downArrow")) {
            s = QString();
            code = Qt::Key_Down;
        } else if (string == QLatin1String("pageUp")) {
            s = QString();
            code = Qt::Key_PageUp;
        } else if (string == QLatin1String("pageDown")) {
            s = QString();
            code = Qt::Key_PageDown;
        } else if (string == QLatin1String("home")) {
            s = QString();
            code = Qt::Key_Home;
        } else if (string == QLatin1String("end")) {
            s = QString();
            code = Qt::Key_End;
        } else if (string == QLatin1String("delete")) {
            s = QString();
            code = Qt::Key_Delete;
        }
    }
    QKeyEvent event(QEvent::KeyPress, code, modifs, s);
    QApplication::sendEvent(m_page, &event);
    QKeyEvent event2(QEvent::KeyRelease, code, modifs, s);
    QApplication::sendEvent(m_page, &event2);
}
Example #23
0
void breakLine(QString& str, QString& after, int textWidth)
{
    if (str.length() <= textWidth)
    {
        return;
    }

    // Найти слово, которое находится на границе textWidth.
    int beginWordPosition = str.lastIndexOf(' ', textWidth - 1) + 1;
    int endWordPosition = str.indexOf(' ', textWidth - 1) - 1;

    // Граничное слово находится в конце строки.
    if (endWordPosition == -2)
    {
        endWordPosition = str.length() - 1;
    }

    // Слово состоит из одной буквы.
    if (beginWordPosition == endWordPosition + 2)
    {
        endWordPosition = beginWordPosition;
    }

    int wordLength = endWordPosition - beginWordPosition + 1;
    QString word = str.mid(beginWordPosition, wordLength);

    // Слово начинается на границе ширины текста.
    if (beginWordPosition == textWidth - 1 && wordLength != 1)
    {
        QString temp = str.left(textWidth - 1);
        after = str.right(str.length() - temp.length());

		temp = temp.trimmed();
        if (temp.length() < textWidth)
        {
            fillSpaces(temp, textWidth);
        }
        str = temp.trimmed();
        return;
    }

    // Расставить в слове мягкие переносы.
    placeHyphens(word, word);

    // В слове нельзя сделать перенос.
    if (word.count('\1') == 0)
    {
        // Слово целиком умещается в ширину текста.
        if (beginWordPosition + wordLength <= textWidth)
        {
            after = str.right(str.length() - textWidth).trimmed();
            str.chop(str.length() - textWidth);
			str = str.trimmed();
			if (str.length() < textWidth)
			{
				fillSpaces(str, textWidth);
			}
			str = str.trimmed();
            return;
        }
        else
        {
            QString temp = str.left(textWidth);
            after = str.right(str.length() - temp.length());
            str = temp.trimmed();
			if (str.length() < textWidth)
			{
				fillSpaces(str, textWidth);
			}
			str = str.trimmed();
            return;
        }
    }

    // Вычислить максимальную длину слова до переноса, как разницу индексов
    // максимально допустимого символа, умещающегося в ширину текста, и начала
    // слова (символ переноса не входит в эту длину).
    int maxWordLengthBeforeBreak = (textWidth - 1) - beginWordPosition;

    // Так как в слове появились мягкие переносы, то нужно увеличить
    // максимальную длину слова до переноса на количество символов,
    // встретившихся перед прежней длиной.
    for (int i = 0; i < maxWordLengthBeforeBreak; ++i)
    {
        if (word[i] == '\1')
        {
            ++maxWordLengthBeforeBreak;
        }
    }
    if (word[maxWordLengthBeforeBreak] == '\1')
    {
        ++maxWordLengthBeforeBreak;
    }

    // Индекс переноса.
    int breakIndex = word.lastIndexOf('\1', maxWordLengthBeforeBreak - 1);

    // В слове можно сделать перенос с учетом ограничения на длину.
    if (breakIndex != -1)
    {
        // Заменить мягкий перенос на '\2' в позиции, не превышающей
        // максимальную длину слова до переноса. Замена производится именно на
        // '\2', а не на знак дефиса, т. к. в строке уже может быть знак дефиса.
        // Иначе не получится легко определить индекс, где нужно разделить
        // строки на две.
        word[breakIndex] = '\2';

        // Удалить все мягкие переносы.
        word.replace('\1', "");

        // Вставить слово с переносом в строку.
        str.remove(beginWordPosition, wordLength);
        str.insert(beginWordPosition, word);

        // Разделить строку на две.
        QStringList strings = str.split('\2');
        str = strings[0] + "-";
        if (str.length() < textWidth)
        {
            fillSpaces(str, textWidth);
        }
        after = strings[1];
		str = str.trimmed();
    }
    // В слове нельзя сделать перенос с учетом ограничения на длину.
    // Разделяем строку по границе начала граничного слова.
    else
    {
        after = str.right(str.length() - beginWordPosition);
        str.chop(str.length() - beginWordPosition);
        if (str.length() < textWidth)
        {
            fillSpaces(str, textWidth);
        }
		str = str.trimmed();
    }
}
Example #24
0
static void initializePinyinMap()
{
    if(g_initialed_pinyin_map)
    {
        return;
    }
    QFile file(":/other/hanzipinyin.txt");
    if(!file.open(QIODevice::ReadOnly))
    {
        ZW_LOG_WARNING(QString("open file is error,filename=%1,error=%2").arg(file.fileName()).arg(file.errorString()));
        return;
    }
    while(!file.atEnd())
    {
        QStringList lineStringList = QString(file.readLine()).split(" ");
        if(lineStringList.count() != 3)
        {
            continue;
        }
        if(lineStringList.at(0) != "#")
        {
            continue;
        }
        QString pinyin = lineStringList.at(1);
        QString hanziString = lineStringList.at(2);
        int count = hanziString.count();
        for(int i = 0; i < count; ++i)
        {
            ushort unicode = hanziString.at(i).unicode();
            if(s_unicodePinYinsMap.contains(unicode))
            {
                QStringList  &existList = s_unicodePinYinsMap[unicode];
                if(!existList.contains(pinyin))
                {
                    existList.append(pinyin);
                }
            }
            else
            {
                s_unicodePinYinsMap.insert(unicode,QStringList(pinyin));
            }
            QString hz =  hanziString.at(i);
            if(s_hanziPinYinsMap.contains(hz))
            {
                QStringList  &existList = s_hanziPinYinsMap[hz];
                if(!existList.contains(pinyin))
                {
                    existList.append(pinyin);
                }
            }
            else
            {
                s_hanziPinYinsMap.insert(hz,QStringList(pinyin));
            }
        }
    }

    ZW_LOG_INFO(QString("first initial s_unicodePinYinsMap=%1,s_hanziPinYinsMap=%2")
                .arg(s_unicodePinYinsMap.count()).arg(s_hanziPinYinsMap.count()));
    g_initialed_pinyin_map = true;
}
Example #25
0
QVariant QDbfSqlModel::data(const QModelIndex &index, int role) const
{

    QVariant value = QSqlQueryModel::data(index, role);
    int i,j,k;

    QByteArray tempDateArray;
    QDate tempDate;
    QTime tempTime;
    quint32 l;
    qint32 l1;
    qint64 l2;
    double db;
    bool ok;
    QString currency;
    //QLocale clocale(QLocale::German);
    QLocale clocale(QLocale::C);
    quint8 r,g,b;
    QByteArray tempByteArray;

    //QList<int> charFields;
    for (i=0;i<charFields.count();i++)
        {
            if (index.column() == charFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignLeft | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(charFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> currencyFields;
    for (i=0;i<currencyFields.count();i++)
        {
            if (index.column() == currencyFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                l2 = *(qint64 *)tempDateArray.data();

                                db = l2;
                                currency.setNum(db/10000,'f',4);

                                value = clocale.toString(db/10000,'f',4);
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(currencyFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> numericFields;
    for (i=0;i<numericFields.count();i++)
        {
            if (index.column() == numericFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                currency=value.toString().simplified();
                                k=currency.count()-1;
                                j=0;
                                ok=false;
                                while (k>0)
                                    {
                                        if (currency.at(k) == '.')
                                            {
                                                ok = true;
                                                break;
                                            }
                                        k--;
                                        j++;
                                    }
                                if (!ok) j=0;
                                value = clocale.toString(currency.toDouble(&ok),'f',j);
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(numericFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> dateFields;
    for (i=0;i<dateFields.count();i++)
        {
            if (index.column() == dateFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                value = value.toDate().toString("dd.MM.yyyy");
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(dateFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> timeFields;
    for (i=0;i<timeFields.count();i++)
        {
            if (index.column() == timeFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                l = *(quint32 *)tempDateArray.data();

                                tempDate = QDate::fromJulianDay(l);

                                l = *(quint32 *)(tempDateArray.data()+4);

                                tempTime.setHMS(0,0,0);
                                tempTime = tempTime.addMSecs(l);

                                value = tempDate.toString("dd.MM.yyyy")+" "+tempTime.toString("hh:mm:ss.zzz");

                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:                                
                                tempByteArray.append(timeFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> doubleFields;
    for (i=0;i<doubleFields.count();i++)
        {
            if (index.column() == doubleFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                db = *(double *)tempDateArray.data();

                                value = db;
                                //value = clocale.toString(db,'f',4);
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(doubleFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> intFields;
    for (i=0;i<intFields.count();i++)
        {
            if (index.column() == intFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                l1 = *(quint32 *)tempDateArray.data();

                                value = l1;

                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(intFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> logicalFields;
    for (i=0;i<logicalFields.count();i++)
        {
            if (index.column() == logicalFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(logicalFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> memoFields;
    for (i=0;i<memoFields.count();i++)
        {
            if (index.column() == memoFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(memoFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> memo4Fields;
    for (i=0;i<memo4Fields.count();i++)
        {
            if (index.column() == memo4Fields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                l = *(quint32 *)tempDateArray.data();

                                value = l;

                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(memo4FieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> generalFields;
    for (i=0;i<generalFields.count();i++)
        {
            if (index.column() == generalFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(generalFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    return value;
}
Example #26
0
int constructSQL(QString calculation, QString &resultSQL, QSqlDatabase db, QString shapeFile, QStringList fields, QString where, QString group, QString descriptions)
{
    int openB;
    int closeB;

    openB = calculation.count("(");
    closeB = calculation.count(")");

    if (openB != closeB)
        return 1;


    QStringList letters;

    letters.append("A");
    letters.append("B");
    letters.append("C");
    letters.append("D");
    letters.append("E");
    letters.append("F");
    letters.append("G");
    letters.append("H");
    letters.append("I");
    letters.append("J");
    letters.append("K");
    letters.append("L");
    letters.append("M");
    letters.append("N");
    letters.append("O");
    letters.append("P");
    letters.append("Q");
    letters.append("R");
    letters.append("S");
    letters.append("T");
    letters.append("U");
    letters.append("V");
    letters.append("W");
    letters.append("X");
    letters.append("Y");
    letters.append("Z");

    QList <TdatasetInfo> datasets;
    QList <TdatasetInfo> datasets2;

    //TB is the raster of the shape, TA is the shape
    TdatasetInfo combdset;
    combdset.code = "B";
    combdset.name = shapeFile + "_raster";
    datasets.append(combdset);

    int dsetcount;
    dsetcount = 1;

    QStringList calcs;
    calcs = calculation.split(",", QString::SkipEmptyParts);
    QString dataset;
    QString operation;
    QString temp;
    int pos;
    int start;
    int end;
    for (pos = 0; pos <= calcs.count()-1;pos++)
    {
        temp = calcs[pos];
        start = temp.indexOf("(");
        end = temp.indexOf(")");
        dataset = temp.mid(start+1,end-start-1);
        operation = temp.left(start);

        if (datasetExists(dataset,db))
        {
            if (!findDataset(dataset,datasets))
            {
                //Stores only unique datasets
                dsetcount++;
                TdatasetInfo dset;
                dset.name = dataset;
                dset.code = letters[dsetcount];
                datasets.append(dset);
            }
            //Stores all the datasets
            TdatasetInfo dset2;
            dset2.name = dataset;
            dset2.operation = operation;
            datasets2.append(dset2);
        }
    }

    if (datasets.count() == 1)
        return 1;


    QStringList lstdescs;
    if (!descriptions.isEmpty())
    {
        lstdescs = descriptions.split(",", QString::SkipEmptyParts);
        if (datasets2.count() != lstdescs.count())
        {
            gbtLog("Descriptions does not match calculations");
            return 1;
        }
    }

    QString calcstr;
    for (pos = 0; pos <= datasets2.count()-1;pos++)
    {
        calcstr = calcstr + datasets2[pos].operation + "(T";
        calcstr = calcstr + getDataSetCode(datasets2[pos].name,datasets);
        calcstr = calcstr + ".cellValue)";
        if (lstdescs.count() > 0)
            calcstr = calcstr + " '" + lstdescs[pos] + "',";
        else
            calcstr = calcstr + ",";
    }
    calcstr = calcstr.left(calcstr.length()-1);


    //Begin the construct of the result SQL

    QString resultSelect;
    //resultSelect = "SELECT T" + datasets[0].code + ".comCode," + calcstr;
    resultSelect = "SELECT ";
    for (pos = 0; pos <= fields.count()-1;pos++)
        resultSelect = resultSelect + "TA." + fields[pos] + ",";
    resultSelect = resultSelect + calcstr;


    QString resultFrom;
    resultFrom = " FROM " + shapeFile + " AS TA,";

    for (pos = 0; pos <= datasets.count()-1;pos++)
    {
        resultFrom = resultFrom + datasets[pos].name + " AS T" + datasets[pos].code + ",";
    }
    resultFrom = resultFrom.left(resultFrom.length()-1);

    QString resultWhere;


    //Link the tables
    if (datasets.count() > 1)
    {
        resultWhere = " WHERE TA.shapeid = TB.shapeid AND ";
        for (pos = 1; pos <= datasets.count()-1;pos++)
        {
            resultWhere = resultWhere + "T" + datasets[pos-1].code + ".geokey = T" + datasets[pos].code + ".geokey AND ";
        }
        resultWhere = resultWhere.left(resultWhere.length()-5);
    }

    if (!where.isEmpty())
        resultWhere = resultWhere + " AND  " + where;

    if (group.isEmpty())
        group = "TA.shapeid";
    resultSQL = resultSelect + resultFrom + resultWhere + " GROUP BY " + group + " ORDER BY TA.shapeid";

    return 0;

}
Example #27
0
Dialog::Dialog(QString parameterNama, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    /*
     * Initialize objects
     */
    this->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    ui->setupUi(this);
    ui->progressBar->hide();
    ui->btnReport->hide();
    ui->infoPaket->hide();
    fileSah = false;
    berhasil = false;
    debconf = false;
    polkitAgent = false;

    ruangKerja = QDir::homePath()+"/.alldeb"; //direktori untuk penyimpanan temporer dan pengaturan alldeb
    programTar = "tar"; //perintah tar untuk mengekstrak dan melihat properti file

    if (!QDir(ruangKerja).exists()) {
        QDir().mkdir(ruangKerja);
    }
    if (!QDir(ruangKerja+"/config").exists()) {
        QDir().mkdir(ruangKerja+"/config");
    }
    tentangProgram = new About(this);

    /**
     * @brief connect
     *
     * Connect objects
     *
     */
    ekstrak = new QProcess(this);
    connect(ekstrak,SIGNAL(finished(int)),this,SLOT(bacaInfoFile()));
    connect(ekstrak,SIGNAL(error(QProcess::ProcessError)),this,SLOT(prosesGagal()));
    daftarFile = new QProcess(this);
    connect(daftarFile,SIGNAL(finished(int)),this,SLOT(bacaFile()));
    connect(daftarFile,SIGNAL(error(QProcess::ProcessError)),this,SLOT(prosesGagal()));
    buatPaketInfo = new QProcess(this);
    connect(buatPaketInfo,SIGNAL(finished(int)),this,SLOT(bacaInfo()));
    connect(buatPaketInfo,SIGNAL(error(QProcess::ProcessError)),this,SLOT(prosesGagal()));
    apt_get1 = new QProcess(this);
    connect(apt_get1,SIGNAL(readyRead()),this,SLOT(bacaHasilAptget()));
    connect(apt_get1,SIGNAL(finished(int)),this,SLOT(instalPaket(int)));
    connect(apt_get1,SIGNAL(error(QProcess::ProcessError)),this,SLOT(prosesGagal()));
    apt_get2 = new QProcess(this);
    connect(apt_get2,SIGNAL(readyRead()),this,SLOT(bacaHasilPerintah()));
    connect(apt_get2,SIGNAL(finished(int)),this,SLOT(hapusTemporer()));
    connect(apt_get2,SIGNAL(finished(int)),this,SLOT(progresSelesai(int)));
    connect(apt_get2,SIGNAL(error(QProcess::ProcessError)),this,SLOT(prosesGagal()));
    connect(ui->tempatFile,SIGNAL(textChanged(QString)),this,SLOT(memilihFile()));

    this->cekSistem();
    this->buatMenu();

    // Jika program dijalankan dengan "Open with..."
    if (parameterNama.count()>0) {
        ui->labelPilih->hide();
        ui->btnCariFile->hide();
        ui->tempatFile->hide();

        QFileInfo berkasAlldeb(parameterNama);
        namaFile = berkasAlldeb.fileName();
        this->titleofWindow(namaFile);
        //ui->tempatFile->setText(namaFile);
        this->bacaFileAlldeb(parameterNama);
    } else {
        ui->btnInstal->setDisabled(true);
    }

    //qDebug() << namaFile;
    //berkasAlldeb.setFileName(parameterNama);
    jml = 0;                        //objek untuk jumlah file deb
    ui->btnMundur->setDisabled(true);

}
Example #28
0
bool parseGpsText(const QString &gps_text, double *latitude, double *longitude)
{
	enum {
		ISO6709D,
		SECONDS,
		MINUTES,
		DECIMAL
	} gpsStyle = ISO6709D;
	int eastWest = 4;
	int northSouth = 1;
	QString regExp;
	/* an empty string is interpreted as 0.0,0.0 and therefore "no gps location" */
	if (gps_text.trimmed() == "") {
		*latitude = 0.0;
		*longitude = 0.0;
		return true;
	}
	// trying to parse all formats in one regexp might be possible, but it seems insane
	// so handle the four formats we understand separately

	// ISO 6709 Annex D representation
	// http://en.wikipedia.org/wiki/ISO_6709#Representation_at_the_human_interface_.28Annex_D.29
	// e.g. 52°49'02.388"N 1°36'17.388"E
	if (gps_text.at(0).isDigit() && (gps_text.count(",") % 2) == 0) {
		gpsStyle = ISO6709D;
		regExp = QString("(\\d+)[" UTF8_DEGREE "\\s](\\d+)[\'\\s](\\d+)([,\\.](\\d+))?[\"\\s]([NS%1%2])"
				 "\\s*(\\d+)[" UTF8_DEGREE "\\s](\\d+)[\'\\s](\\d+)([,\\.](\\d+))?[\"\\s]([EW%3%4])")
			     .arg(tr("N"))
			     .arg(tr("S"))
			     .arg(tr("E"))
			     .arg(tr("W"));
	} else if (gps_text.count(QChar('"')) == 2) {
		gpsStyle = SECONDS;
		regExp = QString("\\s*([NS%1%2])\\s*(\\d+)[" UTF8_DEGREE "\\s]+(\\d+)[\'\\s]+(\\d+)([,\\.](\\d+))?[^EW%3%4]*"
				 "([EW%5%6])\\s*(\\d+)[" UTF8_DEGREE "\\s]+(\\d+)[\'\\s]+(\\d+)([,\\.](\\d+))?")
			     .arg(tr("N"))
			     .arg(tr("S"))
			     .arg(tr("E"))
			     .arg(tr("W"))
			     .arg(tr("E"))
			     .arg(tr("W"));
	} else if (gps_text.count(QChar('\'')) == 2) {
		gpsStyle = MINUTES;
		regExp = QString("\\s*([NS%1%2])\\s*(\\d+)[" UTF8_DEGREE "\\s]+(\\d+)([,\\.](\\d+))?[^EW%3%4]*"
				 "([EW%5%6])\\s*(\\d+)[" UTF8_DEGREE "\\s]+(\\d+)([,\\.](\\d+))?")
			     .arg(tr("N"))
			     .arg(tr("S"))
			     .arg(tr("E"))
			     .arg(tr("W"))
			     .arg(tr("E"))
			     .arg(tr("W"));
	} else {
		gpsStyle = DECIMAL;
		regExp = QString("\\s*([-NS%1%2]?)\\s*(\\d+)[,\\.](\\d+)[^-EW%3%4\\d]*([-EW%5%6]?)\\s*(\\d+)[,\\.](\\d+)")
			     .arg(tr("N"))
			     .arg(tr("S"))
			     .arg(tr("E"))
			     .arg(tr("W"))
			     .arg(tr("E"))
			     .arg(tr("W"));
	}
	QRegExp r(regExp);
	if (r.indexIn(gps_text) != -1) {
		// qDebug() << "Hemisphere" << r.cap(1) << "deg" << r.cap(2) << "min" << r.cap(3) << "decimal" << r.cap(4);
		// qDebug() << "Hemisphere" << r.cap(5) << "deg" << r.cap(6) << "min" << r.cap(7) << "decimal" << r.cap(8);
		switch (gpsStyle) {
		case ISO6709D:
			*latitude = r.cap(1).toInt() + r.cap(2).toInt() / 60.0 +
				    (r.cap(3) + QString(".") + r.cap(5)).toDouble() / 3600.0;
			*longitude = r.cap(7).toInt() + r.cap(8).toInt() / 60.0 +
				     (r.cap(9) + QString(".") + r.cap(11)).toDouble() / 3600.0;
			northSouth = 6;
			eastWest = 12;
			break;
		case SECONDS:
			*latitude = r.cap(2).toInt() + r.cap(3).toInt() / 60.0 +
				    (r.cap(4) + QString(".") + r.cap(6)).toDouble() / 3600.0;
			*longitude = r.cap(8).toInt() + r.cap(9).toInt() / 60.0 +
				     (r.cap(10) + QString(".") + r.cap(12)).toDouble() / 3600.0;
			eastWest = 7;
			break;
		case MINUTES:
			*latitude = r.cap(2).toInt() + (r.cap(3) + QString(".") + r.cap(5)).toDouble() / 60.0;
			*longitude = r.cap(7).toInt() + (r.cap(8) + QString(".") + r.cap(10)).toDouble() / 60.0;
			eastWest = 6;
			break;
		case DECIMAL:
		default:
			*latitude = (r.cap(2) + QString(".") + r.cap(3)).toDouble();
			*longitude = (r.cap(5) + QString(".") + r.cap(6)).toDouble();
			break;
		}
		if (r.cap(northSouth) == "S" || r.cap(northSouth) == tr("S") || r.cap(northSouth) == "-")
			*latitude *= -1.0;
		if (r.cap(eastWest) == "W" || r.cap(eastWest) == tr("W") || r.cap(eastWest) == "-")
			*longitude *= -1.0;
		// qDebug("%s -> %8.5f / %8.5f", gps_text.toLocal8Bit().data(), *latitude, *longitude);
		return true;
	}
	return false;
}
Example #29
0
//TODO: not needed, can be done with QString directly
static QString numberZeroFill( int number, int digits ){
	QString str = QString::number( number );
	while( str.count() < digits )
		str = "0" + str;
	return str;
}
Example #30
0
Value ValueParser::tryParseDate( const QString& str, bool *ok ) const
{
  bool valid = false;
  QDate tmpDate = m_settings->locale()->readDate (str, &valid);
  if (!valid)
  {
    // Try without the year
    // The tricky part is that we need to remove any separator around the year
    // For instance %Y-%m-%d becomes %m-%d and %d/%m/%Y becomes %d/%m
    // If the year is in the middle, say %m-%Y/%d, we'll remove the sep.
    // before it (%m/%d).
    QString fmt = m_settings->locale()->dateFormatShort();
    int yearPos = fmt.indexOf("%Y", 0, Qt::CaseInsensitive);
    if ( yearPos > -1 )
    {
      if ( yearPos == 0 )
      {
        fmt.remove( 0, 2 );
        while ( fmt[0] != '%' )
          fmt.remove( 0, 1 );
      } else
      {
        fmt.remove( yearPos, 2 );
        for ( ; yearPos > 0 && fmt[yearPos-1] != '%'; --yearPos )
          fmt.remove( yearPos, 1 );
      }
      //kDebug(36001) <<"Cell::tryParseDate short format w/o date:" << fmt;
      tmpDate = m_settings->locale()->readDate( str, fmt, &valid );
    }
  }
  if (valid)
  {
    // Note: if shortdate format only specifies 2 digits year, then 3/4/1955
    // will be treated as in year 3055, while 3/4/55 as year 2055
    // (because 55 < 69, see KLocale) and thus there's no way to enter for
    // year 1995

    // The following fixes the problem, 3/4/1955 will always be 1955

    QString fmt = m_settings->locale()->dateFormatShort();
    if( ( fmt.contains( "%y" ) == 1 ) && ( tmpDate.year() > 2999 ) )
      tmpDate = tmpDate.addYears( -1900 );

    // this is another HACK !
    // with two digit years, 0-69 is treated as year 2000-2069 (see KLocale)
    // however, in Excel only 0-29 is year 2000-2029, 30 or later is 1930
    // onwards

    // the following provides workaround for KLocale so we're compatible
    // with Excel
    // (e.g 3/4/45 is Mar 4, 1945 not Mar 4, 2045)
    if( ( tmpDate.year() >= 2030 ) && ( tmpDate.year() <= 2069 ) )
    {
      QString yearFourDigits = QString::number( tmpDate.year() );
      QString yearTwoDigits = QString::number( tmpDate.year() % 100 );

      // if year is 2045, check to see if "2045" isn't there --> actual
      // input is "45"
      if( ( str.count( yearTwoDigits ) >= 1 ) &&
          ( str.count( yearFourDigits ) == 0 ) )
        tmpDate = tmpDate.addYears( -100 );
    }
  }
  if (!valid)
  {
    //try to use the standard Qt date parsing, using ISO 8601 format
    tmpDate = QDate::fromString(str,Qt::ISODate);
    if (tmpDate.isValid())
    {
      valid = true;
    }
  }

  if (ok)
    *ok = valid;

  return Value ( tmpDate, m_settings );
}