QgsGPSInformationWidget::QgsGPSInformationWidget( QgsMapCanvas * thepCanvas, QWidget * parent, Qt::WindowFlags f )
    : QWidget( parent, f )
    , mNmea( nullptr )
    , mpCanvas( thepCanvas )
{
  setupUi( this );

  mpLastLayer = nullptr;

  mLastGpsPosition = QgsPoint( 0.0, 0.0 );

  mpMapMarker = nullptr;
  mpRubberBand = nullptr;
  populateDevices();
  QWidget * mpHistogramWidget = mStackedWidget->widget( 1 );
#ifndef WITH_QWTPOLAR
  mBtnSatellites->setVisible( false );
#endif
  //
  // Set up the graph for signal strength
  //
  mpPlot = new QwtPlot( mpHistogramWidget );
  mpPlot->setAutoReplot( false );   // plot on demand
  //mpPlot->setTitle(QObject::tr("Signal Status"));
  //mpPlot->insertLegend(new QwtLegend(), QwtPlot::BottomLegend);
  // Set axis titles
  //mpPlot->setAxisTitle(QwtPlot::xBottom, QObject::tr("Satellite"));
  //mpPlot->setAxisTitle(QwtPlot::yLeft, QObject::tr("Value"));
  mpPlot->setAxisScale( QwtPlot::xBottom, 0, 20 );
  mpPlot->setAxisScale( QwtPlot::yLeft, 0, 100 );  // max is 50dB SNR, I believe - SLM
  // add a grid
  //QwtPlotGrid * mypGrid = new QwtPlotGrid();
  //mypGrid->attach( mpPlot );
  //display satellites first
  mpCurve = new QwtPlotCurve();
  mpCurve->setRenderHint( QwtPlotItem::RenderAntialiased );
  mpCurve->setPen( QPen( Qt::blue ) );
  mpCurve->setBrush( QBrush( Qt::blue ) );
  mpPlot->enableAxis( QwtPlot::yLeft, false );
  mpPlot->enableAxis( QwtPlot::xBottom, false );
  mpCurve->attach( mpPlot );
  //ensure all children get removed
  mpPlot->setAutoDelete( true );
  QVBoxLayout *mpHistogramLayout = new QVBoxLayout( mpHistogramWidget );
  mpHistogramLayout->setContentsMargins( 0, 0, 0, 0 );
  mpHistogramLayout->addWidget( mpPlot );
  mpHistogramWidget->setLayout( mpHistogramLayout );

  //
  // Set up the polar graph for satellite pos
  //
#ifdef WITH_QWTPOLAR
  QWidget * mpPolarWidget = mStackedWidget->widget( 2 );
  mpSatellitesWidget = new QwtPolarPlot( /*QwtText( tr( "Satellite View" ), QwtText::PlainText ),*/ mpPolarWidget );  // possible title for graph removed for now as it is too large in small windows
  mpSatellitesWidget->setAutoReplot( false );   // plot on demand (after all data has been handled)
  mpSatellitesWidget->setPlotBackground( Qt::white );
  // scales
  mpSatellitesWidget->setScale( QwtPolar::ScaleAzimuth,
                                360, //min - reverse the min/max values to get compass orientation - increasing clockwise
                                0, //max
                                90 //interval - just show cardinal and intermediate (NE, N, NW, etc.) compass points (in degrees)
                              );
  mpSatellitesWidget->setAzimuthOrigin( M_PI_2 );    // to get compass orientation - need to rotate 90 deg. ccw; this is in Radians (not indicated in QwtPolarPlot docs)

//  mpSatellitesWidget->setScaleMaxMinor( QwtPolar::ScaleRadius, 2 );  // seems unnecessary
  mpSatellitesWidget->setScale( QwtPolar::ScaleRadius,
                                90, //min - reverse the min/max to get 0 at edge, 90 at center
                                0, //max
                                45 //interval
                              );

  // grids, axes
  mpSatellitesGrid = new QwtPolarGrid();
  mpSatellitesGrid->setGridAttribute( QwtPolarGrid::AutoScaling, false );   // This fixes the issue of autoscaling on the Radius grid. It is ON by default AND is separate from the scaleData.doAutoScale in QwtPolarPlot::setScale(), etc. THIS IS VERY TRICKY!
  mpSatellitesGrid->setPen( QPen( Qt::black ) );
  QPen minorPen( Qt::gray );  // moved outside of for loop; NOTE setting the minor pen isn't necessary if the minor grids aren't shown
  for ( int scaleId = 0; scaleId < QwtPolar::ScaleCount; scaleId++ )
  {
    //mpSatellitesGrid->showGrid( scaleId );
    //mpSatellitesGrid->showMinorGrid(scaleId);
    mpSatellitesGrid->setMinorGridPen( scaleId, minorPen );
  }
//  mpSatellitesGrid->setAxisPen( QwtPolar::AxisAzimuth, QPen( Qt::black ) );

  mpSatellitesGrid->showAxis( QwtPolar::AxisAzimuth, true );
  mpSatellitesGrid->showAxis( QwtPolar::AxisLeft, false ); //alt axis
  mpSatellitesGrid->showAxis( QwtPolar::AxisRight, false );//alt axis
  mpSatellitesGrid->showAxis( QwtPolar::AxisTop, false );//alt axis
  mpSatellitesGrid->showAxis( QwtPolar::AxisBottom, false );//alt axis
  mpSatellitesGrid->showGrid( QwtPolar::ScaleAzimuth, false ); // hide the grid; just show ticks at edge
  mpSatellitesGrid->showGrid( QwtPolar::ScaleRadius, true );
//  mpSatellitesGrid->showMinorGrid( QwtPolar::ScaleAzimuth, true );
  mpSatellitesGrid->showMinorGrid( QwtPolar::ScaleRadius, true );   // for 22.5, 67.5 degree circles
  mpSatellitesGrid->attach( mpSatellitesWidget );

  //QwtLegend *legend = new QwtLegend;
  //mpSatellitesWidget->insertLegend(legend, QwtPolarPlot::BottomLegend);
  QVBoxLayout *mpPolarLayout = new QVBoxLayout( mpPolarWidget );
  mpPolarLayout->setContentsMargins( 0, 0, 0, 0 );
  mpPolarLayout->addWidget( mpSatellitesWidget );
  mpPolarWidget->setLayout( mpPolarLayout );

  // replot on command
  mpSatellitesWidget->replot();
#endif
  mpPlot->replot();

  // Restore state
  QSettings mySettings;
  mGroupShowMarker->setChecked( mySettings.value( QStringLiteral( "/gps/showMarker" ), "true" ).toBool() );
  mSliderMarkerSize->setValue( mySettings.value( QStringLiteral( "/gps/markerSize" ), "12" ).toInt() );
  mSpinTrackWidth->setValue( mySettings.value( QStringLiteral( "/gps/trackWidth" ), "2" ).toInt() );
  mTrackColor = mySettings.value( QStringLiteral( "/gps/trackColor" ), QColor( Qt::red ) ).value<QColor>();
  QString myPortMode = mySettings.value( QStringLiteral( "/gps/portMode" ), "scanPorts" ).toString();

  mSpinMapExtentMultiplier->setValue( mySettings.value( QStringLiteral( "/gps/mapExtentMultiplier" ), "50" ).toInt() );
  mDateTimeFormat = mySettings.value( QStringLiteral( "/gps/dateTimeFormat" ), "" ).toString(); // zero-length string signifies default format

  mGpsdHost->setText( mySettings.value( QStringLiteral( "/gps/gpsdHost" ), "localhost" ).toString() );
  mGpsdPort->setText( mySettings.value( QStringLiteral( "/gps/gpsdPort" ), 2947 ).toString() );
  mGpsdDevice->setText( mySettings.value( QStringLiteral( "/gps/gpsdDevice" ) ).toString() );

  //port mode
  if ( myPortMode == QLatin1String( "scanPorts" ) )
  {
    mRadAutodetect->setChecked( true );
  }
  else if ( myPortMode == QLatin1String( "internalGPS" ) )
  {
    mRadInternal->setChecked( true );
  }
  else if ( myPortMode == QLatin1String( "explicitPort" ) )
  {
    mRadUserPath->setChecked( true );
  }
  else if ( myPortMode == QLatin1String( "gpsd" ) )
  {
    mRadGpsd->setChecked( true );
  }
  //disable the internal port method if build is without QtLocation
#ifndef HAVE_QT_MOBILITY_LOCATION
  mRadInternal->setDisabled( true );
  mRadAutodetect->setChecked( true );
#endif

  //auto digitising behaviour
  mCbxAutoAddVertices->setChecked( mySettings.value( QStringLiteral( "/gps/autoAddVertices" ), "false" ).toBool() );

  mCbxAutoCommit->setChecked( mySettings.value( QStringLiteral( "/gps/autoCommit" ), "false" ).toBool() );

  //pan mode
  QString myPanMode = mySettings.value( QStringLiteral( "/gps/panMode" ), "recenterWhenNeeded" ).toString();
  if ( myPanMode == QLatin1String( "none" ) )
  {
    radNeverRecenter->setChecked( true );
  }
  else if ( myPanMode == QLatin1String( "recenterAlways" ) )
  {
    radRecenterMap->setChecked( true );
  }
  else
  {
    radRecenterWhenNeeded->setChecked( true );
  }

  mWgs84CRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) );

  mBtnDebug->setVisible( mySettings.value( QStringLiteral( "/gps/showDebug" ), "false" ).toBool() );  // use a registry setting to control - power users/devs could set it

  // status = unknown
  setStatusIndicator( NoData );

  //SLM - added functionality
  mLogFile = nullptr;

  connect( QgisApp::instance()->layerTreeView(), SIGNAL( currentLayerChanged( QgsMapLayer* ) ),
           this, SLOT( updateCloseFeatureButton( QgsMapLayer* ) ) );

  mStackedWidget->setCurrentIndex( 3 ); // force to Options
  mBtnPosition->setFocus( Qt::TabFocusReason );
}
Beispiel #2
0
void dxf2shpConverterGui::restoreState()
{
  QSettings settings;
  restoreGeometry( settings.value( "/Plugin-DXF/geometry" ).toByteArray() );
}
QgsRasterRenderer* QgsRasterRendererRegistry::defaultRendererForDrawingStyle( const QgsRaster::DrawingStyle&  theDrawingStyle, QgsRasterDataProvider* provider ) const
{
  if ( !provider || provider->bandCount() < 1 )
  {
    return nullptr;
  }


  QgsRasterRenderer* renderer = nullptr;
  switch ( theDrawingStyle )
  {
    case QgsRaster::PalettedColor:
    {
      int grayBand = 1; //reasonable default
      QList<QgsColorRampShader::ColorRampItem> colorEntries = provider->colorTable( grayBand );

      //go through list and take maximum value (it could be that entries don't start at 0 or indices are not contiguous)
      int colorArraySize = 0;
      QList<QgsColorRampShader::ColorRampItem>::const_iterator colorIt = colorEntries.constBegin();
      for ( ; colorIt != colorEntries.constEnd(); ++colorIt )
      {
        if ( colorIt->value > colorArraySize )
        {
          colorArraySize = ( int )( colorIt->value );
        }
      }

      colorArraySize += 1; //usually starts at 0
      QColor* colorArray = new QColor[ colorArraySize ];
      colorIt = colorEntries.constBegin();
      QVector<QString> labels;
      for ( ; colorIt != colorEntries.constEnd(); ++colorIt )
      {
        int idx = ( int )( colorIt->value );
        colorArray[idx] = colorIt->color;
        if ( !colorIt->label.isEmpty() )
        {
          if ( labels.size() <= idx ) labels.resize( idx + 1 );
          labels[idx] = colorIt->label;
        }
      }

      renderer = new QgsPalettedRasterRenderer( provider,
          grayBand,
          colorArray,
          colorArraySize,
          labels );
    }
    break;
    case QgsRaster::MultiBandSingleBandGray:
    case QgsRaster::SingleBandGray:
    {
      int grayBand = 1;
      renderer = new QgsSingleBandGrayRenderer( provider, grayBand );

      QgsContrastEnhancement* ce = new QgsContrastEnhancement(( QGis::DataType )(
            provider->dataType( grayBand ) ) );

// Default contrast enhancement is set from QgsRasterLayer, it has already setContrastEnhancementAlgorithm(). Default enhancement must only be set if default style was not loaded (to avoid stats calculation).
      (( QgsSingleBandGrayRenderer* )renderer )->setContrastEnhancement( ce );
      break;
    }
    case QgsRaster::SingleBandPseudoColor:
    {
      int bandNo = 1;
      double minValue = 0;
      double maxValue = 0;
      // TODO: avoid calculating statistics if not necessary (default style loaded)
      minMaxValuesForBand( bandNo, provider, minValue, maxValue );
      QgsRasterShader* shader = new QgsRasterShader( minValue, maxValue );
      renderer = new QgsSingleBandPseudoColorRenderer( provider, bandNo, shader );
      break;
    }
    case QgsRaster::MultiBandColor:
    {
      QSettings s;

      int redBand = s.value( "/Raster/defaultRedBand", 1 ).toInt();
      if ( redBand < 0 || redBand > provider->bandCount() )
      {
        redBand = -1;
      }
      int greenBand = s.value( "/Raster/defaultGreenBand", 2 ).toInt();
      if ( greenBand < 0 || greenBand > provider->bandCount() )
      {
        greenBand = -1;
      }
      int blueBand = s.value( "/Raster/defaultBlueBand", 3 ).toInt();
      if ( blueBand < 0 || blueBand > provider->bandCount() )
      {
        blueBand = -1;
      }

      renderer = new QgsMultiBandColorRenderer( provider, redBand, greenBand, blueBand );
      break;
    }
    case QgsRaster::SingleBandColorDataStyle:
    {
      renderer = new QgsSingleBandColorDataRenderer( provider, 1 );
      break;
    }
    default:
      return nullptr;
  }

  QgsRasterTransparency* tr = new QgsRasterTransparency(); //renderer takes ownership
  int bandCount = renderer->usesBands().size();
  if ( bandCount == 1 )
  {
    QList<QgsRasterTransparency::TransparentSingleValuePixel> transparentSingleList;
    tr->setTransparentSingleValuePixelList( transparentSingleList );
  }
  else if ( bandCount == 3 )
  {
    QList<QgsRasterTransparency::TransparentThreeValuePixel> transparentThreeValueList;
    tr->setTransparentThreeValuePixelList( transparentThreeValueList );
  }
  renderer->setRasterTransparency( tr );
  return renderer;
}
QList<QgsMapToolIdentify::IdentifyResult> QgsMapToolIdentify::identify( int x, int y, IdentifyMode mode, QList<QgsMapLayer*> layerList, LayerType layerType )
{
  QList<IdentifyResult> results;

  mLastPoint = mCanvas->getCoordinateTransform()->toMapCoordinates( x, y );
  mLastExtent = mCanvas->extent();
  mLastMapUnitsPerPixel = mCanvas->mapUnitsPerPixel();

  if ( !mCanvas || mCanvas->isDrawing() )
  {
    return results;
  }

  if ( mode == DefaultQgsSetting )
  {
    QSettings settings;
    mode = static_cast<IdentifyMode>( settings.value( "/Map/identifyMode", 0 ).toInt() );
  }

  if ( mode == ActiveLayer && layerList.isEmpty() )
  {
    QgsMapLayer *layer = mCanvas->currentLayer();

    if ( !layer )
    {
      emit identifyMessage( tr( "No active layer. To identify features, you must choose an active layer." ) );
      return results;
    }

    QApplication::setOverrideCursor( Qt::WaitCursor );

    identifyLayer( &results, layer, mLastPoint, mLastExtent, mLastMapUnitsPerPixel, layerType );
  }
  else
  {
    QApplication::setOverrideCursor( Qt::WaitCursor );

    QStringList noIdentifyLayerIdList = QgsProject::instance()->readListEntry( "Identify", "/disabledLayers" );

    int layerCount;
    if ( layerList.isEmpty() )
      layerCount = mCanvas->layerCount();
    else
      layerCount = layerList.count();


    for ( int i = 0; i < layerCount; i++ )
    {

      QgsMapLayer *layer ;
      if ( layerList.isEmpty() )
        layer = mCanvas->layer( i );
      else
        layer = layerList.value( i );

      emit identifyProgress( i, mCanvas->layerCount() );
      emit identifyMessage( tr( "Identifying on %1..." ).arg( layer->name() ) );

      if ( noIdentifyLayerIdList.contains( layer->id() ) )
        continue;

      if ( identifyLayer( &results, layer,  mLastPoint, mLastExtent, mLastMapUnitsPerPixel, layerType ) )
      {
        if ( mode == TopDownStopAtFirst )
          break;
      }
    }

    emit identifyProgress( mCanvas->layerCount(), mCanvas->layerCount() );
    emit identifyMessage( tr( "Identifying done." ) );
  }

  QApplication::restoreOverrideCursor();

  return results;
}
ServerChoice::ServerChoice(TeamHolder* team) :
    ui(new Ui::ServerChoice), wasConnected(false), team(team)
{
    ui->setupUi(this);
    ui->announcement->hide();

    ServerChoiceModel *model = new ServerChoiceModel();
    model->setParent(ui->serverList);
    filter = new QSortFilterProxyModel(ui->serverList);
    filter->setSourceModel(model);
    filter->setSortRole(ServerChoiceModel::SortRole);
    ui->serverList->setModel(filter);

    connect(ui->description, SIGNAL(anchorClicked(QUrl)), SLOT(anchorClicked(QUrl)));

    QSettings settings;

    registry_connection = new Analyzer(true);
    connect(registry_connection, SIGNAL(connected()), SLOT(connected()));

    registry_connection->connectTo(
        settings.value("ServerChoice/RegistryServer", "registry.pokemon-online.eu").toString(),
        settings.value("ServerChoice/RegistryPort", 5090).toUInt()
    );
    registry_connection->setParent(this);

    ui->switchPort->setIcon(QApplication::style()->standardIcon(QStyle::SP_BrowserReload));

    connect(registry_connection, SIGNAL(connectionError(int,QString)), SLOT(connectionError(int , QString)));
    connect(registry_connection, SIGNAL(regAnnouncementReceived(QString)), ui->announcement, SLOT(setText(QString)));
    connect(registry_connection, SIGNAL(regAnnouncementReceived(QString)), ui->announcement, SLOT(show()));

    connect(registry_connection, SIGNAL(serverReceived(ServerInfo)), model, SLOT(addServer(ServerInfo)));
    connect(this, SIGNAL(clearList()), model, SLOT(clear()));
    connect(registry_connection, SIGNAL(serverReceived(ServerInfo)), SLOT(serverAdded()));

    //TO-DO: Make  the item 0 un-resizable and unselectable - Latios

    ui->serverList->setColumnWidth(0, settings.value("ServerChoice/PasswordProtectedWidth", 26).toInt());
    ui->serverList->setColumnWidth(1, settings.value("ServerChoice/ServerNameWidth", 152).toInt());
    if (settings.contains("ServerChoice/PlayersInfoWidth")) {
        ui->serverList->setColumnWidth(2, settings.value("ServerChoice/PlayersInfoWidth").toInt());
    }
    ui->serverList->horizontalHeader()->setStretchLastSection(true);

    connect(ui->serverList, SIGNAL(activated(QModelIndex)), SLOT(regServerChosen(QModelIndex)));
    connect(ui->serverList, SIGNAL(currentCellChanged(QModelIndex)), SLOT(showDetails(QModelIndex)));

    ui->nameEdit->setText(team->name());
    ui->advServerEdit->addItem(settings.value("ServerChoice/DefaultServer").toString());

    connect(ui->nameEdit, SIGNAL(returnPressed()), SLOT(advServerChosen()));
    connect(ui->advServerEdit->lineEdit(), SIGNAL(returnPressed()), SLOT(advServerChosen()));

    QCompleter *completer = new QCompleter(ui->advServerEdit);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    QStringList res = settings.value("ServerChoice/SavedServers").toStringList();

    foreach (QString r, res) {
        if (r.contains("-")) {
            savedServers.push_back(QStringList() << r.section("-", -1).trimmed() << r.section("-", 0, -2).trimmed());
        } else {
            savedServers.push_back(QStringList() << r << "");
        }
    }

    QStringListModel *m = new QStringListModel(res, completer);

    completer->setModel(m);
    ui->advServerEdit->setCompleter(completer);
    ui->advServerEdit->setModel(m);

    connect(ui->teambuilder, SIGNAL(clicked()), SIGNAL(teambuilder()));
    connect(ui->advancedConnection, SIGNAL(clicked()), SLOT(advServerChosen()));

    QTimer *t = new QTimer(this);
    t->singleShot(5000, this, SLOT(timeout()));

#if QT_VERSION >= QT_VERSION_CHECK(4,8,0)
    ui->serverList->sortByColumn(ServerChoiceModel::Players, Qt::SortOrder(filter->headerData(ServerChoiceModel::Players, Qt::Horizontal, Qt::InitialSortOrderRole).toInt()));
#else
    ui->serverList->sortByColumn(ServerChoiceModel::Players, Qt::DescendingOrder);
#endif
}
CoinControlDialog::CoinControlDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CoinControlDialog),
    model(0)
{
    ui->setupUi(this);
    
    /* Open CSS when configured */
    this->setStyleSheet(GUIUtil::loadStyleSheet());

    // context menu actions
    QAction *copyAddressAction = new QAction(tr("Copy address"), this);
    QAction *copyLabelAction = new QAction(tr("Copy label"), this);
    QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
             copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this);  // we need to enable/disable this
             lockAction = new QAction(tr("Lock unspent"), this);                        // we need to enable/disable this
             unlockAction = new QAction(tr("Unlock unspent"), this);                    // we need to enable/disable this

    // context menu
    contextMenu = new QMenu();
    contextMenu->addAction(copyAddressAction);
    contextMenu->addAction(copyLabelAction);
    contextMenu->addAction(copyAmountAction);
    contextMenu->addAction(copyTransactionHashAction);
    contextMenu->addSeparator();
    contextMenu->addAction(lockAction);
    contextMenu->addAction(unlockAction);

    // context menu signals
    connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
    connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
    connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
    connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
    connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash()));
    connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin()));
    connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin()));

    // clipboard actions
    QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
    QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
    QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
    QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
    QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
    QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this);
    QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this);
    QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);

    connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity()));
    connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount()));
    connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee()));
    connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee()));
    connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes()));
    connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority()));
    connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput()));
    connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange()));

    ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
    ui->labelCoinControlAmount->addAction(clipboardAmountAction);
    ui->labelCoinControlFee->addAction(clipboardFeeAction);
    ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
    ui->labelCoinControlBytes->addAction(clipboardBytesAction);
    ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
    ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
    ui->labelCoinControlChange->addAction(clipboardChangeAction);

    // toggle tree/list mode
    connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool)));
    connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool)));

    // click on checkbox
    connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int)));

    // click on header
#if QT_VERSION < 0x050000
    ui->treeWidget->header()->setClickable(true);
#else
    ui->treeWidget->header()->setSectionsClickable(true);
#endif
    connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int)));

    // ok button
    connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));

    // (un)select all
    connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked()));

    // Toggle lock state
    connect(ui->pushButtonToggleLock, SIGNAL(clicked()), this, SLOT(buttonToggleLockClicked()));

    // change coin control first column label due Qt4 bug. 
    // see https://github.com/bitcoin/bitcoin/issues/5716
    ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString());

    ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84);
    ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100);
    ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170);
    ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 190);
    ui->treeWidget->setColumnWidth(COLUMN_DARKSEND_ROUNDS, 88);
    ui->treeWidget->setColumnWidth(COLUMN_DATE, 80);
    ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100);
    ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100);
    ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true);         // store transacton hash in this column, but dont show it
    ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true);     // store vout index in this column, but dont show it
    ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true);   // store amount int64 in this column, but dont show it
    ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); // store priority int64 in this column, but dont show it
    ui->treeWidget->setColumnHidden(COLUMN_DATE_INT64, true);     // store date int64 in this column, but dont show it

    // default view is sorted by amount desc
    sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder);

    // restore list mode and sortorder as a convenience feature
    QSettings settings;
    if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool())
        ui->radioTreeMode->click();
    if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder"))
        sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt()));
}
Beispiel #7
0
int main(int argc, char** argv)
{
#ifdef ENABLE_CRASH_REPORTER
    getCrashReporterPath(
        crash_reporter_path,
        sizeof(crash_reporter_path)/sizeof(crash_reporter_path[0])
    );

    google_breakpad::ExceptionHandler eh(
        QDir::tempPath().toStdWString().c_str(), 0, &crashCallback,
        0, google_breakpad::ExceptionHandler::HANDLER_ALL
    );
#endif

    Application app(argc, argv);

#ifdef _WIN32
    // Get rid of all references to Qt's installation directory.
    app.setLibraryPaths(QStringList(app.applicationDirPath()));
#endif

    // parse command line arguments
    CommandLine cli(app.arguments());
    CommandLine::set(cli);

    if (cli.hasHelp()) {
        cli.printHelp();
        return 0;
    }

    QString const translation("scantailor_"+QLocale::system().name());
    QTranslator translator;

    // Try loading from the current directory.
    if (!translator.load(translation)) {
        // Now try loading from where it's supposed to be.
        QString path(QString::fromUtf8(TRANSLATIONS_DIR_ABS));
        path += QChar('/');
        path += translation;
        if (!translator.load(path)) {
            path = QString::fromUtf8(TRANSLATIONS_DIR_REL);
            path += QChar('/');
            path += translation;
            translator.load(path);
        }
    }

    app.installTranslator(&translator);

    // This information is used by QSettings.
    app.setApplicationName("Scan Tailor");
    app.setOrganizationName("Scan Tailor");
    app.setOrganizationDomain("scantailor.sourceforge.net");
    QSettings settings;

    PngMetadataLoader::registerMyself();
    TiffMetadataLoader::registerMyself();
    JpegMetadataLoader::registerMyself();

    MainWindow* main_wnd = new MainWindow();
    main_wnd->setAttribute(Qt::WA_DeleteOnClose);
    if (settings.value("mainWindow/maximized") == false) {
        main_wnd->show();
    } else {
        main_wnd->showMaximized();
    }

    if (!cli.projectFile().isEmpty()) {
        main_wnd->openProject(cli.projectFile());
    }

    return app.exec();
}
Beispiel #8
0
QString Helpers::getSettingsUserName(void) const
{
    QSettings s;
    return s.value("user/name").toString();
}
Beispiel #9
0
QString Helpers::getSettingsPassword(void) const
{
    QSettings s;
    return s.value("user/passw").toString();
}
Beispiel #10
0
bool Helpers::isAutoLogin(void) const
{
    QSettings s;
    return s.value("config/autologin", false).toBool();
}
Beispiel #11
0
bool Helpers::isRememberLogin(void) const
{
    QSettings s;
    return s.value("user/remember", false).toBool();
}
void StelMovementMgr::init()
{
	QSettings* conf = StelApp::getInstance().getSettings();
	objectMgr = GETSTELMODULE(StelObjectMgr);
	Q_ASSERT(conf);
	Q_ASSERT(objectMgr);
	connect(objectMgr, SIGNAL(selectedObjectChanged(StelModule::StelModuleSelectAction)),
			this, SLOT(selectedObjectChange(StelModule::StelModuleSelectAction)));

	movementsSpeedFactor=1.;
	flagEnableMoveAtScreenEdge = conf->value("navigation/flag_enable_move_at_screen_edge",false).toBool();
	mouseZoomSpeed = conf->value("navigation/mouse_zoom",30).toInt();
	flagEnableZoomKeys = conf->value("navigation/flag_enable_zoom_keys").toBool();
	flagEnableMoveKeys = conf->value("navigation/flag_enable_move_keys").toBool();
	keyMoveSpeed = conf->value("navigation/move_speed",0.0004f).toFloat();
	keyZoomSpeed = conf->value("navigation/zoom_speed", 0.0004f).toFloat();
	autoMoveDuration = conf->value ("navigation/auto_move_duration",1.5f).toFloat();
	flagManualZoom = conf->value("navigation/flag_manual_zoom").toBool();
	flagAutoZoomOutResetsDirection = conf->value("navigation/auto_zoom_out_resets_direction", true).toBool();
	flagEnableMouseNavigation = conf->value("navigation/flag_enable_mouse_navigation",true).toBool();

	minFov = conf->value("navigation/min_fov",0.001389).toDouble(); // default: minimal FOV = 5"
	maxFov = 100.;
	initFov = conf->value("navigation/init_fov",60.f).toFloat();
	currentFov = initFov;
	setInitConstellationIntensity(conf->value("viewing/constellation_art_intensity", 0.5f).toFloat());

	// With a special code of init_view_position=x/y/2 you can set zenith into the center and atan2(x/y) to bottom of screen.
	// examples: 1/0->0             (-1/0)
	//           -1/0 ->180         (1/0)
	//            0/-1 --> 90       (0/-1)
	//            0/1  ->270        (0/1)
	Vec3f tmp = StelUtils::strToVec3f(conf->value("navigation/init_view_pos").toString());
	if (tmp[2]==2)
	{
		initViewPos.set(0., 0., 1.);
		setViewUpVector(Vec3d(tmp[0], tmp[1], 0.));
		setViewDirectionJ2000(core->altAzToJ2000(Vec3d(0., 0., 1.), StelCore::RefractionOff));
	}
	else
	{
		initViewPos.set(tmp[0], tmp[1], tmp[2]);
		viewDirectionJ2000 = core->altAzToJ2000(initViewPos, StelCore::RefractionOff);
	}

	QString tmpstr = conf->value("navigation/viewing_mode", "horizon").toString();
	if (tmpstr=="equator")
		setMountMode(StelMovementMgr::MountEquinoxEquatorial);
	else
	{
		if (tmpstr=="horizon")
			setMountMode(StelMovementMgr::MountAltAzimuthal);
		else
		{
			qWarning() << "ERROR: Unknown viewing mode type: " << tmpstr;
			setMountMode(StelMovementMgr::MountEquinoxEquatorial);
		}
	}

	QString movementGroup = N_("Movement and Selection");
	addAction("actionSwitch_Equatorial_Mount", N_("Miscellaneous"), N_("Switch between equatorial and azimuthal mount"), "equatorialMount", "Ctrl+M");
	addAction("actionGoto_Selected_Object", movementGroup, N_("Center on selected object"), "setFlagTracking()", "Space");
	addAction("actionZoom_In_Auto", movementGroup, N_("Zoom in on selected object"), "autoZoomIn()", "/");
	addAction("actionZoom_Out_Auto", movementGroup, N_("Zoom out"), "autoZoomOut()", "\\");
	addAction("actionSet_Tracking", movementGroup, N_("Track object"), "tracking", "T");
}
void PCycleSettings::loadSettings()
{
    QSettings settings;
    m_iRSpd1 = settings.value("RSpd1",RAISE1).toInt();
    m_iLSpd1 = settings.value("LSpd1",LOWER1).toInt();
    m_iCloseSpd1 = settings.value("CloseSpd1",CLOSE1).toInt();
    m_iOpenSpd1 = settings.value("OpenSpd1",OPEN1).toInt();
    m_dBreatheClosed1 = settings.value("BreatheClosed1",BREATHE1).toDouble();
    m_dSettleOpen1 = settings.value("SettleOpen1",SETTLE1).toDouble();
    m_dOverLift1 = settings.value("OverLift1",OVERLIFT1).toDouble();

    m_iRSpd2 = settings.value("RSpd2",RAISE2).toInt();
    m_iLSpd2 = settings.value("LSpd2",LOWER2).toInt();
    m_iCloseSpd2 = settings.value("CloseSpd2",CLOSE2).toInt();
    m_iOpenSpd2 = settings.value("OpenSpd2",OPEN2).toInt();
    m_dBreatheClosed2 = settings.value("BreatheClosed2",BREATHE2).toDouble();
    m_dSettleOpen2 = settings.value("SettleOpen2",SETTLE2).toDouble();
    m_dOverLift2 = settings.value("OverLift2",OVERLIFT2).toDouble();

    m_dBTClearInMM = settings.value("BTClearInMM",CUTOFF).toDouble();

    m_dHardZDownMM = settings.value("HardDownZMM",HARDDOWN).toDouble();
    m_dZFlushMM    = settings.value("ZFlushMM",   UP2FLUSH).toDouble();
}
Beispiel #14
0
 void CustomColor::readSettings(QSettings &settings)
 {
   Color::setFromQColor(settings.value("customcolor", QColor(Qt::white)).value<QColor>());
 }
void ccRasterizeTool::generateRaster() const
{
#ifdef CC_GDAL_SUPPORT

	if (!m_cloud || !m_grid.isValid())
		return;

	GDALAllRegister();
	ccLog::PrintDebug("(GDAL drivers: %i)", GetGDALDriverManager()->GetDriverCount());

	const char *pszFormat = "GTiff";
	GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat);
	if (!poDriver)
	{
		ccLog::Error("[GDAL] Driver %s is not supported", pszFormat);
		return;
	}

	char** papszMetadata = poDriver->GetMetadata();
	if( !CSLFetchBoolean( papszMetadata, GDAL_DCAP_CREATE, FALSE ) )
	{
		ccLog::Error("[GDAL] Driver %s doesn't support Create() method", pszFormat);
		return;
	}

	//which (and how many) bands shall we create?
	bool heightBand = true; //height by default
	bool densityBand = false;
	bool allSFBands = false;
	int sfBandIndex = -1; //scalar field index
	int totalBands = 0;

	bool interpolateSF = (getTypeOfSFInterpolation() != INVALID_PROJECTION_TYPE);
	ccPointCloud* pc = m_cloud->isA(CC_TYPES::POINT_CLOUD) ? static_cast<ccPointCloud*>(m_cloud) : 0;

	bool hasSF =  interpolateSF && pc && !m_grid.scalarFields.empty();
	
	RasterExportOptionsDlg reoDlg;
	reoDlg.dimensionsLabel->setText(QString("%1 x %2").arg(m_grid.width).arg(m_grid.height));
	reoDlg.exportHeightsCheckBox->setChecked(heightBand);
	reoDlg.exportDensityCheckBox->setChecked(densityBand);
	reoDlg.exportDisplayedSFCheckBox->setEnabled(hasSF);
	reoDlg.exportAllSFCheckBox->setEnabled(hasSF);
	reoDlg.exportAllSFCheckBox->setChecked(allSFBands);

	if (!reoDlg.exec())
		return;

	//we ask the output filename AFTER displaying the export parameters ;)
	QString outputFilename;
	{
		QSettings settings;
		settings.beginGroup(ccPS::HeightGridGeneration());
		QString imageSavePath = settings.value("savePathImage",QApplication::applicationDirPath()).toString();
		outputFilename = QFileDialog::getSaveFileName(0,"Save height grid raster",imageSavePath+QString("/raster.tif"),"geotiff (*.tif)");

		if (outputFilename.isNull())
			return;

		//save current export path to persistent settings
		settings.setValue("savePathImage",QFileInfo(outputFilename).absolutePath());
	}

	heightBand = reoDlg.exportHeightsCheckBox->isChecked();
	densityBand = reoDlg.exportDensityCheckBox->isChecked();
	if (hasSF)
	{
		assert(pc);
		allSFBands = reoDlg.exportAllSFCheckBox->isChecked() && hasSF;
		if (!allSFBands && reoDlg.exportDisplayedSFCheckBox->isChecked())
		{
			sfBandIndex = pc->getCurrentDisplayedScalarFieldIndex();
			if (sfBandIndex < 0)
				ccLog::Warning("[Rasterize] Cloud has no active (displayed) SF!");
		}
	}

	totalBands = heightBand ? 1 : 0;
	if (densityBand)
	{
		++totalBands;
	}
	if (allSFBands)
	{
		assert(hasSF);
		for (size_t i=0; i<m_grid.scalarFields.size(); ++i)
			if (m_grid.scalarFields[i])
				++totalBands;
	}
	else if (sfBandIndex >= 0)
	{
		++totalBands;
	}
	
	if (totalBands == 0)
	{
		ccLog::Warning("[Rasterize] Warning, can't output a raster with no band! (check export parameters)");
		return;
	}

	//data type
	GDALDataType dataType = (std::max(sizeof(PointCoordinateType),sizeof(ScalarType)) > 4 ? GDT_Float64 : GDT_Float32);

	char **papszOptions = NULL;
	GDALDataset* poDstDS = poDriver->Create(qPrintable(outputFilename),
											static_cast<int>(m_grid.width),
											static_cast<int>(m_grid.height),
											totalBands,
											dataType, 
											papszOptions);

	if (!poDstDS)
	{
		ccLog::Error("[GDAL] Failed to create output raster (not enough memory?)");
		return;
	}

	ccBBox box = getCustomBBox();
	assert(box.isValid());

	//vertical dimension
	const unsigned char Z = getProjectionDimension();
	assert(Z >= 0 && Z <= 2);
	const unsigned char X = Z == 2 ? 0 : Z +1;
	const unsigned char Y = X == 2 ? 0 : X +1;

	double shiftX = box.minCorner().u[X];
	double shiftY = box.minCorner().u[Y];

	double stepX = m_grid.gridStep;
	double stepY = m_grid.gridStep;
	if (pc)
	{
		const CCVector3d& shift = pc->getGlobalShift();
		shiftX -= shift.u[X];
		shiftY -= shift.u[Y];

		double scale = pc->getGlobalScale();
		assert(scale != 0);
		stepX /= scale;
		stepY /= scale;
	}

	double adfGeoTransform[6] = {	shiftX,		//top left x
									stepX,		//w-e pixel resolution (can be negative)
									0,			//0
									shiftY,		//top left y
									0,			//0
									stepY		//n-s pixel resolution (can be negative)
	};

	poDstDS->SetGeoTransform( adfGeoTransform );

	//OGRSpatialReference oSRS;
	//oSRS.SetUTM( 11, TRUE );
	//oSRS.SetWellKnownGeogCS( "NAD27" );
	//char *pszSRS_WKT = NULL;
	//oSRS.exportToWkt( &pszSRS_WKT );
	//poDstDS->SetProjection( pszSRS_WKT );
	//CPLFree( pszSRS_WKT );

	double* scanline = (double*) CPLMalloc(sizeof(double)*m_grid.width);
	int currentBand = 0;

	//exort height band?
	if (heightBand)
	{
		GDALRasterBand* poBand = poDstDS->GetRasterBand(++currentBand);
		assert(poBand);
		poBand->SetColorInterpretation(GCI_Undefined);

		EmptyCellFillOption fillEmptyCellsStrategy = getFillEmptyCellsStrategy(fillEmptyCellsComboBox);

		double emptyCellHeight = 0;
		switch (fillEmptyCellsStrategy)
		{
		case LEAVE_EMPTY:
			emptyCellHeight = m_grid.minHeight-1.0;
			poBand->SetNoDataValue(emptyCellHeight); //should be transparent!
			break;
		case FILL_MINIMUM_HEIGHT:
			emptyCellHeight = m_grid.minHeight;
			break;
		case FILL_MAXIMUM_HEIGHT:
			emptyCellHeight = m_grid.maxHeight;
			break;
		case FILL_CUSTOM_HEIGHT:
			emptyCellHeight = getCustomHeightForEmptyCells();
			break;
		case FILL_AVERAGE_HEIGHT:
			emptyCellHeight = m_grid.meanHeight;
			break;
		default:
			assert(false);
		}

		for (unsigned j=0; j<m_grid.height; ++j)
		{
			const RasterCell* aCell = m_grid.data[j];
			for (unsigned i=0; i<m_grid.width; ++i,++aCell)
			{
				scanline[i] = aCell->h == aCell->h ? aCell->h : emptyCellHeight;
			}

			if (poBand->RasterIO( GF_Write, 0, static_cast<int>(j), static_cast<int>(m_grid.width), 1, scanline, static_cast<int>(m_grid.width), 1, GDT_Float64, 0, 0 ) != CE_None)
			{
				ccLog::Error("[GDAL] An error occurred while writing the height band!");
				if (scanline)
					CPLFree(scanline);
				GDALClose( (GDALDatasetH) poDstDS );
				return;
			}
		}
	}

	//export density band
	if (densityBand)
	{
		GDALRasterBand* poBand = poDstDS->GetRasterBand(++currentBand);
		assert(poBand);
		poBand->SetColorInterpretation(GCI_Undefined);
		for (unsigned j=0; j<m_grid.height; ++j)
		{
			const RasterCell* aCell = m_grid.data[j];
			for (unsigned i=0; i<m_grid.width; ++i,++aCell)
			{
				scanline[i] = aCell->nbPoints;
			}

			if (poBand->RasterIO( GF_Write, 0, static_cast<int>(j), static_cast<int>(m_grid.width), 1, scanline, static_cast<int>(m_grid.width), 1, GDT_Float64, 0, 0 ) != CE_None)
			{
				ccLog::Error("[GDAL] An error occurred while writing the height band!");
				if (scanline)
					CPLFree(scanline);
				GDALClose( (GDALDatasetH) poDstDS );
				return;
			}
		}
	}

	//export SF bands
	if (allSFBands || sfBandIndex >= 0)
	{
		for (size_t k=0; k<m_grid.scalarFields.size(); ++k)
		{
			double* _sfGrid = m_grid.scalarFields[k];
			if (_sfGrid && (allSFBands || sfBandIndex == static_cast<int>(k))) //valid SF grid
			{
				GDALRasterBand* poBand = poDstDS->GetRasterBand(++currentBand);

				double sfNanValue = static_cast<double>(CCLib::ScalarField::NaN());
				poBand->SetNoDataValue(sfNanValue); //should be transparent!
				assert(poBand);
				poBand->SetColorInterpretation(GCI_Undefined);

				for (unsigned j=0; j<m_grid.height; ++j)
				{
					const RasterCell* aCell = m_grid.data[j];
					for (unsigned i=0; i<m_grid.width; ++i,++_sfGrid,++aCell)
					{
						scanline[i] = aCell->nbPoints ? *_sfGrid : sfNanValue;
					}

					if (poBand->RasterIO( GF_Write, 0, static_cast<int>(j), static_cast<int>(m_grid.width), 1, scanline, static_cast<int>(m_grid.width), 1, GDT_Float64, 0, 0 ) != CE_None)
					{
						//the corresponding SF should exist on the input cloud
						CCLib::ScalarField* formerSf = pc->getScalarField(static_cast<int>(k));
						assert(formerSf);
						ccLog::Error(QString("[GDAL] An error occurred while writing the '%1' scalar field band!").arg(formerSf->getName()));
						k = m_grid.scalarFields.size(); //quick stop
						break;
					}
				}
			}
		}
	}

	if (scanline)
		CPLFree(scanline);
	scanline = 0;

	/* Once we're done, close properly the dataset */
	GDALClose( (GDALDatasetH) poDstDS );

	ccLog::Print(QString("[Rasterize] Raster '%1' succesfully saved").arg(outputFilename));

#else
	assert(false);
	ccLog::Error("[Rasterize] GDAL not supported by this version! Can't generate a raster...");
#endif
}
Beispiel #16
0
QString Helpers::getActiveKey() const
{
    QSettings s;
    return s.value("user/activekey").toString();
}
Beispiel #17
0
void rigControlForm::readSettings()
{
  cp=rigController->params();
  QSettings qSettings;
  qSettings.beginGroup(cp->configLabel);
  cp->serialPort=qSettings.value("serialPort","/dev/ttyS0").toString();
  cp->radioModel=qSettings.value("radioModel","dummy").toString();
  cp->civAddress=qSettings.value("civAddress","").toString();
  cp->baudrate=qSettings.value("baudrate",9600).toInt();
  cp->parity=qSettings.value("parity","None").toString();
  cp->stopbits=qSettings.value("stopbits",1).toInt();
  cp->databits=qSettings.value("databits",8).toInt();
  cp->handshake=qSettings.value("handshake","None").toString();
  cp->enableCAT=qSettings.value("enableCAT",0).toBool();
  cp->enableSerialPTT=qSettings.value("enableSerialPTT",0).toBool();
  cp->pttSerialPort=qSettings.value("pttSerialPort","/dev/ttyS0").toString();
  cp->activeRTS=qSettings.value("activeRTS",1).toBool();
  cp->activeDTR=qSettings.value("activeDTR",0).toBool();
  cp->nactiveRTS=qSettings.value("nactiveRTS",1).toBool();
  cp->nactiveDTR=qSettings.value("nactiveDTR",0).toBool();

  cp->enableXMLRPC=qSettings.value("enableXMLRPC",0).toBool();
  cp->XMLRPCPort=qSettings.value("XMLRPCPort","7362").toInt();

  cp->txOnDelay=qSettings.value("txOnDelay",0.0).toDouble();

  cp->pttType=(ptt_type_t)qSettings.value("pttType",(int)RIG_PTT_RIG).toInt();
  qSettings.endGroup();
  setParams();
}
void QuickPrintGui::on_buttonBox_accepted()
{
  writeSettings();
  QSettings mySettings;  // where we keep last used filter in persistant state
  QString myLastUsedDir = mySettings.value( "quickprint/lastSaveAsPdfDir", "." ).toString();

  //create a file dialog
  std::auto_ptr < QFileDialog > myFileDialog
  (
    new QFileDialog(
      this,
      QFileDialog::tr( "Save experiment report to portable document format (.pdf)" ),
      myLastUsedDir,
      tr( "Portable Document Format (*.pdf)" )
    )
  );
  myFileDialog->setFileMode( QFileDialog::AnyFile );
  myFileDialog->setAcceptMode( QFileDialog::AcceptSave );

  //prompt the user for a file name
  QString myOutputFileName;
  if ( myFileDialog->exec() == QDialog::Accepted )
  {
    QStringList myFiles = myFileDialog->selectedFiles();
    if ( !myFiles.isEmpty() )
    {
      myOutputFileName = myFiles[0];
    }
  }

  if ( !myOutputFileName.isEmpty() )
  {
    if ( myFileDialog->selectedFilter() == tr( "Portable Document Format (*.pdf)" ) )
    {
      //ensure the user never omitted the extension from the file name
      if ( !myOutputFileName.toUpper().endsWith( ".PDF" ) )
      {
        myOutputFileName += ".pdf";
      }

      // call plugin print method here
      QString myNorthArrowFile = QgsApplication::pkgDataPath() + "/svg/north_arrows/default.svg";
      QgsQuickPrint myQuickPrint;
      myQuickPrint.setMapCanvas( mpMapCanvas );
      myQuickPrint.setTitle( leMapTitle->text() );
      myQuickPrint.setName( leMapName->text() );
      myQuickPrint.setCopyright( teCopyright->toPlainText() );
      myQuickPrint.setLogo1( QgsApplication::iconsPath() + "/qgis-icon.png" );
      myQuickPrint.setNorthArrow( myNorthArrowFile );
      myQuickPrint.setOutputPdf( myOutputFileName );
      QString myPageSizeString = cboPageSize->itemData( cboPageSize->currentIndex() ).toString();
      myQuickPrint.setPageSize( QgsQuickPrint::stringToPageSize( myPageSizeString ) );
      qDebug( "Page size : %s", myPageSizeString.toLocal8Bit().constData() );
      myQuickPrint.printMap();
    }
    else
    {
      QMessageBox::warning( this, tr( "quickprint" ), tr( "Unknown format: " ) +
                            myFileDialog->selectedFilter() );
    }
    mySettings.setValue( "quickprint/lastSaveAsPdfDir", myFileDialog->directory().absolutePath() );
  }

  //close the dialog
  accept();
}
Beispiel #19
0
QString Notepadqq::npmPath() {
    QSettings s;
    return s.value("Extensions/Runtime_Npm", "").toString();
}
void GlobalSearchView::ReloadSettings() {
  const bool old_show_suggestions = show_suggestions_;

  QSettings s;

  // Library settings
  s.beginGroup(LibraryView::kSettingsGroup);
  const bool pretty = s.value("pretty_covers", true).toBool();
  front_model_->set_use_pretty_covers(pretty);
  back_model_->set_use_pretty_covers(pretty);
  s.endGroup();

  // Global search settings
  s.beginGroup(GlobalSearch::kSettingsGroup);
  const QStringList provider_order =
      s.value("provider_order", QStringList() << "library").toStringList();
  front_model_->set_provider_order(provider_order);
  back_model_->set_provider_order(provider_order);
  show_providers_ = s.value("show_providers", true).toBool();
  show_suggestions_ = s.value("show_suggestions", true).toBool();
  SetGroupBy(LibraryModel::Grouping(
      LibraryModel::GroupBy(
          s.value("group_by1", int(LibraryModel::GroupBy_Artist)).toInt()),
      LibraryModel::GroupBy(
          s.value("group_by2", int(LibraryModel::GroupBy_Album)).toInt()),
      LibraryModel::GroupBy(
          s.value("group_by3", int(LibraryModel::GroupBy_None)).toInt())));
  s.endGroup();

  // Delete any old status widgets
  qDeleteAll(provider_status_widgets_);
  provider_status_widgets_.clear();

  // Toggle visibility of the providers group
  ui_->providers_group->setVisible(show_providers_);

  if (show_providers_) {
    // Sort the list of providers
    QList<SearchProvider*> providers = engine_->providers();
    qSort(providers.begin(), providers.end(),
          std::bind(&CompareProvider, std::cref(provider_order), _1, _2));

    bool any_disabled = false;

    for (SearchProvider* provider : providers) {
      QWidget* parent = ui_->enabled_list;
      if (!engine_->is_provider_usable(provider)) {
        parent = ui_->disabled_list;
        any_disabled = true;
      }

      SearchProviderStatusWidget* widget =
          new SearchProviderStatusWidget(warning_icon_, engine_, provider);

      parent->layout()->addWidget(widget);
      provider_status_widgets_ << widget;
    }

    ui_->disabled_label->setVisible(any_disabled);
  }

  ui_->suggestions_group->setVisible(show_suggestions_);
  if (!show_suggestions_) {
    update_suggestions_timer_->stop();
  }

  if (!old_show_suggestions && show_suggestions_) {
    UpdateSuggestions();
  }
}
bool QgsMapToolIdentify::identifyVectorLayer( QList<IdentifyResult> *results, QgsVectorLayer *layer, QgsPoint point )
{
  if ( !layer )
    return false;

  if ( layer->hasScaleBasedVisibility() &&
       ( layer->minimumScale() > mCanvas->mapRenderer()->scale() ||
         layer->maximumScale() <= mCanvas->mapRenderer()->scale() ) )
  {
    QgsDebugMsg( "Out of scale limits" );
    return false;
  }

  QMap< QString, QString > derivedAttributes;

  derivedAttributes.insert( tr( "(clicked coordinate)" ), point.toString() );

  // load identify radius from settings
  QSettings settings;
  double identifyValue = settings.value( "/Map/identifyRadius", QGis::DEFAULT_IDENTIFY_RADIUS ).toDouble();

  if ( identifyValue <= 0.0 )
    identifyValue = QGis::DEFAULT_IDENTIFY_RADIUS;

  int featureCount = 0;

  QgsFeatureList featureList;

  // toLayerCoordinates will throw an exception for an 'invalid' point.
  // For example, if you project a world map onto a globe using EPSG 2163
  // and then click somewhere off the globe, an exception will be thrown.
  try
  {
    // create the search rectangle
    double searchRadius = mCanvas->extent().width() * ( identifyValue / 100.0 );

    QgsRectangle r;
    r.setXMinimum( point.x() - searchRadius );
    r.setXMaximum( point.x() + searchRadius );
    r.setYMinimum( point.y() - searchRadius );
    r.setYMaximum( point.y() + searchRadius );

    r = toLayerCoordinates( layer, r );

    QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest().setFilterRect( r ).setFlags( QgsFeatureRequest::ExactIntersect ) );
    QgsFeature f;
    while ( fit.nextFeature( f ) )
      featureList << QgsFeature( f );
  }
  catch ( QgsCsException & cse )
  {
    Q_UNUSED( cse );
    // catch exception for 'invalid' point and proceed with no features found
    QgsDebugMsg( QString( "Caught CRS exception %1" ).arg( cse.what() ) );
  }

  QgsFeatureList::iterator f_it = featureList.begin();

  bool filter = false;

  QgsFeatureRendererV2* renderer = layer->rendererV2();
  if ( renderer && renderer->capabilities() & QgsFeatureRendererV2::ScaleDependent )
  {
    // setup scale for scale dependent visibility (rule based)
    renderer->startRender( *( mCanvas->mapRenderer()->rendererContext() ), layer );
    filter = renderer->capabilities() & QgsFeatureRendererV2::Filter;
  }

  for ( ; f_it != featureList.end(); ++f_it )
  {
    QgsFeatureId fid = f_it->id();

    if ( filter && !renderer->willRenderFeature( *f_it ) )
      continue;

    featureCount++;

    derivedAttributes.unite( featureDerivedAttributes( &( *f_it ), layer ) );

    derivedAttributes.insert( tr( "feature id" ), fid < 0 ? tr( "new feature" ) : FID_TO_STRING( fid ) );

    results->append( IdentifyResult( qobject_cast<QgsMapLayer *>( layer ), *f_it, derivedAttributes ) );
  }

  if ( renderer && renderer->capabilities() & QgsFeatureRendererV2::ScaleDependent )
  {
    renderer->stopRender( *( mCanvas->mapRenderer()->rendererContext() ) );
  }

  QgsDebugMsg( "Feature count on identify: " + QString::number( featureCount ) );

  return featureCount > 0;
}
Beispiel #22
0
void QgsGrassTools::restorePosition()
{
  QSettings settings;
  restoreGeometry( settings.value( "/GRASS/windows/tools/geometry" ).toByteArray() );
  show();
}
Beispiel #23
0
Tomatime::Tomatime(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Tomatime)
{
    QCoreApplication::setOrganizationName("Tomatime");
    QCoreApplication::setOrganizationDomain("github.com");
    QCoreApplication::setApplicationName("tomatime");

    ui->setupUi(this);

    // Don't forget to define this
    timer = new QTimer(this);
    timeValue = new QTime();
    restoreAction = new QAction(this);
    quitAction = new QAction(this);
    trayIcon = new QSystemTrayIcon(this);
    trayIconMenu = new QMenu(this);

    // Init Child Dialog
    settingDialog = new Settings(this);
    aboutWidget = new About(this);

    // Initialize value from setting
    QSettings setting;

    setWorkingTime( (setting.value("time/working").isNull() == true ) ? setting.value("time/break", 25).toInt() : setting.value("time/working").toInt() );
    setBreakTime( (setting.value("time/break").isNull() == true ) ? setting.value("time/break", 5).toInt() : setting.value("time/break").toInt() );
    setLongBreakTime( (setting.value("time/longbreak").isNull() ) ? setting.value("time/longbreak", 10).toInt() : setting.value("time/longbreak").toInt() );


    connect(ui->start_button, SIGNAL(clicked()),this, SLOT(clickedStartButton()));
    connect(ui->settings_button, SIGNAL(clicked()),this, SLOT(clickedSettingsButton()));
    connect(ui->stop_button, SIGNAL(clicked()),this, SLOT(clickedStopButton()));

    connect(ui->actionSettings, SIGNAL(triggered()),this,SLOT(settingsMenu()));
    connect(ui->actionAbout, SIGNAL(triggered()),this,SLOT(aboutMenu()));

    // Listen signal from setting
    connect(settingDialog,SIGNAL(emitWorkingTimeValue(int)),this,SLOT(setWorkingTime(int)));
    connect(settingDialog,SIGNAL(emitBreakTimeValue(int)),this,SLOT(setBreakTime(int)));
    connect(settingDialog,SIGNAL(emitLongBreakTimeValue(int)),this,SLOT(setLongBreakTime(int)));
    connect(settingDialog,SIGNAL(emitSetTimer(int,int)),this,SLOT(setTimer(int,int)));

    // Recenter form
    QRect position = frameGeometry();
    position.moveCenter(QDesktopWidget().availableGeometry().center());
    move(position.topLeft());

    // Init LCD
    ui->lcdNumber->display(QTime(0,getWorkingTime(),0).toString());

    // Init working count
    workingCount = 0;

    // Init Timer mode
    // 0 = Working
    // 1 = Short Break
    // 2 = Long Break
    timerMode = 0;

    // Init System tray
    createActions();
    createTrayIcon();
    trayIcon->show();

}
Beispiel #24
0
void AlbumCoverManager::Init() {
  // View menu
  QActionGroup* filter_group = new QActionGroup(this);
  filter_all_ = filter_group->addAction(tr("All albums"));
  filter_with_covers_ = filter_group->addAction(tr("Albums with covers"));
  filter_without_covers_ = filter_group->addAction(tr("Albums without covers"));
  filter_all_->setCheckable(true);
  filter_with_covers_->setCheckable(true);
  filter_without_covers_->setCheckable(true);
  filter_group->setExclusive(true);
  filter_all_->setChecked(true);

  QMenu* view_menu = new QMenu(this);
  view_menu->addActions(filter_group->actions());

  ui_->view->setMenu(view_menu);

  // Context menu

  QList<QAction*> actions = album_cover_choice_controller_->GetAllActions();

  connect(album_cover_choice_controller_->cover_from_file_action(),
          SIGNAL(triggered()), this, SLOT(LoadCoverFromFile()));
  connect(album_cover_choice_controller_->cover_to_file_action(),
          SIGNAL(triggered()), this, SLOT(SaveCoverToFile()));
  connect(album_cover_choice_controller_->cover_from_url_action(),
          SIGNAL(triggered()), this, SLOT(LoadCoverFromURL()));
  connect(album_cover_choice_controller_->search_for_cover_action(),
          SIGNAL(triggered()), this, SLOT(SearchForCover()));
  connect(album_cover_choice_controller_->unset_cover_action(),
          SIGNAL(triggered()), this, SLOT(UnsetCover()));
  connect(album_cover_choice_controller_->show_cover_action(),
          SIGNAL(triggered()), this, SLOT(ShowCover()));

  connect(cover_exporter_, SIGNAL(AlbumCoversExportUpdate(int, int, int)),
          SLOT(UpdateExportStatus(int, int, int)));

  context_menu_->addActions(actions);
  context_menu_->addSeparator();
  context_menu_->addAction(ui_->action_load);
  context_menu_->addAction(ui_->action_add_to_playlist);

  ui_->albums->installEventFilter(this);

  // Connections
  connect(ui_->artists,
          SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)),
          SLOT(ArtistChanged(QListWidgetItem*)));
  connect(ui_->filter, SIGNAL(textChanged(QString)), SLOT(UpdateFilter()));
  connect(filter_group, SIGNAL(triggered(QAction*)), SLOT(UpdateFilter()));
  connect(ui_->view, SIGNAL(clicked()), ui_->view, SLOT(showMenu()));
  connect(ui_->fetch, SIGNAL(clicked()), SLOT(FetchAlbumCovers()));
  connect(ui_->export_covers, SIGNAL(clicked()), SLOT(ExportCovers()));
  connect(cover_fetcher_,
          SIGNAL(AlbumCoverFetched(quint64, QImage, CoverSearchStatistics)),
          SLOT(AlbumCoverFetched(quint64, QImage, CoverSearchStatistics)));
  connect(ui_->action_fetch, SIGNAL(triggered()), SLOT(FetchSingleCover()));
  connect(ui_->albums, SIGNAL(doubleClicked(QModelIndex)),
          SLOT(AlbumDoubleClicked(QModelIndex)));
  connect(ui_->action_add_to_playlist, SIGNAL(triggered()),
          SLOT(AddSelectedToPlaylist()));
  connect(ui_->action_load, SIGNAL(triggered()),
          SLOT(LoadSelectedToPlaylist()));

  // Restore settings
  QSettings s;
  s.beginGroup(kSettingsGroup);

  restoreGeometry(s.value("geometry").toByteArray());
  if (!ui_->splitter->restoreState(s.value("splitter_state").toByteArray())) {
    // Sensible default size for the artists view
    ui_->splitter->setSizes(QList<int>() << 200 << width() - 200);
  }

  connect(app_->album_cover_loader(), SIGNAL(ImageLoaded(quint64, QImage)),
          SLOT(CoverImageLoaded(quint64, QImage)));

  cover_searcher_->Init(cover_fetcher_);

  new ForceScrollPerPixel(ui_->albums, this);
}
Beispiel #25
0
bool U3DIOPlugin::save(const QString &formatName, const QString &fileName, MeshModel &m, const int mask, const RichParameterSet & par, vcg::CallBackPos */*cb*/, QWidget *parent)
{
    vcg::tri::Allocator<CMeshO>::CompactVertexVector(m.cm);
    vcg::tri::Allocator<CMeshO>::CompactFaceVector(m.cm);

    QString errorMsgFormat = "Error encountered while exporting file %1:\n%2";
    string filename = QFile::encodeName(fileName).constData ();
    //std::string filename = fileName.toUtf8().data();
    std::string ex = formatName.toUtf8().data();
    //QString curr = QDir::currentPath();
    //QString tmp(QDir::tempPath());
    //
    //if there are textures file that aren't in tga format I have to convert them
    //
    //I maintain the converted file name (i.e. file_path + originalname without extension + tga) in mesh.textures but I have to revert to the original ones	////before the function return.
    //QStringList oldtextname;
    //for(unsigned int ii = 0; ii < m.cm.textures.size();++ii)
    //	oldtextname.push_back(m.cm.textures[ii].c_str());
    //
    //tmp vector to save the tga created files that should be deleted.
    //QStringList convfile;
    //vcg::tri::io::TGA_Exporter::convertTexturesFiles(m.cm,curr,convfile);

    QStringList textures_to_be_restored;
    QStringList lst = vcg::tri::io::ExporterIDTF<CMeshO>::convertInTGATextures(m.cm,QDir::tempPath(),textures_to_be_restored);
    if(formatName.toUpper() == tr("U3D"))
    {
        qApp->restoreOverrideCursor();
        /*vcg::tri::io::u3dparametersclasses::Movie15Parameters mp;
        mp._campar = new vcg::tri::io::u3dparametersclasses::Movie15Parameters::CameraParameters(m.cm.bbox.Center(),m.cm.bbox.Diag());
        U3D_GUI pw(mp,parent);
        pw.exec();
        qApp->setOverrideCursor(QCursor(Qt::WaitCursor));
        qDebug("Quality parameter %i",mp.positionQuality);*/
        saveParameters(par);
        QSettings settings;

        QString converterPath = computePluginsPath();
        QString converterCommandLine;
#if defined(Q_OS_WIN)
        converterPath += "/IDTFConverter.exe";
        converterCommandLine = converterPath;
#elif defined(Q_OS_MAC)
        converterPath.replace(QString(" "),QString("\\ "));
        converterCommandLine = "\""+converterPath +"/IDTFConverter.sh"+ "\" \"" + converterPath+"\"";
        converterPath = converterPath +"/IDTFConverter.sh";
#elif defined(Q_OS_LINUX)
        converterPath = "/usr/bin/IDTFConverter";
        converterCommandLine = converterPath;
#endif
        if (settings.contains("U3D/converter"))
            converterPath=settings.value("U3D/converter").toString();
        //else
        //	settings.setValue("U3D/converter",converterPath);
        QFileInfo converterFI(converterPath);
        if(!converterFI.exists())
        {
            QMessageBox::warning(parent, tr("Saving Error"), QString("Missing converter executable '%1'").arg(converterPath));
            return false;
        }

        int result = tri::io::ExporterU3D<CMeshO>::Save(m.cm,filename.c_str(),qPrintable(converterCommandLine),_param,mask);
        vcg::tri::io::ExporterIDTF<CMeshO>::removeConvertedTGATextures(lst);
        if(result!=0)
        {
            QMessageBox::warning(parent, tr("Saving Error"), errorMsgFormat.arg(fileName, vcg::tri::io::ExporterU3D<CMeshO>::ErrorMsg(result)));
            return false;
        }
    }

    if(formatName.toUpper() == tr("IDTF"))		int result = tri::io::ExporterIDTF<CMeshO>::Save(m.cm,filename.c_str(),mask);
    vcg::tri::io::ExporterIDTF<CMeshO>::restoreConvertedTextures(m.cm,textures_to_be_restored);
    return true;
}
void ccRasterizeTool::generateImage() const
{
	if (!m_grid.isValid())
		return;

	//default values
	double emptyCellsHeight = 0;
	double minHeight = m_grid.minHeight;
	double maxHeight = m_grid.maxHeight;
	//get real values
	EmptyCellFillOption fillEmptyCellsStrategy = getFillEmptyCellsStrategyExt(	emptyCellsHeight,
																				minHeight,
																				maxHeight);

	QImage bitmap8(m_grid.width,m_grid.height,QImage::Format_Indexed8);
	if (!bitmap8.isNull())
	{
		// Build a custom palette (gray scale)
		QVector<QRgb> palette(256);
		{
			for (unsigned i = 0; i < 256; i++)
				palette[i] = qRgba(i,i,i,255);
		}
		double maxColorComp = 255.99; //.99 --> to avoid round-off issues later!

		if (fillEmptyCellsStrategy == LEAVE_EMPTY)
		{
			palette[255] = qRgba(255,0,255,0); //magenta/transparent color for empty cells (in place of pure white)
			maxColorComp = 254.99;
		}

		bitmap8.setColorTable(palette);
		//bitmap8.fill(255);

		unsigned emptyCellColorIndex = 0;
		switch (fillEmptyCellsStrategy)
		{
		case LEAVE_EMPTY:
			emptyCellColorIndex = 255; //should be transparent!
			break;
		case FILL_MINIMUM_HEIGHT:
			emptyCellColorIndex = 0;
			break;
		case FILL_MAXIMUM_HEIGHT:
			emptyCellColorIndex = 255;
			break;
		case FILL_CUSTOM_HEIGHT:
			{
				double normalizedHeight = (emptyCellsHeight-minHeight)/(maxHeight-minHeight);
				//min and max should have already been updated with custom empty cell height!
				assert(normalizedHeight >= 0.0 && normalizedHeight <= 1.0);
				emptyCellColorIndex = static_cast<unsigned>(floor(normalizedHeight*maxColorComp));
			}
			break;
		case FILL_AVERAGE_HEIGHT:
		default:
			assert(false);
		}

		double range = maxHeight - minHeight;
		if (range < ZERO_TOLERANCE)
			range = 1.0;

		// Filling the image with grid values
		for (unsigned j=0; j<m_grid.height; ++j)
		{
			const RasterCell* aCell = m_grid.data[j];
			for (unsigned i=0; i<m_grid.width; ++i,++aCell)
			{
				if (aCell->h == aCell->h)
				{
					double normalizedHeight = (aCell->h - minHeight)/range;
					assert(normalizedHeight >= 0.0 && normalizedHeight <= 1.0);
					unsigned char val = static_cast<unsigned char>(floor(normalizedHeight*maxColorComp));
					bitmap8.setPixel(i,m_grid.height-1-j,val);
				}
				else //NaN
				{
					bitmap8.setPixel(i,m_grid.height-1-j,emptyCellColorIndex);
				}
			}
		}

		//open file saving dialog
		{
			//add images output file filters
			QString filters;

			//we grab the list of supported image file formats (writing)
			QList<QByteArray> formats = QImageWriter::supportedImageFormats();
			if (formats.empty())
			{
				ccLog::Error("No image format supported by your system?!\n(check that the 'imageformats' directory is alongside CC executable)");
			}
			else
			{
				//we convert this list into a proper "filters" string
				for (int i=0; i<formats.size(); ++i)
					filters.append(QString("%1 image (*.%2)\n").arg(QString(formats[i].data()).toUpper()).arg(formats[i].data()));

				QSettings settings;
				settings.beginGroup(ccPS::HeightGridGeneration());
				QString imageSavePath = settings.value("savePathImage",QApplication::applicationDirPath()).toString();
				QString outputFilename = QFileDialog::getSaveFileName(0,"Save raster image",imageSavePath+QString("/raster_image.%1").arg(formats[0].data()),filters);

				if (!outputFilename.isNull())
				{
					if (bitmap8.save(outputFilename))
					{
						ccLog::Print(QString("[Rasterize] Image '%1' succesfully saved").arg(outputFilename));
						//save current export path to persistent settings
						settings.setValue("savePathImage",QFileInfo(outputFilename).absolutePath());
					}
					else
					{
						ccLog::Error("Failed to save image file!");
					}
				}
			}
		}
	}
	else
	{
		ccLog::Error("Failed to create output image! (not enough memory?)");
	}
}
Beispiel #27
0
void OptionsModel::Init()
{
    QSettings settings;

    // These are Qt-only settings:
    nDisplayUnit = settings.value("nDisplayUnit", blehcoinUnits::BTC).toInt();
    bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool();
    fMinimizeToTray = settings.value("fMinimizeToTray", false).toBool();
    fMinimizeOnClose = settings.value("fMinimizeOnClose", false).toBool();
    nTransactionFee = settings.value("nTransactionFee").toLongLong();
    language = settings.value("language", "").toString();

    // These are shared with core blehcoin; we want
    // command-line options to override the GUI settings:
    if (settings.contains("fUseUPnP"))
        SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool());
    if (settings.contains("addrProxy") && settings.value("fUseProxy").toBool())
        SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString());
    if (settings.contains("nSocksVersion") && settings.value("fUseProxy").toBool())
        SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString());
    if (settings.contains("detachDB"))
        SoftSetBoolArg("-detachdb", settings.value("detachDB").toBool());
    if (!language.isEmpty())
        SoftSetArg("-lang", language.toStdString());
}
void ccRasterizeTool::loadSettings()
{
	QSettings settings;
	settings.beginGroup(ccPS::HeightGridGeneration());
	int projType				= settings.value("ProjectionType",heightProjectionComboBox->currentIndex()).toInt();
	int projDim					= settings.value("ProjectionDim",dimensionComboBox->currentIndex()).toInt();
	bool sfProj					= settings.value("SfProjEnabled",interpolateSFCheckBox->isChecked()).toBool();
	int sfProjStrategy			= settings.value("SfProjStrategy",scalarFieldProjection->currentIndex()).toInt();
	int fillStrategy			= settings.value("FillStrategy",fillEmptyCellsComboBox->currentIndex()).toInt();
	double step					= settings.value("GridStep",gridStepDoubleSpinBox->value()).toDouble();
	double emptyHeight			= settings.value("EmptyCellsHeight",emptyValueDoubleSpinBox->value()).toDouble();
	bool genCountSF				= settings.value("GenerateCountSF",generateCountSFcheckBox->isChecked()).toBool();
	bool resampleCloud			= settings.value("ResampleOrigCloud",resampleCloudCheckBox->isChecked()).toBool();
	int minVertexCount			= settings.value("MinVertexCount",minVertexCountSpinBox->value()).toInt();
	bool ignoreBorders			= settings.value("IgnoreBorders",ignoreContourBordersCheckBox->isChecked()).toBool();
	bool generateCountSF		= settings.value("generateCountSF",generateCountSFcheckBox->isChecked()).toBool();
	bool generateMinHeightSF	= settings.value("generateMinHeightSF",generateMinHeightSFcheckBox->isChecked()).toBool();
	bool generateMaxHeightSF	= settings.value("generateMaxHeightSF",generateMinHeightSFcheckBox->isChecked()).toBool();
	bool generateAbgHeightSF	= settings.value("generateAvgHeightSF",generateAvgHeightSFcheckBox->isChecked()).toBool();
	bool generateStdDevHeightSF	= settings.value("generateStdDevHeightSF",generateStdDevHeightSFcheckBox->isChecked()).toBool();
	bool generateHeightRangeSF	= settings.value("generateHeightRangeSF",generateHeightRangeSFcheckBox->isChecked()).toBool();
	
	settings.endGroup();

	gridStepDoubleSpinBox->setValue(step);
	heightProjectionComboBox->setCurrentIndex(projType);
	fillEmptyCellsComboBox->setCurrentIndex(fillStrategy);
	emptyValueDoubleSpinBox->setValue(emptyHeight);
	dimensionComboBox->setCurrentIndex(projDim);
	interpolateSFCheckBox->setChecked(sfProj);
	scalarFieldProjection->setCurrentIndex(sfProjStrategy);
	generateCountSFcheckBox->setChecked(genCountSF);
	resampleCloudCheckBox->setChecked(resampleCloud);
	minVertexCountSpinBox->setValue(minVertexCount);
	ignoreContourBordersCheckBox->setChecked(ignoreBorders);
	generateCountSFcheckBox->setChecked(generateCountSF);
	generateMinHeightSFcheckBox->setChecked(generateMinHeightSF);
	generateMinHeightSFcheckBox->setChecked(generateMaxHeightSF);
	generateAvgHeightSFcheckBox->setChecked(generateAbgHeightSF);
	generateStdDevHeightSFcheckBox->setChecked(generateStdDevHeightSF);
	generateHeightRangeSFcheckBox->setChecked(generateHeightRangeSF);
}
Beispiel #29
0
// read QSettings values and return them
QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            return GUIUtil::GetStartOnSystemStartup();
        case HideTrayIcon:
            return fHideTrayIcon;
        case MinimizeToTray:
            return fMinimizeToTray;
        case MapPortUPnP:
#ifdef USE_UPNP
            return settings.value("fUseUPnP");
#else
            return false;
#endif
        case MinimizeOnClose:
            return fMinimizeOnClose;

        // default proxy
        case ProxyUse:
            return settings.value("fUseProxy", false);
        case ProxyIP: {
            // contains IP at index 0 and port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            return strlIpPort.at(0);
        }
        case ProxyPort: {
            // contains IP at index 0 and port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            return strlIpPort.at(1);
        }

        // separate Tor proxy
        case ProxyUseTor:
            return settings.value("fUseSeparateProxyTor", false);
        case ProxyIPTor: {
            // contains IP at index 0 and port at index 1
            QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts);
            return strlIpPort.at(0);
        }
        case ProxyPortTor: {
            // contains IP at index 0 and port at index 1
            QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts);
            return strlIpPort.at(1);
        }

#ifdef ENABLE_WALLET
        case SpendZeroConfChange:
            return settings.value("bSpendZeroConfChange");
#endif
        case DisplayUnit:
            return nDisplayUnit;
        case ThirdPartyTxUrls:
            return strThirdPartyTxUrls;
        case Language:
            return settings.value("language");
        case CoinControlFeatures:
            return fCoinControlFeatures;
        case DatabaseCache:
            return settings.value("nDatabaseCache");
        case ThreadsScriptVerif:
            return settings.value("nThreadsScriptVerif");
        case Listen:
            return settings.value("fListen");
        default:
            return QVariant();
        }
    }
    return QVariant();
}
Beispiel #30
0
int main(int argc, char **argv)
{
	//See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions
	/** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory
		on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to
		ensure that resource sharing between contexts stays functional as all internal contexts are created
		using the correct version and profile.
	**/
	{
		QSurfaceFormat format = QSurfaceFormat::defaultFormat();
		format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
		format.setStencilBufferSize(0);
#ifdef CC_GL_WINDOW_USE_QWINDOW
		format.setStereo(true);
#endif
#ifdef Q_OS_MAC
		format.setStereo(false);
		format.setVersion( 2, 1 );
		format.setProfile( QSurfaceFormat::CoreProfile );
#endif
#ifdef QT_DEBUG
		format.setOption(QSurfaceFormat::DebugContext, true);
#endif
		QSurfaceFormat::setDefaultFormat(format);
	}

	//The 'AA_ShareOpenGLContexts' attribute must be defined BEFORE the creation of the Q(Gui)Application
	//DGM: this is mandatory to enable exclusive full screen for ccGLWidget (at least on Windows)
	QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);

	//QT initialiation
	qccApplication app(argc, argv);

	//Locale management
	{
		//Force 'english' locale so as to get a consistent behavior everywhere
		QLocale locale = QLocale(QLocale::English);
		locale.setNumberOptions(QLocale::c().numberOptions());
		QLocale::setDefault(locale);

#ifdef Q_OS_UNIX
		//We reset the numeric locale for POSIX functions
		//See http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings
		setlocale(LC_NUMERIC, "C");
#endif
	}

#ifdef USE_VLD
	VLDEnable();
#endif

	QDir  workingDir = QCoreApplication::applicationDirPath();
	
#ifdef Q_OS_MAC
	// This makes sure that our "working directory" is not within the application bundle	
	if ( workingDir.dirName() == "MacOS" )
	{
		workingDir.cdUp();
		workingDir.cdUp();
		workingDir.cdUp();
	}
#endif

	//store the log message until a valid logging instance is registered
	ccLog::EnableMessageBackup(true);
	
	//restore some global parameters
	{
		QSettings settings;
		settings.beginGroup(ccPS::GlobalShift());
		double maxAbsCoord = settings.value(ccPS::MaxAbsCoord(), ccGlobalShiftManager::MaxCoordinateAbsValue()).toDouble();
		double maxAbsDiag = settings.value(ccPS::MaxAbsDiag(), ccGlobalShiftManager::MaxBoundgBoxDiagonal()).toDouble();
		settings.endGroup();

		ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2").arg(maxAbsCoord, 0, 'e', 0).arg(maxAbsDiag, 0, 'e', 0));
		
		ccGlobalShiftManager::SetMaxCoordinateAbsValue(maxAbsCoord);
		ccGlobalShiftManager::SetMaxBoundgBoxDiagonal(maxAbsDiag);
	}

	//Command line mode?
	bool commandLine = (argc > 1 && argv[1][0] == '-');
	
	//specific commands
	int lastArgumentIndex = 1;
	QTranslator translator;
	if (commandLine)
	{
		//translation file selection
		if (QString(argv[lastArgumentIndex]).toUpper() == "-LANG")
		{
			QString langFilename = QString(argv[2]);

			//Load translation file
			if (translator.load(langFilename, QCoreApplication::applicationDirPath()))
			{
				qApp->installTranslator(&translator);
			}
			else
			{
				QMessageBox::warning(0, QObject::tr("Translation"), QObject::tr("Failed to load language file '%1'").arg(langFilename));
			}
			commandLine = false;
			lastArgumentIndex += 2;
		}
	}

	//splash screen
	QScopedPointer<QSplashScreen> splash(0);
	QTimer splashTimer;

	//standard mode
	if (!commandLine)
	{
		if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0)
		{
			QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!");
			return EXIT_FAILURE;
		}

		//splash screen
		QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png"));
		splash.reset(new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint));
		splash->show();
		QApplication::processEvents();
	}

	//global structures initialization
	FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!)
	ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization
	ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization

	//load the plugins
	tPluginInfoList plugins;
	QStringList dirFilters;
	QStringList pluginPaths;
	{
		QString appPath = QCoreApplication::applicationDirPath();

#if defined(Q_OS_MAC)
		dirFilters << "*.dylib";

		// plugins are in the bundle
		appPath.remove("MacOS");

		pluginPaths += (appPath + "PlugIns/ccPlugins");
#if defined(CC_MAC_DEV_PATHS)
		// used for development only - this is the path where the plugins are built
		// this avoids having to install into the application bundle when developing
		pluginPaths += (appPath + "../../../ccPlugins");
#endif
#elif defined(Q_OS_WIN)
		dirFilters << "*.dll";

		//plugins are in bin/plugins
		pluginPaths << (appPath + "/plugins");
#elif defined(Q_OS_LINUX)
		dirFilters << "*.so";

		// Plugins are relative to the bin directory where the executable is found
		QDir  binDir(appPath);

		if (binDir.dirName() == "bin")
		{
			binDir.cdUp();

			pluginPaths << (binDir.absolutePath() + "/lib/cloudcompare/plugins");
		}
		else
		{
			// Choose a reasonable default to look in
			pluginPaths << "/usr/lib/cloudcompare/plugins";
		}
#else
		#warning Need to specify the plugin path for this OS.
#endif

#ifdef Q_OS_MAC
		// Add any app data paths
		// Plugins in these directories take precendence over the included ones
		QStringList appDataPaths = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);

		for (const QString &appDataPath : appDataPaths)
		{
			pluginPaths << (appDataPath + "/plugins");
		}
#endif
	}

	ccPlugins::LoadPlugins(plugins, pluginPaths, dirFilters);
	
	int result = 0;

	//command line mode
	if (commandLine)
	{
		//command line processing (no GUI)
		result = ccCommandLineParser::Parse(argc, argv, &plugins);
	}
	else
	{
		//main window init.
		MainWindow* mainWindow = MainWindow::TheInstance();
		if (!mainWindow)
		{
			QMessageBox::critical(0, "Error", "Failed to initialize the main application window?!");
			return EXIT_FAILURE;
		}
		mainWindow->dispatchPlugins(plugins, pluginPaths);
		mainWindow->show();
		QApplication::processEvents();

		//show current Global Shift parameters in Console
		{
			ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2")
				.arg(ccGlobalShiftManager::MaxCoordinateAbsValue(), 0, 'e', 0)
				.arg(ccGlobalShiftManager::MaxBoundgBoxDiagonal(), 0, 'e', 0));
		}

		if (argc > lastArgumentIndex)
		{
			if (splash)
			{
				splash->close();
			}

			//any additional argument is assumed to be a filename --> we try to load it/them
			QStringList filenames;
			for (int i = lastArgumentIndex; i < argc; ++i)
			{
				QString arg(argv[i]);
				//special command: auto start a plugin
				if (arg.startsWith(":start-plugin:"))
				{
					QString pluginName = arg.mid(14);
					QString pluginNameUpper = pluginName.toUpper();
					//look for this plugin
					bool found = false;
					for (const tPluginInfo &plugin : plugins)
					{
						if (plugin.object->getName().replace(' ', '_').toUpper() == pluginNameUpper)
						{
							found = true;
							bool success = plugin.object->start();
							if (!success)
							{
								ccLog::Error(QString("Failed to start the plugin '%1'").arg(plugin.object->getName()));
							}
							break;
						}
					}

					if (!found)
					{
						ccLog::Error(QString("Couldn't find the plugin '%1'").arg(pluginName.replace('_', ' ')));
					}
				}
				else
				{
					filenames << arg;
				}
			}

			mainWindow->addToDB(filenames);
		}
		else if (splash)
		{
			//count-down to hide the timer (only effective once the application will have actually started!)
			QObject::connect(&splashTimer, &QTimer::timeout, [&]() { if (splash) splash->close(); QCoreApplication::processEvents(); splash.reset(); });
			splashTimer.setInterval(1000);
			splashTimer.start();
		}

		//change the default path to the application one (do this AFTER processing the command line)
		QDir::setCurrent(workingDir.absolutePath());

		//let's rock!
		try
		{
			result = app.exec();
		}
		catch (...)
		{
			QMessageBox::warning(0, "CC crashed!", "Hum, it seems that CC has crashed... Sorry about that :)");
		}

		//release the plugins
		for (tPluginInfo &plugin : plugins)
		{
			plugin.object->stop(); //just in case
			if (!plugin.qObject->parent())
			{
				delete plugin.object;
				plugin.object = 0;
				plugin.qObject = 0;
			}
		}
	}

	//release global structures
	MainWindow::DestroyInstance();
	FileIOFilter::UnregisterAll();

#ifdef CC_TRACK_ALIVE_SHARED_OBJECTS
	//for debug purposes
	unsigned alive = CCShareable::GetAliveCount();
	if (alive > 1)
	{
		printf("Error: some shared objects (%u) have not been released on program end!",alive);
		system("PAUSE");
	}
#endif

	return result;
}