예제 #1
0
void RunningScriptsWidget::setRunningScripts(const QStringList& list) {
    setUpdatesEnabled(false);
    QLayoutItem* widget;
    while ((widget = ui->scrollAreaWidgetContents->layout()->takeAt(0)) != NULL) {
        delete widget->widget();
        delete widget;
    }
    QHash<QString, int> hash;
    const int CLOSE_ICON_HEIGHT = 12;
    for (int i = 0; i < list.size(); i++) {
        if (!hash.contains(list.at(i))) {
            hash.insert(list.at(i), 1);
        }
        QWidget* row = new QWidget(ui->scrollAreaWidgetContents);
        row->setLayout(new QHBoxLayout(row));

        QUrl url = QUrl(list.at(i));
        QLabel* name = new QLabel(url.fileName(), row);
        if (hash.find(list.at(i)).value() != 1) {
            name->setText(name->text() + "(" + QString::number(hash.find(list.at(i)).value()) + ")");
        }
        ++hash[list.at(i)];
        QPushButton* closeButton = new QPushButton(row);
        closeButton->setFlat(true);
        closeButton->setIcon(
            QIcon(QPixmap(Application::resourcesPath() + "images/kill-script.svg").scaledToHeight(CLOSE_ICON_HEIGHT)));
        closeButton->setSizePolicy(QSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred));
        closeButton->setStyleSheet("border: 0;");
        closeButton->setCursor(Qt::PointingHandCursor);

        connect(closeButton, SIGNAL(clicked()), &_signalMapper, SLOT(map()));
        _signalMapper.setMapping(closeButton, url.toString());

        row->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));

        row->layout()->setContentsMargins(4, 4, 4, 4);
        row->layout()->setSpacing(0);

        row->layout()->addWidget(name);
        row->layout()->addWidget(closeButton);

        row->setToolTip(url.toString());

        QFrame* line = new QFrame(row);
        line->setFrameShape(QFrame::HLine);
        line->setStyleSheet("color: #E1E1E1; margin-left: 6px; margin-right: 6px;");

        ui->scrollAreaWidgetContents->layout()->addWidget(row);
        ui->scrollAreaWidgetContents->layout()->addWidget(line);
    }


    ui->noRunningScriptsLabel->setVisible(list.isEmpty());
    ui->reloadAllButton->setVisible(!list.isEmpty());
    ui->stopAllButton->setVisible(!list.isEmpty());

    ui->scrollAreaWidgetContents->updateGeometry();
    setUpdatesEnabled(true);
    Application::processEvents();
    repaint();
}
예제 #2
0
void QgsVectorLayerRenderer::drawRendererLevels( QgsFeatureIterator &fit )
{
  QHash< QgsSymbol *, QList<QgsFeature> > features; // key = symbol, value = array of features

  QgsSingleSymbolRenderer *selRenderer = nullptr;
  if ( !mSelectedFeatureIds.isEmpty() )
  {
    selRenderer = new QgsSingleSymbolRenderer( QgsSymbol::defaultSymbol( mGeometryType ) ) ;
    selRenderer->symbol()->setColor( mContext.selectionColor() );
    selRenderer->setVertexMarkerAppearance( mVertexMarkerStyle, mVertexMarkerSize );
    selRenderer->startRender( mContext, mFields );
  }

  QgsExpressionContextScope *symbolScope = QgsExpressionContextUtils::updateSymbolScope( nullptr, new QgsExpressionContextScope() );
  mContext.expressionContext().appendScope( symbolScope );

  // 1. fetch features
  QgsFeature fet;
  while ( fit.nextFeature( fet ) )
  {
    if ( mContext.renderingStopped() )
    {
      qDebug( "rendering stop!" );
      stopRenderer( selRenderer );
      delete mContext.expressionContext().popScope();
      return;
    }

    if ( !fet.hasGeometry() )
      continue; // skip features without geometry

    mContext.expressionContext().setFeature( fet );
    QgsSymbol *sym = mRenderer->symbolForFeature( fet, mContext );
    if ( !sym )
    {
      continue;
    }

    if ( !features.contains( sym ) )
    {
      features.insert( sym, QList<QgsFeature>() );
    }
    features[sym].append( fet );

    // new labeling engine
    if ( mContext.labelingEngine() )
    {
      QgsGeometry obstacleGeometry;
      QgsSymbolList symbols = mRenderer->originalSymbolsForFeature( fet, mContext );

      if ( !symbols.isEmpty() && fet.geometry().type() == QgsWkbTypes::PointGeometry )
      {
        obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, mContext, symbols );
      }

      if ( !symbols.isEmpty() )
      {
        QgsExpressionContextUtils::updateSymbolScope( symbols.at( 0 ), symbolScope );
      }

      if ( mLabelProvider )
      {
        mLabelProvider->registerFeature( fet, mContext, obstacleGeometry );
      }
      if ( mDiagramProvider )
      {
        mDiagramProvider->registerFeature( fet, mContext, obstacleGeometry );
      }
    }
  }

  delete mContext.expressionContext().popScope();

  // find out the order
  QgsSymbolLevelOrder levels;
  QgsSymbolList symbols = mRenderer->symbols( mContext );
  for ( int i = 0; i < symbols.count(); i++ )
  {
    QgsSymbol *sym = symbols[i];
    for ( int j = 0; j < sym->symbolLayerCount(); j++ )
    {
      int level = sym->symbolLayer( j )->renderingPass();
      if ( level < 0 || level >= 1000 ) // ignore invalid levels
        continue;
      QgsSymbolLevelItem item( sym, j );
      while ( level >= levels.count() ) // append new empty levels
        levels.append( QgsSymbolLevel() );
      levels[level].append( item );
    }
  }

  // 2. draw features in correct order
  for ( int l = 0; l < levels.count(); l++ )
  {
    QgsSymbolLevel &level = levels[l];
    for ( int i = 0; i < level.count(); i++ )
    {
      QgsSymbolLevelItem &item = level[i];
      if ( !features.contains( item.symbol() ) )
      {
        QgsDebugMsg( "level item's symbol not found!" );
        continue;
      }
      int layer = item.layer();
      QList<QgsFeature> &lst = features[item.symbol()];
      QList<QgsFeature>::iterator fit;
      for ( fit = lst.begin(); fit != lst.end(); ++fit )
      {
        if ( mContext.renderingStopped() )
        {
          stopRenderer( selRenderer );
          return;
        }

        bool sel = mContext.showSelection() && mSelectedFeatureIds.contains( fit->id() );
        // maybe vertex markers should be drawn only during the last pass...
        bool drawMarker = ( mDrawVertexMarkers && mContext.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || sel ) );

        mContext.expressionContext().setFeature( *fit );

        try
        {
          mRenderer->renderFeature( *fit, mContext, layer, sel, drawMarker );
        }
        catch ( const QgsCsException &cse )
        {
          Q_UNUSED( cse );
          QgsDebugMsg( QString( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
                       .arg( fet.id() ).arg( cse.what() ) );
        }
      }
    }
  }

  stopRenderer( selRenderer );
}
예제 #3
0
bool SubScriptObject::hasGlobal(const QString& name){
	return globals.contains(getScriptHash()+"/"+name);
}
예제 #4
0
LocalePage::LocalePage( QWidget* parent )
    : QWidget( parent )
    , m_blockTzWidgetSet( false )
{
    QBoxLayout* mainLayout = new QVBoxLayout;

    QBoxLayout* tzwLayout = new QHBoxLayout;
    mainLayout->addLayout( tzwLayout );
    m_tzWidget = new TimeZoneWidget( this );
    tzwLayout->addStretch();
    tzwLayout->addWidget( m_tzWidget );
    tzwLayout->addStretch();
    setMinimumWidth( m_tzWidget->width() );

    QBoxLayout* bottomLayout = new QHBoxLayout;
    mainLayout->addLayout( bottomLayout );

    m_regionLabel = new QLabel( this );
    bottomLayout->addWidget( m_regionLabel );

    m_regionCombo = new QComboBox( this );
    bottomLayout->addWidget( m_regionCombo );
    m_regionCombo->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred );
    m_regionLabel->setBuddy( m_regionCombo );

    bottomLayout->addSpacing( 20 );

    m_zoneLabel = new QLabel( this );
    bottomLayout->addWidget( m_zoneLabel );

    m_zoneCombo = new QComboBox( this );
    m_zoneCombo->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred );
    bottomLayout->addWidget( m_zoneCombo );
    m_zoneLabel->setBuddy( m_zoneCombo );

    mainLayout->addStretch();

    QBoxLayout* localeLayout = new QHBoxLayout;
    m_localeLabel = new QLabel( this );
    m_localeLabel->setWordWrap( true );
    m_localeLabel->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred );
    localeLayout->addWidget( m_localeLabel );

    m_localeChangeButton = new QPushButton( this );
    m_localeChangeButton->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred );
    localeLayout->addWidget( m_localeChangeButton );
    mainLayout->addLayout( localeLayout );

    QBoxLayout* formatsLayout = new QHBoxLayout;
    m_formatsLabel = new QLabel( this );
    m_formatsLabel->setWordWrap( true );
    m_formatsLabel->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred );
    formatsLayout->addWidget( m_formatsLabel );

    m_formatsChangeButton = new QPushButton( this );
    m_formatsChangeButton->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred );
    formatsLayout->addWidget( m_formatsChangeButton );
    mainLayout->addLayout( formatsLayout );

    setLayout( mainLayout );

    connect( m_regionCombo,
             static_cast< void ( QComboBox::* )( int ) >( &QComboBox::currentIndexChanged ),
             [this]( int currentIndex )
    {
        Q_UNUSED( currentIndex );
        QHash< QString, QList< LocaleGlobal::Location > > regions = LocaleGlobal::getLocations();
        if ( !regions.contains( m_regionCombo->currentData().toString() ) )
            return;

        m_zoneCombo->blockSignals( true );

        m_zoneCombo->clear();

        const QList< LocaleGlobal::Location > zones = regions.value( m_regionCombo->currentData().toString() );
        for ( const LocaleGlobal::Location& zone : zones )
        {
            m_zoneCombo->addItem( LocaleGlobal::Location::pretty( zone.zone ), zone.zone );
        }

        m_zoneCombo->model()->sort( 0 );

        m_zoneCombo->blockSignals( false );

        m_zoneCombo->currentIndexChanged( m_zoneCombo->currentIndex() );
    } );

    connect( m_zoneCombo,
             static_cast< void ( QComboBox::* )( int ) >( &QComboBox::currentIndexChanged ),
             [this]( int currentIndex )
    {
        Q_UNUSED( currentIndex )
        if ( !m_blockTzWidgetSet )
            m_tzWidget->setCurrentLocation( m_regionCombo->currentData().toString(),
                                            m_zoneCombo->currentData().toString() );

        updateGlobalStorage();
    } );
void QgsVectorLayerRenderer::drawRendererV2Levels( QgsFeatureIterator& fit )
{
  QHash< QgsSymbolV2*, QList<QgsFeature> > features; // key = symbol, value = array of features

  QgsSingleSymbolRendererV2* selRenderer = NULL;
  if ( !mSelectedFeatureIds.isEmpty() )
  {
    selRenderer = new QgsSingleSymbolRendererV2( QgsSymbolV2::defaultSymbol( mGeometryType ) );
    selRenderer->symbol()->setColor( mContext.selectionColor() );
    selRenderer->setVertexMarkerAppearance( mVertexMarkerStyle, mVertexMarkerSize );
    selRenderer->startRender( mContext, mFields );
  }

  // 1. fetch features
  QgsFeature fet;
  while ( fit.nextFeature( fet ) )
  {
    if ( !fet.geometry() )
      continue; // skip features without geometry

    if ( mContext.renderingStopped() )
    {
      qDebug( "rendering stop!" );
      stopRendererV2( selRenderer );
      return;
    }

    QgsSymbolV2* sym = mRendererV2->symbolForFeature( fet );
    if ( !sym )
    {
      continue;
    }

    if ( !features.contains( sym ) )
    {
      features.insert( sym, QList<QgsFeature>() );
    }
    features[sym].append( fet );

    if ( mCache )
    {
      // Cache this for the use of (e.g.) modifying the feature's uncommitted geometry.
      mCache->cacheGeometry( fet.id(), *fet.geometry() );
    }

    if ( sym && mContext.labelingEngine() )
    {
      if ( mLabeling )
      {
        mContext.labelingEngine()->registerFeature( mLayerID, fet, mContext );
      }
      if ( mDiagrams )
      {
        mContext.labelingEngine()->registerDiagramFeature( mLayerID, fet, mContext );
      }
    }
  }

  // find out the order
  QgsSymbolV2LevelOrder levels;
  QgsSymbolV2List symbols = mRendererV2->symbols();
  for ( int i = 0; i < symbols.count(); i++ )
  {
    QgsSymbolV2* sym = symbols[i];
    for ( int j = 0; j < sym->symbolLayerCount(); j++ )
    {
      int level = sym->symbolLayer( j )->renderingPass();
      if ( level < 0 || level >= 1000 ) // ignore invalid levels
        continue;
      QgsSymbolV2LevelItem item( sym, j );
      while ( level >= levels.count() ) // append new empty levels
        levels.append( QgsSymbolV2Level() );
      levels[level].append( item );
    }
  }

  // 2. draw features in correct order
  for ( int l = 0; l < levels.count(); l++ )
  {
    QgsSymbolV2Level& level = levels[l];
    for ( int i = 0; i < level.count(); i++ )
    {
      QgsSymbolV2LevelItem& item = level[i];
      if ( !features.contains( item.symbol() ) )
      {
        QgsDebugMsg( "level item's symbol not found!" );
        continue;
      }
      int layer = item.layer();
      QList<QgsFeature>& lst = features[item.symbol()];
      QList<QgsFeature>::iterator fit;
      for ( fit = lst.begin(); fit != lst.end(); ++fit )
      {
        if ( mContext.renderingStopped() )
        {
          stopRendererV2( selRenderer );
          return;
        }

        bool sel = mSelectedFeatureIds.contains( fit->id() );
        // maybe vertex markers should be drawn only during the last pass...
        bool drawMarker = ( mDrawVertexMarkers && mContext.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || sel ) );

        try
        {
          mRendererV2->renderFeature( *fit, mContext, layer, sel, drawMarker );
        }
        catch ( const QgsCsException &cse )
        {
          Q_UNUSED( cse );
          QgsDebugMsg( QString( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
                       .arg( fet.id() ).arg( cse.what() ) );
        }
      }
    }
  }

  stopRendererV2( selRenderer );
}
예제 #6
0
QString QDesktopServices::storageLocation(StandardLocation type)
{
    if (type == QDesktopServices::HomeLocation)
        return QDir::homePath();
    if (type == QDesktopServices::TempLocation)
        return QDir::tempPath();

    // http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
    if (type == QDesktopServices::CacheLocation) {
        QString xdgCacheHome = QLatin1String(qgetenv("XDG_CACHE_HOME"));
        if (xdgCacheHome.isEmpty())
            xdgCacheHome = QDir::homePath() + QLatin1String("/.cache");
        xdgCacheHome += QLatin1Char('/') + QCoreApplication::organizationName()
                    + QLatin1Char('/') + QCoreApplication::applicationName();
        return xdgCacheHome;
    }

    if (type == QDesktopServices::DataLocation) {
        QString xdgDataHome = QLatin1String(qgetenv("XDG_DATA_HOME"));
        if (xdgDataHome.isEmpty())
            xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
        xdgDataHome += QLatin1String("/data/")
                    + QCoreApplication::organizationName() + QLatin1Char('/')
                    + QCoreApplication::applicationName();
        return xdgDataHome;
    }

    // http://www.freedesktop.org/wiki/Software/xdg-user-dirs
    QString xdgConfigHome = QLatin1String(qgetenv("XDG_CONFIG_HOME"));
    if (xdgConfigHome.isEmpty())
        xdgConfigHome = QDir::homePath() + QLatin1String("/.config");
    QFile file(xdgConfigHome + QLatin1String("/user-dirs.dirs"));
    if (file.exists() && file.open(QIODevice::ReadOnly)) {
        QHash<QString, QString> lines;
        QTextStream stream(&file);
        // Only look for lines like: XDG_DESKTOP_DIR="$HOME/Desktop"
        QRegExp exp(QLatin1String("^XDG_(.*)_DIR=(.*)$"));
        while (!stream.atEnd()) {
            QString line = stream.readLine();
            if (exp.indexIn(line) != -1) {
                QStringList lst = exp.capturedTexts();
                QString key = lst.at(1);
                QString value = lst.at(2);
                if (value.length() > 2
                    && value.startsWith(QLatin1Char('\"'))
                    && value.endsWith(QLatin1Char('\"')))
                    value = value.mid(1, value.length() - 2);
                // Store the key and value: "DESKTOP", "$HOME/Desktop"
                lines[key] = value;
            }
        }

        QString key;
        switch (type) {
        case DesktopLocation: key = QLatin1String("DESKTOP"); break;
        case DocumentsLocation: key = QLatin1String("DOCUMENTS"); break;
        case PicturesLocation: key = QLatin1String("PICTURES"); break;
        case MusicLocation: key = QLatin1String("MUSIC"); break;
        case MoviesLocation: key = QLatin1String("VIDEOS"); break;
        default: break;
        }
        if (!key.isEmpty() && lines.contains(key)) {
            QString value = lines[key];
            // value can start with $HOME
            if (value.startsWith(QLatin1String("$HOME")))
                value = QDir::homePath() + value.mid(5);
            return value;
        }
    }

    QDir emptyDir;
    QString path;
    switch (type) {
    case DesktopLocation:
        path = QDir::homePath() + QLatin1String("/Desktop");
        break;
    case DocumentsLocation:
        path = QDir::homePath() + QLatin1String("/Documents");
       break;
    case PicturesLocation:
        path = QDir::homePath() + QLatin1String("/Pictures");
        break;

    case FontsLocation:
        path = QDir::homePath() + QLatin1String("/.fonts");
        break;

    case MusicLocation:
        path = QDir::homePath() + QLatin1String("/Music");
        break;

    case MoviesLocation:
        path = QDir::homePath() + QLatin1String("/Videos");
        break;

    case ApplicationsLocation:
    default:
        break;
    }

    return path;
}
예제 #7
0
bool
Result::isCached( const QString& url )
{
    QMutexLocker lock( &s_mutex );
    return ( s_results.contains( url ) );
}
QString InsertArtificialCodeRepresentation::text() {
    Q_ASSERT(artificialStrings.contains(m_file));
    return artificialStrings[m_file]->data();
}
int main(int argc, char** argv)
{
  QApplication app(argc, argv);

  ctkCommandLineParser parser;
  // Use Unix-style argument names
  parser.setArgumentPrefix("--", "-");

  // Add command line argument names
  parser.addArgument("help", "h", QVariant::Bool, "Print usage information and exit.");
  parser.addArgument("interactive", "I", QVariant::Bool, "Enable interactive mode");

  // Parse the command line arguments
  bool ok = false;
  QHash<QString, QVariant> parsedArgs = parser.parseArguments(QCoreApplication::arguments(), &ok);
  if (!ok)
  {
    QTextStream(stderr, QIODevice::WriteOnly) << "Error parsing arguments: "
                                              << parser.errorString() << "\n";
    return EXIT_FAILURE;
  }

  // Show a help message
  if (parsedArgs.contains("help") || parsedArgs.contains("h"))
  {
    QTextStream(stdout, QIODevice::WriteOnly) << "ctkSimplePythonShell\n"
          << "Usage\n\n"
          << "  ctkSimplePythonShell [options] [<path-to-python-script> ...]\n\n"
          << "Options\n"
          << parser.helpText();
    return EXIT_SUCCESS;
  }
  
  ctkSimplePythonManager pythonManager;
  
  ctkPythonShell shell(&pythonManager);
  shell.setAttribute(Qt::WA_QuitOnClose, true);
  shell.resize(600, 280);
  shell.show();

  shell.setProperty("isInteractive", parsedArgs.contains("interactive"));

  pythonManager.addObjectToPythonMain("_ctkPythonShellInstance", &shell);

  ctkTestWrappedQProperty testWrappedQProperty;
  pythonManager.addObjectToPythonMain("_testWrappedQPropertyInstance", &testWrappedQProperty);

  ctkTestWrappedQInvokable testWrappedQInvokable;
  pythonManager.addObjectToPythonMain("_testWrappedQInvokableInstance", &testWrappedQInvokable);

  ctkTestWrappedSlot testWrappedSlot;
  pythonManager.addObjectToPythonMain("_testWrappedSlotInstance", &testWrappedSlot);

#ifdef CTK_WRAP_PYTHONQT_USE_VTK
  ctkTestWrappedVTKQInvokable testWrappedVTKQInvokable;
  pythonManager.addObjectToPythonMain("_testWrappedVTKQInvokableInstance", &testWrappedVTKQInvokable);

  ctkTestWrappedVTKSlot testWrappedVTKSlot;
  pythonManager.addObjectToPythonMain("_testWrappedVTKSlotInstance", &testWrappedVTKSlot);

  ctkTestWrappedQListOfVTKObject testWrappedQListOfVTKObject;
  pythonManager.addObjectToPythonMain("_testWrappedQListOfVTKObjectInstance", &testWrappedQListOfVTKObject);
#endif

  foreach(const QString& script, parser.unparsedArguments())
    {
    pythonManager.executeFile(script);
    }
  
  return app.exec();
}
예제 #10
0
InsertArtificialCodeRepresentation::~InsertArtificialCodeRepresentation() {
    Q_ASSERT(artificialStrings.contains(m_file));
    artificialStrings.remove(m_file);
}
예제 #11
0
void InsertArtificialCodeRepresentation::setText(const QString& text) {
    Q_ASSERT(artificialStrings.contains(m_file));
    artificialStrings[m_file]->setData(text);
}
예제 #12
0
void QBluetoothDeviceDiscoveryAgentPrivate::start(QBluetoothDeviceDiscoveryAgent::DiscoveryMethods methods)
{
    //TODO Implement discovery method handling (see input parameter)
    requestedMethods = methods;

    if (pendingCancel) {
        pendingStart = true;
        return;
    }

    Q_Q(QBluetoothDeviceDiscoveryAgent);

    if (!adapter.isValid()) {
        qCWarning(QT_BT_ANDROID) << "Device does not support Bluetooth";
        lastError = QBluetoothDeviceDiscoveryAgent::InputOutputError;
        errorString = QBluetoothDeviceDiscoveryAgent::tr("Device does not support Bluetooth");
        emit q->error(lastError);
        return;
    }

    if (!m_adapterAddress.isNull()
        && adapter.callObjectMethod<jstring>("getAddress").toString()
        != m_adapterAddress.toString()) {
        qCWarning(QT_BT_ANDROID) << "Incorrect local adapter passed.";
        lastError = QBluetoothDeviceDiscoveryAgent::InvalidBluetoothAdapterError;
        errorString = QBluetoothDeviceDiscoveryAgent::tr("Passed address is not a local device.");
        emit q->error(lastError);
        return;
    }

    const int state = adapter.callMethod<jint>("getState");
    if (state != 12) {  // BluetoothAdapter.STATE_ON
        lastError = QBluetoothDeviceDiscoveryAgent::PoweredOffError;
        errorString = QBluetoothDeviceDiscoveryAgent::tr("Device is powered off");
        emit q->error(lastError);
        return;
    }

    // check Android v23+ permissions
    // -> BTLE search requires android.permission.ACCESS_COARSE_LOCATION
    if (requestedMethods & QBluetoothDeviceDiscoveryAgent::LowEnergyMethod
        && QtAndroid::androidSdkVersion() >= 23)
    {
        QString permission(QLatin1String("android.permission.ACCESS_COARSE_LOCATION"));

        // do we have required permission already, if so nothing to do
        if (QtAndroidPrivate::checkPermission(permission) == QtAndroidPrivate::PermissionsResult::Denied) {
            qCWarning(QT_BT_ANDROID) << "Requesting ACCESS_COARSE_LOCATION permission";

            QAndroidJniEnvironment env;
            const QHash<QString, QtAndroidPrivate::PermissionsResult> results =
                    QtAndroidPrivate::requestPermissionsSync(env, QStringList() << permission);
            if (!results.contains(permission)
                || results[permission] == QtAndroidPrivate::PermissionsResult::Denied)
            {
                qCWarning(QT_BT_ANDROID) << "Search not possible due to missing permission (ACCESS_COARSE_LOCATION)";
                lastError = QBluetoothDeviceDiscoveryAgent::UnknownError;
                errorString = QBluetoothDeviceDiscoveryAgent::tr("Missing Location permission. Search is not possible.");
                emit q->error(lastError);
                return;
            }
        }

        qCWarning(QT_BT_ANDROID) << "ACCESS_COARSE_LOCATION permission available";
    }

    // install Java BroadcastReceiver
    if (!receiver) {
        // SDP based device discovery
        receiver = new DeviceDiscoveryBroadcastReceiver();
        qRegisterMetaType<QBluetoothDeviceInfo>();
        QObject::connect(receiver, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo,bool)),
                         this, SLOT(processDiscoveredDevices(QBluetoothDeviceInfo,bool)));
        QObject::connect(receiver, SIGNAL(finished()), this, SLOT(processSdpDiscoveryFinished()));
    }
예제 #13
0
//-----------------------------------------------------------------------------
int main(int argc, char * argv[])
{
  QCoreApplication app(argc, argv);

  ctkCommandLineParser parser;
  // Use Unix-style argument names
  parser.setArgumentPrefix("--", "-");
  // Add command line argument names
  parser.addArgument("help", "h", QVariant::Bool, "Print usage information and exit.");
  parser.addArgument("verbose", "v", QVariant::Bool, "Enable verbose output.");
  parser.addArgument("wrapping-namespace", "wns", QVariant::String, "Wrapping namespace.", QVariant("org.commontk.foo"));
  parser.addArgument("target-name", "p", QVariant::String, "Target name.");
  parser.addArgument("check-only", "c", QVariant::Bool, "Return 1 (or 0) indicating if the file"
                     "could be successfully wrapped.");
  parser.addArgument("output-dir", "o", QVariant::String, "Output directory");
  
  // Parse the command line arguments
  bool ok = false;
  QHash<QString, QVariant> parsedArgs = parser.parseArguments(QCoreApplication::arguments(), &ok);
  if (!ok)
    {
    std::cerr << "Error parsing arguments: " << qPrintable(parser.errorString()) << std::endl;
    printHelpUsage();
    return EXIT_FAILURE;
    }
  // Show help message
  if (parsedArgs.contains("help"))
    {
    printHelp(parser);
    return EXIT_SUCCESS;
    }

  QString wrappingNamespace = parsedArgs.value("wrapping-namespace").toString();
  if (wrappingNamespace.isEmpty())
    {
    std::cerr << "error: Wrapping namespace not specified" << std::endl;
    printHelpUsage();
    return EXIT_FAILURE;
    }
  if (!QRegExp("[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)*").exactMatch(wrappingNamespace))
    {
    std::cerr << "error: Invalid wrapping namespace. Should match: [a-zA-Z0-9]+(.[a-zA-Z0-9]+)*" << std::endl;
    printHelpUsage();
    return EXIT_FAILURE;
    }

  QString outputDir = parsedArgs.value("output-dir").toString();
  if (outputDir.isEmpty())
    {
    std::cerr << "error: Output directory not specified" << std::endl;
    printHelpUsage();
    return EXIT_FAILURE;
    }
  QDir dir = QDir(outputDir);
  if (!dir.exists() || !dir.isReadable())
    {
    std::cerr << "error: Output directory non existent or non readable ["
        << qPrintable(outputDir) << "]" << std::endl;
    return EXIT_FAILURE;
    }

  if (parser.unparsedArguments().count() == 0)
    {
    std::cerr << "error: <path-to-cpp-header-file> not specified" << std::endl;
    printHelpUsage();
    return EXIT_FAILURE;
    }

  ctkPythonQtWrapper wrapper;
  wrapper.setVerbose(parsedArgs.contains("verbose"));
  wrapper.setWrappingNamespace(wrappingNamespace);

  if (!wrapper.setOutput(outputDir))
    {
    std::cerr << "error: Failed to set output" << std::endl;
    return EXIT_FAILURE;
    }

  if (!wrapper.setInput(parser.unparsedArguments()))
    {
    std::cerr << "error: Failed to set input" << std::endl;
    return EXIT_FAILURE;
    }

  int rejectedHeaders = wrapper.validateInputFiles();

  if (parsedArgs.contains("check-only"))
    {
    return rejectedHeaders;
    }

  if (rejectedHeaders == parser.unparsedArguments().count())
    {
    std::cerr << "error: All specified headers have been rejected" << std::endl;
    return EXIT_FAILURE;
    }

  QString targetName = parsedArgs.value("target-name").toString();
  if (parser.unparsedArguments().count() == 1)
    {
    if (targetName.isEmpty())
      {
      QFileInfo fileInfo(parser.unparsedArguments().value(0));
      targetName = fileInfo.baseName();
      }
    }
  else
    {
    if (targetName.isEmpty())
      {
      std::cerr << "error: Target name hasn't been specified" << std::endl;
      printHelpUsage();
      return EXIT_FAILURE;
      }
    }
  wrapper.setTargetName(targetName);

  wrapper.generateOutputs();
  
  return EXIT_SUCCESS;
}
예제 #14
0
LocalePage::LocalePage( QWidget* parent )
    : QWidget()
    , m_blockTzWidgetSet( false )
{
    QBoxLayout* mainLayout = new QVBoxLayout;

    QBoxLayout* tzwLayout = new QHBoxLayout;
    mainLayout->addLayout( tzwLayout );
    m_tzWidget = new TimeZoneWidget( this );
    tzwLayout->addStretch();
    tzwLayout->addWidget( m_tzWidget );
    tzwLayout->addStretch();
    setMinimumWidth( m_tzWidget->width() );

    QBoxLayout* bottomLayout = new QHBoxLayout;
    mainLayout->addLayout( bottomLayout );

    QLabel* cityLabel = new QLabel( tr( "Region:" ), this );
    bottomLayout->addWidget( cityLabel );

    m_regionCombo = new QComboBox( this );
    bottomLayout->addWidget( m_regionCombo );
    m_regionCombo->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred );
    cityLabel->setBuddy( m_regionCombo );

    bottomLayout->addSpacing( 20 );

    QLabel* timezoneLabel = new QLabel( tr( "Zone:" ), this );
    bottomLayout->addWidget( timezoneLabel );

    m_timezoneCombo = new QComboBox( this );
    m_timezoneCombo->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred );
    bottomLayout->addWidget( m_timezoneCombo );
    timezoneLabel->setBuddy( m_timezoneCombo );

    mainLayout->addStretch();

    setLayout( mainLayout );

    connect( m_regionCombo,
             static_cast< void ( QComboBox::* )( const QString& ) >( &QComboBox::currentIndexChanged ),
             [this]( const QString& current )
    {
        QHash< QString, QList< LocaleGlobal::Location > > regions = LocaleGlobal::getLocations();
        if ( !regions.contains( current ) )
            return;

        m_timezoneCombo->blockSignals( true );

        m_timezoneCombo->clear();

        QList< LocaleGlobal::Location > zones = regions.value( current );
        foreach ( const LocaleGlobal::Location& zone, zones )
        {
            m_timezoneCombo->addItem( zone.zone );
        }

        m_timezoneCombo->model()->sort( 0 );

        m_timezoneCombo->blockSignals( false );

        m_timezoneCombo->currentIndexChanged( m_timezoneCombo->currentText() );
    });
예제 #15
0
  bool isReservedKeyword(const QString &word)
  {
    static QHash<QChar, QStringList> keywords={
      {QChar('A'), {QString("ALL"), QString("ANALYSE"), QString("ANALYZE"), QString("AND"),
                    QString("ANY"), QString("AS"),      QString("ASC"),     QString("AUTHORIZATION")}},

      {QChar('B'), {QString("BETWEEN"), QString("BIGINT"), QString("BINARY"), QString("BIT"),
                    QString("BOOLEAN"), QString("BOTH")}},

      {QChar('C'), {QString("CASE"),         QString("CAST"),         QString("CHAR"),    QString("CHARACTER"),
                    QString("CHECK"),        QString("COALESCE"),     QString("COLLATE"), QString("COLUMN"),
                    QString("CONSTRAINT"),   QString("CONVERT"),      QString("CREATE"),  QString("CROSS"),
                    QString("CURRENT_DATE"), QString("CURRENT_TIME"), QString("CURRENT_TIMESTAMP"), QString("CURRENT_USER")}},

      {QChar('D'), {QString("DEC"),  QString("DECIMAL"),  QString("DEFAULT"), QString("DEFERRABLE"),
                    QString("DESC"), QString("DISTINCT"), QString("DO")}},

      {QChar('E'), {QString("ELSE"), QString("END"), QString("EXCEPT"), QString("EXISTS"),
                    QString("EXTRACT")}},

      {QChar('F'), {QString("FALSE"),  QString("FLOAT"), QString("FOR"), QString("FOREIGN"),
                    QString("FREEZE"), QString("FROM"),  QString("FULL")}},

      {QChar('G'), {QString("GRANT"), QString("GROUP")}},

      {QChar('H'), {QString("HAVING")}},

      {QChar('I'), {QString("ILIKE"), QString("IN"),      QString("INITIALLY"), QString("INNER"),
                    QString("INT"),   QString("INTEGER"), QString("INTERSECT"), QString("INTERVAL"),
                    QString("INTO"),  QString("IS"),      QString("ISNULL")}},

      {QChar('J'), {QString("JOIN")}},

      {QChar('L'), {QString("LEADING"),   QString("LEFT"), QString("LIKE"), QString("LIMIT"),
                    QString("LOCALTIME"), QString("LOCALTIMESTAMP")}},

      {QChar('N'), {QString("NATURAL"),      QString("NCHAR"),   QString("NEW"), QString("NOCREATEDB"),
                    QString("NOCREATEUSER"), QString("NONE"),    QString("NOT"), QString("NOTHING"),
                    QString("NOTIFY"),       QString("NOTNULL"), QString("NULL"), QString("NULLIF"),
                    QString("NUMERIC")}},

      {QChar('O'), {QString("OFF"),   QString("OFFSET"),  QString("OLD"),   QString("ON"),
                    QString("ONLY"),  QString("OR"),      QString("ORDER"), QString("OUTER"),
                    QString("OVERLAPS"), QString("OVERLAY")}},

      {QChar('P'), {QString("PLACING"), QString("POSITION"), QString("PRIMARY")}},

      {QChar('R'), {QString("REAL"), QString("REFERENCES"), QString("RIGHT"), QString("ROW")}},

      {QChar('S'), {QString("SELECT"),   QString("SESSION_USER"), QString("SETOF"), QString("SIMILAR"),
                    QString("SMALLINT"), QString("SOME"),         QString("SUBSTRING")}},

      {QChar('T'), {QString("TABLE"), QString("THEN"),  QString("TIME"),  QString("TIMESTAMP"),
                    QString("TO"), QString("TRAILING"), QString("TREAT"), QString("TRIM"),
                    QString("TRUE")}},

      {QChar('U'), {QString("UNION"), QString("UNIQUE"), QString("USER"), QString("USING")}},

      {QChar('V'), {QString("VARCHAR"), QString("VERBOSE")}},

      {QChar('W'), {QString("WHEN"), QString("WHERE")}}
    };

    if(word.isEmpty())
      return(false);
    else
    {
      QChar chr=word.at(0).toUpper();

      if(!keywords.contains(chr))
        return(false);
      else
        return(keywords[chr].contains(word.toUpper()));
    }
  }
예제 #16
0
qemical_obj invoke( const char *className, const char *method, value argv, void *target )
{
    Smoke::ModuleIndex classId;

    if ( ( classId = qtcore_Smoke->findClass( className ) )  == Smoke::NullModuleIndex
    ||  ( classId = qtgui_Smoke-> findClass( className ) )  == Smoke::NullModuleIndex ) {
        printf( "Couldn't find class %s!\n", className );
        fflush( stdout );
        caml_failwith( "Couldn't find class" );
    }

    Smoke::ModuleIndex methId;

    if ( ( methId = classId.smoke->findMethod( className, method ) ) == Smoke::NullModuleIndex )
        caml_failwith( "No such method!" );

    if ( methId.index < 0 )
        qDebug( ) << "Ambiguous!";

    Smoke::Class k     = classId.smoke->classes[classId.index];
    Smoke::Method meth = methId.smoke->methods[methId.smoke->methodMaps[methId.index].method];

    int len;
    bool single;

    if ( Is_block( argv ) && Wosize_val( argv ) == 2 && camlPolyvarClasses.contains( Field( argv, 0 ) ) )
        len = 1, single = true;
    else if ( Is_block( argv ) )
        len = Wosize_val( argv ), single = false;
    else
        len = 1, single = true;

    qDebug( ) << len << single;
    Smoke::StackItem stack[len + 1];

    if ( len ) {
        for ( int i = 0; i < len; ++i ) {
            qDebug( ) << i;
            value &v = single ? argv : Field( argv, i );
            Smoke::StackItem &item = stack[i + 1];
            unsigned short t;

            for ( Smoke::Index *i = methId.smoke->argumentList + meth.args; *i; ++i ) {
                t = methId.smoke->types[*i].flags & Smoke::tf_elem;

                switch ( t ) {
                case Smoke::t_voidp:
                    if ( Is_block( v ) ) {
                        if ( Tag_val( v ) == String_tag ) {
                            item.s_voidp = String_val( v );
                        } else if ( Wosize_val( v ) == 2
                                 && camlPolyvarClasses.contains( Field( v, 0 ) ) ) {
                            qDebug( "yes" );
                            item.s_voidp = to_qobj( Field( v, 1 ) )->ptr;
                        } else {
                            int len = Wosize_val( v );

                            if ( !len ) {
                                qDebug( "nil length" );
                                item.s_voidp = nullptr;
                            }

                            qDebug( ) << len;

                            char **arr = new char *[len];

                            for ( int i = 0; i < len; ++i ) {
                                value cur = Field( v, i );

                                switch ( Tag_val( cur ) ) {
                                case String_tag:
                                    arr[i] = String_val( cur );
                                    break;
                                default: caml_failwith( "Match failure!" );
                                }
                            }
                            item.s_voidp = arr;
                        }
                    } else {
                        int *p = new int( Int_val( v ) );
                        printf( "argc points to %p and equals %d\n", p, *p );
                        item.s_voidp = p;
                        break;
                    }
                    break;
                case Smoke::t_bool:
                    item.s_bool   = Bool_val( v );
                    break;
                case Smoke::t_char:
                    item.s_char   = ( char )  Long_val( v );
                    break;
                case Smoke::t_short:
                    item.s_short  = ( short ) Long_val( v );
                    break;
                case Smoke::t_ushort:
                    item.s_ushort = ( short ) Unsigned_long_val( v );
                    break;
                case Smoke::t_int:
                    item.s_int    = Int_val( v );
                    break;
                case Smoke::t_uint:
                    item.s_uint   = Unsigned_int_val( v );
                    break;
                case Smoke::t_long:
                    item.s_long   = Long_val( v );
                    break;
                case Smoke::t_ulong:
                    item.s_ulong  = Unsigned_long_val( v );
                    break;
                case Smoke::t_double:
                    item.s_float  = Double_val( v );
                    break;
                case Smoke::t_enum:
                    item.s_enum   = Long_val( v );
                    break;
                case Smoke::t_class:
                    // assuming 'a qObj
                    item.s_class  = to_qobj( Field( v, 1 ) )->ptr;
                    break;
                default:
                    qDebug( ) << *i;
                    caml_failwith( "Unknown type!" );
                }
            }
        }
    }

    if ( ( meth.flags & Smoke::mf_static ) || ( meth.flags & Smoke::mf_ctor ) )
        ( *k.classFn )( meth.method, nullptr, stack );
    else
        ( *k.classFn )( meth.method, target, stack );

    qemical_obj r( stack[0].s_voidp, true, classId.smoke, classId.index );

    // set binding
    if ( meth.flags & Smoke::mf_ctor ) {
        stack[1].s_voidp = qtguiBinding;
        ( *k.classFn )( 0, r.ptr, stack );
    } // else static method or regular method call

    return r;
}
예제 #17
0
//! [region start]
QRegion MyDecoration::region(const QWidget *widget, const QRect &insideRect,
                             int decorationRegion)
{
    //! [region start]
    //! [calculate the positions of buttons based on the window flags used]
    QHash<DecorationRegion, int> buttons;
    Qt::WindowFlags flags = widget->windowFlags();
    int dx = -buttonMargin - buttonWidth;

    foreach (Qt::WindowType button, buttonHints) {
        if (flags & button) {
            int x = (buttons.size() + 1) * dx;
            buttons[buttonHintMap[button]] = x;
        }
    }
    //! [calculate the positions of buttons based on the window flags used]

    //! [calculate the extent of the title]
    int titleRightMargin = buttons.size() * dx;

    QRect outsideRect(insideRect.left() - border,
                      insideRect.top() - titleHeight - border,
                      insideRect.width() + 2 * border,
                      insideRect.height() + titleHeight + 2 * border);
    //! [calculate the extent of the title]

    //! [check for all regions]
    QRegion region;

    if (decorationRegion == All) {
        region += QRegion(outsideRect) - QRegion(insideRect);
        return region;
    }
    //! [check for all regions]

    //! [compose a region based on the decorations specified]
    if (decorationRegion & Title) {
        QRect rect = outsideRect.adjusted(border, border, -border, 0);
        rect.setHeight(titleHeight);

        // Adjust the width to accommodate buttons.
        rect.setWidth(qMax(0, rect.width() + titleRightMargin));
        region += rect;
    }
    if (decorationRegion & Top) {
        QRect rect = outsideRect.adjusted(border, 0, -border, 0);
        rect.setHeight(border);
        region += rect;
    }
    if (decorationRegion & Left) {
        QRect rect = outsideRect.adjusted(0, border, 0, -border);
        rect.setWidth(border);
        region += rect;
    }
    if (decorationRegion & Right) {
        QRect rect = outsideRect.adjusted(0, border, 0, -border);
        rect.setLeft(rect.right() + 1 - border);
        region += rect;
    }
    if (decorationRegion & Bottom) {
        QRect rect = outsideRect.adjusted(border, 0, -border, 0);
        rect.setTop(rect.bottom() + 1 - border);
        region += rect;
    }
    if (decorationRegion & TopLeft) {
        QRect rect = outsideRect;
        rect.setWidth(border);
        rect.setHeight(border);
        region += rect;
    }
    if (decorationRegion & TopRight) {
        QRect rect = outsideRect;
        rect.setLeft(rect.right() + 1 - border);
        rect.setHeight(border);
        region += rect;
    }
    if (decorationRegion & BottomLeft) {
        QRect rect = outsideRect;
        rect.setWidth(border);
        rect.setTop(rect.bottom() + 1 - border);
        region += rect;
    }
    if (decorationRegion & BottomRight) {
        QRect rect = outsideRect;
        rect.setLeft(rect.right() + 1 - border);
        rect.setTop(rect.bottom() + 1 - border);
        region += rect;
    }
    //! [compose a region based on the decorations specified]

    //! [add a region for each button only if it is present]
    foreach (QDecoration::DecorationRegion testRegion, stateRegions) {
        if (decorationRegion & testRegion and buttons.contains(testRegion)) {
            // Inside the title rectangle
            QRect rect = outsideRect.adjusted(border, border, -border, 0);
            rect.setHeight(titleHeight);

            dx = buttons[testRegion];
            rect.setLeft(rect.right() + 1 + dx);
            rect.setWidth(buttonWidth + buttonMargin);
            region += rect;
        }
    }
    //! [add a region for each button only if it is present]

    //! [region end]
    return region;
}
예제 #18
0
파일: main.cpp 프로젝트: Oaks/sdbtest
 int main(int argc, char *argv[])
 {

  QApplication app(argc, argv);

        // Настроить вывод кириллицы в виджете.
  QTextCodec::setCodecForTr      (QTextCodec::codecForName("Windows-1251"));
  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("Windows-1251"));
  QTextCodec::setCodecForLocale  (QTextCodec::codecForName("Windows-1251"));
  int status=-1;

  qWarning() << "Opening database" << endl;

        // Печать установленных драйверов MySQL.
  QStringList driverList;
  driverList = QSqlDatabase::drivers();
  qDebug() << "Available db drivers: " ;
  QStringList::const_iterator it;
  for (it = driverList.constBegin();it != driverList.constEnd(); ++it)
       qDebug() << (*it).toLocal8Bit().constData() << "   ";
  qDebug() << endl;

        //  Открываем базу данных "base" ,используя драйвер QODBC.
        //
  QString namebase = "basedon";
  QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
  db.setDatabaseName(namebase);
         // печатаем ошибку, если не открыли.
  if(!(status=db.open()))
      {qDebug() <<  "Cannot open database:" << db.lastError().driverText()
                                            << db.lastError().databaseText();
       messbox("База данных "+namebase+" не открыта",db.lastError().driverText());
       return -1; }

  qDebug() <<  "Opened database:" ;
  qDebug() << "database base:\n" << db.tables() << "\n";
            // Из таблицы kp базы данных создаем внутренний
            // аналог - словарь h_KP.
  if ( (status=Read_KP()) !=0 ) return status;

            // таблица sdb_recode содержит подключение  параметров к ADAM.
            //
  QSqlQuery query;
  if(! query.exec("SELECT * FROM sdb_recode")) {
      qDebug() << "Unable to execute \" query.exec(\"SELECT * FROM sdb_recode\") \"\n ";
      messbox("Unable to execute  query.exec");
      return(-1);
  }
  struct s_sdb_recode *sdb_recode;
  QSqlRecord rec = query.record();
  int s_id;
  int iport, iaddress, ibit;
  int oport, oaddress, obit;
  int itestkey, otestkey;

  while(query.next()){
      sdb_recode= new struct s_sdb_recode;
      s_id=
      sdb_recode->S_ID=query.value(rec.indexOf("S_ID")).toInt();
      sdb_recode->PNAME=query.value(rec.indexOf("PNAME")).toString();
      sdb_recode->NOTE=query.value(rec.indexOf("NOTE")).toString();
      sdb_recode->I_NKP=query.value(rec.indexOf("I_NKP")).toInt();
      sdb_recode->I_NSKO=query.value(rec.indexOf("I_NSKO")).toInt();
      sdb_recode->I_IDGR=query.value(rec.indexOf("I_IDGR")).toInt();
      sdb_recode->I_NR=query.value(rec.indexOf("I_NR")).toInt();
      sdb_recode->O_GROUPL=query.value(rec.indexOf("O_GROUPL")).toInt();
      sdb_recode->O_NRLAMP=query.value(rec.indexOf("O_NRLAMP")).toInt();
      sdb_recode->O_GROUPK=query.value(rec.indexOf("O_GROUPK")).toInt();
      sdb_recode->O_NRKEY=query.value(rec.indexOf("O_NRKEY")).toInt();
      sdb_recode->O_KEY_INV=query.value(rec.indexOf("O_KEY_INV")).toInt();
      iport=
      sdb_recode->I_PORT_ADAM=query.value(rec.indexOf("I_PORT_ADAM")).toInt();
      iaddress =
      sdb_recode->I_ADR_ADAM=query.value(rec.indexOf("I_ADR_ADAM")).toInt();
      ibit =
      sdb_recode->I_NR_ADAM=query.value(rec.indexOf("I_NR_ADAM")).toInt();
      oport=
      sdb_recode->O_PORT_ADAM=query.value(rec.indexOf("O_PORT_ADAM")).toInt();
      oaddress=
      sdb_recode->O_ADR_ADAM=query.value(rec.indexOf("O_ADR_ADAM")).toInt();
      obit=
      sdb_recode->O_NR_ADAM=query.value(rec.indexOf("O_NR_ADAM")).toInt();
      sdb_recode->A_TYPE=query.value(rec.indexOf("A_TYPE")).toInt();
      sdb_recode->TAGE_LAMP=query.value(rec.indexOf("TAGE_LAMP")).toString();
      sdb_recode->TAGE_KEY=query.value(rec.indexOf("TAGE_KEY")).toString();
      sdb_recode->TAGE_TIT=query.value(rec.indexOf("TAGE_TIT")).toString();
      sdb_recode->state_key= -1;

      TestBound(iport, iaddress, ibit, s_id);     // Проверить на допустимые значения.
      TestBound(oport, oaddress, obit, s_id);
      
        // Определим в массиве masCOMPort адреса заявленных портов ADAM
        // для OpenCom().
      if (sdb_recode->O_PORT_ADAM != 0)
          masCOMPort[ sdb_recode->O_PORT_ADAM ] = 1;
      if (sdb_recode->I_PORT_ADAM != 0)
          masCOMPort[ sdb_recode->I_PORT_ADAM ] = 1;

        // Внесем в словарь hash_sdb_recode очередную запись базы данных.
      if (!hash_sdb_recode.contains(sdb_recode->S_ID))
          hash_sdb_recode[sdb_recode->S_ID] = sdb_recode;
      else { qDebug() << "base error: id dublicate\n"; return -1;}

      // Формируем словарь h_ADAM_iConnections : ADAM присоедиение(ввод) -> параметр БД.
      // С его помощью ищем дубликатные присоединения.

                    // Создаем интегральный ключ словаря.
      itestkey = iport | iaddress << 8 | ibit << (8*2);
      if ( iport != 0){
        if (!h_ADAM_iConnections.contains(itestkey))
            h_ADAM_iConnections[itestkey] = s_id;
        else { messbox( QString("Дубликатное подключение параметров\n БД с индексами %1 %2")
                                .arg(s_id)
                                .arg(h_ADAM_iConnections[itestkey]));
             return -1;
             }
      }

      // Формируем словарь h_ADAM_oConnections : ADAM присоедиение(вывод) -> параметр БД.
      // С его помощью ищем дубликатные присоединения.

      // Создаем интегральный ключ словаря.
      otestkey = oport | oaddress << 8 | obit << (8*2);
      if ( oport != 0){
          if (!h_ADAM_oConnections.contains(otestkey))
              h_ADAM_oConnections[otestkey] = s_id;
          else { messbox( QString("Дубликатное подключение параметров\n БД с индексами %1 %2")
                          .arg(s_id)
                          .arg(h_ADAM_oConnections[otestkey]));
              return -1;
          }
      }
}

  // Открыть порты  ADAM'ов.
  //
  status=OpenCom();
  if (status){                        // Не все порты открыты.
    QString errports;                 // Определить - какие.
    QString allports = "\n из заявленных ";
    for (int i=0; i<MAX_PORT; i++){
          // "Собираем" все заявленные порты.
      if ( masCOMPort[i] != 0) allports += QString("   %1").arg(i);
          // На индексах не окрытых портов в masCOMPort[] стоят -1.
      if ( masCOMPort[i] < 0 ) errports+= QString("   %1").arg(i);
      else continue;
    }
    messbox("Ошибка при открытии портов ADAM: " + errports + allports);
  }

   Window window;
   window.setWindowTitle(QString("СДЩ(%1) версия %2").arg(namebase).arg(VERSION));
   window.show();
   return app.exec();
 }
예제 #19
0
파일: main.cpp 프로젝트: Andreas665/qt
int main(int argc, char *argv[])
{
    enum ExitCode
    {
        Success,
        ParseFailure,
        ArgumentError,
        WriteError,
        FileFailure
    };

    QCoreApplication app(argc, argv);

    QTextStream errorStream(stderr);

    if (argc != 2)
    {
        errorStream << PrettyPrint::tr(
                       "Usage: prettyprint <path to XML file>\n");
        return ArgumentError;
    }

    QString inputFilePath(QCoreApplication::arguments().at(1));
    QFile inputFile(inputFilePath);

    if (!QFile::exists(inputFilePath))
    {
        errorStream << PrettyPrint::tr(
                       "File %1 does not exist.\n").arg(inputFilePath);
        return FileFailure;

    } else if (!inputFile.open(QIODevice::ReadOnly)) {
        errorStream << PrettyPrint::tr(
                       "Failed to open file %1.\n").arg(inputFilePath);
        return FileFailure;
    }

    QFile outputFile;
    if (!outputFile.open(stdout, QIODevice::WriteOnly))
    {
        QTextStream(stderr) << PrettyPrint::tr("Failed to open stdout.");
        return WriteError;
    }

    QXmlStreamReader reader(&inputFile);
    int indentation = 0;
    QHash<int,QPair<int, int> > indentationStack;

    while (!reader.atEnd())
    {
        reader.readNext();
        if (reader.isStartElement()) {
            indentationStack[indentation] = QPair<int,int>(
                reader.lineNumber(), reader.columnNumber());
            indentation += 1;
        } else if (reader.isEndElement()) {
            indentationStack.remove(indentation);
            indentation -= 1;
        }

        if (reader.error())
        {
            errorStream << PrettyPrint::tr(
                           "Error: %1 in file %2 at line %3, column %4.\n").arg(
                               reader.errorString(), inputFilePath,
                               QString::number(reader.lineNumber()),
                               QString::number(reader.columnNumber()));
            if (indentationStack.contains(indentation-1)) {
                int line = indentationStack[indentation-1].first;
                int column = indentationStack[indentation-1].second;
                errorStream << PrettyPrint::tr(
                               "Opened at line %1, column %2.\n").arg(
                                   QString::number(line),
                                   QString::number(column));
            }
            return ParseFailure;

        } else if (reader.isStartElement() && !reader.name().isEmpty()) {
            outputFile.write(QByteArray().fill(' ', indentation));
            outputFile.write(reader.name().toString().toLocal8Bit());
            outputFile.write(QString(" line %1, column %2\n").arg(
                reader.lineNumber()).arg(reader.columnNumber()).toLocal8Bit());
        }
    }

    return Success;
}
예제 #20
0
void QgsOverlayUtils::resolveOverlaps( const QgsFeatureSource &source, QgsFeatureSink &sink, QgsProcessingFeedback *feedback )
{
  int count = 0;
  int totalCount = source.featureCount();
  if ( totalCount == 0 )
    return;  // nothing to do here

  QgsFeatureId newFid = -1;

  QgsWkbTypes::GeometryType geometryType = QgsWkbTypes::geometryType( QgsWkbTypes::multiType( source.wkbType() ) );

  QgsFeatureRequest requestOnlyGeoms;
  requestOnlyGeoms.setSubsetOfAttributes( QgsAttributeList() );

  QgsFeatureRequest requestOnlyAttrs;
  requestOnlyAttrs.setFlags( QgsFeatureRequest::NoGeometry );

  QgsFeatureRequest requestOnlyIds;
  requestOnlyIds.setFlags( QgsFeatureRequest::NoGeometry );
  requestOnlyIds.setSubsetOfAttributes( QgsAttributeList() );

  // make a set of used feature IDs so that we do not try to reuse them for newly added features
  QgsFeature f;
  QSet<QgsFeatureId> fids;
  QgsFeatureIterator it = source.getFeatures( requestOnlyIds );
  while ( it.nextFeature( f ) )
  {
    if ( feedback->isCanceled() )
      return;

    fids.insert( f.id() );
  }

  QHash<QgsFeatureId, QgsGeometry> geometries;
  QgsSpatialIndex index;
  QHash<QgsFeatureId, QList<QgsFeatureId> > intersectingIds;  // which features overlap a particular area

  // resolve intersections

  it = source.getFeatures( requestOnlyGeoms );
  while ( it.nextFeature( f ) )
  {
    if ( feedback->isCanceled() )
      return;

    QgsFeatureId fid1 = f.id();
    QgsGeometry g1 = f.geometry();
    std::unique_ptr< QgsGeometryEngine > g1engine;

    geometries.insert( fid1, g1 );
    index.insertFeature( f );

    QgsRectangle bbox( f.geometry().boundingBox() );
    const QList<QgsFeatureId> ids = index.intersects( bbox );
    for ( QgsFeatureId fid2 : ids )
    {
      if ( fid1 == fid2 )
        continue;

      if ( !g1engine )
      {
        // use prepared geometries for faster intersection tests
        g1engine.reset( QgsGeometry::createGeometryEngine( g1.constGet() ) );
        g1engine->prepareGeometry();
      }

      QgsGeometry g2 = geometries.value( fid2 );
      if ( !g1engine->intersects( g2.constGet() ) )
        continue;

      QgsGeometry geomIntersection = g1.intersection( g2 );
      if ( !sanitizeIntersectionResult( geomIntersection, geometryType ) )
        continue;

      //
      // add intersection geometry
      //

      // figure out new fid
      while ( fids.contains( newFid ) )
        --newFid;
      fids.insert( newFid );

      geometries.insert( newFid, geomIntersection );
      QgsFeature fx( newFid );
      fx.setGeometry( geomIntersection );

      index.insertFeature( fx );

      // figure out which feature IDs belong to this intersection. Some of the IDs can be of the newly
      // created geometries - in such case we need to retrieve original IDs
      QList<QgsFeatureId> lst;
      if ( intersectingIds.contains( fid1 ) )
        lst << intersectingIds.value( fid1 );
      else
        lst << fid1;
      if ( intersectingIds.contains( fid2 ) )
        lst << intersectingIds.value( fid2 );
      else
        lst << fid2;
      intersectingIds.insert( newFid, lst );

      //
      // update f1
      //

      QgsGeometry g12 = g1.difference( g2 );

      index.deleteFeature( f );
      geometries.remove( fid1 );

      if ( sanitizeDifferenceResult( g12 ) )
      {
        geometries.insert( fid1, g12 );

        QgsFeature f1x( fid1 );
        f1x.setGeometry( g12 );
        index.insertFeature( f1x );
      }

      //
      // update f2
      //

      QgsGeometry g21 = g2.difference( g1 );

      QgsFeature f2old( fid2 );
      f2old.setGeometry( g2 );
      index.deleteFeature( f2old );

      geometries.remove( fid2 );

      if ( sanitizeDifferenceResult( g21 ) )
      {
        geometries.insert( fid2, g21 );

        QgsFeature f2x( fid2 );
        f2x.setGeometry( g21 );
        index.insertFeature( f2x );
      }

      // update our temporary copy of the geometry to what is left from it
      g1 = g12;
      g1engine.reset();
    }

    ++count;
    feedback->setProgress( count / ( double ) totalCount * 100. );
  }

  // release some memory of structures we don't need anymore

  fids.clear();
  index = QgsSpatialIndex();

  // load attributes

  QHash<QgsFeatureId, QgsAttributes> attributesHash;
  it = source.getFeatures( requestOnlyAttrs );
  while ( it.nextFeature( f ) )
  {
    if ( feedback->isCanceled() )
      return;

    attributesHash.insert( f.id(), f.attributes() );
  }

  // store stuff in the sink

  for ( auto i = geometries.constBegin(); i != geometries.constEnd(); ++i )
  {
    if ( feedback->isCanceled() )
      return;

    QgsFeature outFeature( i.key() );
    outFeature.setGeometry( i.value() );

    if ( intersectingIds.contains( i.key() ) )
    {
      const QList<QgsFeatureId> ids = intersectingIds.value( i.key() );
      for ( QgsFeatureId id : ids )
      {
        outFeature.setAttributes( attributesHash.value( id ) );
        sink.addFeature( outFeature, QgsFeatureSink::FastInsert );
      }
    }
    else
    {
      outFeature.setAttributes( attributesHash.value( i.key() ) );
      sink.addFeature( outFeature, QgsFeatureSink::FastInsert );
    }
  }
}
예제 #21
0
AVPixelFormat RasterRenderPrivate::getFormat(QString &chroma)
{
	static QHash<QString, AVPixelFormat> f;
	if (f.isEmpty()){
		f.insert("RV32", AV_PIX_FMT_RGB32);
		f.insert("RV24", AV_PIX_FMT_RGB24);
		f.insert("RGB8", AV_PIX_FMT_RGB8);
		f.insert("RV12", AV_PIX_FMT_RGB444);
		f.insert("RV15", AV_PIX_FMT_RGB555);
		f.insert("RV16", AV_PIX_FMT_RGB565);
		f.insert("RGBA", AV_PIX_FMT_RGBA);
		f.insert("ARGB", AV_PIX_FMT_ARGB);
		f.insert("BGRA", AV_PIX_FMT_BGRA);
		f.insert("I410", AV_PIX_FMT_YUV410P);
		f.insert("I411", AV_PIX_FMT_YUV411P);
		f.insert("I420", AV_PIX_FMT_YUV420P);
		f.insert("IYUV", AV_PIX_FMT_YUV420P);
		f.insert("I422", AV_PIX_FMT_YUV422P);
		f.insert("I440", AV_PIX_FMT_YUV440P);
		f.insert("I444", AV_PIX_FMT_YUV444P);
		f.insert("J420", AV_PIX_FMT_YUVJ420P);
		f.insert("J422", AV_PIX_FMT_YUVJ422P);
		f.insert("J440", AV_PIX_FMT_YUVJ440P);
		f.insert("J444", AV_PIX_FMT_YUVJ444P);
		f.insert("I40A", AV_PIX_FMT_YUVA420P);
		f.insert("I42A", AV_PIX_FMT_YUVA422P);
		f.insert("YUVA", AV_PIX_FMT_YUVA444P);
		f.insert("YA0L", AV_PIX_FMT_YUVA444P10LE);
		f.insert("YA0B", AV_PIX_FMT_YUVA444P10BE);
		f.insert("NV12", AV_PIX_FMT_NV12);
		f.insert("NV21", AV_PIX_FMT_NV21);
		f.insert("I09L", AV_PIX_FMT_YUV420P9LE);
		f.insert("I09B", AV_PIX_FMT_YUV420P9BE);
		f.insert("I29L", AV_PIX_FMT_YUV422P9LE);
		f.insert("I29B", AV_PIX_FMT_YUV422P9BE);
		f.insert("I49L", AV_PIX_FMT_YUV444P9LE);
		f.insert("I49B", AV_PIX_FMT_YUV444P9BE);
		f.insert("I0AL", AV_PIX_FMT_YUV420P10LE);
		f.insert("I0AB", AV_PIX_FMT_YUV420P10BE);
		f.insert("I2AL", AV_PIX_FMT_YUV422P10LE);
		f.insert("I2AB", AV_PIX_FMT_YUV422P10BE);
		f.insert("I4AL", AV_PIX_FMT_YUV444P10LE);
		f.insert("I4AB", AV_PIX_FMT_YUV444P10BE);
		f.insert("UYVY", AV_PIX_FMT_UYVY422);
		f.insert("YUYV", AV_PIX_FMT_YUYV422);
		f.insert("YUY2", AV_PIX_FMT_YUYV422);
	}
	chroma = chroma.toUpper();
	if (f.contains(chroma)){
	}
	else if (chroma == "YV12"){
		chroma = "I420";
	}
	else if (chroma == "NV16"){
		chroma = "NV12";
	}
	else if (chroma == "NV61"){
		chroma = "NV21";
	}
	else if (chroma == "VYUY" ||
		chroma == "YVYU" ||
		chroma == "V422" ||
		chroma == "CYUV"){
		chroma = "UYVY";
	}
	else if (chroma == "V210"){
		chroma = "I0AL";
	}
	else{
		chroma = "I420";
	}
	return f[chroma];
}
예제 #22
0
void StampBrush::drawPreviewLayer(const QVector<QPoint> &points)
{
    mPreviewMap.clear();

    if (mStamp.isEmpty() && !mIsWangFill)
        return;

    if (mIsRandom) {
        if (mRandomCellPicker.isEmpty())
            return;

        QRect bounds;
        for (const QPoint &p : points)
            bounds |= QRect(p, p);

        SharedMap preview = SharedMap::create(mapDocument()->map()->orientation(),
                                              bounds.size(),
                                              mapDocument()->map()->tileSize());

        std::unique_ptr<TileLayer> previewLayer {
            new TileLayer(QString(), bounds.topLeft(), bounds.size())
        };

        for (const QPoint &p : points) {
            const Cell &cell = mRandomCellPicker.pick();
            previewLayer->setCell(p.x() - bounds.left(),
                                  p.y() - bounds.top(),
                                  cell);
        }

        preview->addLayer(previewLayer.release());
        preview->addTilesets(preview->usedTilesets());
        mPreviewMap = preview;
    } else if (mIsWangFill) {
        if (!mWangSet)
            return;

        const TileLayer *tileLayer = currentTileLayer();
        if (!tileLayer)
            return;

        QRegion paintedRegion;
        for (const QPoint &p : points)
            paintedRegion += QRect(p, p);

        const QRect bounds = paintedRegion.boundingRect();
        SharedMap preview = SharedMap::create(mapDocument()->map()->orientation(),
                                              bounds.size(),
                                              mapDocument()->map()->tileSize());

        std::unique_ptr<TileLayer> previewLayer {
            new TileLayer(QString(), bounds.topLeft(), bounds.size())
        };

        WangFiller wangFiller(mWangSet,
                              dynamic_cast<StaggeredRenderer *>(mapDocument()->renderer()),
                              mapDocument()->map()->staggerAxis());

        for (const QPoint &p : points) {
            Cell cell = wangFiller.findFittingCell(*tileLayer,
                                                   *previewLayer,
                                                   paintedRegion,
                                                   p);

            previewLayer->setCell(p.x() - bounds.left(),
                                  p.y() - bounds.top(),
                                  cell);
        }

        preview->addLayer(previewLayer.release());
        preview->addTileset(mWangSet->tileset()->sharedPointer());
        mPreviewMap = preview;
    } else {
        QRegion paintedRegion;
        QVector<PaintOperation> operations;
        QHash<const Map *, QRegion> regionCache;
        QHash<const Map *, Map *> shiftedCopies;

        for (const QPoint &p : points) {
            Map *map = mStamp.randomVariation().map;
            mapDocument()->unifyTilesets(map, mMissingTilesets);

            Map::StaggerAxis mapStaggerAxis = mapDocument()->map()->staggerAxis();

            // if staggered map, makes sure stamp stays the same
            if (mapDocument()->map()->isStaggered()
                    && ((mapStaggerAxis == Map::StaggerY) ? map->height() > 1 : map->width() > 1)) {

                Map::StaggerIndex mapStaggerIndex = mapDocument()->map()->staggerIndex();
                Map::StaggerIndex stampStaggerIndex = map->staggerIndex();

                if (mapStaggerAxis == Map::StaggerY) {
                    bool topIsOdd = (p.y() - map->height() / 2) & 1;

                    if ((stampStaggerIndex == mapStaggerIndex) == topIsOdd) {
                        Map *shiftedMap = shiftedCopies.value(map);
                        if (!shiftedMap) {
                            shiftedMap = new Map(*map);
                            shiftedCopies.insert(map, shiftedMap);

                            LayerIterator it(shiftedMap, Layer::TileLayerType);
                            while (auto tileLayer = static_cast<TileLayer*>(it.next()))
                                shiftRows(tileLayer, stampStaggerIndex);
                        }
                        map = shiftedMap;
                    }
                } else {
                    bool leftIsOdd = (p.x() - map->width() / 2) & 1;

                    if ((stampStaggerIndex == mapStaggerIndex) == leftIsOdd) {
                        Map *shiftedMap = shiftedCopies.value(map);
                        if (!shiftedMap) {
                            shiftedMap = new Map(*map);
                            shiftedCopies.insert(map, shiftedMap);

                            LayerIterator it(shiftedMap, Layer::TileLayerType);
                            while (auto tileLayer = static_cast<TileLayer*>(it.next()))
                                shiftColumns(tileLayer, stampStaggerIndex);
                        }
                        map = shiftedMap;
                    }
                }
            }

            QRegion stampRegion;
            if (regionCache.contains(map)) {
                stampRegion = regionCache.value(map);
            } else {
                stampRegion = map->tileRegion();
                regionCache.insert(map, stampRegion);
            }

            QPoint centered(p.x() - map->width() / 2,
                            p.y() - map->height() / 2);

            const QRegion region = stampRegion.translated(centered.x(),
                                                          centered.y());
            if (!paintedRegion.intersects(region)) {
                paintedRegion += region;

                PaintOperation op = { centered, map };
                operations.append(op);
            }
        }

        const QRect bounds = paintedRegion.boundingRect();
        SharedMap preview = SharedMap::create(mapDocument()->map()->orientation(),
                                              bounds.size(),
                                              mapDocument()->map()->tileSize());

        for (const PaintOperation &op : operations) {
            LayerIterator layerIterator(op.stamp, Layer::TileLayerType);
            while (auto tileLayer = static_cast<TileLayer*>(layerIterator.next())) {
                TileLayer *target = findTileLayerByName(*preview, tileLayer->name());
                if (!target) {
                    target = new TileLayer(tileLayer->name(), bounds.topLeft(), bounds.size());
                    preview->addLayer(target);
                }
                target->merge(op.pos - bounds.topLeft() + tileLayer->position(), tileLayer);
            }
        }

        qDeleteAll(shiftedCopies);

        preview->addTilesets(preview->usedTilesets());
        mPreviewMap = preview;
    }
}
예제 #23
0
void Donations::showDonationsDetails() {
	QSettings settings;
	QSqlQuery query = createDonationsQuery();
	query.exec();
	
	// Clean the GridContainer
	QLayoutItem *child;
	while ((child = detailsLayout->takeAt(0)) != 0) {
		delete ((QLabel *)child->widget());
		delete child;
	}
	
	// Refill with Data
	QHash<QString, double> sum;
	QHash<QString, int> num;
	QString section;
	while (query.next()) {
		section = query.value(4).toString();
		if (!sum.contains(section)) {
			sum.insert(section, 0);
			num.insert(section, 0);
		}
		num.find(section).value()++;
		sum.find(section).value() += query.value(1).toDouble() / 2;
	}
	
	int row = 0;
	int ctotal = 0;
	double stotal = 0.0;
	QHash<QString, double>::const_iterator iter = sum.constBegin();
	while (iter != sum.constEnd()) {
		QLabel *t = new QLabel( tr("<b>Section %1</b>").arg(iter.key()) );
		detailsLayout->addWidget(t, row++, 0);
		
		stotal += iter.value();
		ctotal += num.find(iter.key()).value();
		
		QLabel *kp = new QLabel( tr("Payments:") );
		QLabel *vp = new QLabel( QString("%1").arg(num.find(iter.key()).value()) );
		kp->setAlignment(Qt::AlignRight);
		vp->setAlignment(Qt::AlignRight);
		detailsLayout->addWidget(kp, row, 0);
		detailsLayout->addWidget(vp, row++, 1);
		
		QLabel *kt = new QLabel( tr("Total:") );
		QLabel *vt = new QLabel( QString("%1").arg(iter.value(), 0, 'f', 2) );
		kt->setAlignment(Qt::AlignRight);
		vt->setAlignment(Qt::AlignRight);
		detailsLayout->addWidget(kt, row, 0);
		detailsLayout->addWidget(vt, row++, 1);
		iter++;
	}
	
	// Totals
	QLabel *kp = new QLabel( tr("<b>Payments:</b>") );
	QLabel *vp = new QLabel( QString("<b>%1</b>").arg(ctotal) );
	kp->setAlignment(Qt::AlignLeft);
	vp->setAlignment(Qt::AlignRight);
	detailsLayout->addWidget(kp, row, 0);
	detailsLayout->addWidget(vp, row++, 1);
	
	QLabel *kt = new QLabel( tr("<b>Total:</b>") );
	QLabel *vt = new QLabel( QString("<b>%1</b>").arg(stotal, 0, 'f', 2) );
	kt->setAlignment(Qt::AlignLeft);
	vt->setAlignment(Qt::AlignRight);
	detailsLayout->addWidget(kt, row, 0);
	detailsLayout->addWidget(vt, row++, 1);
}
QList<PlatformspecificRunningExecutableDataInterface *> PlatformSpecificProgramIdentifierHelper::getRunningExecutableDataForPathes(QStringList pathes)
{
    QList<PlatformspecificRunningExecutableDataInterface *> retList;

#if defined(Q_OS_WIN)

    HANDLE hProcessSnap;
    PROCESSENTRY32 pe32;

    // Take a snapshot of all processes in the system.
    hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
    if( hProcessSnap == INVALID_HANDLE_VALUE )
    {
        WLog("FAILED: CreateToolhelp32Snapshot (of processes)");
        return retList;
    }

    // Set the size of the structure before using it.
    pe32.dwSize = sizeof( PROCESSENTRY32 );

    // Retrieve information about the first process,
    // and exit if unsuccessful
    if( !Process32First( hProcessSnap, &pe32 ) )
    {
        WLog("FAILED: Process32First");
        CloseHandle( hProcessSnap );          // clean the snapshot object
        return retList;
    }

    QHash< QString, QList<DWORD> > fileProcHash;
    // Now walk the snapshot of processes
    do
    {
        QString processRelatedExe = QString::fromWCharArray(pe32.szExeFile);
//        DLogS << "Process related exe compare: " << processRelatedExe << relatedExeFileName;
        Q_FOREACH(QString currFilePath, pathes)
        {
            QFileInfo relatedExeFileInfo(currFilePath);
            QString relatedExeFullPath = relatedExeFileInfo.absoluteFilePath();
            QString relatedExeFileName = relatedExeFileInfo.fileName();

            if(processRelatedExe == relatedExeFileName)
            {
                DLogS << "Exe matches a running instance's exe-file: " << processRelatedExe << relatedExeFileName;
                if(PlatformSpecificProgramIdentifierHelper::_isExePathRelatedToProcess(pe32.th32ProcessID, relatedExeFullPath))
                {
                    QList<DWORD> relatedProcIds;
                    if( fileProcHash.contains(relatedExeFullPath) ) {
                        relatedProcIds = fileProcHash.value(relatedExeFullPath);
                    }
                    relatedProcIds.append(pe32.th32ProcessID);
                    fileProcHash[relatedExeFullPath] = relatedProcIds;
                }
            }
        }

    } while( Process32Next( hProcessSnap, &pe32 ) );

    CloseHandle( hProcessSnap );

    QHash< QString, QList<DWORD> >::const_iterator c_it = fileProcHash.constBegin();
    while (c_it != fileProcHash.constEnd()) {
        DLog("Running item: ") << c_it.key() << ":" << c_it.value();
        retList.append(new Win_RunningExecutableData(c_it.key(), c_it.value()));
        ++c_it;
    }

#elif defined(Q_OS_MAC)

    LOG_AS_NOT_IMPLEMENTED;

#endif

    return retList;
}
예제 #25
0
void QInotifyFileSystemWatcherEngine::readFromInotify()
{
    QMutexLocker locker(&mutex);

    // qDebug() << "QInotifyFileSystemWatcherEngine::readFromInotify";

    int buffSize = 0;
    ioctl(inotifyFd, FIONREAD, (char *) &buffSize);
    QVarLengthArray<char, 4096> buffer(buffSize);
    buffSize = read(inotifyFd, buffer.data(), buffSize);
    char *at = buffer.data();
    char * const end = at + buffSize;

    QHash<int, inotify_event *> eventForId;
    while (at < end) {
        inotify_event *event = reinterpret_cast<inotify_event *>(at);

        if (eventForId.contains(event->wd))
            eventForId[event->wd]->mask |= event->mask;
        else
            eventForId.insert(event->wd, event);

        at += sizeof(inotify_event) + event->len;
    }

    QHash<int, inotify_event *>::const_iterator it = eventForId.constBegin();
    while (it != eventForId.constEnd()) {
        const inotify_event &event = **it;
        ++it;

        // qDebug() << "inotify event, wd" << event.wd << "mask" << hex << event.mask;

        int id = event.wd;
        QString path = idToPath.value(id);
        if (path.isEmpty()) {
            // perhaps a directory?
            id = -id;
            path = idToPath.value(id);
            if (path.isEmpty())
                continue;
        }

        // qDebug() << "event for path" << path;

        if ((event.mask & (IN_DELETE_SELF | IN_MOVE_SELF | IN_UNMOUNT)) != 0) {
            pathToID.remove(path);
            idToPath.remove(id);
            inotify_rm_watch(inotifyFd, event.wd);

            if (id < 0)
                emit directoryChanged(path, true);
            else
                emit fileChanged(path, true);
        } else {
            if (id < 0)
                emit directoryChanged(path, false);
            else
                emit fileChanged(path, false);
        }
    }
}
예제 #26
0
bool QTextureGlyphCache::populate(QFontEngine *fontEngine, int numGlyphs, const glyph_t *glyphs,
                                                const QFixedPoint *positions)
{
#ifdef CACHE_DEBUG
    printf("Populating with %d glyphs\n", numGlyphs);
    qDebug() << " -> current transformation: " << m_transform;
#endif

    m_current_fontengine = fontEngine;
    const int margin = m_current_fontengine->glyphMargin(m_type);
    const int paddingDoubled = glyphPadding() * 2;

    bool supportsSubPixelPositions = fontEngine->supportsSubPixelPositions();
    if (fontEngine->m_subPixelPositionCount == 0) {
        if (!supportsSubPixelPositions) {
            fontEngine->m_subPixelPositionCount = 1;
        } else {
            int i = 0;
            while (fontEngine->m_subPixelPositionCount == 0 && i < numGlyphs)
                fontEngine->m_subPixelPositionCount = calculateSubPixelPositionCount(glyphs[i++]);
        }
    }

    QHash<GlyphAndSubPixelPosition, Coord> listItemCoordinates;
    int rowHeight = 0;

    QFontEngine::GlyphFormat format;
    switch (m_type) {
    case Raster_A8: format = QFontEngine::Format_A8; break;
    case Raster_RGBMask: format = QFontEngine::Format_A32; break;
    default: format = QFontEngine::Format_Mono; break;
    }

    // check each glyph for its metrics and get the required rowHeight.
    for (int i=0; i < numGlyphs; ++i) {
        const glyph_t glyph = glyphs[i];

        QFixed subPixelPosition;
        if (supportsSubPixelPositions) {
            QFixed x = positions != 0 ? positions[i].x : QFixed();
            subPixelPosition = fontEngine->subPixelPositionForX(x);
        }

        if (coords.contains(GlyphAndSubPixelPosition(glyph, subPixelPosition)))
            continue;
        if (listItemCoordinates.contains(GlyphAndSubPixelPosition(glyph, subPixelPosition)))
            continue;
        glyph_metrics_t metrics = fontEngine->alphaMapBoundingBox(glyph, subPixelPosition, m_transform, format);

#ifdef CACHE_DEBUG
        printf("(%4x): w=%.2f, h=%.2f, xoff=%.2f, yoff=%.2f, x=%.2f, y=%.2f\n",
               glyph,
               metrics.width.toReal(),
               metrics.height.toReal(),
               metrics.xoff.toReal(),
               metrics.yoff.toReal(),
               metrics.x.toReal(),
               metrics.y.toReal());
#endif        
        GlyphAndSubPixelPosition key(glyph, subPixelPosition);
        int glyph_width = metrics.width.ceil().toInt();
        int glyph_height = metrics.height.ceil().toInt();
        if (glyph_height == 0 || glyph_width == 0) {
            // Avoid multiple calls to boundingBox() for non-printable characters
            Coord c = { 0, 0, 0, 0, 0, 0 };
            coords.insert(key, c);
            continue;
        }
        glyph_width += margin * 2 + 4;
        glyph_height += margin * 2 + 4;
        // align to 8-bit boundary
        if (m_type == QFontEngineGlyphCache::Raster_Mono)
            glyph_width = (glyph_width+7)&~7;

        Coord c = { 0, 0, // will be filled in later
                    glyph_width,
                    glyph_height, // texture coords
                    metrics.x.truncate(),
                    -metrics.y.truncate() }; // baseline for horizontal scripts

        listItemCoordinates.insert(key, c);
        rowHeight = qMax(rowHeight, glyph_height);
    }
    if (listItemCoordinates.isEmpty())
        return true;

    rowHeight += margin * 2 + paddingDoubled;

    if (m_w == 0) {
        if (fontEngine->maxCharWidth() <= QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH)
            m_w = QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH;
        else
            m_w = qt_next_power_of_two(fontEngine->maxCharWidth());
    }

    // now actually use the coords and paint the wanted glyps into cache.
    QHash<GlyphAndSubPixelPosition, Coord>::iterator iter = listItemCoordinates.begin();
    int requiredWidth = m_w;
    while (iter != listItemCoordinates.end()) {
        Coord c = iter.value();

        m_currentRowHeight = qMax(m_currentRowHeight, c.h + margin * 2);

        if (m_cx + c.w > requiredWidth) {
            int new_width = requiredWidth*2;
            while (new_width < m_cx + c.w)
                new_width *= 2;
            if (new_width <= maxTextureWidth()) {
                requiredWidth = new_width;
            } else {
                // no room on the current line, start new glyph strip
                m_cx = 0;
                m_cy += m_currentRowHeight + paddingDoubled;
                m_currentRowHeight = c.h + margin * 2; // New row
            }
        }

        if (maxTextureHeight() > 0 && m_cy + c.h > maxTextureHeight()) {
            // We can't make a cache of the required size, so we bail out
            return false;
        }

        c.x = m_cx;
        c.y = m_cy;

        coords.insert(iter.key(), c);
        m_pendingGlyphs.insert(iter.key(), c);

        m_cx += c.w + paddingDoubled;
        ++iter;
    }
    return true;

}
void QmlProfilerEventChildrenModelProxy::loadData()
{
    clear();
    QmlProfilerDataModel *simpleModel = m_modelManager->qmlModel();
    if (simpleModel->isEmpty())
        return;

    QString rootEventName = tr("<program>");

    // for level computation
    QHash<int, qint64> endtimesPerLevel;
    int level = QmlDebug::Constants::QML_MIN_LEVEL;
    endtimesPerLevel[0] = 0;

    const QSet<QString> eventsInBindingLoop = m_eventsModel->eventsInBindingLoop();

    // compute parent-child relationship and call count
    QHash<int, QString> lastParent;
    const QVector<QmlProfilerDataModel::QmlEventData> eventList = simpleModel->getEvents();
    foreach (const QmlProfilerDataModel::QmlEventData &event, eventList) {
        // whitelist
        if (!m_eventsModel->eventTypeAccepted((QmlDebug::QmlEventType)event.eventType))
            continue;

        // level computation
        if (endtimesPerLevel[level] > event.startTime) {
            level++;
        } else {
            while (level > QmlDebug::Constants::QML_MIN_LEVEL && endtimesPerLevel[level-1] <= event.startTime)
                level--;
        }
        endtimesPerLevel[level] = event.startTime + event.duration;

        QString parentHash = rootEventName;
        QString eventHash = QmlProfilerDataModel::getHashString(event);

        if (level > QmlDebug::Constants::QML_MIN_LEVEL && lastParent.contains(level-1))
            parentHash = lastParent[level-1];

        // generate placeholder if needed
        if (!m_data.contains(parentHash))
            m_data.insert(parentHash, QmlEventRelativesMap());

        if (m_data[parentHash].contains(eventHash)) {
            QmlEventRelativesData *child = &(m_data[parentHash][eventHash]);
            child->calls++;
            child->duration += event.duration;
        } else {
            m_data[parentHash].insert(eventHash, QmlEventRelativesData());
            QmlEventRelativesData *child = &(m_data[parentHash][eventHash]);
            child->displayName = event.displayName;
            child->eventType = event.eventType;
            child->duration = event.duration;
            child->calls = 1;
            child->details = event.data.join(QLatin1String(""));
            child->isBindingLoop = eventsInBindingLoop.contains(parentHash);
        }

        // now lastparent is a string with the hash
        lastParent[level] = eventHash;
    }
}
예제 #28
0
static void
track(const QString &menuId, const QString &menuName, const QHash<QString,KService::Ptr>& includeList, const QHash<QString,KService::Ptr>& excludeList, const QHash<QString,KService::Ptr>& itemList, const QString &comment)
{
    if (itemList.contains(menuId))
        printf("%s: %s INCL %d EXCL %d\n", qPrintable(menuName), qPrintable(comment), includeList.contains(menuId) ? 1 : 0, excludeList.contains(menuId) ? 1 : 0);
}
예제 #29
0
bool SubScriptObject::hasPersistent(const QString& name){
	QString id = getScriptHash()+"/"+name;
	if (persistents.contains(id)) return true;
	return ConfigManagerInterface::getInstance()->existsOption("Script Data/"+id);
}
예제 #30
0
// ----------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	ctkCommandLineParser commandLine;
	commandLine.setArgumentPrefix("--", "-");

	commandLine.beginGroup(QString("Option"));
	commandLine.addArgument("help", "h", QVariant::Bool,
		"Display available command line arguments.");
	commandLine.addArgument("list-resources", "l", QVariant::String,
		"List all resources of an executable or library.");
	commandLine.addArgument("add-resource-bitmap", "", QVariant::StringList,
		"Add resource using the provided <path/to/exec/or/lib> <resourceName> and <path/to/resource>");
	commandLine.addArgument("update-resource-ico", "", QVariant::StringList,
		"Add resource using the provided <path/to/exec/or/lib> <resourceName> and <path/to/resource>");
	commandLine.addArgument("delete-resource", "", QVariant::StringList,
		"Delete resource using the provided <path/to/exec/or/lib> <resourceType> <resourceName>");
	commandLine.endGroup();

	bool ok;
	QHash<QString, QVariant> parsedArgs = commandLine.parseArguments(argc, argv, &ok);
	if (!ok)
		{
		QTextStream(stdout, QIODevice::WriteOnly) << "Error parsing arguments : " << commandLine.errorString() << "\n";
		return EXIT_FAILURE;
		}

	if(parsedArgs.contains("help") || parsedArgs.contains("h"))
		{
		QTextStream(stdout, QIODevice::WriteOnly) << commandLine.helpText() << "\n";
		return EXIT_SUCCESS;
		}

	char* exePath;
	HMODULE hExe;       // handle to existing .EXE file

	if(parsedArgs.contains("list-resources") || parsedArgs.contains("l"))
		{
		// Load the .EXE file that contains the dialog box you want to copy.
		exePath =
			(char*) malloc(strlen(parsedArgs.value("list-resources").toString().toStdString().c_str()) * sizeof(char));
		strcpy(exePath, parsedArgs.value("list-resources").toString().toStdString().c_str());
		hExe = loadLibraryEx(TEXT(exePath), NULL, LOAD_LIBRARY_AS_IMAGE_RESOURCE);

		// List all resources
		EnumResourceTypes(hExe, (ENUMRESTYPEPROC)EnumTypesFunc, 0);

		for (int i = 0; i < resources::Resources.size() ; ++i)
			{
			QTextStream(stdout, QIODevice::WriteOnly) << "Type : " << resources::Resources.at(i).Type <<  " -- " << resources::types[resources::Resources.at(i).Type.toInt()] << "\n";
			QTextStream(stdout, QIODevice::WriteOnly) << "\tName : " << resources::Resources.at(i).Name << "\n";
			QTextStream(stdout, QIODevice::WriteOnly) << "\t\tLang : " << resources::Resources.at(i).Lang << "\n";
			}

		// Clean up.
		if (!FreeLibrary(hExe))
			{
			QTextStream(stdout, QIODevice::WriteOnly) << "Could not free executable : " << exePath << "\n";
			return EXIT_FAILURE;
			}
		}

	else if(parsedArgs.contains("delete-resource"))
		{
		QStringList arguments = parsedArgs.value("delete-resource").toStringList();
		exePath = (char*) malloc(strlen(arguments.at(0).toStdString().c_str()) * sizeof(char));
		strcpy(exePath, arguments.at(0).toStdString().c_str());
		hExe = loadLibraryEx(TEXT(exePath), NULL, LOAD_LIBRARY_AS_IMAGE_RESOURCE);

		// List all resources
		EnumResourceTypes(hExe, (ENUMRESTYPEPROC)EnumTypesFunc, 0);
		FreeLibrary(hExe);

		bool resultat = removeResource(arguments.at(0), arguments.at(1), arguments.at(2));
		if(!resultat)
			{
			return EXIT_FAILURE;
			}
		}

	else if(parsedArgs.contains("add-resource-bitmap"))
		{
		QStringList arguments = parsedArgs.value("add-resource-bitmap").toStringList();

		bool result = addResourceBITMAP(arguments.at(0), arguments.at(1), arguments.at(2));
		if(!result)
			{
			QTextStream(stdout, QIODevice::WriteOnly) << "Resource bitmap couldn't be added.\n";
			return EXIT_FAILURE;
			}
		QTextStream(stdout, QIODevice::WriteOnly) << "Resource bitmap added.\n";
		return EXIT_SUCCESS;
		}

	else if(parsedArgs.contains("update-resource-ico"))
		{
		QStringList arguments = parsedArgs.value("update-resource-ico").toStringList();

		bool result = updateResourceICO(arguments.at(0), arguments.at(1), arguments.at(2));
		if(!result)
			{
			QTextStream(stdout, QIODevice::WriteOnly) << "Resource ico couldn't be updated.\n";
			return EXIT_FAILURE;
			}
		QTextStream(stdout, QIODevice::WriteOnly) << "Resource ico updated.\n";
		return EXIT_SUCCESS;
		}

  return EXIT_SUCCESS;
}