Ejemplo n.º 1
0
void qapp::read_cprops(void)  // read app defaults
{
	QString fname,cline,name,par;
	int flags;
	int apnum = 1;
	
	fname = get_cfile("appdefaults");
	
	if(fname.isNull())
		return;
	
	QFile istr(fname);
	
	if(! istr.open(IO_ReadOnly))
	{
		perror("cannot open appdefaults");
		return;
	}	
	cprops.clear();
	apclients.clear();
	
	while(! istr.atEnd())
	{
		istr.readLine(cline, 1024);
		QTextIStream si(&cline);
	
		si >> name;
		par = si.readLine();

		if(par.find("ToolBar") != -1)
		{
			apclients.insert(name, apnum++);
			continue;
		}
	
		flags = 0;	
		
		int i;
		int paf[] = { WindowListSkip,Sticky,SmallFrame,NoResize,NoTile,NoKey,NoScreen };
		char *pas[] = { "WindowListSkip","Sticky","SmallFrame","NoResize","NoTile","NoKey","NoScreen" };

		for(i=0; i < 7; i++)
		{
			if(par.find(pas[i]) != -1)
				flags |= paf[i];
		}
		
		if(flags)
			cprops.insert(name, flags);
	}
	istr.close();

	// check for clients to update
		
	xwindow *client;
		
	for(client = clients.first(); client != NULL; client = clients.next())
		client->set_pflags();
			
	tb_ap->remove();  // update clients on toolbar
}
Ejemplo n.º 2
0
JavaCatWindow::JavaCatWindow() : QMainWindow(0)
{
    setAttribute(Qt::WA_DeleteOnClose);
    the = this;
    setWindowTitle("Java Catalog");
    commented = 0;

    QMenu * menu;
    QPixmap pixmap;
    QAction *action;

    QToolBar * tools = new QToolBar("operations", this);

    addToolBar(Qt::TopToolBarArea, tools);

    //menu = new QMenu(this);
    menu = menuBar()->addMenu("&File");

    pixmap = QPixmap(fileopen);
    action = tools->addAction(pixmap,"Open", this, SLOT(load()));
    action->setWhatsThis(OpenText);
    action->setToolTip("open");


    action = menu->addAction(pixmap,"&Open", this, SLOT(load()));
    action->setWhatsThis(OpenText);
    action->setToolTip("open");
    action->setShortcut(Qt::CTRL + Qt::Key_O);

    pixmap = QPixmap(filesave);
    action = tools->addAction(pixmap,"Save", this, SLOT(save()));
    action->setWhatsThis(SaveText);
    action->setToolTip("save");


    action = menu->addAction(pixmap,"&Save", this, SLOT(save()));
    action->setWhatsThis(SaveText);
    action->setToolTip("save");
    action->setShortcut(Qt::CTRL + Qt::Key_S);


    menu->addSeparator();

    pixmap = QPixmap(::scan);
    action = tools->addAction(pixmap,"Scan", this, SLOT(save()));
    action->setWhatsThis(ScanText);
    action->setToolTip("scan");

    action = menu->addAction(pixmap,"S&can", this, SLOT(save()));
    action->setWhatsThis(ScanText);
    action->setToolTip("scan");
    action->setShortcut(Qt::CTRL + Qt::Key_C);



    menu->addSeparator();


    action = menu->addAction("&Quit", this, SLOT(quit()), Qt::CTRL + Qt::Key_Q);

    //menu = new QMenu(this);
    menu = menuBar()->addMenu("&Browse");

    pixmap = QPixmap(browsersearch);
    action = tools->addAction(pixmap,"Search", this, SLOT(browser_search()));
    action->setWhatsThis(SearchText);
    action->setToolTip("Search");

    action = menu->addAction(pixmap,"&Search", this, SLOT(browser_search()));
    action->setWhatsThis(SearchText);
    action->setToolTip("Search");
    action->setShortcut(Qt::CTRL + Qt::Key_S);


    pixmap = QPixmap(left_xpm);
    action = tools->addAction(pixmap,"Back", this, SLOT(historic_back()));
    action->setWhatsThis(LeftText);
    action->setToolTip("back");

    pixmap = QPixmap(right_xpm);
    action = tools->addAction(pixmap,"Forward", this, SLOT(historic_forward()));
    action->setWhatsThis(RightText);
    action->setToolTip("forward");

    action = tools->addAction(QApplication::style()->standardIcon(QStyle::SP_TitleBarContextHelpButton).pixmap(200,2000), "Whats's this?",
                               this, SLOT(whats_this()));



    //(void)QWhatsThis::whatsThisButton(tools);

    //

    //menu = new QMenu(this);
    menu = menuBar()->addMenu("&Style");

#if !defined(QT_NO_STYLE_MOTIF)
    menu->addAction("Motif", this, SLOT(motif_style()));
#endif
#if !defined(QT_NO_STYLE_MOTIFPLUS)
    menu->addAction("MotifPlus", this, SLOT(motifplus_style()));
#endif
    menu->addAction("Windows", this, SLOT(windows_style()));

    //

    menuBar()->addSeparator();
    //menu = new QMenu(this);
    menu = menuBar()->addMenu("&Help");

    menu->addAction("&About", this, SLOT(about()), Qt::Key_F1);
    menu->addAction("About&Qt", this, SLOT(aboutQt()));
    menu->addSeparator();
    menu->addAction("What's This", this, SLOT(whatsThis()), Qt::SHIFT + Qt::Key_F1);

    //

    spl = new QSplitter(Qt::Vertical, this/*, "spl"*/);

    browser = new BrowserView(spl);
    comment = new CommentView(spl);

    connect(comment, SIGNAL(refer(const QString &)),
            browser, SLOT(refer(const QString &)));

    spl->addWidget(browser);

    QList<int> lsz = spl->sizes();
    int h = lsz.first() + lsz.last();

    lsz.first() = (h * 3) / 4;
    lsz.last() = h - lsz.first();

    spl->setSizes(lsz);

    //spl->setResizeMode(comment, QSplitter::KeepSize);
    setCentralWidget(spl);
}
Ejemplo n.º 3
0
int QgsZonalStatistics::calculateStatistics( QgsFeedback *feedback )
{
  if ( !mPolygonLayer || mPolygonLayer->geometryType() != QgsWkbTypes::PolygonGeometry )
  {
    return 1;
  }

  QgsVectorDataProvider *vectorProvider = mPolygonLayer->dataProvider();
  if ( !vectorProvider )
  {
    return 2;
  }

  if ( !mRasterLayer )
  {
    return 3;
  }

  if ( mRasterLayer->bandCount() < mRasterBand )
  {
    return 4;
  }

  mRasterProvider = mRasterLayer->dataProvider();
  mInputNodataValue = mRasterProvider->sourceNoDataValue( mRasterBand );

  //get geometry info about raster layer
  int nCellsXProvider = mRasterProvider->xSize();
  int nCellsYProvider = mRasterProvider->ySize();
  double cellsizeX = mRasterLayer->rasterUnitsPerPixelX();
  if ( cellsizeX < 0 )
  {
    cellsizeX = -cellsizeX;
  }
  double cellsizeY = mRasterLayer->rasterUnitsPerPixelY();
  if ( cellsizeY < 0 )
  {
    cellsizeY = -cellsizeY;
  }
  QgsRectangle rasterBBox = mRasterProvider->extent();

  //add the new fields to the provider
  QList<QgsField> newFieldList;
  QString countFieldName;
  if ( mStatistics & QgsZonalStatistics::Count )
  {
    countFieldName = getUniqueFieldName( mAttributePrefix + "count", newFieldList );
    QgsField countField( countFieldName, QVariant::Double, QStringLiteral( "double precision" ) );
    newFieldList.push_back( countField );
  }
  QString sumFieldName;
  if ( mStatistics & QgsZonalStatistics::Sum )
  {
    sumFieldName = getUniqueFieldName( mAttributePrefix + "sum", newFieldList );
    QgsField sumField( sumFieldName, QVariant::Double, QStringLiteral( "double precision" ) );
    newFieldList.push_back( sumField );
  }
  QString meanFieldName;
  if ( mStatistics & QgsZonalStatistics::Mean )
  {
    meanFieldName = getUniqueFieldName( mAttributePrefix + "mean", newFieldList );
    QgsField meanField( meanFieldName, QVariant::Double, QStringLiteral( "double precision" ) );
    newFieldList.push_back( meanField );
  }
  QString medianFieldName;
  if ( mStatistics & QgsZonalStatistics::Median )
  {
    medianFieldName = getUniqueFieldName( mAttributePrefix + "median", newFieldList );
    QgsField medianField( medianFieldName, QVariant::Double, QStringLiteral( "double precision" ) );
    newFieldList.push_back( medianField );
  }
  QString stdevFieldName;
  if ( mStatistics & QgsZonalStatistics::StDev )
  {
    stdevFieldName = getUniqueFieldName( mAttributePrefix + "stdev", newFieldList );
    QgsField stdField( stdevFieldName, QVariant::Double, QStringLiteral( "double precision" ) );
    newFieldList.push_back( stdField );
  }
  QString minFieldName;
  if ( mStatistics & QgsZonalStatistics::Min )
  {
    minFieldName = getUniqueFieldName( mAttributePrefix + "min", newFieldList );
    QgsField minField( minFieldName, QVariant::Double, QStringLiteral( "double precision" ) );
    newFieldList.push_back( minField );
  }
  QString maxFieldName;
  if ( mStatistics & QgsZonalStatistics::Max )
  {
    maxFieldName = getUniqueFieldName( mAttributePrefix + "max", newFieldList );
    QgsField maxField( maxFieldName, QVariant::Double, QStringLiteral( "double precision" ) );
    newFieldList.push_back( maxField );
  }
  QString rangeFieldName;
  if ( mStatistics & QgsZonalStatistics::Range )
  {
    rangeFieldName = getUniqueFieldName( mAttributePrefix + "range", newFieldList );
    QgsField rangeField( rangeFieldName, QVariant::Double, QStringLiteral( "double precision" ) );
    newFieldList.push_back( rangeField );
  }
  QString minorityFieldName;
  if ( mStatistics & QgsZonalStatistics::Minority )
  {
    minorityFieldName = getUniqueFieldName( mAttributePrefix + "minority", newFieldList );
    QgsField minorityField( minorityFieldName, QVariant::Double, QStringLiteral( "double precision" ) );
    newFieldList.push_back( minorityField );
  }
  QString majorityFieldName;
  if ( mStatistics & QgsZonalStatistics::Majority )
  {
    majorityFieldName = getUniqueFieldName( mAttributePrefix + "majority", newFieldList );
    QgsField majField( majorityFieldName, QVariant::Double, QStringLiteral( "double precision" ) );
    newFieldList.push_back( majField );
  }
  QString varietyFieldName;
  if ( mStatistics & QgsZonalStatistics::Variety )
  {
    varietyFieldName = getUniqueFieldName( mAttributePrefix + "variety", newFieldList );
    QgsField varietyField( varietyFieldName, QVariant::Int, QStringLiteral( "int" ) );
    newFieldList.push_back( varietyField );
  }
  QString varianceFieldName;
  if ( mStatistics & QgsZonalStatistics::Variance )
  {
    varianceFieldName = getUniqueFieldName( mAttributePrefix + "variance", newFieldList );
    QgsField varianceField( varianceFieldName, QVariant::Double, QStringLiteral( "double precision" ) );
    newFieldList.push_back( varianceField );
  }
  vectorProvider->addAttributes( newFieldList );

  //index of the new fields
  int countIndex = mStatistics & QgsZonalStatistics::Count ? vectorProvider->fieldNameIndex( countFieldName ) : -1;
  int sumIndex = mStatistics & QgsZonalStatistics::Sum ? vectorProvider->fieldNameIndex( sumFieldName ) : -1;
  int meanIndex = mStatistics & QgsZonalStatistics::Mean ? vectorProvider->fieldNameIndex( meanFieldName ) : -1;
  int medianIndex = mStatistics & QgsZonalStatistics::Median ? vectorProvider->fieldNameIndex( medianFieldName ) : -1;
  int stdevIndex = mStatistics & QgsZonalStatistics::StDev ? vectorProvider->fieldNameIndex( stdevFieldName ) : -1;
  int minIndex = mStatistics & QgsZonalStatistics::Min ? vectorProvider->fieldNameIndex( minFieldName ) : -1;
  int maxIndex = mStatistics & QgsZonalStatistics::Max ? vectorProvider->fieldNameIndex( maxFieldName ) : -1;
  int rangeIndex = mStatistics & QgsZonalStatistics::Range ? vectorProvider->fieldNameIndex( rangeFieldName ) : -1;
  int minorityIndex = mStatistics & QgsZonalStatistics::Minority ? vectorProvider->fieldNameIndex( minorityFieldName ) : -1;
  int majorityIndex = mStatistics & QgsZonalStatistics::Majority ? vectorProvider->fieldNameIndex( majorityFieldName ) : -1;
  int varietyIndex = mStatistics & QgsZonalStatistics::Variety ? vectorProvider->fieldNameIndex( varietyFieldName ) : -1;
  int varianceIndex = mStatistics & QgsZonalStatistics::Variance ? vectorProvider->fieldNameIndex( varianceFieldName ) : -1;

  if ( ( mStatistics & QgsZonalStatistics::Count && countIndex == -1 )
       || ( mStatistics & QgsZonalStatistics::Sum && sumIndex == -1 )
       || ( mStatistics & QgsZonalStatistics::Mean && meanIndex == -1 )
       || ( mStatistics & QgsZonalStatistics::Median && medianIndex == -1 )
       || ( mStatistics & QgsZonalStatistics::StDev && stdevIndex == -1 )
       || ( mStatistics & QgsZonalStatistics::Min && minIndex == -1 )
       || ( mStatistics & QgsZonalStatistics::Max && maxIndex == -1 )
       || ( mStatistics & QgsZonalStatistics::Range && rangeIndex == -1 )
       || ( mStatistics & QgsZonalStatistics::Minority && minorityIndex == -1 )
       || ( mStatistics & QgsZonalStatistics::Majority && majorityIndex == -1 )
       || ( mStatistics & QgsZonalStatistics::Variety && varietyIndex == -1 )
       || ( mStatistics & QgsZonalStatistics::Variance && varianceIndex == -1 )
     )
  {
    //failed to create a required field
    return 8;
  }

  //progress dialog
  long featureCount = vectorProvider->featureCount();

  //iterate over each polygon
  QgsFeatureRequest request;
  request.setSubsetOfAttributes( QgsAttributeList() );
  QgsFeatureIterator fi = vectorProvider->getFeatures( request );
  QgsFeature f;

  bool statsStoreValues = ( mStatistics & QgsZonalStatistics::Median ) ||
                          ( mStatistics & QgsZonalStatistics::StDev ) ||
                          ( mStatistics & QgsZonalStatistics::Variance );
  bool statsStoreValueCount = ( mStatistics & QgsZonalStatistics::Minority ) ||
                              ( mStatistics & QgsZonalStatistics::Majority );

  FeatureStats featureStats( statsStoreValues, statsStoreValueCount );
  int featureCounter = 0;

  QgsChangedAttributesMap changeMap;
  while ( fi.nextFeature( f ) )
  {
    if ( feedback && feedback->isCanceled() )
    {
      break;
    }

    if ( feedback )
    {
      feedback->setProgress( 100.0 * static_cast< double >( featureCounter ) / featureCount );
    }

    if ( !f.hasGeometry() )
    {
      ++featureCounter;
      continue;
    }
    QgsGeometry featureGeometry = f.geometry();

    QgsRectangle featureRect = featureGeometry.boundingBox().intersect( &rasterBBox );
    if ( featureRect.isEmpty() )
    {
      ++featureCounter;
      continue;
    }

    int offsetX, offsetY, nCellsX, nCellsY;
    if ( cellInfoForBBox( rasterBBox, featureRect, cellsizeX, cellsizeY, offsetX, offsetY, nCellsX, nCellsY ) != 0 )
    {
      ++featureCounter;
      continue;
    }

    //avoid access to cells outside of the raster (may occur because of rounding)
    if ( ( offsetX + nCellsX ) > nCellsXProvider )
    {
      nCellsX = nCellsXProvider - offsetX;
    }
    if ( ( offsetY + nCellsY ) > nCellsYProvider )
    {
      nCellsY = nCellsYProvider - offsetY;
    }

    statisticsFromMiddlePointTest( featureGeometry, offsetX, offsetY, nCellsX, nCellsY, cellsizeX, cellsizeY,
                                   rasterBBox, featureStats );

    if ( featureStats.count <= 1 )
    {
      //the cell resolution is probably larger than the polygon area. We switch to precise pixel - polygon intersection in this case
      statisticsFromPreciseIntersection( featureGeometry, offsetX, offsetY, nCellsX, nCellsY, cellsizeX, cellsizeY,
                                         rasterBBox, featureStats );
    }

    //write the statistics value to the vector data provider
    QgsAttributeMap changeAttributeMap;
    if ( mStatistics & QgsZonalStatistics::Count )
      changeAttributeMap.insert( countIndex, QVariant( featureStats.count ) );
    if ( mStatistics & QgsZonalStatistics::Sum )
      changeAttributeMap.insert( sumIndex, QVariant( featureStats.sum ) );
    if ( featureStats.count > 0 )
    {
      double mean = featureStats.sum / featureStats.count;
      if ( mStatistics & QgsZonalStatistics::Mean )
        changeAttributeMap.insert( meanIndex, QVariant( mean ) );
      if ( mStatistics & QgsZonalStatistics::Median )
      {
        std::sort( featureStats.values.begin(), featureStats.values.end() );
        int size =  featureStats.values.count();
        bool even = ( size % 2 ) < 1;
        double medianValue;
        if ( even )
        {
          medianValue = ( featureStats.values.at( size / 2 - 1 ) + featureStats.values.at( size / 2 ) ) / 2;
        }
        else //odd
        {
          medianValue = featureStats.values.at( ( size + 1 ) / 2 - 1 );
        }
        changeAttributeMap.insert( medianIndex, QVariant( medianValue ) );
      }
      if ( mStatistics & QgsZonalStatistics::StDev || mStatistics & QgsZonalStatistics::Variance )
      {
        double sumSquared = 0;
        for ( int i = 0; i < featureStats.values.count(); ++i )
        {
          double diff = featureStats.values.at( i ) - mean;
          sumSquared += diff * diff;
        }
        double variance = sumSquared / featureStats.values.count();
        if ( mStatistics & QgsZonalStatistics::StDev )
        {
          double stdev = std::pow( variance, 0.5 );
          changeAttributeMap.insert( stdevIndex, QVariant( stdev ) );
        }
        if ( mStatistics & QgsZonalStatistics::Variance )
          changeAttributeMap.insert( varianceIndex, QVariant( variance ) );
      }
      if ( mStatistics & QgsZonalStatistics::Min )
        changeAttributeMap.insert( minIndex, QVariant( featureStats.min ) );
      if ( mStatistics & QgsZonalStatistics::Max )
        changeAttributeMap.insert( maxIndex, QVariant( featureStats.max ) );
      if ( mStatistics & QgsZonalStatistics::Range )
        changeAttributeMap.insert( rangeIndex, QVariant( featureStats.max - featureStats.min ) );
      if ( mStatistics & QgsZonalStatistics::Minority || mStatistics & QgsZonalStatistics::Majority )
      {
        QList<int> vals = featureStats.valueCount.values();
        std::sort( vals.begin(), vals.end() );
        if ( mStatistics & QgsZonalStatistics::Minority )
        {
          float minorityKey = featureStats.valueCount.key( vals.first() );
          changeAttributeMap.insert( minorityIndex, QVariant( minorityKey ) );
        }
        if ( mStatistics & QgsZonalStatistics::Majority )
        {
          float majKey = featureStats.valueCount.key( vals.last() );
          changeAttributeMap.insert( majorityIndex, QVariant( majKey ) );
        }
      }
      if ( mStatistics & QgsZonalStatistics::Variety )
        changeAttributeMap.insert( varietyIndex, QVariant( featureStats.valueCount.count() ) );
    }

    changeMap.insert( f.id(), changeAttributeMap );
    ++featureCounter;
  }

  vectorProvider->changeAttributeValues( changeMap );

  if ( feedback )
  {
    feedback->setProgress( 100 );
  }

  mPolygonLayer->updateFields();

  if ( feedback && feedback->isCanceled() )
  {
    return 9;
  }

  return 0;
}
QgsGraduatedSymbolRendererV2* QgsGraduatedSymbolRendererV2::createRenderer(
  QgsVectorLayer* vlayer,
  QString attrName,
  int classes,
  Mode mode,
  QgsSymbolV2* symbol,
  QgsVectorColorRampV2* ramp,
  bool inverted )
{
  if ( classes < 1 )
    return NULL;

  int attrNum = vlayer->fieldNameIndex( attrName );
  double minimum;
  double maximum;

  QScopedPointer<QgsExpression> expression;

  if ( attrNum == -1 )
  {
    // try to use expression
    expression.reset( new QgsExpression( attrName ) );
    if ( expression->hasParserError() || !expression->prepare( vlayer->pendingFields() ) )
      return 0; // should have a means to report errors

    QList<double> values;
    QgsFeatureIterator fit = vlayer->getFeatures();
    QgsFeature feature;
    while ( fit.nextFeature( feature ) )
    {
      values << expression->evaluate( feature ).toDouble();
    }
    qSort( values );
    minimum = values.first();
    maximum = values.last();
  }
  else
  {
    minimum = vlayer->minimumValue( attrNum ).toDouble();
    maximum = vlayer->maximumValue( attrNum ).toDouble();
  }

  QgsDebugMsg( QString( "min %1 // max %2" ).arg( minimum ).arg( maximum ) );
  QList<double> breaks;
  QList<int> labels;
  if ( mode == EqualInterval )
  {
    breaks = _calcEqualIntervalBreaks( minimum, maximum, classes );
  }
  else if ( mode == Pretty )
  {
    breaks = _calcPrettyBreaks( minimum, maximum, classes );
  }
  else if ( mode == Quantile || mode == Jenks || mode == StdDev )
  {
    // get values from layer
    QList<double> values;
    QgsFeature f;
    QStringList lst;
    if ( expression.isNull() )
      lst.append( attrName );
    else
      lst = expression->referencedColumns();

    QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFlags( QgsFeatureRequest::NoGeometry ).setSubsetOfAttributes( lst, vlayer->pendingFields() ) );

    // create list of non-null attribute values
    while ( fit.nextFeature( f ) )
    {
      QVariant v = expression.isNull() ? f.attribute( attrNum ) : expression->evaluate( f );
      if ( !v.isNull() )
        values.append( v.toDouble() );
    }

    // calculate the breaks
    if ( mode == Quantile )
    {
      breaks = _calcQuantileBreaks( values, classes );
    }
    else if ( mode == Jenks )
    {
      breaks = _calcJenksBreaks( values, classes, minimum, maximum );
    }
    else if ( mode == StdDev )
    {
      breaks = _calcStdDevBreaks( values, classes, labels );
    }
  }
  else
  {
    Q_ASSERT( false );
  }

  QgsRangeList ranges;
  double lower, upper = minimum;
  QString label;

  // "breaks" list contains all values at class breaks plus maximum as last break
  int i = 0;
  for ( QList<double>::iterator it = breaks.begin(); it != breaks.end(); ++it, ++i )
  {
    lower = upper; // upper border from last interval
    upper = *it;
    if ( mode == StdDev )
    {
      if ( i == 0 )
      {
        label = "< " + QString::number( labels[i], 'i', 0 ) + " Std Dev";
      }
      else if ( i == labels.count() - 1 )
      {
        label = ">= " + QString::number( labels[i-1], 'i', 0 ) + " Std Dev";
      }
      else
      {
        label = QString::number( labels[i-1], 'i', 0 ) + " Std Dev" + " - " + QString::number( labels[i], 'i', 0 ) + " Std Dev";
      }
    }
    else
    {
      label = QString::number( lower, 'f', 4 ) + " - " + QString::number( upper, 'f', 4 );
    }

    QgsSymbolV2* newSymbol = symbol->clone();
    double colorValue;
    if ( inverted ) colorValue = ( breaks.count() > 1 ? ( double )( breaks.count() - i - 1 ) / ( breaks.count() - 1 ) : 0 );
    else colorValue = ( breaks.count() > 1 ? ( double ) i / ( breaks.count() - 1 ) : 0 );
    newSymbol->setColor( ramp->color( colorValue ) ); // color from (0 / cl-1) to (cl-1 / cl-1)

    ranges.append( QgsRendererRangeV2( lower, upper, newSymbol, label ) );
  }

  QgsGraduatedSymbolRendererV2* r = new QgsGraduatedSymbolRendererV2( attrName, ranges );
  r->setSourceSymbol( symbol->clone() );
  r->setSourceColorRamp( ramp->clone() );
  r->setInvertedColorRamp( inverted );
  r->setMode( mode );
  return r;
}
Ejemplo n.º 5
0
void K3b::DataPropertiesDialog::loadListProperties( const QList<K3b::DataItem*>& items )
{
    m_labelIcon->setPixmap( DesktopIcon( "document-multiple", KIconLoader::SizeLarge ) );

    int files = 0;
    int folders = 0;
    KIO::filesize_t size = 0;
    K3b::Msf blocks = 0;
    for ( QList<K3b::DataItem*>::iterator it = m_dataItems.begin();
          it != m_dataItems.end(); ++it ) {
        K3b::DataItem* item = *it;
        if ( item->isFile() )
            ++files;
        else if ( item->isDir() )
            ++folders;
        blocks += item->blocks();
        size += item->size();
    }
    QString s = i18np( "One Item", "%1 Items", items.count() );
    s += " - ";
    if ( files > 0 )
        s += i18np( "One File", "%1 Files", files );
    else
        s += i18n( "No Files" );
    s += " - ";
    if ( folders > 0 )
        s += i18np( "One Folder", "%1 Folders", folders );
    else
        s += i18n( "No Folders" );
    m_multiSelectionLabel->setText( s );

    m_labelSize->setText( KIO::convertSize(size) );
    m_labelBlocks->setText( QString::number(blocks.lba()) );

    // the location of all items are the same since it is not possible to
    // select items from different folders
    // FIXME: maybe better use QString::section?
    QString location = '/' + items.first()->k3bPath();
    if( location[location.length()-1] == '/' )
        location.truncate( location.length()-1 );
    location.truncate( location.lastIndexOf('/') );
    if( location.isEmpty() )
        location = '/';
    m_labelLocation->setText( location );


    m_checkHideOnJoliet->setChecked( items.first()->hideOnJoliet() );
    for ( QList<K3b::DataItem*>::iterator it = m_dataItems.begin();
          it != m_dataItems.end(); ++it ) {
        K3b::DataItem* item = *it;
        if ( m_checkHideOnJoliet->isChecked() != item->hideOnJoliet() ) {
            m_checkHideOnJoliet->setCheckState( Qt::PartiallyChecked );
            break;
        }
    }
    m_checkHideOnRockRidge->setChecked( items.first()->hideOnRockRidge() );
    for ( QList<K3b::DataItem*>::iterator it = m_dataItems.begin();
          it != m_dataItems.end(); ++it ) {
        K3b::DataItem* item = *it;
        if ( m_checkHideOnRockRidge->isChecked() != item->hideOnRockRidge() ) {
            m_checkHideOnRockRidge->setCheckState( Qt::PartiallyChecked );
            break;
        }
    }

    int weight = items.first()->sortWeight();
    for ( QList<K3b::DataItem*>::iterator it = m_dataItems.begin();
          it != m_dataItems.end(); ++it ) {
        K3b::DataItem* item = *it;
        if ( weight != item->sortWeight() ) {
            weight = 0;
            break;
        }
    }
    m_editSortWeight->setText( QString::number( weight ) );
}
Ejemplo n.º 6
0
void PropertiesWidget::saveSettings() {
  QIniSettings settings;
  settings.setValue("TorrentProperties/Visible", state==VISIBLE);
  // Splitter sizes
  QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget());
  QList<int> sizes;
  if (state == VISIBLE)
    sizes = hSplitter->sizes();
  else
    sizes = slideSizes;
  qDebug("Sizes: %d", sizes.size());
  if (sizes.size() == 2) {
    settings.setValue(QString::fromUtf8("TorrentProperties/SplitterSizes"), QVariant(QString::number(sizes.first())+','+QString::number(sizes.last())));
  }
  settings.setValue("TorrentProperties/FilesListState", filesList->header()->saveState());
  // Remember current tab
  settings.setValue("TorrentProperties/CurrentTab", m_tabBar->currentIndex());
}
Ejemplo n.º 7
0
bool CMindMapEventHandler::onEvent(CDiagramPrivateData *p, QEvent *evt)
{
	bool					r = false;
	CDiagram				*d = NULL;
	CDiagramItem			*item = NULL;
	CMindMapNode			*node = NULL;
	QList<CDiagramItem*>	items;
	
	if ( !p || !p->m_d || p->m_d->mode() == CDiagram::EditTextMode )
		return r;

	d = p->m_d;
	m_pdata = p;

	switch(evt->type())
	{
	case QEvent::GraphicsSceneDragEnter:
        r = dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent*>(evt));
		break;

	case QEvent::GraphicsSceneDragMove:
        r = dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(evt));
		break;

	case QEvent::GraphicsSceneDrop:
        r = dropEvent(static_cast<QGraphicsSceneDragDropEvent*>(evt));
		break;

	case QEvent::GraphicsSceneMousePress:
        if (m_draggedImage->scene() == d)
            d->removeItem(m_draggedImage);
		m_pdata->m_customPressedItem = NULL;
		m_target = NULL;
		break;

	case QEvent::GraphicsSceneMouseMove:
		{
			QGraphicsSceneMouseEvent	*event = NULL;
			QPointF						endPos;
			QPointF						startPos;
			QDrag						*drag = NULL;
			QMimeData					*mime = NULL;
			QByteArray					mimeData;
			QDataStream					dataStream(&mimeData, QIODevice::WriteOnly);

			event = static_cast<QGraphicsSceneMouseEvent*>(evt);
			if (event && d->mode() == CDiagram::CursorMode)
			{
				if (event->buttons() & Qt::LeftButton )
				{
					endPos = event->scenePos();
					startPos = event->buttonDownScenePos(Qt::LeftButton);

					if (!m_pdata->m_customPressedItem)
					{
						items = d->selectedTopLevelItems();
						if (items.length() == 1)
						{
							node = dynamic_cast<CMindMapNode*>(items.first());
                            if (node && node->isMovable() && node->mapToScene( node->boundingRect() ).containsPoint(event->scenePos(), Qt::WindingFill ) )
							{
								m_pdata->m_customPressedItem = node;
							}
							else if (node && node->isRoot())
							{
								r = true;
							}
						}
						else
						{
							foreach (item, items)
							{
								node = dynamic_cast<CMindMapNode*>(item);
								if (node && node->isRoot())
								{
									r = true;
									break;
								}
							}
						}
					}

					// check whether we should start the moving action
					// using manhattanLength.
					if (m_pdata->m_customPressedItem && 
						m_draggedImage->scene() != d && 
						((startPos, endPos).manhattanLength() > QApplication::startDragDistance() ) )
					{
						((CMindMapDragImage*)m_draggedImage)->updateDraggedItemsRect(d, m_pdata->m_customPressedItem);
                        m_pdata->m_d->addItem(m_draggedImage);
						m_draggedImage->setVisible(true);
						m_draggedImageInitPos = m_draggedImage->pos();
						
						dataStream << event->buttonDownScenePos(Qt::LeftButton);
						mime = new QMimeData();
						mime->setData(DND_DRAGMINDMAPNODE, mimeData);

                        drag = new QDrag( d->getMainView() );
						drag->setMimeData(mime);
						
						if (drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::MoveAction) == Qt::MoveAction)
						{
							// Should do something here.
						}

						event->accept();
                        r = true;
					}
				}
			}
Ejemplo n.º 8
0
void
TrackInfoWidget::onStatsLoaded()
{
    QList< Tomahawk::PlaybackLog > history = m_query->playbackHistory( SourceList::instance()->getLocal() );
    const unsigned int trackCounter = m_query->playbackCount( SourceList::instance()->getLocal() );
    const unsigned int artistCounter = m_artist->playbackCount( SourceList::instance()->getLocal() );

    QString stats;

    if ( trackCounter )
        stats = tr( "You've listened to this track %n time(s).", "", trackCounter );
    else
        stats = tr( "You've never listened to this track before." );

    if ( history.count() )
    {
        stats += "\n" + tr( "You first listened to it on %1." ).arg( QDateTime::fromTime_t( history.first().timestamp ).toString( "dd MMM yyyy" ) );
    }

    if ( artistCounter )
        stats += "\n" + tr( "You've listened to %1 %n time(s).", "", artistCounter ).arg( m_artist->name() );
    else
        stats += "\n" + tr( "You've never listened to %1 before." ).arg( m_artist->name() );

    ui->statsLabel->setText( stats );
}
Ejemplo n.º 9
0
/*!\brief reimplementation of the mouseReleaseEvent
 *
 * ...
 */
void LaunchFileView::mouseReleaseEvent(QMouseEvent *event)
{

    if (_handScrolling) {
        _handScrolling = false;
        viewport()->setCursor(_savedCursor);

        event->accept();
        return;
    }
    if (itemAt((event->pos()))){ //else tool crashes
        if (myMode== DeleteItem && event->button() == Qt::LeftButton) {

            if (itemAt(event->pos())->type() == NodeItem::Type) {

                qgraphicsitem_cast<NodeItem *>(itemAt(event->pos()))->removeArrows();
                scene()->removeItem(itemAt(event->pos())); ///removes the Node from the scene
            } else if (itemAt(event->pos())->type() == 8){  // Don't try to kill the View
                if (itemAt(event->pos())->parentItem()->type() == NodeItem::Type){
                    qgraphicsitem_cast<NodeItem *>((itemAt(event->pos()))->parentItem())->removeArrows();
                    scene()->removeItem((itemAt(event->pos()))->parentItem()); ///removes the Node from the scene
                }else
                    scene()->removeItem((itemAt(event->pos()))->parentItem()); ///removes the Parameter

            }else if(itemAt(event->pos())->type() == GroupItem::Type) {
                QList<QGraphicsItem *> list;
                list=itemAt(event->pos())->childItems();
                //qDebug()<<"Begin group items->";

                for (int i = 0; i < list.size(); i++) {
                    if (list.at(i)->type() != 8)

                        (list.at(i))->setParentItem(0);
                  //  qDebug()<<(list.at(i)->type());
                }
                //qDebug()<<"<-End group items";
                scene()->removeItem(itemAt(event->pos()));
            }


            event->setAccepted(true);// tell the base class we are handling this event


        }
    }if (line != 0 && myMode == InsertLine) {

            QList<QGraphicsItem *> startItems = scene()->items(line->line().p1());
            if (startItems.count() && startItems.first() == line)
                startItems.removeFirst();

            QList<QGraphicsItem *> endItems = scene()->items(line->line().p2());
            if (endItems.count() && endItems.first() == line)
                endItems.removeFirst();

            if (startItems.count() &&startItems.first()->type() == 8)
                startItems.first() = startItems.first()->parentItem();
            if (endItems.count() && endItems.first()->type() == 8)
                endItems.first() = endItems.first()->parentItem();


            scene()->removeItem(line); //remove temporary line
            delete line;
            //! [11] //! [12]



            if (startItems.count() > 0 && endItems.count() > 0 &&
                    startItems.first()->type() == NodeItem::Type &&
                    endItems.first()->type() == NodeItem::Type &&
                    startItems.first() != endItems.first()) {
                NodeItem *startItem =
                        qgraphicsitem_cast<NodeItem *>(startItems.first());
                NodeItem *endItem =
                        qgraphicsitem_cast<NodeItem *>(endItems.first());


                RemapArrow *arrow = new RemapArrow(startItem, endItem);
                if (arrow->getArrowData()==true){

                    startItem->addArrow(arrow);
                    endItem->addArrow(arrow);
                    arrow->setZValue(-20);
                    scene()->addItem(arrow);
                    arrow->updatePosition();
                }
            }
        }

    //! [12] //! [13]
    line = 0;

    QGraphicsView::mouseReleaseEvent(event);
}
Ejemplo n.º 10
0
void CallModelTest::testDeleteEvent()
{
    CallModel model;
    watcher.setModel(&model);

    // force change of sorting to SortByContact
    QVERIFY( model.setFilter( CallModel::SortByContact ) );
    QVERIFY( model.getEvents() );
    QVERIFY(watcher.waitForModelReady());

    /* by contact:
     * -----------
     * "", received (0)
     * user2, received (0)
     * user1, received (0)
     */
    // delete first event from hidden number
    Event e = model.event( model.index( 0, 0 ) );
    QVERIFY( e.isValid() );
    QCOMPARE( e.type(), Event::CallEvent );
    qDebug() << "EVENT:" << e.id() << "|" << e.remoteUid() << "|" << e.direction() << "|" << e.isMissedCall() << "|" << e.eventCount();
    QCOMPARE( e.direction(), Event::Inbound );
    QCOMPARE( e.isMissedCall(), false );
    QCOMPARE( e.remoteUid(), QLatin1String("<hidden>") );
    // delete it
    QVERIFY( model.deleteEvent( e.id() ) );
    QVERIFY( watcher.waitForDeleted() );
    // correct test helper lists to match current situation
    QMutableListIterator<TestCallItem> i(testCalls);
    while (i.hasNext()) {
        i.next();
        if (i.value().remoteUid == QLatin1String("<hidden>"))
            i.remove();
    }
    // test if model contains what we want it does
    testGetEvents( CallModel::SortByContact, 2, testCalls );

    /* by contact:
     * -----------
     * user2, received (0)
     * user1, received (0)
     */
    // delete first group from user2
    e = model.event( model.index( 0, 0 ) );
    QVERIFY( e.isValid() );
    QCOMPARE( e.type(), Event::CallEvent );
    qDebug() << "EVENT:" << e.id() << "|" << e.remoteUid() << "|" << e.direction() << "|" << e.isMissedCall() << "|" << e.eventCount();
    QCOMPARE( e.direction(), Event::Inbound );
    QCOMPARE( e.isMissedCall(), false );
    QCOMPARE( e.remoteUid(), REMOTEUID2 );
    // delete it
    QVERIFY( model.deleteEvent( e.id() ) );
    QVERIFY( watcher.waitForDeleted(2) );
    // correct test helper lists to match current situation
    i = QMutableListIterator<TestCallItem>(testCalls);
    while (i.hasNext()) {
        i.next();
        if (i.value().remoteUid == REMOTEUID2)
            i.remove();
    }
    // test if model contains what we want it does
    testGetEvents( CallModel::SortByContact, 1, testCalls );

    // force change of sorting to SortByTime
    QVERIFY( model.setFilter( CallModel::SortByTime ) );
    QVERIFY(watcher.waitForModelReady());

    /* by time:
     * --------
     * user1, received (6)***
     * user1, dialed   (1)
     * user1, missed   (2)
     * user1, dialed   (1)
     * user1, received (2)
     * user1, missed   (1)
     * user1, dialed   (2)
     *
     *     ||
     *     \/
     *
     * user1, dialed   (1)
     * user1, missed   (2)
     * user1, dialed   (1)
     * user1, received (2)
     * user1, missed   (1)
     * user1, dialed   (2)
     */
    // take the event
    e = model.event( model.index( 0, 0 ) );
    QVERIFY( e.isValid() );
    QCOMPARE( e.type(), Event::CallEvent );
    qDebug() << "EVENT:" << e.id() << "|" << e.remoteUid() << "|" << e.direction() << "|" << e.isMissedCall() << "|" << e.eventCount();
    QCOMPARE( e.direction(), Event::Inbound );
    QCOMPARE( e.isMissedCall(), false );
    // delete it
    QVERIFY( model.deleteEvent( e.id() ) );
    QVERIFY( watcher.waitForDeleted(6) );
    // correct test helper lists to match current situation
    foreach (TestCallItem item, testCalls) {
        qDebug() << item.remoteUid << item.callType << item.eventCount;
    }
    testCalls.takeFirst(); testCalls.takeFirst();
    foreach (TestCallItem item, testCalls) {
        qDebug() << item.remoteUid << item.callType << item.eventCount;
    }
    // test if model contains what we want it does
    testGetEvents( CallModel::SortByTime, testCalls.count(), testCalls );

    /* by time:
     * --------
     * user1, dialed   (1) <---\
     * user1, missed   (2)***   regrouping
     * user1, dialed   (1) <---/
     * user1, received (2)
     * user1, missed   (1)
     * user1, dialed   (2)
     *
     *     ||
     *     \/
     *
     * user1, dialed   (2)
     * user1, received (2)
     * user1, missed   (1)
     * user1, dialed   (2)
     */
    // take the event
    e = model.event( model.index( 1, 0 ) );
    QVERIFY( e.isValid() );
    QCOMPARE( e.type(), Event::CallEvent );
    qDebug() << "EVENT:" << e.id() << "|" << e.remoteUid() << "|" << e.direction() << "|" << e.isMissedCall() << "|" << e.eventCount();
    QCOMPARE( e.direction(), Event::Inbound );
    QCOMPARE( e.isMissedCall(), true );
    // delete it
    QVERIFY( model.deleteEvent( e.id() ) );
    QVERIFY( watcher.waitForDeleted(2) );
    // correct test helper lists to match current situation
    testCalls.takeFirst(); testCalls.takeFirst(); testCalls.first().eventCount = 2;
    // test if model contains what we want it does
    testGetEvents( CallModel::SortByTime, testCalls.count(), testCalls );


    // force change of sorting to SortByContact
    QVERIFY( model.setFilter( CallModel::SortByContact ) );
    QVERIFY(watcher.waitForModelReady());
    /* by contact:
     * -----------
     * user1, dialed (0)***
     *
     *    ||
     *    \/
     *
     * (empty)
     */
    // take the event
    e = model.event( model.index( 0, 0 ) );
    QVERIFY( e.isValid() );
    QCOMPARE( e.type(), Event::CallEvent );
    qDebug() << "EVENT:" << e.id() << "|" << e.remoteUid() << "|" << e.direction() << "|" << e.isMissedCall() << "|" << e.eventCount();
    QCOMPARE( e.direction(), Event::Outbound );
    QCOMPARE( e.isMissedCall(), false );
    // delete it
    QVERIFY( model.deleteEvent( e.id() ) );
    QVERIFY( watcher.waitForDeleted(7) );
    // correct test helper lists to match current situation
    testCalls.clear();
    // test if model contains what we want it does
    testGetEvents( CallModel::SortByContact, 0, testCalls );
}
Ejemplo n.º 11
0
void
ReplaceWidget::onPartitionSelected()
{
    if ( Calamares::JobQueue::instance()->globalStorage()->value( "firmwareType" ) == "efi" )
        m_isEfi = true;

    if ( m_ui->partitionTreeView->currentIndex() == QModelIndex() )
    {
        updateStatus( CalamaresUtils::PartitionPartition,
                      tr( "Select where to install %1.<br/>"
                          "<font color=\"red\">Warning: </font>this will delete all files "
                          "on the selected partition." )
                          .arg( *Calamares::Branding::VersionedName ) );
        setNextEnabled( false );
        return;
    }

    bool ok = false;
    double requiredSpaceB = Calamares::JobQueue::instance()
                            ->globalStorage()
                            ->value( "requiredStorageGB" )
                            .toDouble( &ok ) * 1024 * 1024 * 1024;

    PartitionModel* model = qobject_cast< PartitionModel* >( m_ui->partitionTreeView->model() );
    if ( model && ok )
    {
        const QStringList osproberLines = Calamares::JobQueue::instance()
                                    ->globalStorage()
                                    ->value( "osproberLines" ).toStringList();

        Partition* partition = model->partitionForIndex( m_ui->partitionTreeView->currentIndex() );
        if ( !partition ||
             partition->state() != Partition::StateNone )
        {
            updateStatus( CalamaresUtils::Fail,
                          tr( "The selected item does not appear to be a valid partition." ) );
            setNextEnabled( false );
            return;
        }

        if ( partition->roles().has( PartitionRole::Unallocated ) )
        {
            updateStatus( CalamaresUtils::Fail,
                          tr( "%1 cannot be installed on empty space. Please select an "
                              "existing partition." )
                          .arg( *Calamares::Branding::VersionedName ) );
            setNextEnabled( false );
            return;
        }

        if ( partition->roles().has( PartitionRole::Extended ) )
        {
            updateStatus( CalamaresUtils::Fail,
                          tr( "%1 cannot be installed on an extended partition. Please select an "
                              "existing primary or logical partition." )
                          .arg( *Calamares::Branding::VersionedName ) );
            setNextEnabled( false );
            return;
        }

        if ( partition->partitionPath().isEmpty() )
        {
            updateStatus( CalamaresUtils::Fail,
                          tr( "%1 cannot be installed on this partition." )
                          .arg( *Calamares::Branding::VersionedName ) );
            setNextEnabled( false );
            return;
        }

        QString prettyName = tr( "Data partition (%1)" )
                             .arg( partition->fileSystem().name() );
        for ( const QString& line : osproberLines )
        {
            QStringList lineColumns = line.split( ':' );

            QString path = lineColumns.value( 0 ).simplified();
            if ( path == partition->partitionPath() )
            {
                QString osName;
                if ( !lineColumns.value( 1 ).simplified().isEmpty() )
                    osName = lineColumns.value( 1 ).simplified();
                else if ( !lineColumns.value( 2 ).simplified().isEmpty() )
                    osName = lineColumns.value( 2 ).simplified();

                if ( osName.isEmpty() )
                {
                    prettyName = tr( "Unknown system partition (%1)" )
                                 .arg( partition->fileSystem().name() );
                }
                else
                {
                    prettyName = tr ( "%1 system partition (%2)" )
                                 .arg( osName.replace( 0, 1, osName.at( 0 ).toUpper() ) )
                                 .arg( partition->fileSystem().name() );
                }
                break;
            }
        }

        if ( partition->capacity() < requiredSpaceB )
        {
            updateStatus( CalamaresUtils::Fail,
                          tr( "<strong>%4</strong><br/><br/>"
                              "The partition %1 is too small for %2. Please select a partition "
                              "with capacity at least %3 GiB." )
                          .arg( partition->partitionPath() )
                          .arg( *Calamares::Branding::VersionedName )
                          .arg( requiredSpaceB / ( 1024. * 1024. * 1024. ),
                                0, 'f', 1 )
                          .arg( prettyName ) );
            setNextEnabled( false );
            return;
        }

        m_ui->bootComboBox->hide();
        m_ui->bootComboBox->clear();
        m_ui->bootStatusLabel->hide();
        m_ui->bootStatusLabel->clear();

        if ( m_isEfi )
        {
            QList< Partition* > efiSystemPartitions = m_core->efiSystemPartitions();
            if ( efiSystemPartitions.count() == 0 )
            {
                updateStatus( CalamaresUtils::Fail,
                              tr( "<strong>%2</strong><br/><br/>"
                                  "An EFI system partition cannot be found anywhere "
                                  "on this system. Please go back and use manual "
                                  "partitioning to set up %1." )
                              .arg( *Calamares::Branding::ShortProductName )
                              .arg( prettyName ) );
                setNextEnabled( false );
            }
            else if ( efiSystemPartitions.count() == 1 )
            {
                updateStatus( CalamaresUtils::PartitionPartition,
                              tr( "<strong>%3</strong><br/><br/>"
                                  "%1 will be installed on %2.<br/>"
                                  "<font color=\"red\">Warning: </font>all data on partition "
                                  "%2 will be lost.")
                                .arg( *Calamares::Branding::VersionedName )
                                .arg( partition->partitionPath() )
                                .arg( prettyName ) );
                m_ui->bootStatusLabel->show();
                m_ui->bootStatusLabel->setText(
                    tr( "The EFI system partition at %1 will be used for starting %2." )
                        .arg( efiSystemPartitions.first()->partitionPath() )
                        .arg( *Calamares::Branding::ShortProductName ) );
                setNextEnabled( true );
            }
            else
            {
                updateStatus( CalamaresUtils::PartitionPartition,
                              tr( "<strong>%3</strong><br/><br/>"
                                  "%1 will be installed on %2.<br/>"
                                  "<font color=\"red\">Warning: </font>all data on partition "
                                  "%2 will be lost.")
                                .arg( *Calamares::Branding::VersionedName )
                                .arg( partition->partitionPath() )
                                .arg( prettyName ) );
                m_ui->bootStatusLabel->show();
                m_ui->bootStatusLabel->setText( tr( "EFI system partition:" ) );
                m_ui->bootComboBox->show();
                for ( int i = 0; i < efiSystemPartitions.count(); ++i )
                {
                    Partition* efiPartition = efiSystemPartitions.at( i );
                    m_ui->bootComboBox->addItem( efiPartition->partitionPath(), i );
                    if ( efiPartition->devicePath() == partition->devicePath() &&
                         efiPartition->number() == 1 )
                        m_ui->bootComboBox->setCurrentIndex( i );
                }
                setNextEnabled( true );
            }
        }
        else
        {
            updateStatus( CalamaresUtils::PartitionPartition,
                          tr( "<strong>%3</strong><br/><br/>"
                              "%1 will be installed on %2.<br/>"
                              "<font color=\"red\">Warning: </font>all data on partition "
                              "%2 will be lost.")
                            .arg( *Calamares::Branding::VersionedName )
                            .arg( partition->partitionPath() )
                            .arg( prettyName ) );
            setNextEnabled( true );
        }
    }
}
Ejemplo n.º 12
0
void CollapsibleGroup::dropEvent(QDropEvent *event)
{
    frame->setProperty("target", false);
    frame->setStyleSheet(frame->styleSheet());
    const QString effects = QString::fromUtf8(event->mimeData()->data("kdenlive/effectslist"));
    //event->acceptProposedAction();
    QDomDocument doc;
    doc.setContent(effects, true);
    QDomElement e = doc.documentElement();
    int ix = e.attribute("kdenlive_ix").toInt();
    if (ix == 0 || e.tagName() == "effectgroup") {
	if (e.tagName() == "effectgroup") {
	    // dropped a group on another group
	    QDomNodeList pastedEffects = e.elementsByTagName("effect");
	    if (pastedEffects.isEmpty() || m_subWidgets.isEmpty()) {
		// Buggy groups, should not happen
		event->ignore();
		return;
	    }
	    QList <int> pastedEffectIndexes;
	    QList <int> currentEffectIndexes;
	    EffectInfo pasteInfo;
	    pasteInfo.fromString(pastedEffects.at(0).toElement().attribute("kdenlive_info"));
	    if (pasteInfo.groupIndex == -1) {
		// Group dropped from effects list, add effect
		e.setAttribute("kdenlive_ix", m_subWidgets.last()->effectIndex());
		emit addEffect(e);
		event->setDropAction(Qt::CopyAction);
		event->accept();
		return;
	    }
	    // Moving group
	    for (int i = 0; i < pastedEffects.count(); i++) {
		pastedEffectIndexes << pastedEffects.at(i).toElement().attribute("kdenlive_ix").toInt();
	    }
	    for (int i = 0; i < m_subWidgets.count(); i++) {
		currentEffectIndexes << m_subWidgets.at(i)->effectIndex();
	    }
	    kDebug()<<"PASTING: "<<pastedEffectIndexes<<" TO "<<currentEffectIndexes;
	    if (pastedEffectIndexes.at(0) < currentEffectIndexes.at(0)) {
		// Pasting group after current one:
		emit moveEffect(pastedEffectIndexes, currentEffectIndexes.last(), pasteInfo.groupIndex, pasteInfo.groupName);
	    }
	    else {
		// Group moved before current one
		emit moveEffect(pastedEffectIndexes, currentEffectIndexes.first(), pasteInfo.groupIndex, pasteInfo.groupName);
	    }
	    event->setDropAction(Qt::MoveAction);
	    event->accept();
	    return;
	}
	// effect dropped from effects list, add it
	e.setAttribute("kdenlive_info", m_info.toString());
	if (!m_subWidgets.isEmpty()) {
	    e.setAttribute("kdenlive_ix", m_subWidgets.at(0)->effectIndex());
	}
	emit addEffect(e);
	event->setDropAction(Qt::CopyAction);
	event->accept();
	return;
    }
    if (m_subWidgets.isEmpty()) return;
    int new_index = m_subWidgets.last()->effectIndex();
    emit moveEffect(QList <int> () <<ix, new_index, m_info.groupIndex, m_title->text());
    event->setDropAction(Qt::MoveAction);
    event->accept();
}
Ejemplo n.º 13
0
bool QAudioDeviceInfoInternal::testSettings(const QAudioFormat& format) const
{
    // Set nearest to closest settings that do work.
    // See if what is in settings will work (return value).
    int err = 0;
    snd_pcm_t* handle;
    snd_pcm_hw_params_t *params;
    QString dev = device;

    QList<QByteArray> devices = QAudioDeviceInfoInternal::availableDevices(QAudio::AudioOutput);

    if(dev.compare(QLatin1String("default")) == 0) {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
        dev = QLatin1String(devices.first().constData());
#else
        dev = QLatin1String("hw:0,0");
#endif
    } else {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
        dev = device;
#else
        int idx = 0;
        char *name;

        QString shortName = device.mid(device.indexOf(QLatin1String("="),0)+1);

        while(snd_card_get_name(idx,&name) == 0) {
            if(shortName.compare(QLatin1String(name)) == 0)
                break;
            idx++;
        }
        dev = QString(QLatin1String("hw:%1,0")).arg(idx);
#endif
    }
    if(mode == QAudio::AudioOutput) {
        err=snd_pcm_open( &handle,dev.toLocal8Bit().constData(),SND_PCM_STREAM_PLAYBACK,0);
    } else {
        err=snd_pcm_open( &handle,dev.toLocal8Bit().constData(),SND_PCM_STREAM_CAPTURE,0);
    }
    if(err < 0) {
        handle = 0;
        return false;
    }

    bool testChannel = false;
    bool testCodec = false;
    bool testFreq = false;
    bool testType = false;
    bool testSize = false;

    int  dir = 0;

    snd_pcm_nonblock( handle, 0 );
    snd_pcm_hw_params_alloca( &params );
    snd_pcm_hw_params_any( handle, params );

    // set the values!
    snd_pcm_hw_params_set_channels(handle,params,format.channels());
    snd_pcm_hw_params_set_rate(handle,params,format.frequency(),dir);

    err = -1;

    switch(format.sampleSize()) {
        case 8:
            if(format.sampleType() == QAudioFormat::SignedInt)
                err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S8);
            else if(format.sampleType() == QAudioFormat::UnSignedInt)
                err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U8);
            break;
        case 16:
            if(format.sampleType() == QAudioFormat::SignedInt) {
                if(format.byteOrder() == QAudioFormat::LittleEndian)
                    err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S16_LE);
                else if(format.byteOrder() == QAudioFormat::BigEndian)
                    err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S16_BE);
            } else if(format.sampleType() == QAudioFormat::UnSignedInt) {
                if(format.byteOrder() == QAudioFormat::LittleEndian)
                    err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U16_LE);
                else if(format.byteOrder() == QAudioFormat::BigEndian)
                    err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U16_BE);
            }
            break;
        case 32:
            if(format.sampleType() == QAudioFormat::SignedInt) {
                if(format.byteOrder() == QAudioFormat::LittleEndian)
                    err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S32_LE);
                else if(format.byteOrder() == QAudioFormat::BigEndian)
                    err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S32_BE);
            } else if(format.sampleType() == QAudioFormat::UnSignedInt) {
                if(format.byteOrder() == QAudioFormat::LittleEndian)
                    err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U32_LE);
                else if(format.byteOrder() == QAudioFormat::BigEndian)
                    err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U32_BE);
            }
    }

    // For now, just accept only audio/pcm codec
    if(!format.codec().startsWith(QLatin1String("audio/pcm"))) {
        err=-1;
    } else
        testCodec = true;

    if(err>=0 && format.channels() != -1) {
        err = snd_pcm_hw_params_test_channels(handle,params,format.channels());
        if(err>=0)
            err = snd_pcm_hw_params_set_channels(handle,params,format.channels());
        if(err>=0)
            testChannel = true;
    }

    if(err>=0 && format.frequency() != -1) {
        err = snd_pcm_hw_params_test_rate(handle,params,format.frequency(),0);
        if(err>=0)
            err = snd_pcm_hw_params_set_rate(handle,params,format.frequency(),dir);
        if(err>=0)
            testFreq = true;
    }

    if((err>=0 && format.sampleSize() != -1) &&
            (format.sampleType() != QAudioFormat::Unknown)) {
        switch(format.sampleSize()) {
            case 8:
                if(format.sampleType() == QAudioFormat::SignedInt)
                    err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S8);
                else if(format.sampleType() == QAudioFormat::UnSignedInt)
                    err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U8);
                break;
            case 16:
                if(format.sampleType() == QAudioFormat::SignedInt) {
                    if(format.byteOrder() == QAudioFormat::LittleEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S16_LE);
                    else if(format.byteOrder() == QAudioFormat::BigEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S16_BE);
                } else if(format.sampleType() == QAudioFormat::UnSignedInt) {
                    if(format.byteOrder() == QAudioFormat::LittleEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U16_LE);
                    else if(format.byteOrder() == QAudioFormat::BigEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U16_BE);
                }
                break;
            case 32:
                if(format.sampleType() == QAudioFormat::SignedInt) {
                    if(format.byteOrder() == QAudioFormat::LittleEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S32_LE);
                    else if(format.byteOrder() == QAudioFormat::BigEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S32_BE);
                } else if(format.sampleType() == QAudioFormat::UnSignedInt) {
                    if(format.byteOrder() == QAudioFormat::LittleEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U32_LE);
                    else if(format.byteOrder() == QAudioFormat::BigEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U32_BE);
                }
        }
        if(err>=0) {
            testSize = true;
            testType = true;
        }
    }
    if(err>=0)
        err = snd_pcm_hw_params(handle, params);

    if(err == 0) {
        // settings work
        // close()
        if(handle)
            snd_pcm_close(handle);
        return true;
    }
    if(handle)
        snd_pcm_close(handle);

    return false;
}
Ejemplo n.º 14
0
bool QgsHelp::urlExists( const QString &url )
{
  QUrl helpUrl( url );
  QTcpSocket socket;

  QgsSettings settings;
  bool proxyEnabled = settings.value( QStringLiteral( "proxy/proxyEnabled" ), false ).toBool();
  if ( proxyEnabled )
  {
    QNetworkProxy proxy;
    QString proxyHost = settings.value( QStringLiteral( "proxy/proxyHost" ), QString() ).toString();
    int proxyPort = settings.value( QStringLiteral( "proxy/proxyPort" ), QString() ).toString().toInt();
    QString proxyUser = settings.value( QStringLiteral( "proxy/proxyUser" ), QString() ).toString();
    QString proxyPassword = settings.value( QStringLiteral( "proxy/proxyPassword" ), QString() ).toString();

    QString proxyTypeString = settings.value( QStringLiteral( "proxy/proxyType" ), QString() ).toString();

    if ( proxyTypeString == QLatin1String( "DefaultProxy" ) )
    {
      QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery();
      if ( !proxies.isEmpty() )
      {
        proxy = proxies.first();
      }
    }
    else
    {
      QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy;
      if ( proxyTypeString == QLatin1String( "Socks5Proxy" ) )
      {
        proxyType = QNetworkProxy::Socks5Proxy;
      }
      else if ( proxyTypeString == QLatin1String( "HttpProxy" ) )
      {
        proxyType = QNetworkProxy::HttpProxy;
      }
      else if ( proxyTypeString == QLatin1String( "HttpCachingProxy" ) )
      {
        proxyType = QNetworkProxy::HttpCachingProxy;
      }
      else if ( proxyTypeString == QLatin1String( "FtpCachingProxy" ) )
      {
        proxyType = QNetworkProxy::FtpCachingProxy;
      }
      proxy = QNetworkProxy( proxyType, proxyHost, proxyPort, proxyUser, proxyPassword );
    }
    socket.setProxy( proxy );
  }

  socket.connectToHost( helpUrl.host(), 80 );
  if ( socket.waitForConnected() )
  {
    socket.write( "HEAD " + helpUrl.path().toUtf8() + " HTTP/1.1\r\n"
                  "Host: " + helpUrl.host().toUtf8() + "\r\n\r\n" );
    if ( socket.waitForReadyRead() )
    {
      QByteArray bytes = socket.readAll();
      if ( bytes.contains( "200 OK" ) ||  bytes.contains( "302 Found" ) )
      {
        return true;
      }
    }
  }

  return false;
}
Ejemplo n.º 15
0
void ConnectionManager::decodeAddress(const QString& address, ConnectionSettings& settings,
                                      bool checkIfServerGroup)
{
    QString host;
    QString port = "6667";

    // Full-length IPv6 address with port
    // Example: RFC 2732 notation:     [2001:0DB8:0000:0000:0000:0000:1428:57ab]:6666
    // Example: Non-RFC 2732 notation: 2001:0DB8:0000:0000:0000:0000:1428:57ab:6666
    if (address.count(':')==8)
    {
        host = address.section(':',0,-2).remove('[').remove(']');
        port = address.section(':',-1);
    }
    // Full-length IPv6 address without port or not-full-length IPv6 address with port
    // Example: Without port, RFC 2732 notation:     [2001:0DB8:0000:0000:0000:0000:1428:57ab]
    // Example: Without port, Non-RFC 2732 notation: 2001:0DB8:0000:0000:0000:0000:1428:57ab
    // Example: With port, RFC 2732 notation:        [2001:0DB8::1428:57ab]:6666
    else if (address.count(':')>=4)
    {
        // Last segment does not end with ], but the next to last does;
        // Assume not-full-length IPv6 address with port
        // Example: [2001:0DB8::1428:57ab]:6666
        if (address.section(':',0,-2).endsWith(']') && !address.section(':',-1).endsWith(']'))
        {
            host = address.section(':',0,-2).remove('[').remove(']');
            port = address.section(':',-1);
        }
        else
        {
            QString addressCopy = address;
            host = addressCopy.remove('[').remove(']');
        }
    }
    // IPv4 address or ordinary hostname with port
    // Example: IPv4 address with port: 123.123.123.123:6666
    // Example: Hostname with port:     irc.bla.org:6666
    else if (address.count(':')==1)
    {
        host = address.section(':',0,-2);
        port = address.section(':',-1);
    }
    else
        host = address;

    // Try to assign server group.
    if (checkIfServerGroup && Preferences::isServerGroup(host))
    {
        // If host is found to be the name of a server group.

        int serverGroupId = Preferences::serverGroupIdsByName(host).first();

        Konversation::ServerGroupSettingsPtr serverGroup;

        serverGroup = Preferences::serverGroupById(serverGroupId);

        settings.setServerGroup(serverGroup);

        if (serverGroup->serverList().size() > 0)
            settings.setServer(serverGroup->serverList()[0]);
    }
    else
    {
        QList<Konversation::ServerGroupSettingsPtr> groups = Preferences::serverGroupsByServer(host);
        if (!groups.isEmpty())
        {
            // If the host is found to be part of a server group's server list.

            Konversation::ServerGroupSettingsPtr serverGroup = groups.first();

            settings.setServerGroup(serverGroup);
        }

        Konversation::ServerSettings server;

        server.setHost(host);
        server.setPort(port.toInt());

        settings.setServer(server);
    }
}
Ejemplo n.º 16
0
// Return an instance from the pool.
QsciScintillaBase *QsciScintillaBase::pool()
{
    return poolList.first();
}
Ejemplo n.º 17
0
/**
 * @brief This function finds the best representative marker from a group of markers. This is needed to display a thumbnail for a marker group.
 * @param indices A list containing markers.
 * @param sortKey Determines the sorting options and is actually of type GPSImageInfoSorter::SortOptions
 * @return Returns the index of the marker.
 */
QPersistentModelIndex MapViewModelHelper::bestRepresentativeIndexFromList(const QList<QPersistentModelIndex>& list,
                                                                          const int sortKey)
{
    if (list.isEmpty())
    {
        return QPersistentModelIndex();
    }

    // first convert from QPersistentModelIndex to QModelIndex
    QList<QModelIndex> indexList;
    QModelIndex        bestIndex;

    for (int i=0; i < list.count(); ++i)
    {
        const QModelIndex newIndex(list.at(i));
        indexList.append(newIndex);
    }

    switch (d->application)
    {
        case MapWidgetView::ApplicationDigikam:
        {
            // now get the ImageInfos and convert them to GPSImageInfos
            const QList<ImageInfo> imageInfoList =  d->model->imageInfos(indexList);
            GPSImageInfo::List gpsImageInfoList;

            foreach(const ImageInfo& imageInfo, imageInfoList)
            {
                GPSImageInfo gpsImageInfo;

                if (ImagePropertiesSideBarDB::GPSImageInfofromImageInfo(imageInfo, &gpsImageInfo))
                {
                    gpsImageInfoList << gpsImageInfo;
                }
            }

            if (gpsImageInfoList.size()!=indexList.size())
            {
                // this is a problem, and unexpected
                return indexList.first();
            }

            // now determine the best available index
            bestIndex                     = indexList.first();
            GPSImageInfo bestGPSImageInfo = gpsImageInfoList.first();

            for (int i=1; i < gpsImageInfoList.count(); ++i)
            {
                const GPSImageInfo& currentInfo = gpsImageInfoList.at(i);

                if (GPSImageInfoSorter::fitsBetter(bestGPSImageInfo, GeoIface::SelectedNone,
                                                   currentInfo, GeoIface::SelectedNone,
                                                   GeoIface::SelectedNone, GPSImageInfoSorter::SortOptions(sortKey)))
                {
                    bestIndex        = indexList.at(i);
                    bestGPSImageInfo = currentInfo;
                }
            }

            break;
        }

        case MapWidgetView::ApplicationImportUI:
        {
            // now get the CamItemInfo and convert them to GPSImageInfos
            const QList<CamItemInfo> imageInfoList =  d->importModel->camItemInfos(indexList);
            GPSImageInfo::List       gpsImageInfoList;

            foreach(const CamItemInfo& imageInfo, imageInfoList)
            {
                const DMetadata meta(imageInfo.url().toLocalFile());
                double          lat, lng;
                const bool      hasCoordinates = meta.getGPSLatitudeNumber(&lat) && meta.getGPSLongitudeNumber(&lng);

                if (!hasCoordinates)
                {
                    continue;
                }

                GeoIface::GeoCoordinates coordinates(lat, lng);

                double alt;
                const bool haveAlt = meta.getGPSAltitude(&alt);

                if (haveAlt)
                {
                    coordinates.setAlt(alt);
                }

                GPSImageInfo gpsImageInfo;
                gpsImageInfo.coordinates = coordinates;
                gpsImageInfo.dateTime    = meta.getImageDateTime();
                gpsImageInfo.rating      = meta.getImageRating();
                gpsImageInfo.url         = imageInfo.url();
                gpsImageInfoList << gpsImageInfo;
            }

            if (gpsImageInfoList.size()!=indexList.size())
            {
                // this is a problem, and unexpected
                return indexList.first();
            }

            // now determine the best available index
            bestIndex                     = indexList.first();
            GPSImageInfo bestGPSImageInfo = gpsImageInfoList.first();

            for (int i=1; i < gpsImageInfoList.count(); ++i)
            {
                const GPSImageInfo& currentInfo = gpsImageInfoList.at(i);

                if (GPSImageInfoSorter::fitsBetter(bestGPSImageInfo, GeoIface::SelectedNone,
                                                   currentInfo, GeoIface::SelectedNone,
                                                   GeoIface::SelectedNone, GPSImageInfoSorter::SortOptions(sortKey)))
                {
                    bestIndex        = indexList.at(i);
                    bestGPSImageInfo = currentInfo;
                }
            }

            break;
        }
    }
Ejemplo n.º 18
0
  QSharedPointer<CaptureDevice> TimeLapseCapture::parseArguments() {
    QCommandLineParser parser;
    ErrorMessageHelper die(err.device(), &parser);

    parser.setApplicationDescription("Tool for capture sequence of images from digital camera (V4L or GPhoto2 API).");
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption outputOption(QStringList() << "o" << "output",
      QCoreApplication::translate("main", "Output directory."),
      QCoreApplication::translate("main", "directory"));
    parser.addOption(outputOption);

    QCommandLineOption verboseOption(QStringList() << "V" << "verbose",
      QCoreApplication::translate("main", "Verbose output."));
    parser.addOption(verboseOption);

    QCommandLineOption deviceOption(QStringList() << "d" << "device",
      QCoreApplication::translate("main", "Capture device."),
      QCoreApplication::translate("main", "device"));
    parser.addOption(deviceOption);

    QCommandLineOption listOption(QStringList() << "l" << "list",
      QCoreApplication::translate("main", "List available capture devices and exits."));
    parser.addOption(listOption);

    QCommandLineOption intervalOption(QStringList() << "i" << "interval",
      QCoreApplication::translate("main", "Capture interval (in milliseconds). Default is 10000."),
      QCoreApplication::translate("main", "interval"));
    parser.addOption(intervalOption);

    QCommandLineOption cntOption(QStringList() << "c" << "count",
      QCoreApplication::translate("main", "How many images should be captured. Default value is infinite."),
      QCoreApplication::translate("main", "count"));
    parser.addOption(cntOption);

    QCommandLineOption rowOption(QStringList() << "r" << "raw",
      QCoreApplication::translate("main", "Store all captured images in raw."));
    parser.addOption(rowOption);

    QCommandLineOption getShutterSpeedOption(QStringList() << "s" << "shutterspeed-options",
      QCoreApplication::translate("main", "Prints available shutterspeed setting choices and exits."));
    parser.addOption(getShutterSpeedOption);

    QCommandLineOption adaptiveShutterSpeedOption(QStringList() << "a" << "adaptive-shutterspeed",
      QCoreApplication::translate("main",
      "Camera shutterspeed will be adaptively changed after exposure metering.\n"
      "This option setup how many images should be used for exposure metering. \n"
      "Default value is 0 - it means that shutterspeed will not be changed by capture tool."
      ),
      QCoreApplication::translate("main", "count"));
    parser.addOption(adaptiveShutterSpeedOption);

    QCommandLineOption shutterSpeedStepOption(QStringList() << "shutterspeed-step",
      QCoreApplication::translate("main",
      "How large should be step when changing shutterspeed. \n"
      "Default value is 1."
      ),
      QCoreApplication::translate("main", "step"));
    parser.addOption(shutterSpeedStepOption);

    QCommandLineOption minShutterSpeedOption(QStringList() << "min-shutterspeed",
      QCoreApplication::translate("main", "Minimum shutterspeed (fastest shutter) used by adaptive shutterspeed"),
      QCoreApplication::translate("main", "shutterspeed"));
    parser.addOption(minShutterSpeedOption);

    QCommandLineOption maxShutterSpeedOption(QStringList() << "max-shutterspeed",
      QCoreApplication::translate("main",
      "Maximum shutterspeed (slowest shutter) used by adaptive shutterspeed.\n"
      "If camera supports BULB shutterspeed, it can be defined as \"BULB:XX\" here (it means bulb with XX s exposure)."
      ),
      QCoreApplication::translate("main", "shutterspeed"));
    parser.addOption(maxShutterSpeedOption);

    // Process the actual command line arguments given by the user
    parser.process(*this);

    // verbose?
    if (!parser.isSet(verboseOption)) {
      blackHole = new BlackHoleDevice();
      verboseOutput.setDevice(blackHole);
    } else {
      // verbose
      verboseOutput << "Turning on verbose output..." << endl;
      verboseOutput << applicationName() << " " << applicationVersion() << endl;
    }

    // raw?
    storeRawImages = parser.isSet(rowOption);

    // interval
    if (parser.isSet(intervalOption)) {
      bool ok = false;
      long i = parser.value(intervalOption).toLong(&ok);
      if (!ok) die << "Cant parse interval.";
      if (i <= 0) die << "Interval have to be possitive";
      interval = i;
    }

    // count
    if (parser.isSet(cntOption)) {
      bool ok = false;
      int i = parser.value(cntOption).toInt(&ok);
      if (!ok) die << "Cant parse count.";
      cnt = i;
    }

    // list devices?
    QList<QSharedPointer < CaptureDevice>> devices = listDevices();
    QSharedPointer<CaptureDevice> dev;
    if (parser.isSet(listOption)) {
      if (devices.isEmpty()) {
        die << QCoreApplication::translate("main", "No compatible capture device found");
      } else {
        out << "Found devices: " << endl;
        for (QSharedPointer<CaptureDevice> d : devices) {
          out << "  " << d->toString() << endl;
        }
      }
      std::exit(0);
    }
    // capture device
    bool assigned = false;
    if (!parser.isSet(deviceOption)) {
      verboseOutput << "Found devices: " << endl;
      for (QSharedPointer<CaptureDevice> d : devices) {
        if (!assigned) {
          dev = d;
          assigned = true;
        }
        verboseOutput << "  " << d->toString() << endl;
      }
      if (!assigned)
        die << "No supported device.";
    } else {
      QString devVal = parser.value(deviceOption);
      for (QSharedPointer<CaptureDevice> d : devices) {
        if (d->toString().contains(devVal, Qt::CaseInsensitive)) {
          assigned = true;
          dev = d;
          break;
        }
      }
      if (!assigned) {
        die << QString("No device matching \"%1\" found.").arg(devVal);
      }
    }
    out << "Using device " << dev->toString() << endl;

    // getShutterSpeedOption ?
    QList<ShutterSpeedChoice> choices = dev->getShutterSpeedChoices();
    if (parser.isSet(getShutterSpeedOption)) {
      if (choices.isEmpty()) {
        err << "Device " << dev->toShortString() << " don't support shutterspeed setting" << endl;
      } else {
        out << "Device " << dev->toShortString() << " shutterspeed choices:" << endl;
        for (ShutterSpeedChoice ch : choices) {
          out << "  " << ch.toString() << endl;
        }
        out << "Current shutter speed: " << dev->currentShutterSpeed().toString() << endl;
      }
      std::exit(0);
    }

    // automatic chutter speed
    // this functionality is experimental!
    if (parser.isSet(adaptiveShutterSpeedOption)) {
      bool ok = false;
      int changeThreshold = parser.value(adaptiveShutterSpeedOption).toInt(&ok);
      if (!ok) die << "Cant parse adaptive shutterspeed option.";

      if (changeThreshold > 0) {

        if (choices.isEmpty()) {
          die << "Camera don't support shutterspeed setting.";
        } else {

          ShutterSpeedChoice currentShutterSpeed;
          ShutterSpeedChoice minShutterSpeed;
          ShutterSpeedChoice maxShutterSpeed;

          currentShutterSpeed = dev->currentShutterSpeed();
          minShutterSpeed = choices.first();
          for (ShutterSpeedChoice ch : choices) {
            if ((!ch.isBulb()) && ch.toMicrosecond() > maxShutterSpeed.toMicrosecond())
              maxShutterSpeed = ch;
          }

          int shutterSpeedStep = 1;
          if (parser.isSet(shutterSpeedStepOption)) {
            bool ok = false;
            shutterSpeedStep = parser.value(shutterSpeedStepOption).toInt(&ok);
            if (!ok) die << "Cant parse shutterspeed step.";
            if (shutterSpeedStep < 1) die << "Shutterspeed step can be less than one.";
          }
          if (parser.isSet(minShutterSpeedOption)) {
            QString optStr = parser.value(minShutterSpeedOption);
            minShutterSpeed = getShutterSpeed(optStr, choices, &die);
          }
          if (parser.isSet(maxShutterSpeedOption)) {
            QString optStr = parser.value(maxShutterSpeedOption);
            maxShutterSpeed = getShutterSpeed(optStr, choices, &die);
          }

          out << "Using automatic shutter speed:" << endl;
          out << "  current shutter speed: " << currentShutterSpeed.toString() << endl;
          out << "  min shutter speed:     " << minShutterSpeed.toString() << endl;
          out << "  max shutter speed:     " << maxShutterSpeed.toString() << endl;
          out << "  change threshold:      " << changeThreshold << endl;
          out << "  change step:           " << shutterSpeedStep << endl;

          if (minShutterSpeed.toMicrosecond() <= 0
            || maxShutterSpeed.toMicrosecond() <= 0
            || maxShutterSpeed.toMicrosecond() < minShutterSpeed.toMicrosecond())
            die << "Invalid shutter speed configurarion";

          if (maxShutterSpeed.toMs() > interval) {
            err << QString("Warning: Maximum shutter speed (%1 ms) is greater than capture interval (%2 ms)!")
              .arg(maxShutterSpeed.toMs())
              .arg(interval) << endl;
          }
          shutterSpdAlg = new MatrixMeteringAlg(choices, currentShutterSpeed, minShutterSpeed, maxShutterSpeed,
            &err, &verboseOutput, changeThreshold, shutterSpeedStep);
        }
      }
    }

    // output
    if (!parser.isSet(outputOption))
      die << "Output directory is not set";
    output = QDir(parser.value(outputOption));
    if (output.exists())
      err << "Output directory exists already." << endl;
    if (!output.mkpath("."))
      die << QString("Can't create output directory %1 !").arg(output.path());

    return dev;
  }
Ejemplo n.º 19
0
QString MetavoxelEditor::getSelectedAttribute() const {
    QList<QListWidgetItem*> selectedItems = _attributes->selectedItems();
    return selectedItems.isEmpty() ? QString() : selectedItems.first()->text();
}
Ejemplo n.º 20
0
CPlainWriteWindow::CPlainWriteWindow(const QList<CSwordModuleInfo*> & moduleList, CMDIArea * parent)
    : CDisplayWindow(moduleList, parent)
    , m_writeDisplay(0)
{
    setKey( CSwordKey::createInstance(moduleList.first()) );
}
Ejemplo n.º 21
0
static QList<double> _calcPrettyBreaks( double minimum, double maximum, int classes )
{

  // C++ implementation of R's pretty algorithm
  // Based on code for determining optimal tick placement for statistical graphics
  // from the R statistical programming language.
  // Code ported from R implementation from 'labeling' R package
  //
  // Computes a sequence of about 'classes' equally spaced round values
  // which cover the range of values from 'minimum' to 'maximum'.
  // The values are chosen so that they are 1, 2 or 5 times a power of 10.

  QList<double> breaks;
  if ( classes < 1 )
  {
    breaks.append( maximum );
    return breaks;
  }

  int minimumCount = ( int ) classes / 3;
  double shrink = 0.75;
  double highBias = 1.5;
  double adjustBias = 0.5 + 1.5 * highBias;
  int divisions = classes;
  double h = highBias;
  double cell;
  int U;
  bool small = false;
  double dx = maximum - minimum;

  if ( dx == 0 && maximum == 0 )
  {
    cell = 1.0;
    small = true;
    U = 1;
  }
  else
  {
    cell = qMax( qAbs( minimum ), qAbs( maximum ) );
    if ( adjustBias >= 1.5 * h + 0.5 )
    {
      U = 1 + ( 1.0 / ( 1 + h ) );
    }
    else
    {
      U = 1 + ( 1.5 / ( 1 + adjustBias ) );
    }
    small = dx < ( cell * U * qMax( 1, divisions ) * 1e-07 * 3.0 );
  }

  if ( small )
  {
    if ( cell > 10 )
    {
      cell = 9 + cell / 10;
      cell = cell * shrink;
    }
    if ( minimumCount > 1 )
    {
      cell = cell / minimumCount;
    }
  }
  else
  {
    cell = dx;
    if ( divisions > 1 )
    {
      cell = cell / divisions;
    }
  }
  if ( cell < 20 * 1e-07 )
  {
    cell = 20 * 1e-07;
  }

  double base = pow( 10.0, floor( log10( cell ) ) );
  double unit = base;
  if (( 2 * base ) - cell < h *( cell - unit ) )
  {
    unit = 2.0 * base;
    if (( 5 * base ) - cell < adjustBias *( cell - unit ) )
    {
      unit = 5.0 * base;
      if (( 10.0 * base ) - cell < h *( cell - unit ) )
      {
        unit = 10.0 * base;
      }
    }
  }
  // Maybe used to correct for the epsilon here??
  int start = floor( minimum / unit + 1e-07 );
  int end = ceil( maximum / unit - 1e-07 );

  // Extend the range out beyond the data. Does this ever happen??
  while ( start * unit > minimum + ( 1e-07 * unit ) )
  {
    start = start - 1;
  }
  while ( end * unit < maximum - ( 1e-07 * unit ) )
  {
    end = end + 1;
  }
  QgsDebugMsg( QString( "pretty classes: %1" ).arg( end ) );

  // If we don't have quite enough labels, extend the range out
  // to make more (these labels are beyond the data :( )
  int k = floor( 0.5 + end - start );
  if ( k < minimumCount )
  {
    k = minimumCount - k;
    if ( start >= 0 )
    {
      end = end + k / 2;
      start = start - k / 2 + k % 2;
    }
    else
    {
      start = start - k / 2;
      end = end + k / 2 + k % 2;
    }
  }
  double minimumBreak = start * unit;
  //double maximumBreak = end * unit;
  int count = end - start;

  for ( int i = 1; i < count + 1; i++ )
  {
    breaks.append( minimumBreak + i * unit );
  }

  if ( breaks.isEmpty() )
    return breaks;

  if ( breaks.first() < minimum )
  {
    breaks[0] = minimum;
  }
  if ( breaks.last() > maximum )
  {
    breaks[breaks.count()-1] = maximum;
  }

  return breaks;
} // _calcPrettyBreaks
/** Returns the rendered text using the modules in the list and using the key parameter. The displayoptions and filter options are used, too. */
const QString Rendering::CBookDisplay::text( const QList<CSwordModuleInfo*>& modules, const QString& keyName, const CSwordBackend::DisplayOptions displayOptions, const CSwordBackend::FilterOptions filterOptions ) {
    CSwordBookModuleInfo* book = dynamic_cast<CSwordBookModuleInfo*>(modules.first());
    Q_ASSERT(book);

    CSwordBackend::DisplayOptions dOpts = displayOptions;
    dOpts.lineBreaks = true; //books should render with blocks, not with inlined sections

    CDisplayRendering render(dOpts, filterOptions);
    CDisplayRendering::KeyTree tree;
    CDisplayRendering::KeyTreeItem::Settings itemSettings;

    // the number of levels which should be display together, 1 means display no entries together
    int displayLevel = book->config( CSwordModuleInfo::DisplayLevel ).toInt();

    boost::scoped_ptr<CSwordTreeKey> key (
        dynamic_cast<CSwordTreeKey*>( CSwordKey::createInstance(book) )
    );
    key->key(keyName); //set the key to position we'd like to get

    const unsigned long offset = key->getOffset();

    // standard of DisplayLevel, display nothing together
    // if the current key is the root entry don't display anything together!

    if ((displayLevel <= 1) || (key->key().isEmpty() || (key->key() == "/") )) {
        tree.append( new CDisplayRendering::KeyTreeItem( key->key(), modules, itemSettings ) );

        const QString renderedText = render.renderKeyTree(tree);
        key->setOffset( offset );

        qDeleteAll(tree);      // Dispose of the heap allocated objects pointed to in tree.
        return renderedText;
    };

    /**
    * Check whether displaying displayLevel levels together is possible.
    * For this count the childs and parents
    * of the required position
    */

    int possibleLevels = 1; //we start with the default value of displayLevel, which means no entries together

    while ( key->sword::TreeKeyIdx::parent() && (key->key() != "/") && !key->key().isEmpty() ) {//add parents
        ++possibleLevels;
    };

    //   key->key(keyName); //set the key to the start position

    key->setOffset( offset );

    while ( key->firstChild( )) { //add childs
        ++possibleLevels;
    };

    if (possibleLevels < displayLevel) { //too few levels available!
        //display current level, we could also decide to display the available levels together
        tree.append( new CDisplayRendering::KeyTreeItem( key->key(), modules, itemSettings ) );

        const QString renderedText = render.renderKeyTree(tree);
        key->setOffset( offset );
        qDeleteAll(tree);      // Dispose of the heap allocated objects pointed to in tree.
        return renderedText;
    };

    if ((displayLevel > 2) && (displayLevel == possibleLevels)) { //fix not to diplay the whole module
        --displayLevel;
    }

    // at this point we're sure that we can display the required levels toogether
    // at the moment we're at the lowest level, so we only have to go up!
    for (int currentLevel = 1; currentLevel < displayLevel; ++currentLevel) { //we start again with 1 == standard of displayLevel

        if ( !key->sword::TreeKeyIdx::parent() ) { //something went wrong although we checked before! Be safe and return entry's text
            tree.append( new CDisplayRendering::KeyTreeItem( key->key(), modules, itemSettings ) );

            const QString renderedText = render.renderKeyTree(tree);
            key->setOffset( offset );
            qDeleteAll(tree);      // Dispose of the heap allocated objects pointed to in tree.
            return renderedText;
        };
    };

    // no we can display all sub levels together! We checked before that this is possible!
    itemSettings.highlight = (key->key() == keyName);

    tree.append( new CDisplayRendering::KeyTreeItem( key->key(), modules, itemSettings ) );

    //const bool hasToplevelText = !key->strippedText().isEmpty();
    key->firstChild(); //go to the first sibling on the same level

    setupRenderTree(key.get(), &tree, keyName);

    const QString renderedText = render.renderKeyTree(tree);

    key->setOffset( offset ); //restore key

    qDeleteAll(tree);      // Dispose of the heap allocated objects pointed to in tree.
    return renderedText;
}
bool QAudioOutputPrivate::open()
{
    if(opened)
        return true;

#ifdef DEBUG_AUDIO
    QTime now(QTime::currentTime());
    qDebug()<<now.second()<<"s "<<now.msec()<<"ms :open()";
#endif
    timeStamp.restart();
    elapsedTimeOffset = 0;

    int dir;
    int err=-1;
    int count=0;
    unsigned int freakuency=settings.frequency();

    QString dev = QLatin1String(m_device.constData());
    QList<QByteArray> devices = QAudioDeviceInfoInternal::availableDevices(QAudio::AudioOutput);
    if(dev.compare(QLatin1String("default")) == 0) {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
        dev = QLatin1String(devices.first().constData());
#else
        dev = QLatin1String("hw:0,0");
#endif
    } else {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
        dev = QLatin1String(m_device);
#else
        int idx = 0;
        char *name;

        QString shortName = QLatin1String(m_device.mid(m_device.indexOf('=',0)+1).constData());

	while(snd_card_get_name(idx,&name) == 0) {
            if(qstrncmp(shortName.toLocal8Bit().constData(),name,shortName.length()) == 0)
                break;
            idx++;
	}
        dev = QString(QLatin1String("hw:%1,0")).arg(idx);
#endif
    }

    // Step 1: try and open the device
    while((count < 5) && (err < 0)) {
        err=snd_pcm_open(&handle,dev.toLocal8Bit().constData(),SND_PCM_STREAM_PLAYBACK,0);
        if(err < 0)
            count++;
    }
    if (( err < 0)||(handle == 0)) {
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        return false;
    }
    snd_pcm_nonblock( handle, 0 );

    // Step 2: Set the desired HW parameters.
    snd_pcm_hw_params_alloca( &hwparams );

    bool fatal = false;
    QString errMessage;
    unsigned int chunks = 8;

    err = snd_pcm_hw_params_any( handle, hwparams );
    if ( err < 0 ) {
        fatal = true;
        errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_any: err = %1").arg(err);
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_rate_resample( handle, hwparams, 1 );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_rate_resample: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_access( handle, hwparams, access );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_access: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = setFormat();
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_format: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_channels( handle, hwparams, (unsigned int)settings.channels() );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_channels: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_rate_near( handle, hwparams, &freakuency, 0 );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_rate_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_buffer_time_near(handle, hwparams, &buffer_time, &dir);
        if ( err < 0 ) {
            fatal = true;
                errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_buffer_time_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_period_time_near(handle, hwparams, &period_time, &dir);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_period_time_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_periods_near(handle, hwparams, &chunks, &dir);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_periods_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params(handle, hwparams);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params: err = %1").arg(err);
        }
    }
    if( err < 0) {
        qWarning()<<errMessage;
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        return false;
    }
    snd_pcm_hw_params_get_buffer_size(hwparams,&buffer_frames);
    buffer_size = snd_pcm_frames_to_bytes(handle,buffer_frames);
    snd_pcm_hw_params_get_period_size(hwparams,&period_frames, &dir);
    period_size = snd_pcm_frames_to_bytes(handle,period_frames);
    snd_pcm_hw_params_get_buffer_time(hwparams,&buffer_time, &dir);
    snd_pcm_hw_params_get_period_time(hwparams,&period_time, &dir);

    // Step 3: Set the desired SW parameters.
    snd_pcm_sw_params_t *swparams;
    snd_pcm_sw_params_alloca(&swparams);
    snd_pcm_sw_params_current(handle, swparams);
    snd_pcm_sw_params_set_start_threshold(handle,swparams,period_frames);
    snd_pcm_sw_params_set_stop_threshold(handle,swparams,buffer_frames);
    snd_pcm_sw_params_set_avail_min(handle, swparams,period_frames);
    snd_pcm_sw_params(handle, swparams);

    // Step 4: Prepare audio
    if(audioBuffer == 0)
        audioBuffer = new char[snd_pcm_frames_to_bytes(handle,buffer_frames)];
    snd_pcm_prepare( handle );
    snd_pcm_start(handle);

    // Step 5: Setup callback and timer fallback
    snd_async_add_pcm_handler(&ahandler, handle, async_callback, this);
    bytesAvailable = bytesFree();

    // Step 6: Start audio processing
    timer->start(period_time/1000);

    clockStamp.restart();
    timeStamp.restart();
    elapsedTimeOffset = 0;
    errorState  = QAudio::NoError;
    totalTimeValue = 0;
    opened = true;

    return true;
}
Ejemplo n.º 24
0
void ZhiyuanCard::use(Room *room, ServerPlayer *source, const QList<ServerPlayer *> &targets) const{
    targets.first()->obtainCard(this);
    room->setPlayerMark(source, "zhiyuan", source->getMark("zhiyuan") - 1);
}
Ejemplo n.º 25
0
K3b::DataPropertiesDialog::DataPropertiesDialog( const QList<K3b::DataItem*>& dataItems, QWidget* parent )
    : QDialog( parent )
{
    setWindowTitle( i18n("File Properties") );

    m_dataItems = dataItems;

    m_labelIcon = new QLabel( this );
    if ( dataItems.count() == 1 ) {
        m_editName = new KLineEdit( this );
        m_editName->setValidator( K3b::Validators::iso9660Validator( false, this ) );
        m_labelType = new QLabel( this );
        m_labelLocalName = new KSqueezedTextLabel( this );
        m_labelLocalLocation = new KSqueezedTextLabel( this );
        m_labelLocalLinkTarget = new KSqueezedTextLabel( this );
        m_extraInfoLabel = new QLabel( this );
    }
    else {
        m_multiSelectionLabel = new QLabel( this );
    }

    m_labelLocation = new KSqueezedTextLabel( this );
    m_labelSize = new QLabel( this );
    m_labelBlocks = new QLabel( this );

    // layout
    // -----------------------------
    QGridLayout* grid = new QGridLayout( this );

    grid->addWidget( m_labelIcon, 0, 0 );
    if ( dataItems.count() == 1 ) {
        grid->addWidget( m_editName, 0, 2 );
    }
    else {
        grid->addWidget( m_multiSelectionLabel, 0, 2 );
    }
    int row = 1;

    m_spacerLine = new QFrame( this );
    m_spacerLine->setFrameStyle( QFrame::HLine | QFrame::Sunken );
    grid->addWidget( m_spacerLine, row, 0, 1, 3 );
    ++row;
    if ( dataItems.count() == 1 ) {
        grid->addWidget( new QLabel( i18n("Type:"), this ), row, 0 );
        grid->addWidget( m_labelType, row++, 2 );
        grid->addWidget( m_extraInfoLabel, row++, 2 );
    }
    grid->addWidget( new QLabel( i18n("Location:"), this ), row, 0 );
    grid->addWidget( m_labelLocation, row++, 2 );
    grid->addWidget( new QLabel( i18n("Size:"), this ), row, 0 );
    grid->addWidget( m_labelSize, row++, 2 );
    grid->addWidget( new QLabel( i18n("Used blocks:"), this ), row, 0 );
    grid->addWidget( m_labelBlocks, row++, 2 );

    m_spacerLine = new QFrame( this );
    m_spacerLine->setFrameStyle( QFrame::HLine | QFrame::Sunken );
    grid->addWidget( m_spacerLine, row, 0, 1, 3 );
    ++row;

    if ( dataItems.count() == 1 ) {
        m_labelLocalNameText = new QLabel( i18n("Local name:"), this );
        grid->addWidget( m_labelLocalNameText, row, 0 );
        grid->addWidget( m_labelLocalName, row++, 2 );
        m_labelLocalLocationText = new QLabel( i18n("Local location:"), this );
        grid->addWidget( m_labelLocalLocationText, row, 0 );
        grid->addWidget( m_labelLocalLocation, row++, 2 );
        m_labelLocalLinkTargetText = new QLabel( i18n("Local link target:"), this );
        grid->addWidget( m_labelLocalLinkTargetText, row, 0 );
        grid->addWidget( m_labelLocalLinkTarget, row++, 2 );
    }

    grid->addItem( new QSpacerItem( 50, 1, QSizePolicy::Fixed, QSizePolicy::Fixed ), 0, 1 );
    grid->setColumnStretch( 2, 1 );


    // OPTIONS
    // /////////////////////////////////////////////////
    QTabWidget* optionTab = new QTabWidget( this );
    m_spacerLine = new QFrame( this );
    m_spacerLine->setFrameStyle( QFrame::HLine | QFrame::Sunken );

    grid->addWidget( m_spacerLine, row++, 0, 1, 3 );
    grid->setRowStretch( row++, 1 );
    grid->addWidget( optionTab, row++, 0, 1, 3 );

    QWidget* hideBox = new QWidget( optionTab );
    QGridLayout* hideBoxGrid = new QGridLayout( hideBox );
    m_checkHideOnRockRidge = new QCheckBox( i18n("Hide on RockRidge"), hideBox );
    m_checkHideOnJoliet = new QCheckBox( i18n("Hide on Joliet"), hideBox );
    hideBoxGrid->addWidget( m_checkHideOnRockRidge, 0, 0 );
    hideBoxGrid->addWidget( m_checkHideOnJoliet, 1, 0 );
    hideBoxGrid->setRowStretch( 2, 1 );
//   grid->addMultiCellWidget( m_checkHideOnRockRidge, 10, 10, 0, 2 );
//   grid->addMultiCellWidget( m_checkHideOnJoliet, 11, 11, 0, 2 );

    QWidget* sortingBox = new QWidget( optionTab );
    QGridLayout* sortingBoxGrid = new QGridLayout( sortingBox );
    m_editSortWeight = new KLineEdit( sortingBox );
    m_editSortWeight->setValidator( new QIntValidator( -2147483647, 2147483647, m_editSortWeight ) );
    m_editSortWeight->setAlignment( Qt::AlignRight );
    sortingBoxGrid->addWidget( new QLabel( i18n("Sort weight:"), sortingBox ), 0, 0 );
    sortingBoxGrid->addWidget( m_editSortWeight, 0, 1 );
    sortingBoxGrid->setColumnStretch( 1, 1 );
    sortingBoxGrid->setRowStretch( 1, 1 );

    optionTab->addTab( hideBox, i18n("Settings") );
    optionTab->addTab( sortingBox, i18n("Advanced") );


    // load the data
    // ----------------------------
    if ( dataItems.count() == 1 ) {
        loadItemProperties( dataItems.first() );
    }
    else {
        loadListProperties( dataItems );
    }


    m_checkHideOnRockRidge->setToolTip( i18n("Hide this file in the RockRidge filesystem") );
    m_checkHideOnJoliet->setToolTip( i18n("Hide this file in the Joliet filesystem") );
    m_editSortWeight->setToolTip( i18n("Modify the physical sorting") );
    m_checkHideOnRockRidge->setWhatsThis( i18n("<p>If this option is checked, the file or folder "
                                               "(and its entire contents) will be hidden on the "
                                               "ISO 9660 and RockRidge filesystem.</p>"
                                               "<p>This is useful, for example, for having different README "
                                               "files for RockRidge and Joliet, which can be managed "
                                               "by hiding README.joliet on RockRidge and README.rr "
                                               "on the Joliet filesystem.</p>") );
    m_checkHideOnJoliet->setWhatsThis( i18n("<p>If this option is checked, the file or folder "
                                            "(and its entire contents) will be hidden on the "
                                            "Joliet filesystem.</p>"
                                            "<p>This is useful, for example, for having different README "
                                            "files for RockRidge and Joliet, which can be managed "
                                            "by hiding README.joliet on RockRidge and README.rr "
                                            "on the Joliet filesystem.</p>") );
    m_editSortWeight->setWhatsThis( i18n("<p>This value modifies the physical sort order of the files "
                                         "in the ISO 9660 filesystem. A higher weighting means that the "
                                         "file will be located closer to the beginning of the image "
                                         "(and the disk)."
                                         "<p>This option is useful in order to optimize the data layout "
                                         "on a medium."
                                         "<p><b>Caution:</b> This does not sort the order of the file "
                                         "names that appear in the ISO 9660 folder. "
                                         "It sorts the order in which the file data is "
                                         "written to the image.") );

    QDialogButtonBox* buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this );
    grid->addWidget( buttonBox, row++, 0, 1, 3 );
    connect( buttonBox, SIGNAL(accepted()), SLOT(accept()) );
    connect( buttonBox, SIGNAL(rejected()), SLOT(reject()) );
}
Ejemplo n.º 26
0
void SCgView::updateActionsState(int idx)
{
    mContextObject = 0;

    QList <QGraphicsItem*> items = scene()->selectedItems();
    if(items.size() == 1)
        if(SCgObject::isSCgObjectType(items.first()->type()))
            mContextObject = static_cast<SCgObject*>(items.first());

    if(mContextObject && mContextObject->type() == SCgNode::Type)
    {
        mActionChangeContent->setEnabled(true);
        mActionChangeContent->setVisible(true);
        SCgNode *node = static_cast<SCgNode*>(mContextObject);

        bool isContentData = node->isContentData();
        if(isContentData)
        {
            mActionChangeContent->setText(tr("Change content"));

            mActionShowContent->setChecked(node->isContentVisible());
        }
        else
            mActionChangeContent->setText(tr("Set content"));

        mActionDeleteContent->setEnabled(isContentData);
        mActionDeleteContent->setVisible(isContentData);

        mActionShowContent->setEnabled(isContentData);
        mActionShowContent->setVisible(isContentData);

    }else
    {
        mActionChangeContent->setEnabled(false);
        mActionChangeContent->setVisible(false);
        mActionShowContent->setEnabled(false);
        mActionShowContent->setVisible(false);
        mActionDeleteContent->setEnabled(false);
        mActionDeleteContent->setVisible(false);
    }

    bool pairType = (mContextObject != 0) && (mContextObject->type() == SCgPair::Type);

    mActionSwapPairOrient->setEnabled(pairType);
    mActionSwapPairOrient->setVisible(pairType);

    mActionChangeIdtf->setEnabled(mContextObject);
    mActionChangeIdtf->setVisible(mContextObject);

    mActionContourDelete->setEnabled(mContextObject && mContextObject->type() == SCgContour::Type);
    mActionContourDelete->setVisible(mContextObject && mContextObject->type() == SCgContour::Type);

    bool isAnySelected = !scene()->selectedItems().isEmpty();
    mActionDelete->setEnabled(isAnySelected);
    mActionCut->setEnabled(isAnySelected);
    mActionCopy->setEnabled(isAnySelected);

    //check for showed/hidden contents
    items = scene()->items();
    SCgNode *node = 0;
    bool oneContentShowed = false, oneContentHidden = false;
    for(int i = 0; i < items.size(); ++i)
    {
        node = qgraphicsitem_cast<SCgNode*>(items.at(i));
        if (node && node->isContentVisible())
            oneContentShowed = true;
        else if (node && !node->isContentVisible() && node->isContentData())
            oneContentHidden = true;
    }
    mActionShowAllContent->setEnabled(oneContentHidden);
    mActionHideAllContent->setEnabled(oneContentShowed);
}
Ejemplo n.º 27
0
RunControl *WinRtDebugSupport::createDebugRunControl(WinRtRunConfiguration *runConfig,
                                                     Core::Id mode,
                                                     QString *errorMessage)
{
    // FIXME: This is just working for local debugging;
    using namespace Debugger;
    DebuggerStartParameters params;
    params.startMode = AttachExternal;
    // The first Thread needs to be resumed manually.
    params.commandsAfterConnect = "~0 m";

    QFileInfo debuggerHelper(QCoreApplication::applicationDirPath()
                             + QLatin1String("/winrtdebughelper.exe"));
    if (!debuggerHelper.isExecutable()) {
        *errorMessage = tr("The WinRT debugging helper is missing from your Qt Creator "
                           "installation. It was assumed to be located at %1").arg(
                    debuggerHelper.absoluteFilePath());
        return 0;
    }

    if (useQmlDebugging(runConfig)) {
        quint16 qmlDebugPort = 0;
        if (!getFreePort(qmlDebugPort, errorMessage))
            return 0;
        runConfig->setArguments(runConfig->arguments() + QLatin1Char(' ')
                    + QmlDebug::qmlDebugTcpArguments(QmlDebug::QmlDebuggerServices, qmlDebugPort));
        params.qmlServerAddress = QHostAddress::LocalHost;
        params.qmlServerPort = qmlDebugPort;
    }

    WinRtRunnerHelper *runner = new WinRtRunnerHelper(runConfig, errorMessage);
    if (!errorMessage->isEmpty())
        return 0;

    QLocalServer server;
    server.listen(QLatin1String("QtCreatorWinRtDebugPIDPipe"));

    runner->debug(debuggerHelper.absoluteFilePath());
    if (!runner->waitForStarted()) {
        *errorMessage = tr("Cannot start the WinRT Runner Tool.");
        return 0;
    }

    if (!server.waitForNewConnection(10000)) {
        *errorMessage = tr("Cannot establish connection to the WinRT debugging helper.");
        return 0;
    }

    while (server.hasPendingConnections()) {
        QLocalSocket *connection = server.nextPendingConnection();
        if (connection->waitForReadyRead(1000)) {
            const QByteArray &output = connection->readAll();
            QList<QByteArray> arg = output.split(':');
            if (arg.first() == "PID") {
                bool ok =false;
                params.attachPID = arg.last().toInt(&ok);
                if (!ok) {
                    *errorMessage = tr("Cannot extract the PID from the WinRT debugging helper. "
                                       "(output: %1)").arg(QString::fromLocal8Bit(output));
                    return 0;
                }
                server.close();
                Debugger::DebuggerRunControl *debugRunControl
                        = createDebuggerRunControl(params, runConfig, errorMessage, mode);
                runner->setDebugRunControl(debugRunControl);
                new WinRtDebugSupport(debugRunControl, runner);
                return debugRunControl;
            }
        }
    }

    server.close();

    *errorMessage = tr("Cannot create an appropriate run control for "
                       "the current run configuration.");

    return 0;
}
Ejemplo n.º 28
0
/** handle the results of the TopDown operator
  * pid ==  0 -> no operator or node have no holistic operator
  * pid == -1 -> can't start process
  * never call for "root" node (this is not root node)
  * this can be "last" node
  */
int INode::evalTopDown(int pid)
{
#ifdef DEBUGMSG
  qDebug("#*  INode::evalTopDown(%s)(%p): pid=%d Start\n",
         (const char *) name(), this, pid);
#endif
  CHECK_PTR(sNode_);
//Hier Absturz weil parent = 0
  CHECK_PTR(parent());
  INode* parent=INode::parent();
  if (pid <= 0) {
#ifdef DEBUGMSG
    qDebug
      ("#  (ERROR -1/0) evalTopDown: can't start process \n  try it structural\n");
#endif
#warning Without Dummy TopDown nothing works
    if (!isLast() && !truncation())
      childTopDown();           //do it structural
    else if (isLast()) {                      //is last node
      status(MI);
      execState(BU);
      parent->childUnlink(this);      //!remove this temporary INode
      parent->decrementCount();
      return 0;
    } else { //is trash
      status(TRASH);
      execState(BU);
      parent->childUnlink(this);      //!remove this temporary INode
      parent->decrementCount();
      return 0;
    }
  }

  if (sNode_->holistic()) {     //pid > 0
    QList < INode > iNodeList = sNode_->evalTopDown(this);
#ifdef DEBUGMSG
qDebug("##*** evalTopDown: %d(min) < %d(ist) < %d(max)",sNode()->minNumNode(),iNodeList.count(), sNode()->maxNumNode());
#endif
    if (!(sNode()->minNumNode() == 0 && sNode()->maxNumNode() == 0 )) //beide eintraege null -> alles erlaubt
      if (iNodeList.count() < sNode()->minNumNode() || iNodeList.count() > sNode()->maxNumNode() ) {
#ifdef DEBUGMSG
qDebug("*****  iNodeList.count %d, sNode->minNumNode %d, sNode->maxNumNode %d \n",iNodeList.count(),sNode()->minNumNode(),sNode()->maxNumNode());
#endif
        status(MI);
        execState(BU);
        truncation(TRUE);
        //! unlink here
        parent->status(TRASH);
        parent->truncation(TRUE);
        parent->childUnlink(this);      //!remove this temporary INode
        parent->decrementCount();
        return 0;
      }
#ifdef DEBUGMSG
    qDebug("#  (INFO) sNode is holistic; count new nodes: %d\n", iNodeList.count());
#endif

    if (iNodeList.isEmpty()) {
#ifdef DEBUGMSG
      qDebug("#  (warning) operator return no result - missing Instance");
#endif
      status(MI);
      execState(BU);
      //! unlink here
      parent->childUnlink(this);      //!remove this temporary INode
      parent->decrementCount();
      return 0;
    }

    parent->incrementCount(iNodeList.count() - 1);
    INode *el;
    parent->childUnlink(this);        //!remove this temporary INode
    for (el = iNodeList.first(); el != 0; el = iNodeList.next()) {
#ifdef DEBUGMSG
      qDebug("# einhaengen: (%p) %s in %s", this,(const char *)el->name(), (const char *)parent->name());
#endif
      if (el->isLast())
        el->status(CI);  //el->execState(BU); ???????????
      else
        el->status(PI);
      el->execState(TD); //}?????????????
      parent->childLink(el);         //insert the new INodes
      analysis_->nodeChange(el);
      if (el->isLast())
        parent->decrementCount();
      else
        el->childTopDown();     //last node have no children
    }
    //delete this; //XXXX
#ifdef DEBUGMSG
      qDebug("# einhaengen: (%p) fertig in %s",this,(const char *)parent->name());
#endif
    return 0;
  }
  else {
    qDebug
      ("#  (ERROR 1) taskFinished no operator found \n  try it structural\n");
    if (isLast())
      qDebug("#  (ERROR 1) last node must be holistic!\n");
    parent->childUnlink(this);        //!remove this temporary INode
    return 0;
  }
}
Ejemplo n.º 29
0
void CppToolsPlugin::test_codegen_definition_middle_member()
{
    const QByteArray srcText = "\n"
            "class Foo\n"  // line 1
            "{\n"
            "void foo();\n" // line 3
            "void bar();\n" // line 4
            "void car();\n" // line 5
            "};\n"
            "\n";

    const QByteArray dstText = QString::fromLatin1(
                "\n"
                "#include \"%1/file.h\"\n" // line 1
                "int x;\n"
                "\n"
                "void Foo::foo()\n" // line 4
                "{\n"
                "\n"
                "}\n" // line 7
                "\n"
                "void Foo::car()\n" // line 9
                "{\n"
                "\n"
                "}\n"
                "\n"
                "int y;\n").arg(QDir::tempPath()).toLatin1();

    Document::Ptr src = Document::create(QDir::tempPath() + QLatin1String("/file.h"));
    Utils::FileSaver srcSaver(src->fileName());
    srcSaver.write(srcText);
    srcSaver.finalize();
    src->setUtf8Source(srcText);
    src->parse();
    src->check();
    QCOMPARE(src->diagnosticMessages().size(), 0);
    QCOMPARE(src->globalSymbolCount(), 1U);

    Document::Ptr dst = Document::create(QDir::tempPath() + QLatin1String("/file.cpp"));
    dst->addIncludeFile(Document::Include(QLatin1String("file.h"), src->fileName(), 1,
                                          Client::IncludeLocal));
    Utils::FileSaver dstSaver(dst->fileName());
    dstSaver.write(dstText);
    dstSaver.finalize();
    dst->setUtf8Source(dstText);
    dst->parse();
    dst->check();
    QCOMPARE(dst->diagnosticMessages().size(), 0);
    QCOMPARE(dst->globalSymbolCount(), 4U);

    Snapshot snapshot;
    snapshot.insert(src);
    snapshot.insert(dst);

    Class *foo = src->globalSymbolAt(0)->asClass();
    QVERIFY(foo);
    QCOMPARE(foo->line(), 1U);
    QCOMPARE(foo->column(), 7U);
    QCOMPARE(foo->memberCount(), 3U);
    Declaration *decl = foo->memberAt(1)->asDeclaration();
    QVERIFY(decl);
    QCOMPARE(decl->line(), 4U);
    QCOMPARE(decl->column(), 6U);

    CppRefactoringChanges changes(snapshot);
    InsertionPointLocator find(changes);
    QList<InsertionLocation> locList = find.methodDefinition(decl);
    QVERIFY(locList.size() == 1);
    InsertionLocation loc = locList.first();
    QCOMPARE(loc.fileName(), dst->fileName());
    QCOMPARE(loc.line(), 7U);
    QCOMPARE(loc.column(), 2U);
    QCOMPARE(loc.prefix(), QLatin1String("\n\n"));
    QCOMPARE(loc.suffix(), QString());
}
Ejemplo n.º 30
0
void qapp::tile_order(xwindow *actclient)
{
	if(smode)
		return;

	xwindow *client,*tmcl=NULL;

	int cct=0,cheight,lh=0;
	QWidget *dt = QApplication::desktop();

	if(actclient != NULL && (clients.find(actclient) == -1 || ! actclient->is_tileable() || actclient->is_unmapped() || ! is_curdesk(actclient)))
		actclient = NULL;

	for(client = clients.first(); client != NULL; client = clients.next())
	{
		if(client != actclient && ! client->is_unmapped() && is_curdesk(client) && client->is_tileable())
			cct++;
	}

	if(actclient == NULL && cct > 0)
		cct--;

	tmaxclient = NULL;
		
	if(cct)
		cheight = (dt->height()-defaults::tb_height)/cct;

	int xpos,xcw,ypos,yp;
	ypos = yp = defaults::toolbar_top?defaults::tb_height+1:0;
	xpos = (int)(dt->width()*defaults::tleftspace);
	xcw = dt->width()-xpos-1;
	
	for(client = clients.first(); client != NULL; client = clients.next())
	{
		if(! client->is_tileable() || client->is_unmapped() || ! is_curdesk(client)) 
			continue;

		if(actclient == NULL || cct == 0)
			actclient = client;
			
		if(client == actclient)
		{
			tmcl = tmaxclient = client;
			continue;
		}
		
		if(lh < 0)
			lh = 0;
			
		client->minimize_frame(cct > defaults::wminframe?TRUE:FALSE);
			
		lh = client->set_tile(xpos+1, ypos-lh, xcw, cheight+lh);
		ypos += cheight;
	}

	if(tmcl != NULL)
	{
		tmcl->minimize_frame(FALSE);
		tmcl->set_tile(0, yp, xpos, dt->height()-defaults::tb_height);
	}
	
	if(actclient != NULL)
		clients.prepend(clients.take(clients.find(actclient)));
}