void QgsManageConnectionsDialog::doExportImport()
{
  QList<QListWidgetItem *> selection = listConnections->selectedItems();
  if ( selection.isEmpty() )
  {
    QMessageBox::warning( this, tr( "Export/import error" ),
                          tr( "You should select at least one connection from list." ) );
    return;
  }

  QStringList items;
  for ( int i = 0; i < selection.size(); ++i )
  {
    items.append( selection.at( i )->text() );
  }

  if ( mDialogMode == Export )
  {
    QString fileName = QFileDialog::getSaveFileName( this, tr( "Save connections" ), ".",
                       tr( "XML files (*.xml *.XML)" ) );
    if ( fileName.isEmpty() )
    {
      return;
    }

    // ensure the user never ommited the extension from the file name
    if ( !fileName.toLower().endsWith( ".xml" ) )
    {
      fileName += ".xml";
    }

    mFileName = fileName;

    QDomDocument doc;
    switch ( mConnectionType )
    {
      case WMS:
        doc = saveOWSConnections( items, "WMS" );
        break;
      case WFS:
        doc = saveWFSConnections( items );
        break;
      case PostGIS:
        doc = savePgConnections( items );
        break;
      case MSSQL:
        doc = saveMssqlConnections( items );
        break;
      case WCS:
        doc = saveOWSConnections( items, "WCS" );
        break;
      case Oracle:
        doc = saveOracleConnections( items );
        break;
    }

    QFile file( mFileName );
    if ( !file.open( QIODevice::WriteOnly | QIODevice::Text ) )
    {
      QMessageBox::warning( this, tr( "Saving connections" ),
                            tr( "Cannot write file %1:\n%2." )
                            .arg( mFileName )
                            .arg( file.errorString() ) );
      return;
    }

    QTextStream out( &file );
    doc.save( out, 4 );
  }
  else // import connections
  {
    QFile file( mFileName );
    if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
    {
      QMessageBox::warning( this, tr( "Loading connections" ),
                            tr( "Cannot read file %1:\n%2." )
                            .arg( mFileName )
                            .arg( file.errorString() ) );
      return;
    }

    QDomDocument doc;
    QString errorStr;
    int errorLine;
    int errorColumn;

    if ( !doc.setContent( &file, true, &errorStr, &errorLine, &errorColumn ) )
    {
      QMessageBox::warning( this, tr( "Loading connections" ),
                            tr( "Parse error at line %1, column %2:\n%3" )
                            .arg( errorLine )
                            .arg( errorColumn )
                            .arg( errorStr ) );
      return;
    }

    switch ( mConnectionType )
    {
      case WMS:
        loadOWSConnections( doc, items, "WMS" );
        break;
      case WFS:
        loadWFSConnections( doc, items );
        break;
      case PostGIS:
        loadPgConnections( doc, items );
        break;
      case MSSQL:
        loadMssqlConnections( doc, items );
        break;
      case WCS:
        loadOWSConnections( doc, items, "WCS" );
        break;
      case Oracle:
        loadOracleConnections( doc, items );
        break;
    }
    // clear connections list and close window
    listConnections->clear();
    accept();
  }

  mFileName = "";
}
Example #2
0
inline QString
albumCacheKey( const Tomahawk::artist_ptr& artist, const QString& albumName )
{
    return QString( "%1\t\t%2" ).arg( artist->name().toLower() ).arg( albumName.toLower() );
}
Example #3
0
void DTVChannel::SetSIStandard(const QString &si_std)
{
    QMutexLocker locker(&dtvinfo_lock);
    sistandard = si_std.toLower();
    sistandard.detach();
}
void MainWindow::translate()
{
    QString no_commata = ui->text_assembler->toPlainText();
    no_commata.replace(", ", " ");
    no_commata.replace(",", " ");
    ui->text_assembler->setPlainText(no_commata);


    QStringList commands = ui->text_assembler->toPlainText().split("\n");

    QString binaryResult;

    for(int i = 0; i < commands.size(); i++)
    {
        QString command = commands.at(i).split("#").first();
        QString operation = command.split(" ").first();

        if(operation.toLower() == "add")
        {
            binaryResult += translateAdd(command) + "\n";
        }
        else if(operation.toLower() == "mul")
        {
            binaryResult += translateMul(command) + "\n";
        }
        else if(operation.toLower() == "sub")
        {
            binaryResult += translateMinus(command) + "\n";
        }
        else if(operation.toLower() == "div")
        {
            binaryResult += translateDiv(command) + "\n";
        }
        else if(operation.toLower() == "load_fixed")
        {
            binaryResult += translateLoadFixed(command) + "\n";
        }
        else if(operation.toLower() == "store_fixed")
        {
            binaryResult += translateStoreFixed(command) + "\n";
        }
        else if(operation.toLower() == "add_register_first_half")
        {
            binaryResult += translateAddRegisterFirstHalf(command) + "\n";
        }
        else if(operation.toLower() == "add_register_second_half")
        {
            binaryResult += translateAddRegisterSecondHalf(command) + "\n";
        }
        else if(operation.toLower() == "push")
        {
            binaryResult += translatePush(command) + "\n";
        }
        else if(operation.toLower() == "pop")
        {
            binaryResult += translatePop(command) + "\n";
        }
        else if(operation.toLower() == "jump_fixed")
        {
            binaryResult += translateJumpFixed(command) + "\n";
        }
        else if(operation.toLower() == "jump_register")
        {
            binaryResult += translateJumpRegister(command) + "\n";
        }
        else if(operation.toLower() == "branch_on_equal")
        {
            binaryResult += translateBranchOnEqual(command) + "\n";
        }
        else if(operation.toLower() == "set_stack_pointer")
        {
            binaryResult += translateStackPointer(command) + "\n";
        }
        else if(operation.toLower() == "load_register")
        {
            binaryResult += translateLoadRegister(command) + "\n";
        }
        else if(operation.toLower() == "store_register")
        {
            binaryResult += translateStoreRegister(command) + "\n";
        }
        else if(operation.toLower() == "nop")
        {
            binaryResult += "0x6000\n";
        }

        qDebug() << binaryResult;
    }

    ui->text_binary->setPlainText(binaryResult);
}
Example #5
0
void
MetarListModel::fetchMetar(const QString& _icao) {
  __myHttpHandler->fetchData(VatsimDataHandler::getSingleton().getMetarUrl() + "?id=" + _icao.toLower());
  __requests.enqueue(_icao.simplified());
}
QgsMemoryProvider::QgsMemoryProvider( const QString& uri )
    : QgsVectorDataProvider( uri )
    , mSpatialIndex( nullptr )
{
  // Initialize the geometry with the uri to support old style uri's
  // (ie, just 'point', 'line', 'polygon')
  QUrl url = QUrl::fromEncoded( uri.toUtf8() );
  QString geometry;
  if ( url.hasQueryItem( "geometry" ) )
  {
    geometry = url.queryItemValue( "geometry" );
  }
  else
  {
    geometry = url.path();
  }

  geometry = geometry.toLower();
  if ( geometry == "point" )
    mWkbType = QGis::WKBPoint;
  else if ( geometry == "linestring" )
    mWkbType = QGis::WKBLineString;
  else if ( geometry == "polygon" )
    mWkbType = QGis::WKBPolygon;
  else if ( geometry == "multipoint" )
    mWkbType = QGis::WKBMultiPoint;
  else if ( geometry == "multilinestring" )
    mWkbType = QGis::WKBMultiLineString;
  else if ( geometry == "multipolygon" )
    mWkbType = QGis::WKBMultiPolygon;
  else
    mWkbType = QGis::WKBUnknown;

  if ( url.hasQueryItem( "crs" ) )
  {
    QString crsDef = url.queryItemValue( "crs" );
    mCrs.createFromString( crsDef );
  }

  mNextFeatureId = 1;

  mNativeTypes
  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), "integer", QVariant::Int, 0, 10 )
  // Decimal number from OGR/Shapefile/dbf may come with length up to 32 and
  // precision up to length-2 = 30 (default, if width is not specified in dbf is length = 24 precision = 15)
  // We know that double (QVariant::Double) has only 15-16 significant numbers,
  // but setting that correct limits would disable the use of memory provider with
  // data from Shapefiles. In any case, the data are handled as doubles.
  // So the limits set here are not correct but enable use of data from Shapefiles.
  << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "double", QVariant::Double, 0, 32, 0, 30 )
  << QgsVectorDataProvider::NativeType( tr( "Text (string)" ), "string", QVariant::String, 0, 255 )

  // date type
  << QgsVectorDataProvider::NativeType( tr( "Date" ), "date", QVariant::Date, -1, -1, -1, -1 )

  // integer types
  << QgsVectorDataProvider::NativeType( tr( "Whole number (smallint - 16bit)" ), "int2", QVariant::Int, -1, -1, 0, 0 )
  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 32bit)" ), "int4", QVariant::Int, -1, -1, 0, 0 )
  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64bit)" ), "int8", QVariant::LongLong, -1, -1, 0, 0 )
  << QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), "numeric", QVariant::Double, 1, 20, 0, 20 )
  << QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), "decimal", QVariant::Double, 1, 20, 0, 20 )

  // floating point
  << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "real", QVariant::Double, -1, -1, -1, -1 )
  << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), "double precision", QVariant::Double, -1, -1, -1, -1 )

  // string types
  << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), "text", QVariant::String, -1, -1, -1, -1 )
  ;

  if ( url.hasQueryItem( "field" ) )
  {
    QList<QgsField> attributes;
    QRegExp reFieldDef( "\\:"
                        "(int|integer|real|double|string|date)" // type
                        "(?:\\((\\d+)"                // length
                        "(?:\\,(\\d+))?"                // precision
                        "\\))?"
                        "$", Qt::CaseInsensitive );
    QStringList fields = url.allQueryItemValues( "field" );
    for ( int i = 0; i < fields.size(); i++ )
    {
      QString name = fields.at( i );
      QVariant::Type type = QVariant::String;
      QString typeName( "string" );
      int length = 255;
      int precision = 0;

      int pos = reFieldDef.indexIn( name );
      if ( pos >= 0 )
      {
        name = name.mid( 0, pos );
        typeName = reFieldDef.cap( 1 ).toLower();
        if ( typeName == "int" || typeName == "integer" )
        {
          type = QVariant::Int;
          typeName = "integer";
          length = 10;
        }
        else if ( typeName == "real" || typeName == "double" )
        {
          type = QVariant::Double;
          typeName = "double";
          length = 20;
          precision = 5;
        }
        else if ( typeName == "date" )
        {
          type = QVariant::Date;
          typeName = "date";
          length = 10;
        }

        if ( reFieldDef.cap( 2 ) != "" )
        {
          length = reFieldDef.cap( 2 ).toInt();
        }
        if ( reFieldDef.cap( 3 ) != "" )
        {
          precision = reFieldDef.cap( 3 ).toInt();
        }
      }
      if ( name != "" )
        attributes.append( QgsField( name, type, typeName, length, precision ) );
    }
    addAttributes( attributes );
  }

  if ( url.hasQueryItem( "index" ) && url.queryItemValue( "index" ) == "yes" )
  {
    createSpatialIndex();
  }

}
Example #7
0
PeopleMap ParsePeople(QDomElement people)
{
    PeopleMap ret;

    QDomElement person = people.firstChildElement("person");
    if (!person.isNull())
    {
        while (!person.isNull())
        {
            if (person.hasAttribute("job"))
            {
                QString jobstring = person.attribute("job");
                PeopleType type;
                if (jobstring.toLower() == "actor")
                    type = ACTOR;
                else if (jobstring.toLower() == "author")
                    type = AUTHOR;
                else if (jobstring.toLower() == "producer")
                    type = PRODUCER;
                else if (jobstring.toLower() == "executive producer")
                    type = EXECPRODUCER;
                else if (jobstring.toLower() == "director")
                    type = DIRECTOR;
                else if (jobstring.toLower() == "cinematographer")
                    type = CINEMATOGRAPHER;
                else if (jobstring.toLower() == "composer")
                    type = COMPOSER;
                else if (jobstring.toLower() == "editor")
                    type = EDITOR;
                else if (jobstring.toLower() == "casting")
                    type = CASTINGDIRECTOR;
                else if (jobstring.toLower() == "artist")
                    type = ARTIST;
                else if (jobstring.toLower() == "album artist")
                    type = ALBUMARTIST;
                else if (jobstring.toLower() == "guest star")
                    type = GUESTSTAR;
                else
                    type = ACTOR;

                PersonInfo info;
                if (person.hasAttribute("name"))
                    info.name = person.attribute("name");
                if (person.hasAttribute("character"))
                    info.role = person.attribute("character");
                if (person.hasAttribute("thumb"))
                    info.thumbnail = person.attribute("thumb");
                if (person.hasAttribute("url"))
                    info.url = person.attribute("url");

                ret.insert(type,info);
            }
            person = person.nextSiblingElement("person");
        }
    }
    return ret;
}
Example #8
0
void LDesktop::UpdateBackground(){
  //Get the current Background
  if(bgupdating || bgWindow==0){ return; } //prevent multiple calls to this at the same time
  bgupdating = true;
  if(DEBUG){ qDebug() << " - Update Desktop Background for screen:" << desktopnumber; }
  //Get the list of background(s) to show
  QStringList bgL = settings->value(DPREFIX+"background/filelist", QStringList()).toStringList();
  //qDebug() << " - List:" << bgL << CBG;
    //Remove any invalid files
    for(int i=0; i<bgL.length(); i++){
      if( (!QFile::exists(bgL[i]) && bgL[i]!="default" && !bgL[i].startsWith("rgb(") ) || bgL[i].isEmpty()){ bgL.removeAt(i); i--; }
    }
    if(bgL.isEmpty()){ bgL << "default"; } //always fall back on the default
  //Determine if the background needs to be changed
  //qDebug() << "BG List:" << bgL << oldBGL << CBG << bgtimer->isActive();
  if(bgL==oldBGL && !CBG.isEmpty() && bgtimer->isActive()){
    //No background change scheduled - just update the widget
    bgWindow->update();
    bgupdating=false;
    return;
  }
  oldBGL = bgL; //save this for later
  //Determine which background to use next
  int index;
  if(CBG.isEmpty()){ index = ( qrand() % bgL.length() ); } //random first wallpaper
  else{ 
    //Go to the next in the list
    index = bgL.indexOf(CBG); 
    if(index < 0 || index >= bgL.length()-1){ index = 0; } //if invalid or last item in the list - go to first
    else{ index++; } //go to next
  }
  QString bgFile = bgL[index];
  //Save this file as the current background
  CBG = bgFile;
  //qDebug() << " - Set Background to:" << CBG << index << bgL;
  if( (bgFile.toLower()=="default")){ bgFile = LOS::LuminaShare()+"desktop-background.jpg"; }
  //Now set this file as the current background
  QString style;
  QString format = settings->value(DPREFIX+"background/format","stretch").toString();
  if(bgFile.startsWith("rgb(")){ style = "QWidget#bgWindow{ border-image: none; background-color: %1;}";
  }else if( format == "center"){ style = "QWidget#bgWindow{ background: black url(%1); background-position: center; background-repeat: no-repeat; }";
  }else if( format == "topleft"){ style = "QWidget#bgWindow{ background: black url(%1); background-position: top left; background-repeat: no-repeat; }";
  }else if( format == "topright"){ style = "QWidget#bgWindow{ background: black url(%1); background-position: top right; background-repeat: no-repeat; }";
  }else if( format == "bottomleft"){ style = "QWidget#bgWindow{ background: black url(%1); background-position: bottom left; background-repeat: no-repeat; }";
  }else if( format == "bottomright"){ style = "QWidget#bgWindow{ background: black url(%1); background-position: bottom right; background-repeat: no-repeat; }";
  }else if( format == "tile"){ style = "QWidget#bgWindow{ background-color: black; border-image:url(%1) repeat;}";
  }else{ /* STRETCH*/ style = "QWidget#bgWindow{ background-color: black; border-image:url(%1) stretch;}"; }
  style = style.arg(bgFile);
  bgWindow->setStyleSheet(style);
  bgWindow->show();
  //Now reset the timer for the next change (if appropriate)
  if(bgtimer->isActive()){ bgtimer->stop(); }
  if(bgL.length() > 1){
    //get the length of the timer (in minutes)
    int min = settings->value(DPREFIX+"background/minutesToChange",5).toInt();
    //restart the internal timer
    if(min > 0){
      bgtimer->start(min*60000); //convert from minutes to milliseconds
    }
  }
  //Now update the panel backgrounds
  for(int i=0; i<PANELS.length(); i++){
    PANELS[i]->update();
    PANELS[i]->show();
  }
  bgupdating=false;
}
Example #9
0
bool TypeRuleParser::startElement(const QString &namespaceURI,
                                  const QString &localName, const QString &qName,
                                  const QXmlAttributes &atts)
{
    Q_UNUSED(namespaceURI);
    Q_UNUSED(qName);

    // Save current element so that we know where the characters() belong to
    QString name(localName.toLower());

    // Is this a known element?
    if (!schema().knownElement(name)) {
        QStringList chdn = schema().children(_elems.top());
        typeRuleErrorLoc(QString("Element \"%1\" is unknown. Allowed "
                              "elements in this context are: %2")
                      .arg(name)
                      .arg(chdn.isEmpty() ? QString("(none)") : chdn.join(", ")));
    }

    // Is this an allowed children of this element?
    if (!schema().allowedChild(_elems.top(), name)) {
        QStringList chdn = schema().children(_elems.top());
        typeRuleErrorLoc(QString("Element \"%1\" not allowed here. Allowed "
                              "elements in this context are: %2")
                      .arg(name)
                      .arg(chdn.isEmpty() ? QString("(none)") : chdn.join(", ")));
    }

    const XmlElement& elem = schema().element(name);
    static const KeyValueStore osFilterAttr = OsFilter::supportedFilters();
    OsFilter* osf = 0;
    QString attr;

    KeyValueStore attributes;

    // Check the element's attributes
    for (int i = 0; i < atts.count(); ++i) {
        // Compare attributes case-insensitive
        attr = atts.localName(i).toLower();
        // Is the attribute known to OsFilter?
        if (osFilterAttr.contains(attr)) {
            // Create a new OS filter, if not yet done
            if (!osf) {
                // Are OS filters allowed here?
                if (!elem.optionalAttributes.contains(attr))
                    typeRuleErrorLoc(QString("Operating system filters are not "
                                             "allowed for element \"%1\".")
                                     .arg(name));

                // Create new filter based on the stack top (if exists)
                osf = _osfStack.isEmpty() ?
                            new OsFilter() : new OsFilter(*_osfStack.top().osf);
                _osfStack.push(OsFilterScope(name, osf));
            }
            osf->parseOption(attr, atts.value(i));
        }
        else if (!elem.optionalAttributes.contains(attr) &&
                 !elem.requiredAttributes.contains(attr))
        {
            QStringList list(elem.requiredAttributes);
            list.append(elem.optionalAttributes);
            typeRuleErrorLoc(QString("Unknown attribute \"%1\" for element \"%2\". "
                                     "Allowed attributes are: %3")
                             .arg(attr)
                             .arg(name)
                             .arg(list.isEmpty() ? QString("(none)") : list.join(", ")));
        }
        else {
            attributes[attr] = atts.value(i);

            if (attr == xml::priority) {
                bool ok;
                int prio = atts.value(i).toInt(&ok);
                if (!ok)
                    typeRuleErrorLoc(QString("Not a valid integer number: %1")
                                     .arg(atts.value(i)));
                _priorities.push(PriorityScope(name, prio));
            }
        }
    }

    // Did we find all required attributes?
    for (int i = 0; i < elem.requiredAttributes.size(); ++i) {
        if (atts.index(elem.requiredAttributes[i]) < 0)
            typeRuleErrorLoc(QString("Element \"%1\" requires attribute \"%2\" "
                                     "to be specified.")
                             .arg(name)
                             .arg(elem.requiredAttributes[i]));
    }

    // Check if the OS filter is same
    if (osf) {
        if (!osf->minVersion().isEmpty() && !osf->maxVersion().isEmpty() &&
            OsFilter::compareVersions(osf->minVersion(), osf->maxVersion()) > 0)
        {
            typeRuleErrorLoc(QString("Within element \"%0\": min. OS version "
                                     "is larger than max. version: %1 > %2")
                             .arg(name)
                             .arg(osf->minVersion().join("."))
                             .arg(osf->maxVersion().join(".")));
        }
    }

    // Check if we have multiple elements of that name in current scope
    if (!elem.allowMultiple && _children.top().contains(name)) {
        typeRuleErrorLoc(QString("Only one element \"%1\" is allowed here.")
                      .arg(name));
    }

    // <typeknowledge>
    if (name == xml::typeknowledge) {
        // Parse the version
        bool ok;
        float ver = atts.value(xml::version).toFloat(&ok);
        if (!ok)
            typeRuleErrorLoc(QString("Non-numeric version specified: %1")
                          .arg(atts.value(xml::version)));
        // Print a warning if version is newer than the current one
        if (ver > xml::currentVer)
            Console::warnMsg(QString("The rule file \"%1\" has version %2, our "
                                   "version is %3.")
                           .arg(ShellUtil::shortFileName(_reader->currFile()))
                           .arg(ver)
                           .arg(xml::currentVer));
    }
    // <rule>
    else if (name == xml::rule) {
        _rule = new TypeRule();
        _rule->setSrcLine(_locator ? _locator->lineNumber() : -1);
    }
    // <filter>
    else if (name == xml::filter)
        _filter = new InstanceFilter();
    // <action>
    else if (name == xml::action) {
        errorIfNull(_rule);
        TypeRuleAction::ActionType type =
                TypeRuleAction::strToActionType(attributes[xml::type]);
        TypeRuleAction* action = 0;

        switch (type) {
        case TypeRuleAction::atExpression:
            action = new ExpressionAction();
            break;

        case TypeRuleAction::atFunction:
            if (!attributes.contains(xml::file)) {
                typeRuleErrorLoc(QString("Action type \"%1\" in attribute \"%2\" "
                                      "requires the file name to be specified "
                                      "in the additional attribute \"%3\" in "
                                      "element \"%4\".")
                                .arg(attributes[xml::type])
                                .arg(xml::type)
                                .arg(xml::file)
                                .arg(name));
            }
            action = new FuncCallScriptAction();
            break;

        case TypeRuleAction::atInlineCode:
            action = new ProgramScriptAction();
            break;

        default: {
            typeRuleErrorLoc(QString("Unknown action type '%1', must be one "
                                     "of: %2")
                            .arg(attributes[xml::type])
                            .arg(TypeRuleAction::supportedActionTypes().join(", ")));
        }
        }

        action->setSrcLine(_locator ? _locator->lineNumber() : 0);
        _rule->setAction(action);
    }

    // Clear old data
    _cdata.clear();

    // Push element and attributes onto stack
    _elems.push(name);
    _attributes.push(attributes);
    _children.top().insert(name);
    _children.push(QSet<QString>());

    return true;
}
Example #10
0
static QVariant fcnLower( const QVariantList& values, QgsFeature* , QgsExpression* parent )
{
  QString str = getStringValue( values.at( 0 ), parent );
  return QVariant( str.toLower() );
}
/*!
  Render a plot to a file

  Supported formats are:

  - pdf\n
    Portable Document Format PDF
  - ps\n
    Postcript
  - svg\n
    Scalable Vector Graphics SVG
  - all image formats supported by Qt\n
    see QImageWriter::supportedImageFormats()

  Scalable vector graphic formats like PDF or SVG are superior to
  raster graphics formats.

  \param plot Plot widget
  \param fileName Path of the file, where the document will be stored
  \param format Format for the document
  \param sizeMM Size for the document in millimeters.
  \param resolution Resolution in dots per Inch (dpi)

  \sa renderTo(), render(), QwtPainter::setRoundingAlignment()
*/
void QwtPlotRenderer::renderDocument( QwtPlot *plot,
    const QString &fileName, const QString &format,
    const QSizeF &sizeMM, int resolution )
{
    if ( plot == NULL || sizeMM.isEmpty() || resolution <= 0 )
        return;

    QString title = plot->title().text();
    if ( title.isEmpty() )
        title = "Plot Document";

    const double mmToInch = 1.0 / 25.4;
    const QSizeF size = sizeMM * mmToInch * resolution;

    const QRectF documentRect( 0.0, 0.0, size.width(), size.height() );

    const QString fmt = format.toLower();
    if ( fmt == "pdf" )
    {
#ifndef QT_NO_PRINTER
        QPrinter printer;
        printer.setColorMode( QPrinter::Color );
        printer.setFullPage( true );
        printer.setPaperSize( sizeMM, QPrinter::Millimeter );
        printer.setDocName( title );
        printer.setOutputFileName( fileName );
        printer.setOutputFormat( QPrinter::PdfFormat );
        printer.setResolution( resolution );

        QPainter painter( &printer );
        render( plot, &painter, documentRect );
#endif
    }
    else if ( fmt == "ps" )
    {
#if QT_VERSION < 0x050000
#ifndef QT_NO_PRINTER
        QPrinter printer;
        printer.setColorMode( QPrinter::Color );
        printer.setFullPage( true );
        printer.setPaperSize( sizeMM, QPrinter::Millimeter );
        printer.setDocName( title );
        printer.setOutputFileName( fileName );
        printer.setOutputFormat( QPrinter::PostScriptFormat );
        printer.setResolution( resolution );

        QPainter painter( &printer );
        render( plot, &painter, documentRect );
#endif
#endif
    }
    else if ( fmt == "svg" )
    {
#ifndef QWT_NO_SVG
#ifdef QT_SVG_LIB
#if QT_VERSION >= 0x040500
        QSvgGenerator generator;
        generator.setTitle( title );
        generator.setFileName( fileName );
        generator.setResolution( resolution );
        generator.setViewBox( documentRect );

        QPainter painter( &generator );
        render( plot, &painter, documentRect );
#endif
#endif
#endif
    }
    else
    {
        if ( QImageWriter::supportedImageFormats().indexOf(
            format.toLatin1() ) >= 0 )
        {
            const QRect imageRect = documentRect.toRect();
            const int dotsPerMeter = qRound( resolution * mmToInch * 1000.0 );

            QImage image( imageRect.size(), QImage::Format_ARGB32 );
            image.setDotsPerMeterX( dotsPerMeter );
            image.setDotsPerMeterY( dotsPerMeter );
            image.fill( QColor( Qt::white ).rgb() );

            QPainter painter( &image );
            render( plot, &painter, imageRect );
            painter.end();

            image.save( fileName, format.toLatin1() );
        }
    }
}
Example #12
0
void Query::run(sc::SearchReplyProxy const& reply)
{
    try {
        // Start by getting information about the query
        const sc::CannedQuery &query(sc::SearchQueryBase::query());

        // Get the query string
        string query_string = query.query_string();
        qCDebug(Qry) << "Query string is:" << QString::fromStdString(query_string);

        // Checking out which sources are enabled.
        QList<BaseClient*> sources;
        if (settings().at("coursera").get_bool())
            sources.append(&m_coursera);
        if (settings().at("udemy").get_bool())
            sources.append(&m_udemy);
        if (settings().at("edx").get_bool())
            sources.append(&m_edx);
        if (settings().at("udacity").get_bool())
            sources.append(&m_udacity);
        if (settings().at("iversity").get_bool())
            sources.append(&m_iversity);
        if (settings().at("openLearning").get_bool())
            sources.append(&m_openLearning);
        qCDebug(Qry) << "Source count:" << sources.count();

        // Working with departments.
        sc::Department::SPtr all_depts = sc::Department::create("", query, _("All"));
        sc::DepartmentList depList;
        QList<Department> list = DepartmentManager::departments();
        for (int i = 0; i < list.length(); i++)
            depList.push_back(sc::Department::create(list[i].id.toStdString(), query, list[i].label.toStdString()));
        all_depts->set_subdepartments(depList);

        // Register the root department on the reply
        reply->register_departments(all_depts);

        QString selectedDepartment = QString::fromStdString(query.department_id());
        qCDebug(Qry) << "Selected department:" << selectedDepartment;

        QSet<QString> uniqueSet;
        for(int i = 0; i < sources.count(); ++i)
        {
            QString sourceCatName = sources[i]->name();
            auto sourceList = sources[i]->courses(QString::fromStdString(query_string));

            auto templ = settings().at("textPosition").get_int() ? CURRENT_TEMPLATE_OV : CURRENT_TEMPLATE;
            auto sourceCategory = reply->register_category(sourceCatName.toLower().toStdString(),
                                                             sourceCatName.toStdString(),
                                                             "", sc::CategoryRenderer(templ));

            //qCDebug(Qry) << "Processing source:" << sourceCatName;

            for (const auto &course : sourceList)
            {

                // Department check.
                if (!selectedDepartment.isEmpty() && !DepartmentManager::isMatch(course, selectedDepartment))
                    continue;

                // Duplicate results cause Dash to crash.
                if (uniqueSet.contains(course.link))
                {
                    qCDebug(Qry) << "Duplicate:" << course.link;
                    continue;
                }
                uniqueSet.insert(course.link);


                sc::CategorisedResult res(sourceCategory);

                // We must have a URI
                res.set_uri(course.link.toStdString());
                res.set_title(course.title.toStdString());
                res.set_art(course.art.toStdString());
                res["headline"] = course.headline.toStdString();
                res["description"] = course.description.toStdString();
                res["source"] = sourceCatName.toStdString();
                res["extra"] = course.extra.toStdString();
                if (!course.video.isEmpty())
                    res["video_url"] = course.video.toStdString();
                res["departments"] = course.departments.join(';').toStdString();

                // Add instructors to map.
                if (course.instructors.count() > 0)
                {
                    std::vector<sc::Variant> images, names, bios;
                    for (auto j = course.instructors.begin(); j != course.instructors.end(); ++j)
                    {
                        images.push_back(sc::Variant(j->image.toStdString()));
                        names.push_back(sc::Variant(j->name.toStdString()));
                        bios.push_back(sc::Variant((j->bio.length() < 150 ? j->bio : j->bio.left(150) + "...").toStdString()));
                    }
                    res["instr_images"] = images;
                    res["instr_names"] = names;
                    res["instr_bios"] = bios;
                }

                // Push the result
                if (!reply->push(res))
                    return;
            }

            qCDebug(Qry) << "Finished with source:" << sourceCatName;
        }

    } catch (domain_error &e) {
        // Handle exceptions being thrown by the client API
        cerr << e.what() << endl;
        reply->error(current_exception());
    }
}
Example #13
0
bool VConfigManager::isValidKeySequence(const QString &p_seq)
{
    return p_seq.isEmpty()
           || (p_seq.toLower() != "ctrl+q" && !QKeySequence(p_seq).isEmpty());
}
bool QgsCoordinateReferenceSystem::createFromOgcWmsCrs( QString theCrs )
{
  if ( loadFromDb( QgsApplication::srsDbFilePath(), "lower(auth_name||':'||auth_id)", theCrs.toLower() ) )
    return true;

  if ( theCrs.compare( "CRS:84", Qt::CaseInsensitive ) == 0 )
  {
    createFromSrsId( GEOCRS_ID );
    return true;
  }

  return false;
}
Example #15
0
bool MyMoneyXmlContentHandler::endElement(const QString& /* namespaceURI */, const QString& /* localName */, const QString& qName)
{
  bool rc = true;
  QString s = qName.toLower();
  if (m_level) {
    m_currNode = m_currNode.parentNode().toElement();
    m_level--;
    if (!m_level) {
      try {
        if (s == "transaction") {
          MyMoneyTransaction t0(m_baseNode);
          if (!t0.id().isEmpty()) {
            MyMoneyTransaction t1(m_reader->d->nextTransactionID(), t0);
            m_reader->d->tList[t1.uniqueSortKey()] = t1;
          }
          m_reader->signalProgress(++m_elementCount, 0);
        } else if (s == "account") {
          MyMoneyAccount a(m_baseNode);
          if (!a.id().isEmpty())
            m_reader->d->aList[a.id()] = a;
          m_reader->signalProgress(++m_elementCount, 0);
        } else if (s == "payee") {
          MyMoneyPayee p(m_baseNode);
          if (!p.id().isEmpty())
            m_reader->d->pList[p.id()] = p;
        } else if (s == "tag") {
          MyMoneyTag ta(m_baseNode);
          if (!ta.id().isEmpty())
            m_reader->d->taList[ta.id()] = ta;
        } else if (s == "currency") {
          MyMoneySecurity s(m_baseNode);
          if (!s.id().isEmpty())
            m_reader->d->secList[s.id()] = s;
          m_reader->signalProgress(++m_elementCount, 0);
        } else if (s == "security") {
          MyMoneySecurity s(m_baseNode);
          if (!s.id().isEmpty())
            m_reader->d->secList[s.id()] = s;
          m_reader->signalProgress(++m_elementCount, 0);
        } else if (s == "keyvaluepairs") {
          MyMoneyKeyValueContainer kvp(m_baseNode);
          m_reader->m_storage->setPairs(kvp.pairs());
        } else if (s == "institution") {
          MyMoneyInstitution i(m_baseNode);
          if (!i.id().isEmpty())
            m_reader->d->iList[i.id()] = i;
        } else if (s == "report") {
          MyMoneyReport r(m_baseNode);
          if (!r.id().isEmpty())
            m_reader->d->rList[r.id()] = r;
          m_reader->signalProgress(++m_elementCount, 0);
        } else if (s == "budget") {
          MyMoneyBudget b(m_baseNode);
          if (!b.id().isEmpty())
            m_reader->d->bList[b.id()] = b;
        } else if (s == "fileinfo") {
          rc = m_reader->readFileInformation(m_baseNode);
          m_reader->signalProgress(-1, -1);
        } else if (s == "user") {
          rc = m_reader->readUserInformation(m_baseNode);
          m_reader->signalProgress(-1, -1);
        } else if (s == "scheduled_tx") {
          MyMoneySchedule s(m_baseNode);
          if (!s.id().isEmpty())
            m_reader->d->sList[s.id()] = s;
        } else if (s == "price") {
          MyMoneyPrice p(m_reader->d->m_fromSecurity, m_reader->d->m_toSecurity, m_baseNode);
          m_reader->d->prList[MyMoneySecurityPair(m_reader->d->m_fromSecurity, m_reader->d->m_toSecurity)][p.date()] = p;
          m_reader->signalProgress(++m_elementCount, 0);
        } else if (s == "onlinejob") {
          onlineJob job(m_baseNode);
          if (!job.id().isEmpty())
            m_reader->d->onlineJobList[job.id()] = job;
        } else {
          m_errMsg = i18n("Unknown XML tag %1 found in line %2", qName, m_loc->lineNumber());
          kWarning() << m_errMsg;
          rc = false;
        }
      } catch (const MyMoneyException &e) {
        m_errMsg = i18n("Exception while creating a %1 element: %2", s, e.what());
        kWarning() << m_errMsg;
        rc = false;
      }
      m_doc = QDomDocument();
    }
  } else {
    if (s == "institutions") {
      // last institution read, now dump them into the engine
      m_reader->m_storage->loadInstitutions(m_reader->d->iList);
      m_reader->d->iList.clear();
    } else if (s == "accounts") {
      // last account read, now dump them into the engine
      m_reader->m_storage->loadAccounts(m_reader->d->aList);
      m_reader->d->aList.clear();
      m_reader->signalProgress(-1, -1);
    } else if (s == "payees") {
      // last payee read, now dump them into the engine
      m_reader->m_storage->loadPayees(m_reader->d->pList);
      m_reader->d->pList.clear();
    } else if (s == "tags") {
      // last tag read, now dump them into the engine
      m_reader->m_storage->loadTags(m_reader->d->taList);
      m_reader->d->taList.clear();
    } else if (s == "transactions") {
      // last transaction read, now dump them into the engine
      m_reader->m_storage->loadTransactions(m_reader->d->tList);
      m_reader->d->tList.clear();
      m_reader->signalProgress(-1, -1);
    } else if (s == "schedules") {
      // last schedule read, now dump them into the engine
      m_reader->m_storage->loadSchedules(m_reader->d->sList);
      m_reader->d->sList.clear();
    } else if (s == "securities") {
      // last security read, now dump them into the engine
      m_reader->m_storage->loadSecurities(m_reader->d->secList);
      m_reader->d->secList.clear();
      m_reader->signalProgress(-1, -1);
    } else if (s == "currencies") {
      // last currency read, now dump them into the engine
      m_reader->m_storage->loadCurrencies(m_reader->d->secList);
      m_reader->d->secList.clear();
      m_reader->signalProgress(-1, -1);
    } else if (s == "reports") {
      // last report read, now dump them into the engine
      m_reader->m_storage->loadReports(m_reader->d->rList);
      m_reader->d->rList.clear();
      m_reader->signalProgress(-1, -1);
    } else if (s == "budgets") {
      // last budget read, now dump them into the engine
      m_reader->m_storage->loadBudgets(m_reader->d->bList);
      m_reader->d->bList.clear();
    } else if (s == "prices") {
      // last price read, now dump them into the engine
      m_reader->m_storage->loadPrices(m_reader->d->prList);
      m_reader->d->bList.clear();
      m_reader->signalProgress(-1, -1);
    } else if (s == "onlinejobs") {
      m_reader->m_storage->loadOnlineJobs(m_reader->d->onlineJobList);
      m_reader->d->onlineJobList.clear();
    }
  }
  return rc;
}
Example #16
0
bool TypeRuleParser::endElement(const QString &namespaceURI,
                                const QString &localName, const QString &qName)
{
    Q_UNUSED(namespaceURI);
    Q_UNUSED(qName);

    // Handle all elements in lower case
    QString name(localName.toLower());

    // <rule>
    if (name == xml::rule) {
        errorIfNull(_rule);
        // We require a filter and an action
        if (!_children.top().contains(xml::filter))
            typeRuleErrorLoc(QString("No filter specified for rule in line %1.")
                             .arg(_rule->srcLine()));
        if (!_children.top().contains(xml::action))
            typeRuleErrorLoc(QString("No action specified for rule in line %1.")
                             .arg(_rule->srcLine()));
        // Set the priority
        _rule->setPriority(_priorities.isEmpty() ? 0 : _priorities.top().prio);
        // Pass the rule on to the reader
        _reader->appendRule(_rule, _osfStack.isEmpty() ? 0 : _osfStack.top().osf);
        _rule = 0;
    }
    // <ruleinclude>
    else if (name == xml::ruleinclude)
        _reader->appendRulesInclude(_cdata.trimmed());
    // <scriptinclude>
    else if (name == xml::scriptinclude)
        _reader->appendScriptInclude(_cdata.trimmed());
    // <include>
    else if (name == xml::include) {
        bool ret = _reader->includeRulesFile(_cdata.trimmed());
        if (!ret)
            typeRuleErrorLoc(QString("Unable to resolve included file \"%1\".")
                     .arg(_cdata.trimmed()));
    }
    // <name>
    if (name == xml::name) {
        errorIfNull(_rule);
        _rule->setName(_cdata.trimmed());
    }
    // <description>
    if (name == xml::description) {
        errorIfNull(_rule);
        _rule->setDescription(_cdata.trimmed());
    }
    // <action>
    else if (name == xml::action) {
        errorIfNull(_rule);
        errorIfNull(_rule->action());

        switch (_rule->action()->actionType()) {
        case TypeRuleAction::atInlineCode: {
            ProgramScriptAction* action =
                    dynamic_cast<ProgramScriptAction*>(_rule->action());
            action->setSourceCode(_cdata);
            break;
        }
        case TypeRuleAction::atFunction: {
            QString value = _attributes.top().value(xml::file);
            QString file = _reader->absoluteScriptFilePath(value);
            if (file.isEmpty())
                typeRuleErrorLoc(QString("Unable to locate script file \"%1\".")
                         .arg(value));

            FuncCallScriptAction* action =
                    dynamic_cast<FuncCallScriptAction*>(_rule->action());
            action->setFunction(_cdata.trimmed());
            action->setScriptFile(file);
            break;
        }
        case TypeRuleAction::atExpression: {
            if (_children.isEmpty() ||
                !_children.top().contains(xml::srcType) ||
                !_children.top().contains(xml::targetType) ||
                !_children.top().contains(xml::expression))
            {
                typeRuleErrorLoc(QString("Action type \"%1\" in element \"%2\" "
                                         "requires the following child "
                                         "elements: %3, %4, %5")
                                 .arg(xml::expression)
                                 .arg(name)
                                 .arg(xml::srcType)
                                 .arg(xml::targetType)
                                 .arg(xml::expression));
            }
            break;
        }
        default:
            typeRuleErrorLoc(QString("Action type \"%1\" unknown for attribute "
                                  "\"%2\" in element \"%3\".")
                             .arg(_attributes.top().value(xml::type))
                             .arg(xml::type)
                             .arg(name));
        }
    }
    // <sourcetype>
    // <targettype>
    // <expression>
    else if (name == xml::srcType || name == xml::targetType ||
             name == xml::expression)
    {
        errorIfNull(_rule);

        ExpressionAction* action = dynamic_cast<ExpressionAction*>(_rule->action());
        if (!action)
            typeRuleErrorLoc(QString("Element \"%1\" only valid for action "
                                     "type \"%2\".")
                             .arg(name)
                             .arg(xml::expression));

        if (name == xml::srcType)
            action->setSourceTypeStr(_cdata.trimmed());
        else if (name == xml::targetType)
            action->setTargetTypeStr(_cdata.trimmed());
        else
            action->setExpressionStr(_cdata.trimmed());
    }
    // <filter>
    else if (name == xml::filter) {
        errorIfNull(_rule);
        // We require a non-empty filter
        if (_children.top().isEmpty())
            typeRuleErrorLoc(QString("Empty filter specified."));

        _rule->setFilter(_filter);
        _filter = 0;
    }
    // All children of <filter>
    else if (InstanceFilter::supportedFilters().contains(name)) {
        errorIfNull(_filter);
        _filter->parseOption(name, _cdata.trimmed(), &_attributes.top());
    }

    // See if the scope of the OS filter is at its end
    if (!_osfStack.isEmpty() && _osfStack.top().elem == name) {
        // Delete filter and remove it from stack
        delete _osfStack.top().osf;
        _osfStack.pop();
    }

    // See if the scope of the priority is at its end
    if (!_priorities.isEmpty() && _priorities.top().elem == name)
        _priorities.pop();

    // Pop element from stack
    _elems.pop();
    _children.pop();
    _attributes.pop();

    return true;
}
Example #17
0
SqlCommandList KraftDB::parseCommandFile( const QString& file )
{
    QString sqlFile;
    QString env = QString::fromUtf8( qgetenv( "KRAFT_HOME" ) );
    if( !env.isEmpty() && env.right(1) != QDir::separator () ) {
        env += QDir::separator ();
    }

    QString driverPrefix = "mysql"; // Default on mysql
    if( mDatabaseDriver.toLower() == "qsqlite") {
        driverPrefix = "sqlite3";
    }

    // kDebug() << "XXXXXXXXXX: " << stdDirs.resourceDirs("data");

    if( env.isEmpty() ) {
        // Environment-Variable is empty, search in KDE paths
        QString fragment = QString("kraft/dbmigrate/%1/%2").arg(driverPrefix).arg(file );
        sqlFile = KStandardDirs::locate("data", fragment );
        kDebug() << "Searching for this fragment: " << fragment;
        // search in dbcreate as well.
        if ( sqlFile.isEmpty() ) {
            fragment = QString("kraft/dbinit/%1/%2").arg(driverPrefix).arg(file );
            kDebug() << "Also searching in " << fragment;
            sqlFile = KStandardDirs::locate( "data", fragment );
        }
    } else {
        // read from environment variable path
        QString envPath = QString( "%1/database/%2/%3").arg(env).arg(driverPrefix).arg(file);
        kDebug() << "Environment variable KRAFT_HOME set, searching for DB setup files in " << envPath;
        if( QFile::exists( envPath ) ) {
            sqlFile = envPath;
        } else if( QFile::exists( QString( "%1/database/%2/migration/%3").arg(env).arg(driverPrefix).arg(file ) ) ){
            sqlFile = QString( "%1/database/%2/migration/%3").arg(env).arg(driverPrefix).arg(file );
        }
    }

    SqlCommandList retList;

    if ( ! sqlFile.isEmpty() ) {
        kDebug() << "Opening migration file " << sqlFile << endl;

        QFile f( sqlFile );
        if ( !f.open( QIODevice::ReadOnly ) ) {
            kDebug() << "Could not open " << sqlFile << endl;
        } else {
            QTextStream ts( &f );
            ts.setCodec("UTF-8");

            QString allSql = ts.readAll(); //Not sure of this one!
            QStringList sqlList = allSql.split(";");

            QRegExp reg( "\\s*(#|--)\\s*message:? ?(.*)\\s*\\n" );
            QRegExp failreg( "\\s*(#|--)\\s*mayfail\\s*\\n" );
            reg.setMinimal( true );

            QListIterator<QString> it(sqlList);

            while( it.hasNext() ) {
                QString msg, command;

                QString sqlFragment = it.next().trimmed();

                int pos = reg.indexIn( sqlFragment.toLower(),  0 );
                if ( pos > -1 ) {
                    msg = reg.cap( 2 );
                    // kDebug() << "SQL-Commands-Parser: Msg: >" << msg << "<" << endl;
                }

                bool mayfail = false;
                pos = failreg.indexIn( sqlFragment.toLower(), 0 );
                if( pos > -1 ) {
                    mayfail = true;
                }
                bool clean = false;
                while( ! clean ) {
                    if(  sqlFragment.startsWith("#") || sqlFragment.startsWith("--") ) {
                        // remove the comment line.
                        int newLinePos = sqlFragment.indexOf('\n');
                        // kDebug() << "Found newline in <" << sqlFragment << ">:" << newLinePos;
                        if(newLinePos > 0) {
                            sqlFragment = sqlFragment.remove( 0, 1+sqlFragment.indexOf('\n') );
                        } else {
                            sqlFragment = QString();
                        }
                        // kDebug() << "Left over SQL Fragment:" << sqlFragment;
                    } else {
                        clean = true;
                    }
                }

                if( !sqlFragment.isEmpty() ) {

                    if( sqlFragment.startsWith( "CREATE TRIGGER", Qt::CaseInsensitive )) {
                        // Triggers contain a ; which scares the parser. In case of triggers we pull
                        // the next item in the list which should be the END; keyword.
                        command = sqlFragment + ";";
                        if( it.hasNext())
                            command += it.next();
                    } else {
                        // ordinary command, we take it as it is.
                        command = sqlFragment;
                    }
                    if( !( command.isEmpty() && msg.isEmpty() ) ) {
                        retList.append( SqlCommand( command, msg, mayfail ) );
                    }
                }
            }
        }
    } else {
        kDebug() << "ERR: Can not find sql file " << file;
    }

    return retList;
}
Example #18
0
int main(int argc, char **argv)
{
    bool bPromptForBackend    = false;
    bool bBypassAutoDiscovery = false;
    bool upgradeAllowed = false;

    bool cmdline_err;
    MythCommandLineParser cmdline(
        kCLPOverrideSettingsFile |
        kCLPOverrideSettings     |
        kCLPWindowed             |
        kCLPNoWindowed           |
        kCLPGetSettings          |
        kCLPQueryVersion         |
        kCLPVerbose              |
#ifdef USING_X11
        kCLPDisplay              |
#endif // USING_X11
        kCLPExtra                |
        kCLPGeometry);

    // Handle --help before QApplication is created, so that
    // we can print help even if X11 is absent.
    for (int argpos = 1; argpos < argc; ++argpos)
    {
        QString arg(argv[argpos]);
        if (arg == "-h" || arg == "--help" || arg == "--usage")
        {
            ShowUsage(cmdline);
            return GENERIC_EXIT_OK;
        }
    }

    for (int argpos = 1; argpos < argc; ++argpos)
    {
        if (cmdline.PreParse(argc, argv, argpos, cmdline_err))
        {
            if (cmdline_err)
                return GENERIC_EXIT_INVALID_CMDLINE;
            if (cmdline.WantsToExit())
                return GENERIC_EXIT_OK;
        }
    }

#ifdef Q_WS_MACX
    // Without this, we can't set focus to any of the CheckBoxSetting, and most
    // of the MythPushButton widgets, and they don't use the themed background.
    QApplication::setDesktopSettingsAware(false);
#endif
    QApplication a(argc, argv);

    QString pluginname;

    QFileInfo finfo(a.argv()[0]);

    QString binname = finfo.baseName();

    VERBOSE(VB_IMPORTANT, QString("%1 version: %2 [%3] www.mythtv.org")
                            .arg(binname)
                            .arg(MYTH_SOURCE_PATH)
                            .arg(MYTH_SOURCE_VERSION));

    bool ResetSettings = false;

    if (binname.toLower() != "mythfrontend")
        pluginname = binname;

    for (int argpos = 1; argpos < a.argc(); ++argpos)
    {
        if (!strcmp(a.argv()[argpos],"--prompt") ||
            !strcmp(a.argv()[argpos],"-p" ))
        {
            bPromptForBackend = true;
        }
        else if (!strcmp(a.argv()[argpos],"--disable-autodiscovery") ||
                 !strcmp(a.argv()[argpos],"-d" ))
        {
            bBypassAutoDiscovery = true;
        }
        else if (!strcmp(a.argv()[argpos],"-l") ||
            !strcmp(a.argv()[argpos],"--logfile"))
        {
            if (a.argc()-1 > argpos)
            {
                logfile = a.argv()[argpos+1];
                if (logfile.startsWith('-'))
                {
                    cerr << "Invalid or missing argument"
                            " to -l/--logfile option\n";
                    return GENERIC_EXIT_INVALID_CMDLINE;
                }
                else
                {
                    ++argpos;
                }
            }
            else
            {
                cerr << "Missing argument to -l/--logfile option\n";
                return GENERIC_EXIT_INVALID_CMDLINE;
            }
        }
        else if (cmdline.Parse(a.argc(), a.argv(), argpos, cmdline_err))
        {
            if (cmdline_err)
                return GENERIC_EXIT_INVALID_CMDLINE;
            if (cmdline.WantsToExit())
                return GENERIC_EXIT_OK;
        }
    }
    QMap<QString,QString> settingsOverride = cmdline.GetSettingsOverride();

    if (logfile.size())
    {
        if (log_rotate(1) < 0)
            cerr << "cannot open logfile; using stdout/stderr" << endl;
        else
        {
            VERBOSE(VB_IMPORTANT, QString("%1 version: %2 [%3] www.mythtv.org")
                                    .arg(binname)
                                    .arg(MYTH_SOURCE_PATH)
                                    .arg(MYTH_SOURCE_VERSION));

            signal(SIGHUP, &log_rotate_handler);
        }
    }

    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
        cerr << "Unable to ignore SIGPIPE\n";

    if (!cmdline.GetDisplay().isEmpty())
    {
        MythUIHelper::SetX11Display(cmdline.GetDisplay());
    }

    if (!cmdline.GetGeometry().isEmpty())
    {
        MythUIHelper::ParseGeometryOverride(cmdline.GetGeometry());
    }

    CleanupGuard callCleanup(cleanup);

    gContext = new MythContext(MYTH_BINARY_VERSION);
    g_pUPnp  = new MediaRenderer();
    if (!g_pUPnp->initialized())
    {
        delete g_pUPnp;
        g_pUPnp = NULL;
    }

    // Override settings as early as possible to cover bootstrapped screens
    // such as the language prompt
    settingsOverride = cmdline.GetSettingsOverride();
    if (settingsOverride.size())
    {
        QMap<QString, QString>::iterator it;
        for (it = settingsOverride.begin(); it != settingsOverride.end(); ++it)
        {
            VERBOSE(VB_IMPORTANT, QString("Setting '%1' being forced to '%2'")
                                          .arg(it.key()).arg(*it));
            gCoreContext->OverrideSettingForSession(it.key(), *it);
        }
    }

    if (!gContext->Init(true, g_pUPnp, bPromptForBackend, bBypassAutoDiscovery))
    {
        VERBOSE(VB_IMPORTANT, "Failed to init MythContext, exiting.");
        return GENERIC_EXIT_NO_MYTHCONTEXT;
    }

    if (!GetMythDB()->HaveSchema())
    {
        if (!InitializeMythSchema())
            return GENERIC_EXIT_DB_ERROR;
    }

    gCoreContext->SetAppName(binname);

    for(int argpos = 1; argpos < a.argc(); ++argpos)
    {
        if (!strcmp(a.argv()[argpos],"-l") ||
            !strcmp(a.argv()[argpos],"--logfile"))
        {
            // Arg processing for logfile already done (before MythContext)
            ++argpos;
        } else if (!strcmp(a.argv()[argpos],"-v") ||
                   !strcmp(a.argv()[argpos],"--verbose"))
        {
            // Arg processing for verbose already done (before MythContext)
            ++argpos;
        }
        else if (!strcmp(a.argv()[argpos],"-r") ||
                 !strcmp(a.argv()[argpos],"--reset"))
        {
            ResetSettings = true;
        }
        else if (!strcmp(a.argv()[argpos],"--prompt") ||
                 !strcmp(a.argv()[argpos],"-p" ))
        {
        }
        else if (!strcmp(a.argv()[argpos],"--disable-autodiscovery") ||
                 !strcmp(a.argv()[argpos],"-d" ))
        {
        }
        else if (!strcmp(a.argv()[argpos],"--upgrade-schema") ||
                 !strcmp(a.argv()[argpos],"-u" ))
        {
            upgradeAllowed = true;
        }
        else if (cmdline.Parse(a.argc(), a.argv(), argpos, cmdline_err))
        {
            if (cmdline_err)
            {
                return GENERIC_EXIT_INVALID_CMDLINE;
            }

            if (cmdline.WantsToExit())
            {
                return GENERIC_EXIT_OK;
            }
        }
        else if ((argpos + 1 == a.argc()) &&
                 (!QString(a.argv()[argpos]).startsWith('-')))
        {
            pluginname = a.argv()[argpos];
        }
        else
        {
            cerr << "Invalid argument: " << a.argv()[argpos] << endl;
            ShowUsage(cmdline);
            return GENERIC_EXIT_INVALID_CMDLINE;
        }
    }

    QStringList settingsQuery = cmdline.GetSettingsQuery();
    if (!settingsQuery.empty())
    {
        QStringList::const_iterator it = settingsQuery.begin();
        for (; it != settingsQuery.end(); ++it)
        {
            QString value = gCoreContext->GetSetting(*it);
            QString out = QString("\tSettings Value : %1 = %2")
                .arg(*it).arg(value);
            cout << out.toLocal8Bit().constData() << endl;
        }
        return GENERIC_EXIT_OK;
    }

    QString fileprefix = GetConfDir();

    QDir dir(fileprefix);
    if (!dir.exists())
        dir.mkdir(fileprefix);

    if (ResetSettings)
    {
        AppearanceSettings as;
        as.Save();

        gCoreContext->SaveSetting("Theme", DEFAULT_UI_THEME);
        gCoreContext->SaveSetting("Language", "");
        gCoreContext->SaveSetting("Country", "");

        return GENERIC_EXIT_OK;
    }

    setuid(getuid());

    VERBOSE(VB_IMPORTANT,
            QString("Enabled verbose msgs: %1").arg(verboseString));

    LCD::SetupLCD();
    if (LCD *lcd = LCD::Get())
        lcd->setupLEDs(RemoteGetRecordingMask);

    MythTranslation::load("mythfrontend");

    QString themename = gCoreContext->GetSetting("Theme", DEFAULT_UI_THEME);

    QString themedir = GetMythUI()->FindThemeDir(themename);
    if (themedir.isEmpty())
    {
        VERBOSE(VB_IMPORTANT, QString("Couldn't find theme '%1'")
                .arg(themename));
        return GENERIC_EXIT_NO_THEME;
    }

    GetMythUI()->LoadQtConfig();

    themename = gCoreContext->GetSetting("Theme", DEFAULT_UI_THEME);
    themedir = GetMythUI()->FindThemeDir(themename);
    if (themedir.isEmpty())
    {
        VERBOSE(VB_IMPORTANT, QString("Couldn't find theme '%1'")
                .arg(themename));
        return GENERIC_EXIT_NO_THEME;
    }

    MythMainWindow *mainWindow = GetMythMainWindow();
    mainWindow->Init();
    mainWindow->setWindowTitle(QObject::tr("MythTV Frontend"));

    if (!UpgradeTVDatabaseSchema(upgradeAllowed))
    {
        VERBOSE(VB_IMPORTANT,
                "Couldn't upgrade database to new schema, exiting.");
        return GENERIC_EXIT_DB_OUTOFDATE;
    }

    WriteDefaults();

    // Refresh Global/Main Menu keys after DB update in case there was no DB
    // when they were written originally
    mainWindow->ResetKeys();

    InitJumpPoints();

    // We must reload the translation after a language change and this
    // also means clearing the cached/loaded theme strings, so reload the
    // theme which also triggers a translation reload
    if (LanguageSelection::prompt())
        GetMythMainWindow()->JumpTo("Reload Theme");

    internal_media_init();

    CleanupMyOldInUsePrograms();

    pmanager = new MythPluginManager();
    gContext->SetPluginManager(pmanager);

    if (pluginname.size())
    {
        if (pmanager->run_plugin(pluginname) ||
            pmanager->run_plugin("myth" + pluginname))
        {
            qApp->exec();

            return GENERIC_EXIT_OK;
        }
        else
            return GENERIC_EXIT_INVALID_CMDLINE;
    }

    MediaMonitor *mon = MediaMonitor::GetMediaMonitor();
    if (mon)
    {
        mon->StartMonitoring();
        mainWindow->installEventFilter(mon);
    }

    NetworkControl *networkControl = NULL;
    if (gCoreContext->GetNumSetting("NetworkControlEnabled", 0))
    {
        int networkPort = gCoreContext->GetNumSetting("NetworkControlPort", 6545);
        networkControl = new NetworkControl();
        if (!networkControl->listen(QHostAddress::Any,networkPort))
            VERBOSE(VB_IMPORTANT,
                    QString("NetworkControl failed to bind to port %1.")
                    .arg(networkPort));
    }

    if (!RunMenu(themedir, themename) && !resetTheme(themedir, themename))
    {
        return GENERIC_EXIT_NO_THEME;
    }

    // Setup handler for USR1 signals to reload theme
    signal(SIGUSR1, &signal_USR1_handler);
    // Setup handler for USR2 signals to restart LIRC
    signal(SIGUSR2, &signal_USR2_handler);

    ThemeUpdateChecker *themeUpdateChecker = NULL;
    if (gCoreContext->GetNumSetting("ThemeUpdateNofications", 1))
        themeUpdateChecker = new ThemeUpdateChecker();

    MythSystemEventHandler *sysEventHandler = new MythSystemEventHandler();
    GetMythMainWindow()->RegisterSystemEventHandler(sysEventHandler);

    BackendConnectionManager bcm;

    PreviewGeneratorQueue::CreatePreviewGeneratorQueue(
        PreviewGenerator::kRemote, 50, 60);

    int ret = qApp->exec();

    PreviewGeneratorQueue::TeardownPreviewGeneratorQueue();

    if (themeUpdateChecker)
        delete themeUpdateChecker;

    delete sysEventHandler;

    pmanager->DestroyAllPlugins();

    if (mon)
        mon->deleteLater();

    delete networkControl;

    DestroyMythMainWindow();

    return ret;

}
Example #19
0
int typeOf(const QString& fileName)
{
    QStringList parts = fileName.split( "." );
    QString extension;
    if ( parts.size() > 1 )
        extension = parts.last();

    // Let's be trusting about extensions
    if ( extension.toLower() == "mp3" )
        return MP3;
    else if ( extension.toLower() == "ogg" )
        return OGG;
    else if ( extension.toLower() == "oga" )
        return FLAC;
    else if ( extension.toLower() == "flac" )
        return FLAC;
    else if ( extension.toLower() == "aac" )
        return AAC;
    else if ( extension.toLower() == "m4a" )
        return AAC;

    // So much for relying on extensions.  Let's try file magic instead.
    FILE *fp = NULL;
    unsigned char header[35];

    fp = fopen(QFile::encodeName(fileName), "rb");
    if ( !fp )
    {
        return UNKNOWN;
    }
    int fType = UNKNOWN;
    fread( header, 1, 35, fp );

    // Some formats can have ID3 tags (or not), so let's just
    // get them out of the way first before we check what we have.
    if ( memcmp( header, "ID3", 3) == 0 )
    {
        int tagsize = 0;
        /* high bit is not used */
        tagsize = (header[6] << 21) | (header[7] << 14) |
            (header[8] <<  7) | (header[9] <<  0);

        tagsize += 10;
        fseek( fp, tagsize, SEEK_SET );
        fread( header, 1, 35, fp );
    }

    if ( (header[0] == 0xFF) && ((header[1] & 0xFE) == 0xFA ) )
    {
        fType = MP3;
    }
    else if ( memcmp(header, "OggS", 4) == 0 )
    {
        if ( memcmp(&header[29], "vorbis", 6) == 0 )
        {
            // ogg vorbis (.ogg)
            fType = OGG;
        }
        else if ( memcmp(&header[29], "FLAC", 4) == 0 )
        {
            // ogg flac (.oga)
            fType = FLAC;
        }
    }
    else if ( memcmp(header, "fLaC", 4 ) == 0 )
    {
        // flac file
        fType = FLAC;
    }
    else if ( (header[0] == 0xFF) && ((header[1] & 0xF6) == 0xF0) )
    {
        // aac adts
        fType = AAC;
    }
    else if (memcmp(header, "ADIF", 4) == 0)
    {
        // aac adif
        fType = AAC;
    }
    else if ( memcmp( &header[4], "ftyp", 4 ) == 0 )
    {
        // mp4 header: aac
        fType = AAC;
    }

    fclose(fp);
    return fType;
}
Example #20
0
static void TVMenuCallback(void *data, QString &selection)
{
    (void)data;
    QString sel = selection.toLower();

    if (sel.left(9) == "settings ")
    {
        GetMythUI()->AddCurrentLocation("Setup");
        gCoreContext->ActivateSettingsCache(false);
    }

    if (sel == "tv_watch_live")
        startTVNormal();
    else if (sel == "tv_watch_live_epg")
        startTVInGuide();
    else if (sel.left(18) == "tv_watch_recording")
    {
        // use selection here because its case is untouched
        if ((selection.length() > 19) && (selection.mid(18, 1) == " "))
            startPlaybackWithGroup(selection.mid(19));
        else
            startPlayback();
    }
    else if (sel == "tv_schedule")
        startGuide();
    else if (sel == "tv_delete")
        startDelete();
    else if (sel == "tv_manualschedule")
        startManualSchedule();
    else if (sel == "tv_custom_record")
        startCustomEdit();
    else if (sel == "tv_fix_conflicts")
        startManaged();
    else if (sel == "tv_set_recpriorities")
        startProgramRecPriorities();
    else if (sel == "tv_manage_recording_rules")
        startManageRecordingRules();
    else if (sel == "tv_progfind")
        startFinder();
    else if (sel == "tv_search_title")
        startSearchTitle();
    else if (sel == "tv_search_keyword")
        startSearchKeyword();
    else if (sel == "tv_search_people")
        startSearchPeople();
    else if (sel == "tv_search_power")
        startSearchPower();
    else if (sel == "tv_search_stored")
        startSearchStored();
    else if (sel == "tv_search_channel")
        startSearchChannel();
    else if (sel == "tv_search_category")
        startSearchCategory();
    else if (sel == "tv_search_movie")
        startSearchMovie();
    else if (sel == "tv_search_new")
        startSearchNew();
    else if (sel == "tv_search_time")
        startSearchTime();
    else if (sel == "tv_previous")
        startPrevious();
    else if (sel == "settings appearance")
    {
        AppearanceSettings *settings = new AppearanceSettings();
        DialogCode res = settings->exec();
        delete settings;

        if (kDialogCodeRejected != res)
        {
            qApp->processEvents();
            GetMythMainWindow()->JumpTo("Reload Theme");
        }
    }
    else if (sel == "settings themechooser")
    {
        MythScreenStack *mainStack = GetMythMainWindow()->GetMainStack();
        ThemeChooser *tp = new ThemeChooser(mainStack);

        if (tp->Create())
            mainStack->AddScreen(tp);
        else
            delete tp;
    }
    else if (sel == "settings setupwizard")
    {
        MythScreenStack *mainStack = GetMythMainWindow()->GetMainStack();
        GeneralSetupWizard *sw = new GeneralSetupWizard(mainStack, "setupwizard");

        if (sw->Create())
            mainStack->AddScreen(sw);
        else
            delete sw;
    }
    else if (sel == "settings grabbers")
    {
        MythScreenStack *mainStack = GetMythMainWindow()->GetMainStack();
        GrabberSettings *gs = new GrabberSettings(mainStack, "grabbersettings");

        if (gs->Create())
            mainStack->AddScreen(gs);
        else
            delete gs;
    }
    else if (sel == "screensetupwizard")
    {
       startAppearWiz();
    }
    else if (sel == "setup_keys")
    {
        startKeysSetup();
    }
    else if (sel == "settings recording")
    {
        ProfileGroupEditor editor;
        editor.exec();
    }
    else if (sel == "settings playgroup")
    {
        PlayGroupEditor editor;
        editor.exec();
    }
    else if (sel == "settings general")
    {
        GeneralSettings settings;
        settings.exec();
    }
    else if (sel == "settings audiogeneral")
    {
        AudioGeneralSettings audiosettings;
        audiosettings.exec();
    }
    else if (sel == "settings maingeneral")
    {
        MainGeneralSettings mainsettings;
        mainsettings.exec();
        QStringList strlist( QString("REFRESH_BACKEND") );
        gCoreContext->SendReceiveStringList(strlist);
    }
    else if (sel == "settings audiogeneral")
    {
        AudioGeneralSettings audiosettings;
        audiosettings.exec();
    }
    else if (sel == "settings playback")
    {
        PlaybackSettings settings;
        settings.exec();
    }
    else if (sel == "settings osd")
    {
        OSDSettings settings;
        settings.exec();
    }
    else if (sel == "settings epg")
    {
        EPGSettings settings;
        settings.exec();
    }
    else if (sel == "settings channelgroups")
    {
        ChannelGroupEditor editor;
        editor.exec();
    }
    else if (sel == "settings generalrecpriorities")
    {
        GeneralRecPrioritiesSettings settings;
        settings.exec();
    }
    else if (sel == "settings channelrecpriorities")
    {
        startChannelRecPriorities();
    }
    else if (sel == "settings custompriority")
    {
        startCustomPriority();
    }
    else if (sel == "system_events")
    {
        MythScreenStack *mainStack = GetMythMainWindow()->GetMainStack();

        MythSystemEventEditor *msee = new MythSystemEventEditor(
                                    mainStack, "System Event Editor");

        if (msee->Create())
            mainStack->AddScreen(msee);
        else
            delete msee;
    }
    else if (sel == "tv_status")
        showStatus();
    else if (sel == "exiting_app")
        handleExit();
    else
        VERBOSE(VB_IMPORTANT, "Unknown menu action: " + selection);

    if (sel.left(9) == "settings ")
    {
        GetMythUI()->RemoveCurrentLocation();

        gCoreContext->ActivateSettingsCache(true);
        RemoteSendMessage("CLEAR_SETTINGS_CACHE");

        if (sel == "settings general" ||
            sel == "settings generalrecpriorities")
            ScheduledRecording::signalChange(0);
    }
}
QString MainWindow::operationToNumber(const QString &_operation)
{
    if(_operation.toLower() == "add")
    {
        return "0x0";
    }
    else if(_operation.toLower() == "sub")
    {
        return "0x1";
    }
    else if(_operation.toLower() == "mul")
    {
        return "0x2";
    }
    else if(_operation.toLower() == "div")
    {
        return "0x3";
    }
    else if(_operation.toLower() == "load_fixed")
    {
        return "0x4";
    }
    else if(_operation.toLower() == "store_fixed")
    {
        return "0x5";
    }
    else if(_operation.toLower() == "add_register_first_half")
    {
        return "0x6";
    }
    else if(_operation.toLower() == "add_register_second_half")
    {
        return "0x7";
    }
    else if(_operation.toLower() == "push")
    {
        return "0x8";
    }
    else if(_operation.toLower() == "pop")
    {
        return "0x9";
    }
    else if(_operation.toLower() == "jump_fixed")
    {
        return "0xA";
    }
    else if(_operation.toLower() == "jump_register")
    {
        return "0xB";
    }
    else if(_operation.toLower() == "branch_on_equal")
    {
        return "0xC";
    }
    else if(_operation.toLower() == "set_stack_pointer")
    {
        return "0xD";
    }
    else if(_operation.toLower() == "load_register")
    {
        return "0xE";
    }
    else if(_operation.toLower() == "store_register")
    {
        return "0xF";
    }

    else
    {
        return ("error");
    }
}
Example #22
0
void QHexScrollArea::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e)

    QPainter painter;
    painter.begin(viewport());
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::TextAntialiasing, true);

    painter.fillRect(0,0,width(), height(), QBrush(0xD7D7AF));

    QFont font = this->font();
    QFontMetrics fm = this->fontMetrics();

    painter.setFont(font);

    int ssw = fm.width(" ");                                                // width of space symbol
    int zsw = fm.width("0");                                                // width of zero symbol

    int div = maxDataCount / bytesPerRow;                                   // data size divide to 16. number of maximum rows
    int mod = maxDataCount % bytesPerRow;                                   // data size module to 16. number of bytes at last row

    maxRowsCount = div;
    if (mod > 0) maxRowsCount += 1;

    int rowNumberW = 2 * ssw + fm.width(QString::number(maxRowsCount));     // width of row number column
    int rowNumberH = viewport()->height();                                  // height of row number column

    // painting lines number column background
    painter.fillRect(0, 0, rowNumberW, rowNumberH, QBrush(0xD4D0C8));
    painter.fillRect(getRowNumberWidth(), 0, getByteNumberWidth(), height(), QBrush(QColor(0xAFAF87)));
    painter.fillRect(getRowNumberWidth(), 0, width(), fm.height()+4, QBrush(QColor(0xAFAF87)));

    // number of rows visible on viewport
    int viewportRow = (int) ceil( (double)(viewport()->height() - (double)fm.height() ) / (double)fm.height() );

    // updating verticalScrollBar settings
    verticalScrollBar()->setMinimum(0);

    if (maxRowsCount > viewportRow)
    {
        verticalScrollBar()->setMaximum( (maxRowsCount - viewportRow) + 1);
    }
    else
    {
        verticalScrollBar()->setMaximum(0);
    }

    verticalScrollBar()->setPageStep(10);
    verticalScrollBar()->setSingleStep(1);

    int vsbValue = verticalScrollBar()->value();
    int hsbValue = horizontalScrollBar()->value();
    Q_UNUSED(hsbValue)

    font.setBold(false);
    painter.setFont(font);

    // painting header
    painter.setPen(0x5F5F00);
    int x = rowNumberW+zsw*8 + ssw*2;
    int y = fm.height();
    painter.drawText(x, y, " 00 01 02 03  04 05 06 07   08 09 0A 0B  0C 0D 0E 0F                     ");

    qint64 minLine = vsbValue;                                          // minimum visible line number
    qint64 maxLine = vsbValue + viewportRow;                            // maximum visible line number

    if (maxRowsCount < maxLine)
        maxLine = maxRowsCount;

    qint64 minData = minLine * bytesPerRow;                             // minimum visible byte
    qint64 maxData = maxLine * bytesPerRow;                             // maximum visible data

    if ( maxData > maxDataCount)
    {
        maxData = maxDataCount;
    }

    QByteArray buffer;
    emit fillBuffer(buffer, minData, maxData);

    for (qint64 i = minLine; i < maxLine; i++)
    {
        quint32 x = zsw;
        quint32 y = (i-vsbValue+1)*fm.height() + fm.height();

        QByteArray data = buffer.mid( (int)( i - minLine ) * 16, 16);

        QString line = QString::number(i);
//       int length = 9-line.length();
        int length = QString::number(maxRowsCount).length() - QString::number(i).length();
        for (int j=0; j<length; j++)
            line.prepend(" ");
        if (mShowUpperLine) line = line.toUpper();

        /* bytes number and filling 0 to start*/
        QString bytes = QString::number(i*bytesPerRow,16);
        length = 8-bytes.length();
        for (int j=0; j<length; j++)
            bytes.prepend("0");
        if (mShowUpperData)
            bytes = bytes.toUpper();

        /* data hex string */
        QString h = QString("%1 %2 %3 %4  %5 %6 %7 %8   %9 %10 %11 %12  %13 %14 %15 %16")
                .arg(QString(data.mid(0x00, 1).toHex()))
                .arg(QString(data.mid(0x01, 1).toHex()))
                .arg(QString(data.mid(0x02, 1).toHex()))
                .arg(QString(data.mid(0x03, 1).toHex()))
                .arg(QString(data.mid(0x04, 1).toHex()))
                .arg(QString(data.mid(0x05, 1).toHex()))
                .arg(QString(data.mid(0x06, 1).toHex()))
                .arg(QString(data.mid(0x07, 1).toHex()))
                .arg(QString(data.mid(0x08, 1).toHex()))
                .arg(QString(data.mid(0x09, 1).toHex()))
                .arg(QString(data.mid(0x0A, 1).toHex()))
                .arg(QString(data.mid(0x0B, 1).toHex()))
                .arg(QString(data.mid(0x0C, 1).toHex()))
                .arg(QString(data.mid(0x0D, 1).toHex()))
                .arg(QString(data.mid(0x0E, 1).toHex()))
                .arg(QString(data.mid(0x0F, 1).toHex()));
         h = h.toLower();

        /* data char string */
        QString c;
        for (int j=0; j < data.size(); j++)
        {
            c.append(QChar(data.at(j)).isPrint() ? QChar(data.at(j)) : '.');
        }

        /* drawing row number */
        font.setBold(true);
        painter.setFont(font);
        painter.setPen(0x5F5F00);
        painter.drawText(x, y, line);

        /* drawing data sequence number */
        x = rowNumberW + zsw;
        font.setBold(false);
        painter.setFont(font);
        painter.setPen(0x5F5F00);
        painter.drawText(x, y, bytes);

        /* drawing data */
        x = x + zsw*8 + ssw*2;
        painter.setPen(0x5F5F00);
        painter.drawText(x, y, h);
        x += zsw*32 + ssw*22;
        painter.drawText(x, y, c);
    }

    // paint selection

    painter.setRenderHint(QPainter::Antialiasing, false);

    if (selectedByte != -1)
    {
        quint32 cn = selectedByte % bytesPerRow;                           // column number
        quint32 rn = selectedByte / bytesPerRow;                           // row number

        quint32 sel_x = rowNumberW + zsw * 8 + ssw * 3;
        sel_x -=  ssw / 2;

        if (cn >= 0 && cn <= 3)
            sel_x += cn * zsw * 3;
        if (cn >= 4 && cn <= 7)
            sel_x += cn * zsw * 3 + zsw * 1;
        if (cn >= 8 && cn <= 11)
            sel_x += cn * zsw * 3 + zsw * 3;
        if (cn >= 12 && cn <= 15)
            sel_x += cn * zsw * 3 + zsw * 4;

        quint32 rw = ssw * 3 - 2;                                           // selected rectange width

        quint32 sel_y = 0;
        if (minLine <= rn && rn <= maxLine)
        {
            rn -= minLine;
            sel_y = fm.height() * (rn+1);
        }
        else
        {
            sel_y = -100;
        }

        QBrush brush(QColor(0x00, 0xff, 0xff, 100));
        painter.fillRect(sel_x, sel_y+4, rw, 18, brush);           // painting selected byte
        painter.drawRect(sel_x, sel_y+4, rw, 18);                       // painting selected byte
    }

//    paintSelections(painter);

//    paintSelection(painter);

//    paintBlinking(painter);

    painter.end();
}
/**
 * Parse a single <TextStyle> element
 *
 * \return an ITextStyle representing the <TextStyle> element
 */
ITextStyle* StyleParser::parseTextStyleElement( QXmlStreamReader* xml ) {
    TextStyle* ts = new TextStyle();
    ts->setName( xml->attributes().value( "name" ).toString() );
    bool hAlign = false;
    bool vAlign = false;

    while ( !( xml->isEndElement() && ( xml->name() == "TextStyle" ) ) ) {
        xml->readNext();

        if ( xml->isStartElement() ) {
            if ( xml->name() == "Font" ) {
                ts->setFontName( xml->readElementText() );
            }

            if ( xml->name() == "Size" ) {
                ts->setPointSize( xml->readElementText().toInt() );
            }

            if ( xml->name() == "Bold" ) {
                ts->setBold( true );
            }

            if ( xml->name() == "Italic" ) {
                ts->setItalic( true );
            }

            if ( xml->name() == "Color" ) {
                int r = xml->attributes().value( "r" ).toString().toInt();
                int g = xml->attributes().value( "g" ).toString().toInt();
                int b = xml->attributes().value( "b" ).toString().toInt();
                int a = xml->attributes().value( "a" ).toString().toInt();
                ts->setForeColor( QColor( r, g, b, a ) );
                ts->setRgbaColorString( QString( "rgba(%1,%2,%3,%4)" ).arg( r )
                                        .arg( g )
                                        .arg( b )
                                        .arg( a ) );
            }

            if ( xml->name() == "HAlign" ) {
                QString a = xml->readElementText();
                hAlign = true;

                if ( a.toLower() == "left" )
                    ts->addAlignment( Qt::AlignLeft );
                else if ( a.toLower() == "right" )
                    ts->addAlignment( Qt::AlignRight );
                else if ( a.toLower() == "center" )
                    ts->addAlignment( Qt::AlignHCenter );
                else
                    hAlign = false;
            }

            if ( xml->name() == "VAlign" ) {
                QString a = xml->readElementText();
                vAlign = true;

                if ( a.toLower() == "top" )
                    ts->addAlignment( Qt::AlignTop );
                else if ( a.toLower() == "bottom" )
                    ts->addAlignment( Qt::AlignBottom );
                else if ( a.toLower() == "center" )
                    ts->addAlignment( Qt::AlignVCenter );
                else
                    vAlign = false;
            }
        }
    }

    //Set some default values
    if ( !hAlign )
        ts->addAlignment( Qt::AlignLeft );

    if ( !vAlign )
        ts->addAlignment( Qt::AlignTop );

    return ts;
}
Example #24
0
void
Grids::processCommand(int idx, QString cmd)
{
  bool ok;
  QString origCmd = cmd;
  cmd = cmd.toLower();
  QStringList list = cmd.split(" ", QString::SkipEmptyParts);
  
  if (list[0] == "normalize" ||
      list[0] == "normalise")
    {
      m_grids[idx]->normalize();
    }
  else if (list[0] == "insertrow")
    {
      if (list.count() == 2)
	{
	  int r = list[1].toInt();
	  m_grids[idx]->insertRow(r);
	}
      else
	QMessageBox::information(0, "Error", "Row number not specified");
    }	   
  else if (list[0] == "removerow")
    {
      if (list.count() == 2)
	{
	  int r = list[1].toInt();
	  m_grids[idx]->removeRow(r);
	}
      else
	QMessageBox::information(0, "Error", "Row number not specified");
    }	   
  else if (list[0] == "insertcol")
    {
      if (list.count() == 2)
	{
	  int r = list[1].toInt();
	  m_grids[idx]->insertCol(r);
	}
      else
	QMessageBox::information(0, "Error", "Row number not specified");
    }	   
  else if (list[0] == "removecol")
    {
      if (list.count() == 2)
	{
	  int r = list[1].toInt();
	  m_grids[idx]->removeCol(r);
	}
      else
	QMessageBox::information(0, "Error", "Row number not specified");
    }	   
  else if (list[0] == "sticktosurface")
    {
      int radius = 1;
      if (list.size() > 1)
	{
	  radius = list[1].toInt(&ok);
	  radius = qMin(radius, 200);
	}
      QList< QPair<Vec, Vec> > gridPNs = m_grids[idx]->getPointsAndNormals();
      emit gridStickToSurface(idx, radius, gridPNs);
    }
  else if (list[0] == "save")
    {
      QString flnm;
      flnm = QFileDialog::getSaveFileName(0,
					  "Save grid points to text file",
					  Global::previousDirectory(),
					  "Files (*.*)");
      
      if (flnm.isEmpty())
	return;
      
      QList<Vec> pts = m_grids[idx]->points();
      
      QFile fgrid(flnm);
      fgrid.open(QFile::WriteOnly | QFile::Text);
      QTextStream fd(&fgrid);
      fd << m_grids[idx]->columns()
	 << "   "
	 <<  m_grids[idx]->rows()
	 << "\n";
      for(int pi=0; pi < pts.count(); pi++)
	fd << pts[pi].x << " " << pts[pi].y << " " << pts[pi].z << "\n";
      
      fd.flush();
    }
  else
    QMessageBox::information(0, "Grid Command Error",
			     QString("Cannot understand the command : ") +
			     cmd);
  
}
Example #25
0
void Menu::selectCharacterEncoding(QAction *action)
{
	MainWindow *mainWindow = MainWindow::findMainWindow(parent());

	if (!mainWindow)
	{
		return;
	}

	QString encoding;

	if (action && action->data().toInt() > 0)
	{
		QTextCodec *codec = QTextCodec::codecForMib(action->data().toInt());

		if (codec)
		{
			encoding = codec->name();
		}
	}

	mainWindow->getWindowsManager()->setOption(QLatin1String("Content/DefaultCharacterEncoding"), encoding.toLower());
}
Example #26
0
static void createGtkrc( bool exportColors, const QPalette& cg, bool exportGtkTheme, const QString& gtkTheme, int version )
{
    // lukas: why does it create in ~/.kde/share/config ???
    // pfeiffer: so that we don't overwrite the user's gtkrc.
    // it is found via the GTK_RC_FILES environment variable.
    KSaveFile saveFile( KStandardDirs::locateLocal( "config", 2==version?"gtkrc-2.0":"gtkrc" ) );
    if ( !saveFile.open() )
        return;

    QTextStream t ( &saveFile );
    t.setCodec( QTextCodec::codecForLocale () );

    t << i18n(
            "# created by KDE, %1\n"
            "#\n"
            "# If you do not want KDE to override your GTK settings, select\n"
            "# Appearance -> Colors in the System Settings and disable the checkbox\n"
            "# \"Apply colors to non-KDE4 applications\"\n"
            "#\n"
            "#\n", QDateTime::currentDateTime().toString());

    if ( 2==version ) {  // we should maybe check for MacOS settings here
        t << endl;
        t << "gtk-alternative-button-order = 1" << endl;
        t << endl;
    }

    if (exportGtkTheme)
    {
        QString gtkStyle;
        if (gtkTheme.toLower() == "oxygen")
            gtkStyle = QString("oxygen-gtk");
        else
            gtkStyle = gtkTheme;

        bool exist_gtkrc = false;
        QByteArray gtkrc = getenv(gtkEnvVar(version));
        QStringList listGtkrc = QFile::decodeName(gtkrc).split(":");
        if (listGtkrc.contains(saveFile.fileName()))
            listGtkrc.removeAll(saveFile.fileName());
        listGtkrc.append(QDir::homePath() + userGtkrc(version));
        listGtkrc.append(QDir::homePath() + "/.gtkrc-2.0-kde");
        listGtkrc.append(QDir::homePath() + "/.gtkrc-2.0-kde4");
        listGtkrc.removeAll("");
        listGtkrc.removeDuplicates();
        for (int i = 0; i < listGtkrc.size(); ++i)
        {
            if ((exist_gtkrc = QFile::exists(listGtkrc.at(i))))
                break;
        }

        if (!exist_gtkrc)
        {
            QString gtk2ThemeFilename;
            gtk2ThemeFilename = QString("%1/.themes/%2/gtk-2.0/gtkrc").arg(QDir::homePath()).arg(gtkStyle);
            if (!QFile::exists(gtk2ThemeFilename)) {
                QStringList gtk2ThemePath;
                gtk2ThemeFilename.clear();
                QByteArray xdgDataDirs = getenv("XDG_DATA_DIRS");
                gtk2ThemePath.append(QDir::homePath() + "/.local");
                gtk2ThemePath.append(QFile::decodeName(xdgDataDirs).split(":"));
                gtk2ThemePath.removeDuplicates();
                for (int i = 0; i < gtk2ThemePath.size(); ++i)
                {
                    gtk2ThemeFilename = QString("%1/themes/%2/gtk-2.0/gtkrc").arg(gtk2ThemePath.at(i)).arg(gtkStyle);
                    if (QFile::exists(gtk2ThemeFilename))
                        break;
                    else
                        gtk2ThemeFilename.clear();
                }
            }

            if (!gtk2ThemeFilename.isEmpty())
            {
                t << "include \"" << gtk2ThemeFilename << "\"" << endl;
                t << endl;
                t << "gtk-theme-name=\"" << gtkStyle << "\"" << endl;
                t << endl;
                if (gtkStyle == "oxygen-gtk")
                    exportColors = false;
            }
        }

    }

    if (exportColors)
    {
        t << "style \"default\"" << endl;
        t << "{" << endl;
        t << "  bg[NORMAL] = " << color( cg.color( QPalette::Active, QPalette::Background ) ) << endl;
        t << "  bg[SELECTED] = " << color( cg.color(QPalette::Active, QPalette::Highlight) ) << endl;
        t << "  bg[INSENSITIVE] = " << color( cg.color( QPalette::Active, QPalette::Background ) ) << endl;
        t << "  bg[ACTIVE] = " << color( cg.color( QPalette::Active, QPalette::Mid ) ) << endl;
        t << "  bg[PRELIGHT] = " << color( cg.color( QPalette::Active, QPalette::Background ) ) << endl;
        t << endl;
        t << "  base[NORMAL] = " << color( cg.color( QPalette::Active, QPalette::Base ) ) << endl;
        t << "  base[SELECTED] = " << color( cg.color(QPalette::Active, QPalette::Highlight) ) << endl;
        t << "  base[INSENSITIVE] = " << color( cg.color( QPalette::Active, QPalette::Background ) ) << endl;
        t << "  base[ACTIVE] = " << color( cg.color(QPalette::Active, QPalette::Highlight) ) << endl;
        t << "  base[PRELIGHT] = " << color( cg.color(QPalette::Active, QPalette::Highlight) ) << endl;
        t << endl;
        t << "  text[NORMAL] = " << color( cg.color(QPalette::Active, QPalette::Text) ) << endl;
        t << "  text[SELECTED] = " << color( cg.color(QPalette::Active, QPalette::HighlightedText) ) << endl;
        t << "  text[INSENSITIVE] = " << color( cg.color( QPalette::Active, QPalette::Mid ) ) << endl;
        t << "  text[ACTIVE] = " << color( cg.color(QPalette::Active, QPalette::HighlightedText) ) << endl;
        t << "  text[PRELIGHT] = " << color( cg.color(QPalette::Active, QPalette::HighlightedText) ) << endl;
        t << endl;
        t << "  fg[NORMAL] = " << color ( cg.color( QPalette::Active, QPalette::Foreground ) ) << endl;
        t << "  fg[SELECTED] = " << color( cg.color(QPalette::Active, QPalette::HighlightedText) ) << endl;
        t << "  fg[INSENSITIVE] = " << color( cg.color( QPalette::Active, QPalette::Mid ) ) << endl;
        t << "  fg[ACTIVE] = " << color( cg.color( QPalette::Active, QPalette::Foreground ) ) << endl;
        t << "  fg[PRELIGHT] = " << color( cg.color( QPalette::Active, QPalette::Foreground ) ) << endl;
        t << "}" << endl;
        t << endl;
        t << "class \"*\" style \"default\"" << endl;
        t << endl;

        // tooltips don't have the standard background color
        t << "style \"ToolTip\"" << endl;
        t << "{" << endl;
        QPalette group = QToolTip::palette();
        t << "  bg[NORMAL] = " << color( group.color( QPalette::Active, QPalette::Background ) ) << endl;
        t << "  base[NORMAL] = " << color( group.color( QPalette::Active, QPalette::Base ) ) << endl;
        t << "  text[NORMAL] = " << color( group.color( QPalette::Active, QPalette::Text ) ) << endl;
        t << "  fg[NORMAL] = " << color( group.color( QPalette::Active, QPalette::Foreground ) ) << endl;
        t << "}" << endl;
        t << endl;
        t << "widget \"gtk-tooltip\" style \"ToolTip\"" << endl;
        t << "widget \"gtk-tooltips\" style \"ToolTip\"" << endl;
        t << endl;


        // highlight the current (mouse-hovered) menu-item
        // not every button, checkbox, etc.
        t << "style \"MenuItem\"" << endl;
        t << "{" << endl;
        t << "  bg[PRELIGHT] = " << color( cg.color(QPalette::Highlight) ) << endl;
        t << "}" << endl;
        t << endl;
        t << "class \"*MenuItem\" style \"MenuItem\"" << endl;
        t << endl;
    }

}
Example #27
0
void DTVChannel::SetTuningMode(const QString &tuning_mode)
{
    QMutexLocker locker(&dtvinfo_lock);
    tuningMode = tuning_mode.toLower();
    tuningMode.detach();
}
Example #28
0
bool MyMoneyXmlContentHandler::startElement(const QString& /* namespaceURI */, const QString& /* localName */, const QString& qName, const QXmlAttributes & atts)
{
  if (m_level == 0) {
    QString s = qName.toLower();
    if (s == "transaction"
        || s == "account"
        || s == "price"
        || s == "payee"
        || s == "tag"
        || s == "currency"
        || s == "security"
        || s == "keyvaluepairs"
        || s == "institution"
        || s == "report"
        || s == "budget"
        || s == "fileinfo"
        || s == "user"
        || s == "scheduled_tx"
        || s == "onlinejob") {
      m_baseNode = m_doc.createElement(qName);
      for (int i = 0; i < atts.count(); ++i) {
        m_baseNode.setAttribute(atts.qName(i), atts.value(i));
      }
      m_currNode = m_baseNode;
      m_level = 1;

    } else if (s == "transactions") {
      qDebug("reading transactions");
      if (atts.count()) {
        int count = atts.value(QLatin1String("count")).toInt();
        m_reader->signalProgress(0, count, i18n("Loading transactions..."));
        m_elementCount = 0;
      }
    } else if (s == "accounts") {
      qDebug("reading accounts");
      if (atts.count()) {
        int count = atts.value(QLatin1String("count")).toInt();
        m_reader->signalProgress(0, count, i18n("Loading accounts..."));
        m_elementCount = 0;
      }
    } else if (s == "securities") {
      qDebug("reading securities");
      if (atts.count()) {
        int count = atts.value(QLatin1String("count")).toInt();
        m_reader->signalProgress(0, count, i18n("Loading securities..."));
        m_elementCount = 0;
      }
    } else if (s == "currencies") {
      qDebug("reading currencies");
      if (atts.count()) {
        int count = atts.value(QLatin1String("count")).toInt();
        m_reader->signalProgress(0, count, i18n("Loading currencies..."));
        m_elementCount = 0;
      }
    } else if (s == "reports") {
      qDebug("reading reports");
      if (atts.count()) {
        int count = atts.value(QLatin1String("count")).toInt();
        m_reader->signalProgress(0, count, i18n("Loading reports..."));
        m_elementCount = 0;
      }
    } else if (s == "prices") {
      qDebug("reading prices");
      if (atts.count()) {
        int count = atts.value(QLatin1String("count")).toInt();
        m_reader->signalProgress(0, count, i18n("Loading prices..."));
        m_elementCount = 0;
      }
    } else if (s == "pricepair") {
      if (atts.count()) {
        m_reader->d->m_fromSecurity = atts.value(QLatin1String("from"));
        m_reader->d->m_toSecurity = atts.value(QLatin1String("to"));
      }
    }

  } else {
    m_level++;
    QDomElement node = m_doc.createElement(qName);
    for (int i = 0; i < atts.count(); ++i) {
      node.setAttribute(atts.qName(i), atts.value(i));
    }
    m_currNode.appendChild(node);
    m_currNode = node;
  }
  return true;
}
Example #29
0
bool XMLParseBase::parseBool(const QString &text)
{
    QString s = text.toLower();
    return (s == "yes" || s == "true" || s.toInt());
}
void QgsManageConnectionsDialog::loadOWSConnections( const QDomDocument &doc, const QStringList &items, const QString &service )
{
  QDomElement root = doc.documentElement();
  if ( root.tagName() != "qgs" + service.toUpper() + "Connections" )
  {
    QMessageBox::information( this, tr( "Loading connections" ),
                              tr( "The file is not an %1 connections exchange file." ).arg( service ) );
    return;
  }

  QString connectionName;
  QSettings settings;
  settings.beginGroup( "/Qgis/connections-" + service.toLower() );
  QStringList keys = settings.childGroups();
  settings.endGroup();
  QDomElement child = root.firstChildElement();
  bool prompt = true;
  bool overwrite = true;

  while ( !child.isNull() )
  {
    connectionName = child.attribute( "name" );
    if ( !items.contains( connectionName ) )
    {
      child = child.nextSiblingElement();
      continue;
    }

    // check for duplicates
    if ( keys.contains( connectionName ) && prompt )
    {
      int res = QMessageBox::warning( this,
                                      tr( "Loading connections" ),
                                      tr( "Connection with name '%1' already exists. Overwrite?" )
                                      .arg( connectionName ),
                                      QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::NoToAll | QMessageBox::Cancel );

      switch ( res )
      {
        case QMessageBox::Cancel:
          return;
        case QMessageBox::No:
          child = child.nextSiblingElement();
          continue;
        case QMessageBox::Yes:
          overwrite = true;
          break;
        case QMessageBox::YesToAll:
          prompt = false;
          overwrite = true;
          break;
        case QMessageBox::NoToAll:
          prompt = false;
          overwrite = false;
          break;
      }
    }

    if ( keys.contains( connectionName ) && !overwrite )
    {
      child = child.nextSiblingElement();
      continue;
    }

    // no dups detected or overwrite is allowed
    settings.beginGroup( "/Qgis/connections-" + service.toLower() );
    settings.setValue( QString( "/" + connectionName + "/url" ) , child.attribute( "url" ) );
    settings.setValue( QString( "/" + connectionName + "/ignoreGetMapURI" ), child.attribute( "ignoreGetMapURI" ) == "true" );
    settings.setValue( QString( "/" + connectionName + "/ignoreGetFeatureInfoURI" ), child.attribute( "ignoreGetFeatureInfoURI" ) == "true" );
    settings.setValue( QString( "/" + connectionName + "/ignoreAxisOrientation" ), child.attribute( "ignoreAxisOrientation" ) == "true" );
    settings.setValue( QString( "/" + connectionName + "/invertAxisOrientation" ), child.attribute( "invertAxisOrientation" ) == "true" );
    settings.setValue( QString( "/" + connectionName + "/referer" ), child.attribute( "referer" ) );
    settings.setValue( QString( "/" + connectionName + "/smoothPixmapTransform" ), child.attribute( "smoothPixmapTransform" ) == "true" );
    settings.endGroup();

    if ( !child.attribute( "username" ).isEmpty() )
    {
      settings.beginGroup( "/Qgis/" + service.toUpper() + "/" + connectionName );
      settings.setValue( "/username", child.attribute( "username" ) );
      settings.setValue( "/password", child.attribute( "password" ) );
      settings.endGroup();
    }
    child = child.nextSiblingElement();
  }
}