bool AMDatamanAppControllerForActions2::startupCreateUserInterface()
{
	AMErrorMon::information(this, AMDATAMANAPPCONTROLLER_STARTUP_MESSAGES, "Acquaman Startup: Populating User Interface");
	qApp->processEvents();
	settingsMasterView_ = 0;
	issueSubmissionView_ = 0;
	bottomBar_ = new AMBottomBar();
	// These buttons are never used.  Hiding them.
	bottomBar_->fullScreenButton->hide();
	bottomBar_->adjustScanFinishButton->hide();
	bottomBar_->restartScanButton->hide();
	mw_->addBottomWidget(bottomBar_);
	connect(bottomBar_, SIGNAL(addButtonClicked()), this, SLOT(onAddButtonClicked()));
	connect(bottomBar_, SIGNAL(pauseScanIssued()), this, SIGNAL(pauseScanIssued()));
	connect(bottomBar_, SIGNAL(resumeScanIssued()), this, SIGNAL(resumeScanIssued()));
	connect(bottomBar_, SIGNAL(stopScanIssued()), this, SIGNAL(stopScanIssued()));

	// Create panes in the main window:
	////////////////////////////////////

	// A heading for the scan editors
	scanEditorsParentItem_ = mw_->windowPaneModel()->headingItem("Open Scans");


	// Make a dataview widget and add it under two links/headings: "Runs" and "Experiments". See AMMainWindowModel for more information.
	////////////////////////////////////
	dataView_ = new AMDataViewWithActionButtons();
	dataView_->setWindowTitle("Data");

	QStandardItem* dataViewItem = new QStandardItem();
	dataViewItem->setData(qVariantFromValue((QWidget*)dataView_), AM::WidgetRole);
	dataViewItem->setFlags(Qt::ItemIsEnabled);	// enabled, but should not be selectable
	QFont font = QFont("Lucida Grande", 10, QFont::Bold);
	font.setCapitalization(QFont::AllUppercase);
	dataViewItem->setFont(font);
	dataViewItem->setData(QBrush(QColor::fromRgb(100, 109, 125)), Qt::ForegroundRole);
	dataViewItem->setData(true, AMWindowPaneModel::DockStateRole);

	mw_->windowPaneModel()->appendRow(dataViewItem);

	runsParentItem_ = new QStandardItem(QIcon(":/22x22/view_calendar_upcoming_days.png"), "Runs");
	mw_->windowPaneModel()->initAliasItem(runsParentItem_, dataViewItem, "Runs", -1);
	dataViewItem->appendRow(runsParentItem_);
	experimentsParentItem_ = new QStandardItem(QIcon(":/applications-science.png"), "Experiments");
	mw_->windowPaneModel()->initAliasItem(experimentsParentItem_, dataViewItem, "Experiments", -1);
	dataViewItem->appendRow(experimentsParentItem_);

	// Hook into the sidebar and add Run and Experiment links below these headings.
	runExperimentInsert_ = new AMRunExperimentInsert(AMDatabase::database("user"), runsParentItem_, experimentsParentItem_, this);
	connect(runExperimentInsert_, SIGNAL(newExperimentAdded(QModelIndex)), this, SLOT(onNewExperimentAdded(QModelIndex)));

	// connect the activated signal from the dataview to our own slot
	connect(dataView_, SIGNAL(selectionActivated(QList<QUrl>)), this, SLOT(onDataViewItemsActivated(QList<QUrl>)));
	connect(dataView_, SIGNAL(selectionActivatedSeparateWindows(QList<QUrl>)), this, SLOT(onDataViewItemsActivatedSeparateWindows(QList<QUrl>)));
	connect(dataView_, SIGNAL(selectionExported(QList<QUrl>)), this, SLOT(onDataViewItemsExported(QList<QUrl>)));
	connect(dataView_, SIGNAL(launchScanConfigurationsFromDb(QList<QUrl>)), this, SLOT(onLaunchScanConfigurationsFromDb(QList<QUrl>)));
	connect(dataView_, SIGNAL(fixCDF(QUrl)), this, SLOT(fixCDF(QUrl)));

	// When 'alias' links are clicked in the main window sidebar, we might need to notify some widgets of the details
	connect(mw_, SIGNAL(aliasItemActivated(QWidget*,QString,QVariant)), this, SLOT(onMainWindowAliasItemActivated(QWidget*,QString,QVariant)));
	/////////////////////////

	// Make connections:
	//////////////////////////////

	connect(mw_, SIGNAL(currentPaneChanged(QWidget*)), this, SLOT(onCurrentPaneChanged(QWidget*)));

	// show main window
	mw_->show();

	return true;
}
Example #2
0
void AnalysisThread::addUdpNode(int protoInd)
{
    struct udphdr* pudp_header = (struct udphdr *)this->snifferData.protocalVec.at(protoInd)->pProtocal;

    QStandardItem* udpitem = new QStandardItem();
    this->len = sizeof(struct udphdr);
    setUserRoleData(udpitem);

    QStandardItem* item = new QStandardItem();
    uint16_t src_port = ntohs(pudp_header->source);
    this->len = sizeof(src_port);
    item->setText(QString("Source port: %1").arg(src_port));
    setUserRoleData(item);
    udpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    uint16_t dst_port = ntohs(pudp_header->dest);
    this->len = sizeof(dst_port);
    item->setText(QString("Destination port: %1").arg(dst_port));
    setUserRoleData(item);
    udpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    u_int16_t len = ntohs(pudp_header->len);
    this->len = sizeof(len);
    item->setText(QString("Length: %1").arg(len));
    setUserRoleData(item);
    udpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    u_int16_t check = ntohs(pudp_header->check);
    this->len = sizeof(check);
    item->setText(QString("Checksum: 0x%1 [validation disabled]")
            .arg(check,0,16));
    setUserRoleData(item);
    udpitem->appendRow(item);
    this->offset += this->len;

    udpitem->setText(QString("User Datagram Protocol, Src Port: %1, Dst Port: %2")
            .arg(src_port)
            .arg(dst_port));

    this->model->setItem(this->irow++, 0, udpitem);   

    // Add the application data, we just analysis ssdp
    ApplicationData* pad = NULL;
    try{
        pad = static_cast<ApplicationData*>(this->snifferData.
               protocalVec.at(protoInd+1)->pProtocal);
    } catch(std::exception)
    {
        return;
    }
    if (pad == NULL)
    {
        return;
    }

    if (pad->strProtocal == SnifferType::SSDP_PROTOCAL)
    {
        addHttpNode(pad);
    }

}
Example #3
0
void AnalysisThread::addEtherNode(int protoInd)
{
    SnifferProtocal* psp = this->snifferData.protocalVec.at(protoInd);
    struct ether_header* pether_header = (struct ether_header *)psp->pProtocal;
    QStandardItem* etheritem = new QStandardItem();
    this->offset = 0;
    this->len = sizeof(struct ether_header);
    setUserRoleData(etheritem);
    
    QString tmpmacDst = SnifferUtil::macToHost(pether_header->ether_dhost);
    QString tmpmacSrc = SnifferUtil::macToHost(pether_header->ether_shost);
    etheritem->setText(QString("Ethernet V2, Src: %1, Dst: %2")
            .arg(tmpmacSrc)
            .arg(tmpmacDst));


    // Destination
    QStandardItem* item = new QStandardItem();
    item->setText("Destination: " + tmpmacDst);
    this->len = sizeof(pether_header->ether_dhost);
    setUserRoleData(item);
    
    QStandardItem* childitem = new QStandardItem();
    this->len = sizeof(pether_header->ether_dhost);
    setUserRoleData(childitem);
    childitem->setText("Address: " + tmpmacDst);
    item->appendRow(childitem);

    childitem = new QStandardItem();
    if (SnifferUtil::getBit(pether_header->ether_dhost[1], 6))
    {
        childitem->setText(QString(".... ..1. .... .... .... .... = LG bit: Locally administered address (this is NOT the factory default)"));
    }
    else
    {
        childitem->setText(QString(".... ..0. .... .... .... .... = LG bit: Globally unique address (factory default)"));
    }
    this->len = 3;
    setUserRoleData(childitem);
    item->appendRow(childitem);

    childitem = new QStandardItem();
    if (SnifferUtil::getBit(pether_header->ether_dhost[1], 7))
    {
        childitem->setText(QString(".... ...1 .... .... .... .... = IG bit: Group address (multicast/broadcast)"));
    }
    else
    {
        childitem->setText(QString(".... ...0 .... .... .... .... = IG bit: Individual address (unicast)"));
    }

    setUserRoleData(childitem);
    item->appendRow(childitem);
    etheritem->appendRow(item);
    this->offset += sizeof(pether_header->ether_dhost);

    // Source 
    item = new QStandardItem();
    item->setText("Source: " + tmpmacSrc);
    this->len = sizeof(pether_header->ether_shost);
    setUserRoleData(item);
    
    childitem = new QStandardItem();
    this->len = sizeof(pether_header->ether_shost);
    setUserRoleData(childitem);
    childitem->setText("Address: " + tmpmacSrc);
    item->appendRow(childitem);

    childitem = new QStandardItem();

    if (SnifferUtil::getBit(pether_header->ether_shost[1], 6))
    {
        childitem->setText(QString(".... ..1. .... .... .... .... = LG bit: Locally administered address (this is NOT the factory default)"));
    }
    else
    {
        childitem->setText(QString(".... ..0. .... .... .... .... = LG bit: Globally unique address (factory default)"));
    }
    this->len = 3;
    setUserRoleData(childitem);
    item->appendRow(childitem);

    childitem = new QStandardItem();
    if (SnifferUtil::getBit(pether_header->ether_shost[1], 7))
    {
        childitem->setText(QString(".... ...1 .... .... .... .... = IG bit: Group address (multicast/broadcast)"));
    }
    else
    {
        childitem->setText(QString(".... ...0 .... .... .... .... = IG bit: Individual address (unicast)"));
    }

    setUserRoleData(childitem);
    item->appendRow(childitem);

    etheritem->appendRow(item);
    this->offset += sizeof(pether_header->ether_shost);

    // Get the protocal type
    int type = ntohs(pether_header->ether_type);
    this->len = sizeof(pether_header->ether_type);

    switch(type)
    {
        case ETHERTYPE_IP:
        {
            item = new QStandardItem();
            item->setText(QString("Type: IP (0x%1)").arg(type,4, 16,QLatin1Char('0')));
            setUserRoleData(item);
            etheritem->appendRow(item);
            this->offset += this->len;
            this->model->setItem(this->irow++, 0, etheritem);   

            addIpNode(protoInd+1);
            break;
        }
        case ETHERTYPE_IPV6:
        {
            item = new QStandardItem();
            item->setText(QString("Type: IPV6 (0x%1)").arg(type,4, 16,QLatin1Char('0')));
            etheritem->appendRow(item);
            this->model->setItem(this->irow++, 0, etheritem);   
            setUserRoleData(item);
            this->offset += this->len;

            addIpV6Node(protoInd+1);
            break;
        }
        case ETHERTYPE_ARP:
        {
            item = new QStandardItem();
            item->setText(QString("Type: ARP (0x%1)").arg(type,4, 16,QLatin1Char('0')));
            setUserRoleData(item);
            etheritem->appendRow(item);
            this->model->setItem(this->irow++, 0, etheritem);   
            this->offset += this->len;

            addArpNode(protoInd+1);
            break;
        }
        default:
        {
            qDebug("Current the sniffer can not analysis the ethernet type:%0x", type);
            break;
        }
    }
}
/**
  \brief Add an ICD association \e asso to the model.
  This member will firstly check if the association can be added to the model.
*/
bool IcdCollectionModel::addAssociation(const Internal::IcdAssociation &asso)
{
    // Can add this association ?
    if (!canAddThisAssociation(asso)) {
        Utils::Log::addError(this, tr("Can not add this Association: %1-%2")
                             .arg(icdBase()->getIcdCode(asso.mainSid()).toString())
                             .arg(icdBase()->getIcdCode(asso.associatedSid()).toString()));
        return false;
    }

    // add Code to model
    d->m_SIDs.append(asso.mainSid().toInt());
    d->m_SIDs.append(asso.associatedSid().toInt());

    // Find root item (mainItem) based on the SID
    QStandardItem *parentItem = 0;
    QStandardItem *main = 0;
    QList<QStandardItem *> list;
    if (asso.mainIsDag()) {
        list = findItems(asso.mainCodeWithDagStar(), Qt::MatchExactly, 0);
    } else {
        list = findItems(asso.associatedCodeWithDagStar(), Qt::MatchExactly, 0);
    }
    if (list.count()==0) {
        parentItem = invisibleRootItem();
        if (asso.mainIsDag()) {
            main = new QStandardItem(asso.mainCodeWithDagStar());
            list
                    << main
                    << new QStandardItem(asso.mainLabel())
                    << new QStandardItem(asso.mainCode())     // Code without daget
                    << new QStandardItem(asso.mainDaget())    // Human readable daget
                    << new QStandardItem(asso.dagCode())      // DagCode
                    << new QStandardItem(asso.mainSid().toString())
                    ;
        } else {
            main = new QStandardItem(asso.associatedCodeWithDagStar());
            list
                    << main
                    << new QStandardItem(asso.associatedLabel())
                    << new QStandardItem(asso.associatedCode())     // Code without daget
                    << new QStandardItem(asso.associatedDaget())    // Human readable daget
                    << new QStandardItem(icdBase()->invertDagCode(asso.dagCode()))
                    << new QStandardItem(asso.associatedSid().toString())
                    ;
        }
        parentItem->appendRow(list);
        parentItem = main;
    } else {
        parentItem = list.at(0);
    }
    list.clear();
    if (asso.mainIsDag()) {
        list
                << new QStandardItem(asso.associatedCodeWithDagStar())
                << new QStandardItem(asso.associatedLabel())
                << new QStandardItem(asso.associatedCode())     // Code without daget
                << new QStandardItem(asso.associatedDaget())    // Human readable daget
                << new QStandardItem(icdBase()->invertDagCode(asso.dagCode()))
                << new QStandardItem(asso.associatedSid().toString())
                ;
    } else {
        list
                << new QStandardItem(asso.mainCodeWithDagStar())
                << new QStandardItem(asso.mainLabel())
                << new QStandardItem(asso.mainCode())     // Code without daget
                << new QStandardItem(asso.mainDaget())    // Human readable daget
                << new QStandardItem(asso.dagCode())      // DagCode
                << new QStandardItem(asso.mainSid().toString())
                ;
    }
    parentItem->appendRow(list);

    // get all exclusions
    if (asso.mainIsDag()) {
        d->m_ExcludedSIDs << icdBase()->getExclusions(asso.mainSid());
    } else {
        d->m_ExcludedSIDs << icdBase()->getExclusions(asso.associatedSid());
    }

    return true;
}
Example #5
0
void AnalysisThread::addArpNode(int protoInd)
{
    struct ether_arp* parp_header = (struct ether_arp *)this->snifferData.protocalVec.at(protoInd)->pProtocal;

    QStandardItem* arpitem = new QStandardItem();
    this->len = sizeof(struct ether_arp);
    unsigned short int op = ntohs(parp_header->ea_hdr.ar_op);
    if (op == 0x01)
    {
        arpitem->setText("Address Resolution Protocol (request)");
    } 
    else if (op == 0x02)
    {
        arpitem->setText("Address Resolution Protocol (response)");
    }
    setUserRoleData(arpitem);

    // Hardware type, here we just analysis the Ether type
    QStandardItem* item = new QStandardItem();
    if (ntohs(parp_header->ea_hdr.ar_hrd) == 0x01)
    {
        item->setText("Hardware type: Ethernet (1)");
    }
    else
    {
        item->setText(QString("Hardware type: 1%").arg(ntohs(parp_header->ea_hdr.ar_hrd)));
    }
    this->len = sizeof(parp_header->ea_hdr.ar_hrd);
    setUserRoleData(item);
    arpitem->appendRow(item);
    this->offset += this->len;
    // Protocal type, here we just analysis the ip type
    item = new QStandardItem();
    if (ntohs(parp_header->ea_hdr.ar_pro) == 0x0800)
    {
        item->setText("Protocol type: IP (0x0800)");
    }
    else
    {
        item->setText(QString("Protocol type: %1").arg(ntohs(parp_header->ea_hdr.ar_pro)));
    }
    this->len = sizeof(parp_header->ea_hdr.ar_pro);
    setUserRoleData(item);
    arpitem->appendRow(item);
    this->offset += this->len;

    // hardware size and protocal size
    item = new QStandardItem();
    this->len = sizeof(parp_header->ea_hdr.ar_hln);
    item->setText(QString("Hardware size: %1").arg(parp_header->ea_hdr.ar_hln));
    setUserRoleData(item);
    arpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    this->len = sizeof(parp_header->ea_hdr.ar_pln);
    item->setText(QString("Protocal size: %1").arg(parp_header->ea_hdr.ar_pln));
    setUserRoleData(item);
    arpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    this->len = sizeof(op);
    if (op == 0x01)
    {
        item->setText("Opcode: request (1)");
    }
    else if (op == 0x02)
    {
        item->setText("Opcode: response (1)");
    }
    else
    {
        qDebug("Error arp op code: %0x", op);
    }
    setUserRoleData(item);
    arpitem->appendRow(item);
    this->offset += this->len;

    // Add address
    item = new QStandardItem();
    this->len = sizeof(parp_header->arp_sha);
    item->setText(QString("Sender MAC address: %1")
            .arg(SnifferUtil::macToHost(parp_header->arp_sha)));
    setUserRoleData(item);
    arpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    this->len = sizeof(parp_header->arp_spa);
    item->setText(QString("Sender IP address: %1")
            .arg(SnifferUtil::netToIp(parp_header->arp_spa)));
    setUserRoleData(item);
    arpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    this->len = sizeof(parp_header->arp_tha);
    item->setText(QString("Target MAC address: %1")
            .arg(SnifferUtil::macToHost(parp_header->arp_tha)));
    setUserRoleData(item);
    arpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    this->len = sizeof(parp_header->arp_tpa);
    item->setText(QString("Target IP address: %1")
            .arg(SnifferUtil::netToIp(parp_header->arp_tpa)));
    setUserRoleData(item);
    arpitem->appendRow(item);
    this->offset += this->len;

    this->model->setItem(this->irow++, 0, arpitem);   
}
ConfigurationContentsWidget::ConfigurationContentsWidget(Window *window) : ContentsWidget(window),
	m_model(new QStandardItemModel(this)),
	m_ui(new Ui::ConfigurationContentsWidget)
{
	m_ui->setupUi(this);

	QSettings defaults(QLatin1String(":/schemas/options.ini"), QSettings::IniFormat, this);
	const QStringList groups = defaults.childGroups();

	for (int i = 0; i < groups.count(); ++i)
	{
		QStandardItem *groupItem = new QStandardItem(Utils::getIcon(QLatin1String("inode-directory")), groups.at(i));

		defaults.beginGroup(groups.at(i));

		const QStringList keys = defaults.childGroups();

		for (int j = 0; j < keys.count(); ++j)
		{
			const QString key = QStringLiteral("%1/%2").arg(groups.at(i)).arg(keys.at(j));
			const QString type = defaults.value(QStringLiteral("%1/type").arg(keys.at(j))).toString();
			const QVariant defaultValue = SettingsManager::getDefaultValue(key);
			const QVariant value = SettingsManager::getValue(key);
			QList<QStandardItem*> optionItems;
			optionItems.append(new QStandardItem(keys.at(j)));
			optionItems.append(new QStandardItem(type));
			optionItems.append(new QStandardItem(value.toString()));
			optionItems[2]->setData(QSize(-1, 30), Qt::SizeHintRole);
			optionItems[2]->setData(key, Qt::UserRole);
			optionItems[2]->setData(type, (Qt::UserRole + 1));
			optionItems[2]->setData(((type == "enumeration") ? defaults.value(QStringLiteral("%1/choices").arg(keys.at(j))).toStringList() : QVariant()), (Qt::UserRole + 2));

			if (value != defaultValue)
			{
				QFont font = optionItems[0]->font();
				font.setBold(true);

				optionItems[0]->setFont(font);
			}

			groupItem->appendRow(optionItems);
		}

		defaults.endGroup();

		m_model->appendRow(groupItem);
	}

	QStringList labels;
	labels << tr("Name") << tr("Type") << tr("Value");

	m_model->setHorizontalHeaderLabels(labels);
	m_model->sort(0);

	m_ui->configurationView->setModel(m_model);
	m_ui->configurationView->setItemDelegate(new ItemDelegate(this));
	m_ui->configurationView->setItemDelegateForColumn(2, new OptionDelegate(false, this));
	m_ui->configurationView->header()->setTextElideMode(Qt::ElideRight);

	connect(SettingsManager::getInstance(), SIGNAL(valueChanged(QString,QVariant)), this, SLOT(optionChanged(QString,QVariant)));
	connect(m_ui->configurationView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(currentChanged(QModelIndex,QModelIndex)));
	connect(m_ui->filterLineEdit, SIGNAL(textChanged(QString)), this, SLOT(filterConfiguration(QString)));
}
Example #7
0
void QgsDb2TableModel::addTableEntry( const QgsDb2LayerProperty &layerProperty )
{
  QgsDebugMsg( QStringLiteral( " DB2 **** %1.%2.%3 type=%4 srid=%5 pk=%6 sql=%7" )
               .arg( layerProperty.schemaName )
               .arg( layerProperty.tableName )
               .arg( layerProperty.geometryColName )
               .arg( layerProperty.type )
               .arg( layerProperty.srid )
               .arg( layerProperty.pkCols.join( ',' ) )
               .arg( layerProperty.sql ) );

  // is there already a root item with the given scheme Name?
  QStandardItem *schemaItem = nullptr;
  QList<QStandardItem *> schemaItems = findItems( layerProperty.schemaName, Qt::MatchExactly, DbtmSchema );

  // there is already an item for this schema
  if ( schemaItems.size() > 0 )
  {
    schemaItem = schemaItems.at( DbtmSchema );
  }
  else
  {
    // create a new toplevel item for this schema
    schemaItem = new QStandardItem( layerProperty.schemaName );
    schemaItem->setFlags( Qt::ItemIsEnabled );
    invisibleRootItem()->setChild( invisibleRootItem()->rowCount(), schemaItem );
  }

  QgsWkbTypes::Type wkbType = QgsDb2TableModel::wkbTypeFromDb2( layerProperty.type );
  if ( wkbType == QgsWkbTypes::Unknown && layerProperty.geometryColName.isEmpty() )
  {
    wkbType = QgsWkbTypes::NoGeometry;
  }

  bool needToDetect = wkbType == QgsWkbTypes::Unknown && layerProperty.type != QLatin1String( "GEOMETRYCOLLECTION" );

  QList<QStandardItem *> childItemList;

  QStandardItem *schemaNameItem = new QStandardItem( layerProperty.schemaName );
  schemaNameItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable );

  QStandardItem *typeItem = new QStandardItem( iconForWkbType( wkbType ),
      needToDetect
      ? tr( "Detecting…" )
      : QgsWkbTypes::displayString( wkbType ) );
  typeItem->setData( needToDetect, Qt::UserRole + 1 );
  typeItem->setData( wkbType, Qt::UserRole + 2 );

  QStandardItem *tableItem = new QStandardItem( layerProperty.tableName );
  QStandardItem *geomItem = new QStandardItem( layerProperty.geometryColName );
  QStandardItem *sridItem = new QStandardItem( layerProperty.srid );
  sridItem->setEditable( false );

  QString pkText;
  QString pkCol;
  switch ( layerProperty.pkCols.size() )
  {
    case 0:
      break;
    case 1:
      pkText = layerProperty.pkCols[0];
      pkCol = pkText;
      break;
    default:
      pkText = tr( "Select…" );
      break;
  }

  QStandardItem *pkItem = new QStandardItem( pkText );
  if ( pkText == tr( "Select…" ) )
    pkItem->setFlags( pkItem->flags() | Qt::ItemIsEditable );

  pkItem->setData( layerProperty.pkCols, Qt::UserRole + 1 );
  pkItem->setData( pkCol, Qt::UserRole + 2 );

  QStandardItem *selItem = new QStandardItem( QLatin1String( "" ) );
  selItem->setFlags( selItem->flags() | Qt::ItemIsUserCheckable );
  selItem->setCheckState( Qt::Checked );
  selItem->setToolTip( tr( "Disable 'Fast Access to Features at ID' capability to force keeping the attribute table in memory (e.g. in case of expensive views)." ) );

  QStandardItem *sqlItem = new QStandardItem( layerProperty.sql );

  childItemList << schemaNameItem;
  childItemList << tableItem;
  childItemList << typeItem;
  childItemList << geomItem;
  childItemList << sridItem;
  childItemList << pkItem;
  childItemList << selItem;
  childItemList << sqlItem;

  bool detailsFromThread = needToDetect ||
                           ( wkbType != QgsWkbTypes::NoGeometry && layerProperty.srid.isEmpty() );

  if ( detailsFromThread || pkText == tr( "Select…" ) )
  {
    Qt::ItemFlags flags = Qt::ItemIsSelectable;
    if ( detailsFromThread )
      flags |= Qt::ItemIsEnabled;

    for ( QStandardItem *item : qgis::as_const( childItemList ) )
    {
      item->setFlags( item->flags() & ~flags );
    }
  }

  schemaItem->appendRow( childItemList );

  ++mTableCount;
}
Example #8
0
/*!
   \brief TreeModel::setObject

 */
void TreeModel::setObject( QObject* object )
{
    // Clean up workspace if necessary.
    if ( mp_object &&
         mp_object != object )
    {
        // Remove connections.
        for ( int i = 0 ; i < mp_object->metaObject()->propertyCount(); ++i )
        {
            if ( mp_object->metaObject()->property( i ).hasNotifySignal() )
            {
                QMetaMethod signal = mp_object->metaObject()->property( i ).notifySignal();
                bool res = disconnect( mp_object, signal, this, m_updateSlot  );
                Q_ASSERT( res );
            }
        }
        // Delete items.
        deleteAllItems();
        // Clear the mapping.
        m_propertyIndexToItemMap.clear();
    }

    mp_object = object;

    if ( !object )
    {
        // No object is passed, nothing needs to be done.
        return;
    }

    // A valdid object is passed, fill the QTreeView with it's properties.
    int propertyCount = object->metaObject()->propertyCount();
    for ( int i = 0; i < propertyCount; ++i )
    {
        QMetaProperty metaProperty = object->metaObject()->property( i );
        QString typeName = metaProperty.name();
        QVariant value   = object->property( metaProperty.name() );

        QList<QStandardItem*> itemRow;

        QStandardItem* first = createItem( metaProperty, typeName, false );
        itemRow.append( first );
//        if ( metaProperty.isEnumType() )
//        {
//            qDebug() << metaProperty.type();
//            qDebug() << metaProperty.typeName();
//            QString name = metaProperty.typeName();
//            if ( name == "SkeletonData::Joints" )
//            {
//                qDebug() << "GOT IT";
//            }
//        }
        // Unwrap special QVariant types.
        if ( value.canConvert<QVector3D>() )
        {
            // Case: QVector3D

            QVector3D vec = qvariant_cast<QVector3D>( value );
            QList<QStandardItem*> nextRow;

            // Extract values from QVector3D
            QStandardItem* tmp = nullptr;

            // x-coordinate
            tmp= createItem( metaProperty, "x", false );
            nextRow.append( tmp );
            tmp = createItem( metaProperty, vec.x(), true );
            nextRow.append( tmp );
            tmp = createItem( metaProperty, "float", false );
            nextRow.append( tmp );
            first->appendRow( nextRow );
            nextRow.clear();

            // y-coordinate
            tmp= createItem( metaProperty, "y", false );
            nextRow.append( tmp );
            tmp = createItem( metaProperty, vec.y(), true );
            nextRow.append( tmp );
            tmp = createItem( metaProperty, "float", false );
            nextRow.append( tmp );
            first->appendRow( nextRow );
            nextRow.clear();

            // z-coordinte
            tmp= createItem( metaProperty, "z", false );
            nextRow.append( tmp );
            tmp = createItem( metaProperty, vec.z(), true );
            nextRow.append( tmp );
            tmp = createItem( metaProperty, "float", false );
            nextRow.append( tmp );
            first->appendRow( nextRow );

            // Append second and third item on the top level.
            tmp = createItem( metaProperty, value, false );
            itemRow.append( tmp );
            tmp = createItem( metaProperty, "QVector3D", false );
            itemRow.append( tmp );
        }
        else if ( value.canConvert<cv::Size>() )
        {
            // Case: cv::Size

            cv::Size size = qvariant_cast<cv::Size>( value );
            QList<QStandardItem*> nextRow;

            // Extract values from cv::Size
            QStandardItem* tmp = nullptr;

            // Width
            tmp= createItem( metaProperty, tr( "width" ), false );
            nextRow.append( tmp );
            tmp = createItem( metaProperty, size.width, true );
            nextRow.append( tmp );
            tmp = createItem( metaProperty, "uchar", false );
            nextRow.append( tmp );
            first->appendRow( nextRow );
            nextRow.clear();

            // Height
            tmp= createItem( metaProperty, tr( "height" ), false );
            nextRow.append( tmp );
            tmp = createItem( metaProperty, size.height, true );
            nextRow.append( tmp );
            tmp = createItem( metaProperty, "uchar", false );
            nextRow.append( tmp );
            first->appendRow( nextRow );
            nextRow.clear();

            // Append editable data.
            tmp = createItem( metaProperty, value, false );
            connectProperty( mp_object, metaProperty, tmp );
            itemRow.append( tmp );
        }
        else if ( value.canConvert<FixedPropertyVector>() )
        {
            // Case: FixedPropertyVector

            FixedPropertyVector vec = qvariant_cast<FixedPropertyVector>( value );
            QList<QStandardItem*> nextRow;

            QStandardItem* tmp;
            for ( int i = 0; i < vec.size(); ++i )
            {
                nextRow.clear();
                // Append name.
                tmp = createItem( metaProperty, QString::number( i ), false );
                nextRow.append( tmp );
                // Append data.
                tmp = createItem( metaProperty, vec.at( i ), true );
                nextRow.append( tmp );
                // Append type informations.
                tmp = createItem( metaProperty, "float", false );
                nextRow.append( tmp );

                first->appendRow( nextRow );
            }
            // Append editable data.
            tmp = createItem( metaProperty, value, false );
            connectProperty( mp_object, metaProperty, tmp );
            itemRow.append( tmp );
        }
        else
        {
            // Append editable data.
            QStandardItem*  tmp = createItem( metaProperty, value, true );
            connectProperty( mp_object, metaProperty, tmp );
            itemRow.append( tmp );
        }

        // Append type informations.
        QStandardItem* tmp = createItem( metaProperty, value.typeName(), false );
        itemRow.append( tmp );

        // Append the row to the invisible root item.
        appendRow( itemRow );
    }
}
void FlatProxyModelTester::test()
{
    qDebug()<<"set 1 row, 1 column";
    m_standardmodel.setColumnCount( 1 );
    m_standardmodel.setRowCount( 1 );

    m_standardmodel.setHorizontalHeaderLabels( QStringList() << "Column 1" );
    m_flatmodel.setSourceModel( &m_standardmodel );
    
    QCOMPARE( m_flatmodel.columnCount(), 2 ); // it adds an extra column
    QCOMPARE( m_flatmodel.rowCount(), 1 );
    QCOMPARE( m_flatmodel.headerData( 0, Qt::Horizontal ), QVariant( "Column 1" ) );
    
    m_standardmodel.setData( m_standardmodel.index( 0, 0 ), "Index 0,0" );

    QModelIndex idx = m_flatmodel.index( 0, 0 );
    QVERIFY( idx.isValid() );
    qDebug()<<"Index 0,0:"<<idx.data();

    QCOMPARE( idx.data(), QVariant( "Index 0,0" ) );
    
    qDebug()<<"1 row, set 2 columns";
    m_standardmodel.setColumnCount( 2 );
    QCOMPARE( m_flatmodel.columnCount(), 3 ); // it adds an extra column
    m_flatmodel.setHeaderData( 1, Qt::Horizontal, "Column 2" );
    QCOMPARE( m_flatmodel.headerData( 1, Qt::Horizontal ), QVariant( "Column 2" ) );
    m_standardmodel.setData( m_standardmodel.index( 0, 1 ), "Index 0,1" );
    idx = m_flatmodel.index( 0, 1 );
    QVERIFY( idx.isValid() );
    qDebug()<<"Index 0,1:"<<idx.data();
    QCOMPARE( idx.data(), QVariant( "Index 0,1" ) );

    qDebug()<<"Set 2 rows, 2 columns";
    m_standardmodel.setRowCount( 2 );
    QCOMPARE( m_flatmodel.rowCount(), 2 );
    m_standardmodel.setData( m_standardmodel.index( 1, 0 ), "Index 1,0" );
    idx = m_flatmodel.index( 1, 0 );
    QVERIFY( idx.isValid() );
    qDebug()<<"Index 1,0:"<<idx.data();
    QCOMPARE( idx.data(), QVariant( "Index 1,0" ) );

    m_standardmodel.setData( m_standardmodel.index( 1, 1 ), "Index 1,1" );
    idx = m_flatmodel.index( 1, 1 );
    QVERIFY( idx.isValid() );
    qDebug()<<"Index 1,1:"<<idx.data();
    QCOMPARE( idx.data(), QVariant( "Index 1,1" ) );
    
    qDebug()<<"Add child on last index, adds a new row 1 in the flat model";

    // NOTE: m_standardmodel.insertRow( 0, m_standardmodel.index( 1, 0 ) );
    // does not work as there will be no columns and thus no valid indexes for this row
    QStandardItem *item = m_standardmodel.itemFromIndex( m_standardmodel.index( 1, 0 ) );
    QList<QStandardItem*> items;
    items << new QStandardItem( "Child last column 1" ) << new QStandardItem( "Child last column 2" );
    item->appendRow( items );
    QCOMPARE( m_flatmodel.rowCount(), 3 );
    idx = m_flatmodel.index( 2, 0 );
    QCOMPARE( idx.data(), QVariant( "Child last column 1" ) );
    idx = m_flatmodel.index( 2, 1 );
    QCOMPARE( idx.data(), QVariant( "Child last column 2" ) );

    qDebug()<<"add child on first index";
    
    item = m_standardmodel.itemFromIndex( m_standardmodel.index( 0, 0 ) );
    items.clear();
    items << new QStandardItem( "Child first column 1" ) << new QStandardItem( "Child first column 2" );
    item->appendRow( items );
    QCOMPARE( m_flatmodel.rowCount(), 4 );
    idx = m_flatmodel.index( 1, 0 );
    QCOMPARE( idx.data(), QVariant( "Child first column 1" ) );
    idx = m_flatmodel.index( 1, 1 );
    QCOMPARE( idx.data(), QVariant( "Child first column 2" ) );

    qDebug()<<"add row (2) on top level between first and last";
    
    item = m_standardmodel.invisibleRootItem();
    items.clear();
    items << new QStandardItem( "New index 1,0" ) << new QStandardItem( "New index 1,1" );
    item->insertRow( 1, items );
    QCOMPARE( m_flatmodel.rowCount(), 5 );
    idx = m_flatmodel.index( 2, 0 );
    QCOMPARE( idx.data(), QVariant( "New index 1,0" ) );
    idx = m_flatmodel.index( 2, 1 );
    QCOMPARE( idx.data(), QVariant( "New index 1,1" ) );

    qDebug()<<"Add child on middle index, adds row 3 to flat model";
    
    item = m_standardmodel.itemFromIndex( m_standardmodel.index( 1, 0 ) );
    items.clear();
    items << new QStandardItem( "Child middle column 1" ) << new QStandardItem( "Child middle column 2" );
    item->appendRow( items );
    QCOMPARE( m_flatmodel.rowCount(), 6 );
    idx = m_flatmodel.index( 3, 0 );
    QCOMPARE( idx.data().toString(), QVariant( "Child middle column 1" ).toString() );
    idx = m_flatmodel.index( 3, 1 );
    QCOMPARE( idx.data(), QVariant( "Child middle column 2" ) );

    qDebug()<<"Add child on middle index's child, adds row 4 to flat model";
    
    QModelIndex parent = m_standardmodel.index( 1, 0 );
    QCOMPARE( parent.data().toString(), QString( "New index 1,0" ) );
    idx = m_standardmodel.index( 0, 0, parent );
    QCOMPARE( idx.data().toString(), QString( "Child middle column 1" ) );
    item = m_standardmodel.itemFromIndex( idx );
    items.clear();
    items << new QStandardItem( "Child of middle child column 1" ) << new QStandardItem( "Child of middle child column 2" );
    item->appendRow( items );
    QCOMPARE( m_flatmodel.rowCount(), 7 );
    idx = m_flatmodel.index( 4, 0 );
    QCOMPARE( idx.data().toString(), QVariant( "Child of middle child column 1" ).toString() );
    idx = m_flatmodel.index( 4, 1 );
    QCOMPARE( idx.data(), QVariant( "Child of middle child column 2" ) );

    qDebug()<<"Add child on middle index at row 0, adds row 3 to flat model";
    
    idx = m_standardmodel.index( 1, 0 );
    QCOMPARE( idx.data().toString(), QString( "New index 1,0" ) );
    item = m_standardmodel.itemFromIndex( idx );
    items.clear();
    items << new QStandardItem( "Index 1,0 -> Index 0,0" ) << new QStandardItem( "Index 1,0 -> Index 0,1" );
    item->insertRow( 0, items );
    QCOMPARE( m_flatmodel.rowCount(), 8 );
    idx = m_flatmodel.index( 3, 0 );
    QCOMPARE( idx.data().toString(), QVariant( "Index 1,0 -> Index 0,0" ).toString() );
    idx = m_flatmodel.index( 3, 1 );
    QCOMPARE( idx.data(), QVariant( "Index 1,0 -> Index 0,1" ) );

    qDebug()<<"Add child on middle index at row 1, adds row 4 to flat model";
    
    idx = m_standardmodel.index( 1, 0 );
    QCOMPARE( idx.data().toString(), QString( "New index 1,0" ) );
    item = m_standardmodel.itemFromIndex( idx );
    items.clear();
    items << new QStandardItem( "Index 1,0 -> Index 1,0" ) << new QStandardItem( "Index 1,0 -> Index 1,1" );
    item->insertRow( 1, items );
    QCOMPARE( m_flatmodel.rowCount(), 9 );
    idx = m_flatmodel.index( 4, 0 );
    QCOMPARE( idx.data().toString(), QVariant( "Index 1,0 -> Index 1,0" ).toString() );
    idx = m_flatmodel.index( 4, 1 );
    QCOMPARE( idx.data(), QVariant( "Index 1,0 -> Index 1,1" ) );

    qDebug()<<"Add child on middle index at last row (4), adds row 8 to flat model";
    
    idx = m_standardmodel.index( 1, 0 );
    QCOMPARE( idx.data().toString(), QString( "New index 1,0" ) );
    item = m_standardmodel.itemFromIndex( idx );
    items.clear();
    items << new QStandardItem( "Index 1,0 -> Index 4,0" ) << new QStandardItem( "Index 1,0 -> Index 4,1" );
    item->insertRow( 3, items );
    QCOMPARE( m_standardmodel.rowCount( m_standardmodel.index( 1, 0 ) ), 4 );
    QCOMPARE( m_flatmodel.rowCount(), 10 );
    idx = m_flatmodel.index( 7, 0 );
    QCOMPARE( idx.data().toString(), QVariant( "Index 1,0 -> Index 4,0" ).toString() );
    idx = m_flatmodel.index( 7, 1 );
    QCOMPARE( idx.data(), QVariant( "Index 1,0 -> Index 4,1" ) );
}
Example #10
0
void ClassifierTrainer::updatePositivesGroup()
{
    project->load(); // get the latest from the file system

    // remove existing model if it exists
    if (positivesModel) delete positivesModel;

    // create column headers for the model
    positivesModel = new QStandardItemModel();
    positivesModel->setColumnCount(5);
    positivesModel->setHeaderData(0, Qt::Horizontal, "Image", Qt::DisplayRole);
    positivesModel->setHeaderData(1, Qt::Horizontal, "X", Qt::DisplayRole);
    positivesModel->setHeaderData(2, Qt::Horizontal, "Y", Qt::DisplayRole);
    positivesModel->setHeaderData(3, Qt::Horizontal, "Width", Qt::DisplayRole);
    positivesModel->setHeaderData(4, Qt::Horizontal, "Height", Qt::DisplayRole);

    QStandardItem *invisibleRootNode = positivesModel->invisibleRootItem();
    QList<QString> *keys = project->positives();
    qDebug() << "Number of positives loaded: " << keys->length();
    for(int i=0; i < keys->length(); i++)
    {
        QString path = keys->at(i);
        QStandardItem *imageRowItem = new QStandardItem(path);
        imageRowItem->setEditable(false);
        imageRowItem->setIcon(QIcon(":/assets/img/image.png"));

        QList<Section> sections = project->positive_sections()->values(path);
        for(int j=0; j < sections.length(); j++)
        {
            Section s = sections.at(j);

            // first column
            QString firstColumn = path;
            QStandardItem *firstColumnItem = new QStandardItem(firstColumn);
            firstColumnItem->setIcon(QIcon(":/assets/img/shading.png"));
            firstColumnItem->setEditable(false);

            // second column
            QStandardItem *secondColumnItem = new QStandardItem(QString::number(s.x()));
            secondColumnItem->setEditable(false);

            // third column
            QStandardItem *thirdColumnItem = new QStandardItem(QString::number(s.y()));
            thirdColumnItem->setEditable(false);

            // fourth column
            QStandardItem *fourthColumnItem = new QStandardItem(QString::number(s.width()));
            fourthColumnItem->setEditable(false);

            // fifth column
            QStandardItem *fifthColumnItem = new QStandardItem(QString::number(s.height()));
            fifthColumnItem->setEditable(false);

            QList<QStandardItem *> sectionRowItems;
            sectionRowItems.append(firstColumnItem);
            sectionRowItems.append(secondColumnItem);
            sectionRowItems.append(thirdColumnItem);
            sectionRowItems.append(fourthColumnItem);
            sectionRowItems.append(fifthColumnItem);

            imageRowItem->appendRow(sectionRowItems);
        }
        invisibleRootNode->appendRow(imageRowItem);
    }

    positivesTreeView->setModel(positivesModel);
    positivesTreeView->setColumnWidth(0, 350);
    positivesTreeView->resizeColumnToContents(1);
    positivesTreeView->resizeColumnToContents(2);
    positivesTreeView->resizeColumnToContents(3);
    positivesTreeView->resizeColumnToContents(4);
    positivesTreeView->expandAll();
}
void Workspace::AddProject(QString& projectFullPath, bool load)
{
    QFileInfo projectFileInfo(projectFullPath);

    // Extract project name from path.
    QString projectNameQ = projectFileInfo.fileName().remove(".ndtr");
    std::string projectName = Utils::StringQ2W(projectNameQ);

    // If not exists, create dir to store images.
    QDir projectDir = projectFileInfo.absoluteDir();
    // Create dir if not exist.
    if (!projectDir.exists(projectNameQ))
    {
        projectDir.mkdir(projectNameQ);
    }
    projectDir.cd(projectNameQ);

    // There can't be more projects with same name.
    if (m_Projects.count(projectName))
    {
        // "Project with the same name is already loaded."
        throw std::exception();
    }

    // Initialize project.
    m_Projects[projectName] = unique_ptr<Project>(new Project());
    m_ProjectsPersistentState[projectName] = true; // loaded or saved
    Project* project = m_Projects[projectName].get();
    project->Init(projectName,
                  projectFullPath.toStdString(),
                  projectDir.absolutePath().toStdString());

    // Load/Save project.
    if (load)
    {
        // If exists load project from file.
        if(!ProjectParser::Load(project))
        {
            // "Failed to load project file."
            throw std::exception();
        }
    }
    else
    {
        // Save project file. Serialize as XML.
        if (!ProjectParser::Save(project))
        {
            // "Failed to save project file."
            throw std::exception();
        }
    }

    // TODO: Move to method. Add images to view.
    // Add project to project model view.
    QStandardItem* rootItem = m_ProjectsModel.invisibleRootItem();
    ProjectItem* projectItem = new ProjectItem(projectName);
    QList<QStandardItem*> projectItems;
    projectItems << projectItem;
    rootItem->appendRow(projectItems);

    for (Document* doc : project->GetDocuments())
    {
        auto projRowItem = m_ProjectsModel.findItems(Utils::StringW2Q(projectName));
        ProjectItem* projectItem = (ProjectItem*) projRowItem.first();

        ProjectItem* docItem = new ProjectItem(doc->GetName(), true);
        QList<QStandardItem*> docRowItem;
        docRowItem << docItem;
        projectItem->appendRow(docItem);
    }

    // Set new project as current project.
    SetCurrent(projectName);
}
    // Insert a queue content to the model
    bool packCreationQueueToItem(const PackCreationQueue &queue)
    {
        // Already inserted?
        if (isPackCreationQueueAlreadyInserted(queue))
            return true;

        QFont bold;
        bold.setBold(true);

        // Create the root item for this queue
        QStandardItem *rootItem = 0;
        if (_format == PackCreationModel::ShowByServer) {
            // nothing to do
        } else if (_format == PackCreationModel::ShowByQueue) {
            rootItem = new QStandardItem(tkTr(Trans::Constants::_1_COLON_2)
                                                .arg(tkTr(Trans::Constants::QUEUE))
                                                .arg(queue.sourceAbsolutePathFile()));
            rootItem->setToolTip(queue.sourceAbsolutePathFile());
            rootItem->setFont(bold);
            rootItem->setCheckable(true);
            rootItem->setCheckState(Qt::Checked);
            q->invisibleRootItem()->appendRow(rootItem);
            insertPackCreationQueueInCache(queue, rootItem);
        } else {
            LOG_ERROR_FOR(q, "Format not supported");
            return false;
        }

        // Get the content of the queue and create the tree for each pack
        QHash<QString, QStandardItem *> serversUidToItem;
        foreach(const RequestedPackCreation &request, queue.queue()) {
            if (_packDescriptionFilesIncluded.contains(request.descriptionFilePath))
                continue;
            _packDescriptionFilesIncluded.append(request.descriptionFilePath);

            // Get the serverUid root item
            QStandardItem *server = 0;
            if (_format == PackCreationModel::ShowByQueue) {
                server = serversUidToItem.value(request.serverUid, 0);
            } else if (_format == PackCreationModel::ShowByServer) {
                server = serverItem(request.serverUid);
            }

            // If the server is not available yet: create it
            if (!server) {
                server = new QStandardItem(tkTr(Trans::Constants::_1_COLON_2)
                                           .arg(tkTr(Trans::Constants::SERVER))
                                           .arg(request.serverUid));
                if (_format == PackCreationModel::ShowByQueue) {
                    // In this format
                    // append the server item in the cache and the queueItem
                    serversUidToItem.insert(request.serverUid, server);
                    server->setCheckable(true);
                    server->setCheckState(Qt::Checked);
                    server->setFont(bold);
                    rootItem->appendRow(server);
                } else if (_format == PackCreationModel::ShowByServer) {
                    // In this format
                    // append the server item in the central cache and the rootItem
                    addServerItem(request.serverUid, server);
                    rootItem = server;
                    rootItem->setFont(bold);
                    rootItem->setCheckable(true);
                    rootItem->setCheckState(Qt::Checked);
                    q->invisibleRootItem()->appendRow(rootItem);
                }
            }

            // Include datapack to the server item
            server->appendRow(packToItem(request.descriptionFilePath, queue));
        }

        return true;
    }
Example #13
0
	void AccountsSettings::addAccount (QObjectList accObjects)
	{
		IBookmarksService *ibs = qobject_cast<IBookmarksService*> (sender ());
		if (!ibs)
		{
			qWarning () << Q_FUNC_INFO
					<< sender ()
					<< "ins't IBookmarksService";
			return;
		}

		QObjectList accounts;
		Q_FOREACH (QObject *accObj, accObjects)
		{
			IAccount *account = qobject_cast<IAccount*> (accObj);
			if (Id2Account_.contains (account->GetAccountID ()))
				continue;

			if (!account->GetPassword ().isEmpty ())
				Core::Instance ().SavePassword (accObj);
			else
				account->SetPassword (Core::Instance ().GetPassword (accObj));

			Id2Account_ [account->GetAccountID ()] = accObj;

			accounts << accObj;

			const QModelIndex& index = GetServiceIndex (ibs->GetObject ());
			QStandardItem *parentItem = 0;
			if (!index.isValid ())
			{
				parentItem = new QStandardItem (ibs->GetServiceIcon (), ibs->GetServiceName ());
				parentItem->setEditable (false);
				Item2Service_ [parentItem] = ibs;
				AccountsModel_->appendRow (parentItem);
			}
			else
				parentItem = AccountsModel_->itemFromIndex (index);

			QList<QStandardItem*> record;
			QStandardItem *item = new QStandardItem (account->GetLogin ());
			item->setEditable (false);
			item->setCheckable (true);
			item->setCheckState (account->IsSyncing () ? Qt::Checked : Qt::Unchecked);

			if (account->IsSyncing ())
			{
				Core::Instance ().AddActiveAccount (accObj);
				IBookmarksService *ibs = qobject_cast<IBookmarksService*> (account->GetParentService ());
				ibs->DownloadBookmarks (account->GetObject (), account->GetLastDownloadDateTime ());
				ibs->UploadBookmarks (account->GetObject (), Core::Instance ().GetAllBookmarks ());
			}

			Item2Account_ [item] = account;

			QStandardItem *uploaditem = new QStandardItem (account->GetLastUploadDateTime ()
					.toString (Qt::DefaultLocaleShortDate));
			uploaditem->setEditable (false);

			QStandardItem *downloaditem = new QStandardItem (account->GetLastDownloadDateTime ()
					.toString (Qt::DefaultLocaleShortDate));
			uploaditem->setEditable (false);

			record << item
					<< uploaditem
					<< downloaditem;
			parentItem->appendRow (record);

			if (account->IsSyncing ())
				Core::Instance ().AddActiveAccount (accObj);

			Ui_.AccountsView_->expandAll ();

			Scheduled_ = false;
			ScheduleResize ();
		}
void RxDev::fillItemModel_availableNodes(QString nodeFile, Specfile &node){

    QBrush b;

    QStandardItem *group = new QStandardItem(QString("%1").arg(QString::fromStdString(node.type)));

    QStandardItem *child;
    QStandardItem *item;
        QStandardItem *item2;
    child = new QStandardItem(QString("path"));
    item = new QStandardItem(QString("%1").arg(nodeFile));
    b.setColor(Qt::blue);
    child->setForeground(b);
    b.setColor(Qt::black);
    item->setForeground(b);
    child->appendRow(item);
    // the appendRow function appends the child as new row
    group->appendRow(child);


    child = new QStandardItem(QString("type"));
    item = new QStandardItem(QString("%1").arg(QString::fromStdString(node.type)));
    child->appendRow(item);
    child = new QStandardItem(QString("package"));
    item = new QStandardItem(QString("%1").arg(QString::fromStdString(node.package)));
    b.setColor(Qt::blue);
    child->setForeground(b);
    child->appendRow(item);
    group->appendRow(child);

    child = new QStandardItem(QString("subscriptions"));
     for(std::list<Topic_Type>::iterator iter=node.subscriptions.begin();iter != node.subscriptions.end();iter++ )
     {
         item = new QStandardItem(QString::fromStdString(Topic_Type(*iter).topic));
         item2 = new QStandardItem(QString::fromStdString(Topic_Type(*iter).topictype));
         b.setColor(Qt::red);
         item->setForeground(b);
         b.setColor(Qt::gray);
         item2->setForeground(b);
         item->appendRow(item2);
         child->appendRow(item);
     }
     b.setColor(Qt::blue);
     child->setForeground(b);


    group->appendRow(child);

    child = new QStandardItem(QString("publications"));
    for(std::list<Topic_Type>::iterator iter=node.publications.begin();iter != node.publications.end();iter++ )
    {
        item = new QStandardItem(QString::fromStdString(Topic_Type(*iter).topic));
        item2 = new QStandardItem(QString::fromStdString(Topic_Type(*iter).topictype));
        b.setColor(Qt::red);
        item->setForeground(b);
        b.setColor(Qt::gray);
        item2->setForeground(b);
        item->appendRow(item2);
        child->appendRow(item);
    }
    b.setColor(Qt::blue);
    child->setForeground(b);


    group->appendRow(child);

    child = new QStandardItem(QString("services"));
    for(std::list<Topic_Type>::iterator iter=node.services.begin();iter != node.services.end();iter++ )
    {
        item = new QStandardItem(QString::fromStdString(Topic_Type(*iter).topic));
        item2 = new QStandardItem(QString::fromStdString(Topic_Type(*iter).topictype));
        b.setColor(Qt::red);
        item->setForeground(b);
        b.setColor(Qt::gray);
        item2->setForeground(b);
        item->appendRow(item2);
        child->appendRow(item);
    }
    b.setColor(Qt::blue);
    child->setForeground(b);

    group->appendRow(child);

    child = new QStandardItem(QString("parameters"));
    for(std::list<Name_Type_Default>::iterator iter=node.parameters.begin();iter != node.parameters.end();iter++ )
    {
        item = new QStandardItem(QString::fromStdString(Name_Type_Default(*iter).paramName));
        item2 = new QStandardItem("type: "+QString::fromStdString(Name_Type_Default(*iter).paramType));
        b.setColor(Qt::red);
        item->setForeground(b);
        b.setColor(Qt::gray);
        item2->setForeground(b);
        item->appendRow(item2);
        item2 = new QStandardItem("default: "+QString::fromStdString(Name_Type_Default(*iter).paramDefault));
        b.setColor(Qt::black);
        item2->setForeground(b);
        item->appendRow(item2);
        item2 = new QStandardItem("range: "+QString::fromStdString(Name_Type_Default(*iter).paramRange));
        b.setColor(Qt::gray);
        item2->setForeground(b);
        item->appendRow(item2);
        child->appendRow(item);
    }
    b.setColor(Qt::blue);
    child->setForeground(b);

    group->appendRow(child);
    b.setColor(Qt::darkBlue);
    QFont font;
    font.setBold(true);
    group->setFont(font);
    group->setForeground(b);

    // append group as new row to the model. model takes the ownership of the item
    if (!(node.type.length()==0) && !(node.package.length()==0))
        model_availableNodes->appendRow(group);
        ui->treeView_availableNodes->setAutoFillBackground(true);
}
void NotifyOptionsWidget::createTreeModel()
{
	static const struct { ushort kind; QString name; } KindsList[] = { 
		{ INotification::PopupWindow, tr("Display a notification in popup window") },
		{ INotification::SoundPlay, tr("Play sound at the notification") },
		{ INotification::ShowMinimized, tr("Show the corresponding window minimized in the taskbar") },
		{ INotification::AlertWidget, tr("Highlight the corresponding window in the taskbar") },
		{ INotification::TabPageNotify, tr("Display a notification in tab") },
		{ INotification::RosterNotify, tr("Display a notification in your roster") },
		{ INotification::TrayNotify, tr("Display a notification in tray") },
		{ INotification::TrayAction, tr("Display a notification in tray context menu") },
		{ INotification::AutoActivate, tr("Immediately activate the notification") },
		{ 0, QString::null }
	};

	FModel.clear();
	FModel.setColumnCount(2);

	INotificationType globalType;
	globalType.order = 0;
	globalType.kindMask = 0xFFFF;
	globalType.title = tr("Allowed types of notifications");
	globalType.icon = IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS);

	QMap<QString,INotificationType> notifyTypes;
	notifyTypes.insert(QString::null,globalType);
	foreach(const QString &typeId, FNotifications->notificationTypes())
		notifyTypes.insert(typeId,FNotifications->notificationType(typeId));

	for(QMap<QString,INotificationType>::const_iterator it=notifyTypes.constBegin(); it!=notifyTypes.constEnd(); ++it)
	{
		if (!it->title.isEmpty() && it->kindMask>0)
		{
			QStandardItem *typeNameItem = new QStandardItem(it->title);
			typeNameItem->setFlags(Qt::ItemIsEnabled);
			typeNameItem->setData(it.key(),MDR_TYPE);
			typeNameItem->setData(it->order,MDR_SORT);
			typeNameItem->setIcon(it->icon);
			setItemBold(typeNameItem,true);

			QStandardItem *typeEnableItem = new QStandardItem;
			typeEnableItem->setFlags(Qt::ItemIsEnabled);

			FTypeItems.insert(it.key(),typeNameItem);
			FModel.invisibleRootItem()->appendRow(QList<QStandardItem *>() << typeNameItem << typeEnableItem);

			for (int index =0; KindsList[index].kind!=0; index++)
			{
				if ((it->kindMask & KindsList[index].kind)>0)
				{
					QStandardItem *kindNameItem = new QStandardItem(KindsList[index].name);
					kindNameItem->setFlags(Qt::ItemIsEnabled);
					kindNameItem->setData(index,MDR_SORT);

					QStandardItem *kindEnableItem = new QStandardItem();
					kindEnableItem->setFlags(Qt::ItemIsEnabled);
					kindEnableItem->setTextAlignment(Qt::AlignCenter);
					kindEnableItem->setCheckable(true);
					kindEnableItem->setCheckState(Qt::PartiallyChecked);
					kindEnableItem->setData(it.key(),MDR_TYPE);
					kindEnableItem->setData(KindsList[index].kind,MDR_KIND);

					typeNameItem->appendRow(QList<QStandardItem *>() << kindNameItem << kindEnableItem);
				}
			}
		}
	}
}
NetworkActivityWidget::NetworkActivityWidget( QWidget* parent )
    : QWidget( parent )
    , d_ptr( new NetworkActivityWidgetPrivate ( this ) )
{
    Q_D( NetworkActivityWidget );
    QWidget* widget = new QWidget();

    d->ui->setupUi( widget );

    d->crumbModelLeft = new QStandardItemModel( this );
    d->sortedProxy = new QSortFilterProxyModel( this );

    // d_func()->ui->breadCrumbLeft->setRootIcon( TomahawkUtils::defaultPixmap( TomahawkUtils::NetworkActivity, TomahawkUtils::Original ) );
    connect( d->ui->breadCrumbLeft, SIGNAL( activateIndex( QModelIndex ) ), SLOT( leftCrumbIndexChanged( QModelIndex ) ) );

    // Build up breadcrumb
    QStandardItem* rootItem = d->crumbModelLeft->invisibleRootItem();
    // Breadcumps for Charts
    {
        QStandardItem* chartItem = new QStandardItem( tr( "Charts" ) );
        rootItem->appendRow( chartItem );
        QStandardItem* overallItem = new QStandardItem( tr( "Overall" ) );
        overallItem->setData( OverallChart, Breadcrumb::DefaultRole );
        chartItem->appendRow( overallItem );
        QStandardItem* yearItem = new QStandardItem( tr( "Last Year" ) );
        yearItem->setData( YearChart, Breadcrumb::DefaultRole );
        chartItem->appendRow( yearItem );
        QStandardItem* monthItem = new QStandardItem( tr( "Last Month" ) );
        monthItem->setData( MonthChart, Breadcrumb::DefaultRole );
        chartItem->appendRow( monthItem );
        QStandardItem* weekItem = new QStandardItem( tr( "Last Week" ) );
        weekItem->setData( WeekChart, Breadcrumb::DefaultRole );
        chartItem->appendRow( weekItem );
    }
    // Breadcrumbs for Loved Tracks
    {
        QStandardItem* lovedItem = new QStandardItem( tr( "Loved Tracks" ) );
        rootItem->appendRow( lovedItem );
        QStandardItem* topItem = new QStandardItem( tr( "Top Loved" ) );
        topItem->setData( TopLoved, Breadcrumb::DefaultRole );
        lovedItem->appendRow( topItem );
        QStandardItem* recentlyItem = new QStandardItem( tr( "Recently Loved" ) );
        recentlyItem->setData( RecentlyLoved, Breadcrumb::DefaultRole );
        lovedItem->appendRow( recentlyItem );
    }
    d->sortedProxy->setSourceModel( d->crumbModelLeft );
    d->ui->breadCrumbLeft->setModel( d->sortedProxy );
    d->ui->breadCrumbLeft->setVisible( true );

    {
        TrackItemDelegate* del = new TrackItemDelegate( d->ui->tracksViewLeft, d->ui->tracksViewLeft->proxyModel(), true );
        d->ui->tracksViewLeft->setPlaylistItemDelegate( del );
        d->ui->tracksViewLeft->proxyModel()->setStyle( PlayableProxyModel::Short );
        d->ui->tracksViewLeft->setAutoResize( true );
        d->ui->tracksViewLeft->setAlternatingRowColors( false );
        d->ui->tracksViewLeft->setSortingEnabled( false );
        d->ui->tracksViewLeft->setEmptyTip( tr( "Sorry, we are still loading the charts." ) );

        QPalette p = d->ui->tracksViewLeft->palette();
        p.setColor( QPalette::Text, TomahawkStyle::PAGE_TRACKLIST_TRACK_SOLVED );
        p.setColor( QPalette::BrightText, TomahawkStyle::PAGE_TRACKLIST_TRACK_UNRESOLVED );
        p.setColor( QPalette::Foreground, TomahawkStyle::PAGE_TRACKLIST_NUMBER );
        p.setColor( QPalette::Highlight, TomahawkStyle::PAGE_TRACKLIST_HIGHLIGHT );
        p.setColor( QPalette::HighlightedText, TomahawkStyle::PAGE_TRACKLIST_HIGHLIGHT_TEXT );

        d->ui->tracksViewLeft->setPalette( p );

        TomahawkStyle::stylePageFrame( d->ui->tracksViewLeft );
        TomahawkStyle::stylePageFrame( d->ui->chartsFrame );
    }

    // Trending Tracks
    {
        d->trendingTracksModel = new PlaylistModel( d->ui->trendingTracksView );
        d->ui->trendingTracksView->proxyModel()->setStyle( PlayableProxyModel::Short );
        d->ui->trendingTracksView->overlay()->setEnabled( true );
        d->ui->trendingTracksView->setPlaylistModel( d->trendingTracksModel );
        d->ui->trendingTracksView->setAutoResize( true );
        d->ui->trendingTracksView->setAlternatingRowColors( false );
        d->ui->trendingTracksView->setEmptyTip( tr( "Sorry, we couldn't find any trending tracks." ) );
        d->trendingTracksModel->startLoading();

        QPalette p = d->ui->trendingTracksView->palette();
        p.setColor( QPalette::Text, TomahawkStyle::PAGE_TRACKLIST_TRACK_SOLVED );
        p.setColor( QPalette::BrightText, TomahawkStyle::PAGE_TRACKLIST_TRACK_UNRESOLVED );
        p.setColor( QPalette::Foreground, TomahawkStyle::PAGE_TRACKLIST_NUMBER );
        p.setColor( QPalette::Highlight, TomahawkStyle::PAGE_TRACKLIST_HIGHLIGHT );
        p.setColor( QPalette::HighlightedText, TomahawkStyle::PAGE_TRACKLIST_HIGHLIGHT_TEXT );

        d->ui->trendingTracksView->setPalette( p );

        TomahawkStyle::stylePageFrame( d->ui->trendingTracksView );
        TomahawkStyle::stylePageFrame( d->ui->trendingTracksFrame );
    }
    {
        QFont f = d->ui->trendingTracksLabel->font();
        f.setFamily( "Roboto" );

        QPalette p = d->ui->trendingTracksLabel->palette();
        p.setColor( QPalette::Foreground, TomahawkStyle::PAGE_CAPTION );

        d->ui->trendingTracksLabel->setFont( f );
        d->ui->trendingTracksLabel->setPalette( p );
    }

    // Hot Playlists
    {
        TomahawkStyle::stylePageFrame( d->ui->playlistsFrame );

        QFont f = d->ui->hotPlaylistsLabel->font();
        f.setFamily( "Roboto" );

        QPalette p = d->ui->hotPlaylistsLabel->palette();
        p.setColor( QPalette::Foreground, TomahawkStyle::PAGE_CAPTION );

        d->ui->hotPlaylistsLabel->setFont( f );
        d->ui->hotPlaylistsLabel->setPalette( p );
    }

    {
        d->ui->playlistView->setItemDelegate( new PlaylistDelegate() );
        d->ui->playlistView->setVerticalScrollMode( QAbstractItemView::ScrollPerPixel );

        QPalette p = d->ui->playlistView->palette();
        p.setColor( QPalette::Text, TomahawkStyle::PAGE_FOREGROUND );
        p.setColor( QPalette::BrightText, TomahawkStyle::PAGE_FOREGROUND );
        p.setColor( QPalette::Foreground, TomahawkStyle::PAGE_FOREGROUND );
        p.setColor( QPalette::Highlight, TomahawkStyle::PAGE_FOREGROUND );
        p.setColor( QPalette::HighlightedText, TomahawkStyle::PAGE_BACKGROUND );

        d->ui->playlistView->setPalette( p );
        d->ui->playlistView->overlay()->setPalette( p );
        TomahawkStyle::styleScrollBar( d->ui->playlistView->verticalScrollBar() );
        TomahawkStyle::stylePageFrame( d->ui->playlistView );
        TomahawkStyle::stylePageFrame( d->ui->playlistsFrame );

        connect( d->ui->playlistView, SIGNAL( activated( QModelIndex ) ), SLOT( onPlaylistActivated( QModelIndex ) ) );
    }

    // Trending artists
    {
        d->artistsModel = new PlayableModel( d->ui->trendingArtistsView );
        d->ui->trendingArtistsView->setPlayableModel( d->artistsModel );
        d->artistsModel->startLoading();
    }
    {
        d->ui->trendingArtistsView->proxyModel()->sort( -1 );
        d->ui->trendingArtistsView->proxyModel()->setHideDupeItems( true );

        d->ui->trendingArtistsView->setAutoResize( true );
        d->ui->trendingArtistsView->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
        TomahawkStyle::stylePageFrame( d->ui->trendingArtistsView );
        TomahawkStyle::stylePageFrame( d->ui->trendingArtistsFrame );
    }
    {
        QFont f = d->ui->trendingArtistsLabel->font();
        f.setFamily( "Roboto" );

        QPalette p = d->ui->trendingArtistsLabel->palette();
        p.setColor( QPalette::Foreground, TomahawkStyle::PAGE_CAPTION );

        d->ui->trendingArtistsLabel->setFont( f );
        d->ui->trendingArtistsLabel->setPalette( p );
    }

    {
        QScrollArea* area = new QScrollArea();
        area->setWidgetResizable( true );
        area->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOn );
        area->setWidget( widget );

        QPalette pal = palette();
        pal.setBrush( backgroundRole(), TomahawkStyle::PAGE_BACKGROUND );
        area->setPalette( pal );
        area->setAutoFillBackground( true );
        area->setFrameShape( QFrame::NoFrame );
        area->setAttribute( Qt::WA_MacShowFocusRect, 0 );

        QVBoxLayout* layout = new QVBoxLayout();
        layout->addWidget( area );
        setLayout( layout );
        TomahawkUtils::unmarginLayout( layout );
    }

    MetaPlaylistInterface* mpl = new MetaPlaylistInterface();
    mpl->addChildInterface( d->ui->trendingTracksView->playlistInterface() );
    mpl->addChildInterface( d->ui->tracksViewLeft->playlistInterface() );
    d->playlistInterface = playlistinterface_ptr( mpl );

    // Load data in separate thread
    d->workerThread = new QThread();
    d->workerThread->start();
    d->worker = new NetworkActivityWorker();
    d->worker->moveToThread( d->workerThread );
    connect( d->worker, SIGNAL( trendingTracks( QList<Tomahawk::track_ptr> ) ),
             SLOT( trendingTracks( QList<Tomahawk::track_ptr> ) ),
             Qt::QueuedConnection );
    connect( d->worker, SIGNAL( hotPlaylists(QList<Tomahawk::playlist_ptr>) ),
             SLOT(hotPlaylists(QList<Tomahawk::playlist_ptr>)),
             Qt::QueuedConnection );
    connect( d->worker, SIGNAL( trendingArtists( QList< Tomahawk::artist_ptr > ) ),
             SLOT( trendingArtists( QList< Tomahawk::artist_ptr > ) ),
             Qt::QueuedConnection );
    connect( d->worker, SIGNAL( finished() ),
             d->workerThread, SLOT( quit() ),
             Qt::QueuedConnection );
    // connect( d->workerThread, SIGNAL( finished() ), d->workerThread, SLOT( deleteLater() ), Qt::QueuedConnection );
    // connect( d->workerThread, SIGNAL( destroyed() ), d->worker, SLOT( deleteLater() ), Qt::QueuedConnection );
    QMetaObject::invokeMethod( d->worker, "run", Qt::QueuedConnection );
}
Example #17
0
void QgsPgTableModel::addTableEntry( const QgsPostgresLayerProperty &layerProperty )
{
  QgsDebugMsg( layerProperty.toString() );

  // is there already a root item with the given scheme Name?
  QStandardItem *schemaItem = nullptr;

  for ( int i = 0; i < layerProperty.size(); i++ )
  {
    QgsWkbTypes::Type wkbType = layerProperty.types[ i ];
    int srid = layerProperty.srids[ i ];

    if ( wkbType == QgsWkbTypes::Unknown && layerProperty.geometryColName.isEmpty() )
    {
      wkbType = QgsWkbTypes::NoGeometry;
    }

    QString tip;
    bool withTipButSelectable = false;
    if ( wkbType == QgsWkbTypes::Unknown )
    {
      tip = tr( "Specify a geometry type in the '%1' column" ).arg( tr( "Data Type" ) );
    }
    else if ( wkbType != QgsWkbTypes::NoGeometry && srid == std::numeric_limits<int>::min() )
    {
      tip = tr( "Enter a SRID into the '%1' column" ).arg( tr( "SRID" ) );
    }
    else if ( !layerProperty.pkCols.isEmpty() )
    {
      tip = tr( "Select columns in the '%1' column that uniquely identify features of this layer" ).arg( tr( "Feature id" ) );
      withTipButSelectable = true;
    }

    QStandardItem *schemaNameItem = new QStandardItem( layerProperty.schemaName );
    QStandardItem *typeItem = new QStandardItem( iconForWkbType( wkbType ), wkbType == QgsWkbTypes::Unknown ? tr( "Select…" ) : QgsPostgresConn::displayStringForWkbType( wkbType ) );
    typeItem->setData( wkbType == QgsWkbTypes::Unknown, Qt::UserRole + 1 );
    typeItem->setData( wkbType, Qt::UserRole + 2 );
    if ( wkbType == QgsWkbTypes::Unknown )
      typeItem->setFlags( typeItem->flags() | Qt::ItemIsEditable );

    QStandardItem *geomTypeItem = new QStandardItem( QgsPostgresConn::displayStringForGeomType( layerProperty.geometryColType ) );

    QStandardItem *tableItem = new QStandardItem( layerProperty.tableName );
    QStandardItem *commentItem = new QStandardItem( layerProperty.tableComment );
    QStandardItem *geomItem  = new QStandardItem( layerProperty.geometryColName );
    QStandardItem *sridItem  = new QStandardItem( wkbType != QgsWkbTypes::NoGeometry ? QString::number( srid ) : QString() );
    sridItem->setEditable( wkbType != QgsWkbTypes::NoGeometry && srid == std::numeric_limits<int>::min() );
    if ( sridItem->isEditable() )
    {
      sridItem->setText( tr( "Enter…" ) );
      sridItem->setFlags( sridItem->flags() | Qt::ItemIsEditable );
    }

    QStandardItem *pkItem = new QStandardItem( QString() );
    if ( !layerProperty.pkCols.isEmpty() )
    {
      pkItem->setText( tr( "Select…" ) );
      pkItem->setFlags( pkItem->flags() | Qt::ItemIsEditable );
    }
    else
      pkItem->setFlags( pkItem->flags() & ~Qt::ItemIsEditable );

    pkItem->setData( layerProperty.pkCols, Qt::UserRole + 1 );

    QStringList defPk( QgsSettings().value( QStringLiteral( "/PostgreSQL/connections/%1/keys/%2/%3" ).arg( mConnName, layerProperty.schemaName, layerProperty.tableName ), QStringList() ).toStringList() );

    if ( !layerProperty.pkCols.isEmpty() && defPk.isEmpty() )
    {
      // If we have a view with multiple possible columns to be used as the primary key, for convenience
      // let's select the first one - this is what the browser dock already does. We risk that a wrong column
      // will be used, but most of the time we should be fine.
      defPk = QStringList( layerProperty.pkCols[0] );
    }

    pkItem->setData( defPk, Qt::UserRole + 2 );
    if ( !defPk.isEmpty() )
      pkItem->setText( defPk.join( ',' ) );

    QStandardItem *selItem = new QStandardItem( QString() );
    selItem->setFlags( selItem->flags() | Qt::ItemIsUserCheckable );
    selItem->setCheckState( Qt::Checked );
    selItem->setToolTip( headerData( Columns::DbtmSelectAtId, Qt::Orientation::Horizontal, Qt::ToolTipRole ).toString() );

    QStandardItem *checkPkUnicityItem  = new QStandardItem( QString() );
    checkPkUnicityItem->setFlags( checkPkUnicityItem->flags() | Qt::ItemIsUserCheckable );

    // Legacy: default value is determined by project option to trust layer's metadata
    // TODO: remove this default from QGIS 4 and leave default value to false?
    // checkPkUnicity has only effect on views and materialized views, so we can safely disable it
    if ( layerProperty.isView || layerProperty.isMaterializedView )
    {
      checkPkUnicityItem->setCheckState( QgsProject::instance( )->trustLayerMetadata() ? Qt::CheckState::Unchecked : Qt::CheckState::Checked );
      checkPkUnicityItem->setToolTip( headerData( Columns::DbtmCheckPkUnicity, Qt::Orientation::Horizontal, Qt::ToolTipRole ).toString() );
    }
    else
    {
      checkPkUnicityItem->setCheckState( Qt::CheckState::Unchecked );
      checkPkUnicityItem->setFlags( checkPkUnicityItem->flags() & ~ Qt::ItemIsEnabled );
      checkPkUnicityItem->setToolTip( tr( "This option is only available for views and materialized views." ) );
    }

    QStandardItem *sqlItem = new QStandardItem( layerProperty.sql );

    QList<QStandardItem *> childItemList;

    childItemList << schemaNameItem;
    childItemList << tableItem;
    childItemList << commentItem;
    childItemList << geomItem;
    childItemList << geomTypeItem;
    childItemList << typeItem;
    childItemList << sridItem;
    childItemList << pkItem;
    childItemList << selItem;
    childItemList << checkPkUnicityItem;
    childItemList << sqlItem;

    const auto constChildItemList = childItemList;
    for ( QStandardItem *item : constChildItemList )
    {
      if ( tip.isEmpty() || withTipButSelectable )
        item->setFlags( item->flags() | Qt::ItemIsSelectable );
      else
        item->setFlags( item->flags() & ~Qt::ItemIsSelectable );

      if ( tip.isEmpty() && item != checkPkUnicityItem && item != selItem )
      {
        item->setToolTip( QString() );
      }
      else
      {
        if ( item == schemaNameItem )
          item->setData( QgsApplication::getThemeIcon( QStringLiteral( "/mIconWarning.svg" ) ), Qt::DecorationRole );

        if ( item == schemaNameItem || item == tableItem || item == geomItem )
        {
          item->setToolTip( tip );
        }
      }
    }

    if ( !schemaItem )
    {
      QList<QStandardItem *> schemaItems = findItems( layerProperty.schemaName, Qt::MatchExactly, DbtmSchema );

      // there is already an item for this schema
      if ( !schemaItems.isEmpty() )
      {
        schemaItem = schemaItems.at( DbtmSchema );
      }
      else
      {
        // create a new toplevel item for this schema
        schemaItem = new QStandardItem( layerProperty.schemaName );
        schemaItem->setFlags( Qt::ItemIsEnabled );
        invisibleRootItem()->setChild( invisibleRootItem()->rowCount(), schemaItem );
      }
    }

    schemaItem->appendRow( childItemList );

    ++mTableCount;
  }
}
Example #18
0
void QgsPgTableModel::addTableEntry( const QgsPostgresLayerProperty& layerProperty )
{
  QgsDebugMsg( layerProperty.toString() );

  // is there already a root item with the given scheme Name?
  QStandardItem *schemaItem = 0;

  for ( int i = 0; i < layerProperty.size(); i++ )
  {
    QGis::WkbType wkbType = layerProperty.types[ i ];
    int srid = layerProperty.srids[ i ];
    if ( wkbType == QGis::WKBUnknown && layerProperty.geometryColName.isEmpty() )
    {
      wkbType = QGis::WKBNoGeometry;
    }

    bool selectable = wkbType == QGis::WKBNoGeometry || ( wkbType != QGis::WKBUnknown && srid != INT_MIN );

    QStandardItem *schemaNameItem = new QStandardItem( layerProperty.schemaName );
    QStandardItem *typeItem = new QStandardItem( iconForWkbType( wkbType ), wkbType == QGis::WKBUnknown ? tr( "Select..." ) : QgsPostgresConn::displayStringForWkbType( wkbType ) );
    typeItem->setData( wkbType == QGis::WKBUnknown, Qt::UserRole + 1 );
    typeItem->setData( wkbType, Qt::UserRole + 2 );
    if ( wkbType == QGis::WKBUnknown )
      typeItem->setFlags( typeItem->flags() | Qt::ItemIsEditable );

    QStandardItem *geomTypeItem = new QStandardItem( QgsPostgresConn::displayStringForGeomType( layerProperty.geometryColType ) );

    QStandardItem *tableItem = new QStandardItem( layerProperty.tableName );
    QStandardItem *geomItem  = new QStandardItem( layerProperty.geometryColName );
    QStandardItem *sridItem  = new QStandardItem( wkbType != QGis::WKBNoGeometry ? QString::number( srid ) : "" );
    sridItem->setEditable( wkbType != QGis::WKBNoGeometry && srid == INT_MIN );
    if ( sridItem->isEditable() )
    {
      sridItem->setText( tr( "Enter..." ) );
      sridItem->setFlags( sridItem->flags() | Qt::ItemIsEditable );
    }

    QString pkCol = "";
    if ( layerProperty.pkCols.size() > 0 )
    {
      pkCol = layerProperty.pkCols[0];
    }

    QStandardItem *pkItem = new QStandardItem( pkCol );
    if ( layerProperty.pkCols.size() > 1 )
      pkItem->setFlags( pkItem->flags() | Qt::ItemIsEditable );
    else
      pkItem->setFlags( pkItem->flags() & ~Qt::ItemIsEditable );

    pkItem->setData( layerProperty.pkCols, Qt::UserRole + 1 );
    pkItem->setData( pkCol, Qt::UserRole + 2 );

    QStandardItem *selItem = new QStandardItem( "" );
    selItem->setFlags( selItem->flags() | Qt::ItemIsUserCheckable );
    selItem->setCheckState( Qt::Checked );
    selItem->setToolTip( tr( "Disable 'Fast Access to Features at ID' capability to force keeping the attribute table in memory (e.g. in case of expensive views)." ) );

    QStandardItem* sqlItem = new QStandardItem( layerProperty.sql );

    QList<QStandardItem*> childItemList;

    childItemList << schemaNameItem;
    childItemList << tableItem;
    childItemList << geomItem;
    childItemList << geomTypeItem;
    childItemList << typeItem;
    childItemList << sridItem;
    childItemList << pkItem;
    childItemList << selItem;
    childItemList << sqlItem;

    foreach ( QStandardItem *item, childItemList )
    {
      if ( selectable )
      {
        item->setFlags( item->flags() | Qt::ItemIsSelectable );
      }
      else
      {
        item->setFlags( item->flags() & ~Qt::ItemIsSelectable );
      }
    }

    if ( !schemaItem )
    {
      QList<QStandardItem*> schemaItems = findItems( layerProperty.schemaName, Qt::MatchExactly, dbtmSchema );

      // there is already an item for this schema
      if ( schemaItems.size() > 0 )
      {
        schemaItem = schemaItems.at( dbtmSchema );
      }
      else
      {
        // create a new toplevel item for this schema
        schemaItem = new QStandardItem( layerProperty.schemaName );
        schemaItem->setFlags( Qt::ItemIsEnabled );
        invisibleRootItem()->setChild( invisibleRootItem()->rowCount(), schemaItem );
      }
    }

    schemaItem->appendRow( childItemList );

    ++mTableCount;
  }
}
Example #19
0
void ArgumentsEditor::setupCall()
{
    m_model->clear();

    QStringList headers;
    headers.append(tr("Argument"));
    headers.append(tr("Value"));
    m_model->setColumnCount(2);
    m_model->setHorizontalHeaderLabels(headers);
    m_ui.argsTabWidget->removeTab(
        m_ui.argsTabWidget->indexOf(m_ui.shaderTab));

    if (!m_call)
        return;

    m_ui.callLabel->setText(m_call->name());
    QStandardItem *rootItem = m_model->invisibleRootItem();
    for (int i = 0; i < m_call->argNames().count(); ++i) {
        QString argName = m_call->argNames()[i];
        QVariant val = m_call->arguments()[i];
        QStandardItem *nameItem = new QStandardItem(argName);
        nameItem->setFlags(nameItem->flags() ^ Qt::ItemIsEditable);
        QList<QStandardItem*> topRow;
        topRow.append(nameItem);

        if (val.canConvert<ApiArray>()) {
            ApiArray array = val.value<ApiArray>();
            QVector<QVariant> vals = array.values();

            QVariant firstVal = vals.value(0);
            if (firstVal.userType() == QVariant::String) {
                m_ui.argsTabWidget->addTab(
                    m_ui.shaderTab, argName);
                setupShaderEditor(vals);
                delete nameItem;
                continue;
            } else if (isVariantEditable(firstVal)) {
                for (int i = 0; i < vals.count(); ++i) {
                    QList<QStandardItem*> row;

                    QStandardItem *idx = new QStandardItem();
                    idx->setFlags(idx->flags() ^ Qt::ItemIsEditable);
                    idx->setText(tr("%1)").arg(i));

                    QStandardItem *col = new QStandardItem();
                    col->setFlags(col->flags() | Qt::ItemIsEditable);
                    col->setData(vals[i], Qt::EditRole);
                    row.append(idx);
                    row.append(col);
                    nameItem->appendRow(row);
                }
            } else {
                qDebug()<<"\tUnsupported array = "<<firstVal;
                delete nameItem;
                continue;
            }
        } else  if (val.canConvert<ApiPointer>()) {
            ApiPointer ptr = val.value<ApiPointer>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(ptr.toString());
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else if (val.canConvert<ApiEnum>()) {
            ApiEnum en = val.value<ApiEnum>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(en.toString());
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else if (val.canConvert<ApiBitmask>()) {
            ApiBitmask mask = val.value<ApiBitmask>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(mask.toString());
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else if (val.canConvert<ApiStruct>()) {
            ApiStruct str = val.value<ApiStruct>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(str.toString());
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else if (val.userType() == QVariant::ByteArray) {
            QByteArray ba = val.value<QByteArray>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(
                tr("<binary data, size = %1 bytes>").arg(ba.size()));
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else {
            QStandardItem *item
                = new QStandardItem();

            if (isVariantEditable(val)) {
                item->setFlags(item->flags() | Qt::ItemIsEditable);
            } else {
                QIcon icon(":/resources/emblem-locked.png");
                item->setIcon(icon);
                item->setFlags(item->flags() ^ Qt::ItemIsEditable);
                item->setToolTip(tr("Argument is read-only"));
            }
            item->setData(val, Qt::EditRole);
            topRow.append(item);
        }
        rootItem->appendRow(topRow);
    }
}
void QgsOracleTableModel::addTableEntry( const QgsOracleLayerProperty &layerProperty )
{
  QgsDebugMsg( layerProperty.toString() );

  if ( layerProperty.isView && layerProperty.pkCols.isEmpty() )
  {
    QgsDebugMsg( QStringLiteral( "View without pk skipped." ) );
    return;
  }

  // is there already a root item with the given scheme Name?
  QStandardItem *ownerItem = nullptr;

  for ( int i = 0; i < layerProperty.size(); i++ )
  {
    QgsWkbTypes::Type wkbType = layerProperty.types[ i ];
    int srid = layerProperty.srids[ i ];


    QString tip;
    if ( wkbType == QgsWkbTypes::Unknown )
    {
      tip = tr( "Specify a geometry type" );
    }
    else if ( wkbType != QgsWkbTypes::NoGeometry && srid == 0 )
    {
      tip = tr( "Enter a SRID" );
    }

    if ( tip.isEmpty() && layerProperty.isView )
    {
      tip = tr( "Select a primary key" );
    }

    QStandardItem *ownerNameItem = new QStandardItem( layerProperty.ownerName );
    QStandardItem *typeItem = new QStandardItem( iconForWkbType( wkbType ), wkbType == QgsWkbTypes::Unknown ? tr( "Select…" ) : QgsOracleConn::displayStringForWkbType( wkbType ) );
    typeItem->setData( wkbType == QgsWkbTypes::Unknown, Qt::UserRole + 1 );
    typeItem->setData( wkbType, Qt::UserRole + 2 );
    if ( wkbType == QgsWkbTypes::Unknown )
      typeItem->setFlags( typeItem->flags() | Qt::ItemIsEditable );

    QStandardItem *tableItem = new QStandardItem( layerProperty.tableName );
    QStandardItem *geomItem  = new QStandardItem( layerProperty.geometryColName );
    QStandardItem *sridItem  = new QStandardItem( wkbType != QgsWkbTypes::NoGeometry ? QString::number( srid ) : "" );
    sridItem->setEditable( wkbType != QgsWkbTypes::NoGeometry && srid == 0 );
    if ( sridItem->isEditable() )
    {
      sridItem->setText( tr( "Enter…" ) );
      sridItem->setFlags( sridItem->flags() | Qt::ItemIsEditable );
    }

    QStandardItem *pkItem = new QStandardItem( "" );
    if ( layerProperty.isView )
    {
      pkItem->setText( tr( "Select…" ) );
      pkItem->setFlags( pkItem->flags() | Qt::ItemIsEditable );
    }
    else
      pkItem->setFlags( pkItem->flags() & ~Qt::ItemIsEditable );

    pkItem->setData( layerProperty.isView, Qt::UserRole + 1 );
    pkItem->setData( false, Qt::UserRole + 2 ); // not selected

    QStandardItem *selItem = new QStandardItem( "" );
    selItem->setFlags( selItem->flags() | Qt::ItemIsUserCheckable );
    selItem->setCheckState( Qt::Checked );
    selItem->setToolTip( tr( "Disable 'Fast Access to Features at ID' capability to force keeping the attribute table in memory (e.g. in case of expensive views)." ) );

    QStandardItem *sqlItem = new QStandardItem( layerProperty.sql );

    QList<QStandardItem *> childItemList;
    childItemList << ownerNameItem;
    childItemList << tableItem;
    childItemList << typeItem;
    childItemList << geomItem;
    childItemList << sridItem;
    childItemList << pkItem;
    childItemList << selItem;
    childItemList << sqlItem;

    Q_FOREACH ( QStandardItem *item, childItemList )
    {
      if ( tip.isEmpty() )
      {
        item->setFlags( item->flags() | Qt::ItemIsSelectable | Qt::ItemIsEnabled );
        item->setToolTip( "" );
      }
      else
      {
        item->setFlags( item->flags() & ~Qt::ItemIsSelectable );

        if ( item == ownerNameItem || item == tableItem || item == geomItem )
        {
          item->setFlags( item->flags() & ~Qt::ItemIsEnabled );
          item->setToolTip( tip );
        }
      }
    }

    if ( !ownerItem )
    {
      QList<QStandardItem *> ownerItems = findItems( layerProperty.ownerName, Qt::MatchExactly, DbtmOwner );

      // there is already an item for this schema
      if ( ownerItems.size() > 0 )
      {
        ownerItem = ownerItems.at( DbtmOwner );
      }
      else
      {
        // create a new toplevel item for this schema
        ownerItem = new QStandardItem( layerProperty.ownerName );
        ownerItem->setFlags( Qt::ItemIsEnabled );
        invisibleRootItem()->setChild( invisibleRootItem()->rowCount(), ownerItem );
      }
    }

    ownerItem->appendRow( childItemList );

    ++mTableCount;
  }
}
Example #21
0
void
NewReleasesWidget::infoSystemInfo( Tomahawk::InfoSystem::InfoRequestData requestData, QVariant output )
{
    if ( requestData.caller != s_newReleasesIdentifier )
        return;

    if ( !output.canConvert< QVariantMap >() )
    {
        tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "Could not parse output";
        return;
    }

    QVariantMap returnedData = output.toMap();
    switch ( requestData.type )
    {
        case InfoSystem::InfoNewReleaseCapabilities:
        {
            tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "Got InfoNewReleaseCapabilities";
            QStandardItem *rootItem = m_crumbModelLeft->invisibleRootItem();

            foreach ( const QString label, returnedData.keys() )
            {
                QStandardItem *childItem = parseNode( rootItem, label, returnedData[label] );
                rootItem->appendRow(childItem);
                tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "NewReleases:" << label;
            }
            break;
        }

        case InfoSystem::InfoNewRelease:
        {
            if ( !returnedData.contains("type") )
                break;
            const QString type = returnedData["type"].toString();
            if ( !returnedData.contains(type) )
                break;

            const QString releaseId = requestData.input.value< Tomahawk::InfoSystem::InfoStringHash >().value( "nr_id" );

            m_queuedFetches.remove( releaseId );

            ChartDataLoader* loader = new ChartDataLoader();
            loader->setProperty( "nrid", releaseId );
            loader->moveToThread( m_workerThread );

            if ( type == "albums" )
            {
                loader->setType( ChartDataLoader::Album );
                loader->setData( returnedData[ "albums" ].value< QList< Tomahawk::InfoSystem::InfoStringHash > >() );

                connect( loader, SIGNAL( albums( Tomahawk::ChartDataLoader*, QList< Tomahawk::album_ptr > ) ), this, SLOT( newReleasesLoaded( Tomahawk::ChartDataLoader*, QList<Tomahawk::album_ptr> ) ) );

                PlayableModel* albumModel = new PlayableModel( ui->albumsView );

                m_albumModels[ releaseId ] = albumModel;

                if ( m_queueItemToShow == releaseId )
                    setLeftViewAlbums( albumModel );
            }
            else
            {
                // intentionally unhandled
            }

            QMetaObject::invokeMethod( loader, "go", Qt::QueuedConnection );
            break;
        }
Example #22
0
void QgsPgTableModel::addTableEntry( const QgsPostgresLayerProperty& layerProperty )
{
  QgsDebugMsg( layerProperty.toString() );

  // is there already a root item with the given scheme Name?
  QStandardItem *schemaItem = 0;

  for ( int i = 0; i < layerProperty.size(); i++ )
  {
    QGis::WkbType wkbType = layerProperty.types[ i ];
    int srid = layerProperty.srids[ i ];

    if ( wkbType == QGis::WKBUnknown && layerProperty.geometryColName.isEmpty() )
    {
      wkbType = QGis::WKBNoGeometry;
    }

    QString tip;
    if ( wkbType == QGis::WKBUnknown )
    {
      tip = tr( "Specify a geometry type in the '%1' column" ).arg( tr( "Data Type" ) );
    }
    else if ( wkbType != QGis::WKBNoGeometry && srid == INT_MIN )
    {
      tip = tr( "Enter a SRID into the '%1' column" ).arg( tr( "SRID" ) );
    }
    else if ( !layerProperty.pkCols.isEmpty() )
    {
      tip = tr( "Select columns in the '%1' column that uniquely identify features of this layer" ).arg( tr( "Feature id" ) );
    }

    QStandardItem *schemaNameItem = new QStandardItem( layerProperty.schemaName );
    QStandardItem *typeItem = new QStandardItem( iconForWkbType( wkbType ), wkbType == QGis::WKBUnknown ? tr( "Select..." ) : QgsPostgresConn::displayStringForWkbType( wkbType ) );
    typeItem->setData( wkbType == QGis::WKBUnknown, Qt::UserRole + 1 );
    typeItem->setData( wkbType, Qt::UserRole + 2 );
    if ( wkbType == QGis::WKBUnknown )
      typeItem->setFlags( typeItem->flags() | Qt::ItemIsEditable );

    QStandardItem *geomTypeItem = new QStandardItem( QgsPostgresConn::displayStringForGeomType( layerProperty.geometryColType ) );

    QStandardItem *tableItem = new QStandardItem( layerProperty.tableName );
    QStandardItem *commentItem = new QStandardItem( layerProperty.tableComment );
    QStandardItem *geomItem  = new QStandardItem( layerProperty.geometryColName );
    QStandardItem *sridItem  = new QStandardItem( wkbType != QGis::WKBNoGeometry ? QString::number( srid ) : "" );
    sridItem->setEditable( wkbType != QGis::WKBNoGeometry && srid == INT_MIN );
    if ( sridItem->isEditable() )
    {
      sridItem->setText( tr( "Enter..." ) );
      sridItem->setFlags( sridItem->flags() | Qt::ItemIsEditable );
    }

    QStandardItem *pkItem = new QStandardItem( "" );
    if ( !layerProperty.pkCols.isEmpty() )
    {
      pkItem->setText( tr( "Select..." ) );
      pkItem->setFlags( pkItem->flags() | Qt::ItemIsEditable );
    }
    else
      pkItem->setFlags( pkItem->flags() & ~Qt::ItemIsEditable );

    pkItem->setData( layerProperty.pkCols, Qt::UserRole + 1 );
    pkItem->setData( "", Qt::UserRole + 2 );

    QStandardItem *selItem = new QStandardItem( "" );
    selItem->setFlags( selItem->flags() | Qt::ItemIsUserCheckable );
    selItem->setCheckState( Qt::Checked );
    selItem->setToolTip( tr( "Disable 'Fast Access to Features at ID' capability to force keeping the attribute table in memory (e.g. in case of expensive views)." ) );

    QStandardItem* sqlItem = new QStandardItem( layerProperty.sql );

    QList<QStandardItem*> childItemList;

    childItemList << schemaNameItem;
    childItemList << tableItem;
    childItemList << commentItem;
    childItemList << geomItem;
    childItemList << geomTypeItem;
    childItemList << typeItem;
    childItemList << sridItem;
    childItemList << pkItem;
    childItemList << selItem;
    childItemList << sqlItem;

    Q_FOREACH ( QStandardItem *item, childItemList )
    {
      if ( tip.isEmpty() )
      {
        item->setFlags( item->flags() | Qt::ItemIsSelectable );
        item->setToolTip( "" );
      }
      else
      {
        item->setFlags( item->flags() & ~Qt::ItemIsSelectable );

        if ( item == schemaNameItem )
          item->setData( QgsApplication::getThemeIcon( "/mIconWarn.png" ), Qt::DecorationRole );

        if ( item == schemaNameItem || item == tableItem || item == geomItem )
        {
          item->setToolTip( tip );
        }
      }
    }

    if ( !schemaItem )
    {
      QList<QStandardItem*> schemaItems = findItems( layerProperty.schemaName, Qt::MatchExactly, dbtmSchema );

      // there is already an item for this schema
      if ( !schemaItems.isEmpty() )
      {
        schemaItem = schemaItems.at( dbtmSchema );
      }
      else
      {
        // create a new toplevel item for this schema
        schemaItem = new QStandardItem( layerProperty.schemaName );
        schemaItem->setFlags( Qt::ItemIsEnabled );
        invisibleRootItem()->setChild( invisibleRootItem()->rowCount(), schemaItem );
      }
    }

    schemaItem->appendRow( childItemList );

    ++mTableCount;
  }
}
Example #23
0
void AnalysisThread::addIpNode(int protoInd)
{
    struct ip* pip_header = (struct ip *)this->snifferData.protocalVec.at(protoInd)->pProtocal;

    int orignalOffset = this->offset;
    QStandardItem* ipitem = new QStandardItem();
    this->len = pip_header->ip_hl * 4;
    setUserRoleData(ipitem);
    ipitem->setText(QString("Internet Protocol Version 4, Src: %1, Dst: %2")
            .arg(inet_ntoa(pip_header->ip_src))
            .arg(inet_ntoa(pip_header->ip_dst)));

    QStandardItem* item = new QStandardItem();
    item->setText("Version: 4");
    this->len = 1;
    setUserRoleData(item);
    ipitem->appendRow(item);

    item = new QStandardItem();
    this->len = 1;
    item->setText(QString("Header length: %1 bytes").arg(pip_header->ip_hl * 4));
    setUserRoleData(item);
    ipitem->appendRow(item);
    this->offset += this->len;

    // ECN(last 2 bits) and DSCP(first 6 bits) type
    item = new QStandardItem();
    this->len = sizeof(pip_header->ip_tos);
    item->setText(QString("Differentiated Services Field: 0x%1 (DSCP 0x%2: %3; ECN: 0x%4: %5)")
            .arg(SnifferUtil::byteToHexStr(pip_header->ip_tos,16))
            .arg(SnifferUtil::byteToHexStr(IPTOS_DSCP(pip_header->ip_tos),16))
            .arg(SnifferUtil::getDSCPDesc(pip_header->ip_tos))
            .arg(SnifferUtil::byteToHexStr(IPTOS_ECN(pip_header->ip_tos),16))
            .arg(SnifferUtil::getECNDesc(pip_header->ip_tos)));
    setUserRoleData(item);

    // DSCP
    QStandardItem* childitem = new QStandardItem();
    childitem->setText(QString("%1.. = Differentiated Services Codepoint: %2 (0x%3)")
            .arg(SnifferUtil::byteToHexStr(pip_header->ip_tos,2).left(6))
            .arg(SnifferUtil::getDSCPDesc(pip_header->ip_tos))
            .arg(SnifferUtil::byteToHexStr(IPTOS_DSCP(pip_header->ip_tos),16)));
    setUserRoleData(childitem);
    item->appendRow(childitem);

    // ECN
    childitem = new QStandardItem();
    childitem->setText(QString(".... ..%1 = Explicit Congestion Notification: %2 (0x%3)")
            .arg(SnifferUtil::byteToHexStr(pip_header->ip_tos,2).right(2))
            .arg(SnifferUtil::getECNDesc(pip_header->ip_tos))
            .arg(SnifferUtil::byteToHexStr(IPTOS_ECN(pip_header->ip_tos),16)));
    setUserRoleData(childitem);
    item->appendRow(childitem);
    
    ipitem->appendRow(item);
    this->offset += this->len;

    // Total length and Indentification
    item = new QStandardItem();
    this->len = sizeof(pip_header->ip_len);
    item->setText(QString("Total Length: %1").arg(ntohs(pip_header->ip_len)));
    setUserRoleData(item);
    ipitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    this->len = sizeof(pip_header->ip_id);
    item->setText(QString("Identification: 0x%1 (%2)")
            .arg(ntohs(pip_header->ip_id),0,16)
            .arg(ntohs(pip_header->ip_id)));
    setUserRoleData(item);
    ipitem->appendRow(item);
    this->offset += this->len;

    // ip Flag
    item = new QStandardItem();
    this->len = sizeof(pip_header->ip_off);
    short flag = pip_header->ip_off & (0xffff - IP_OFFMASK);
    item->setText(QString("Flag: 0x%1")
            .arg(flag));
    flag = flag>>8; // Get the higher 8 bit of the flag
    setUserRoleData(item);

    childitem = new QStandardItem();
    if (SnifferUtil::getBit(flag,0))
    {
        childitem->setText("1... .... = Reserved bit: Set");
    }
    else
    {
        childitem->setText("0... .... = Reserved bit: Not set");
    }
    setUserRoleData(childitem);
    item->appendRow(childitem);

    childitem = new QStandardItem();
    if (SnifferUtil::getBit(flag,1))
    {
        childitem->setText(".1.. .... = Don't Fragment: Set");
    }
    else
    {
        childitem->setText(".0.. .... = Don't Fragment: Not set");
    }
    setUserRoleData(childitem);
    item->appendRow(childitem);

    childitem = new QStandardItem();
    if (SnifferUtil::getBit(flag,2))
    {
        childitem->setText("..1. .... = More Fragments: Set");
    }
    else
    {
        childitem->setText("..0. .... = More Fragments: Not set");
    }
    setUserRoleData(childitem);
    item->appendRow(childitem);

    ipitem->appendRow(item);
    // ip offset and time to live
    item = new QStandardItem();
    this->len = sizeof(pip_header->ip_off);
    item->setText(QString("Fragment offset: %1").arg(ntohs(pip_header->ip_off)));
    setUserRoleData(item);
    ipitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    this->len = sizeof(pip_header->ip_ttl);
    item->setText(QString("Time to live: %1").arg(pip_header->ip_ttl));
    setUserRoleData(item);
    ipitem->appendRow(item);
    this->offset += this->len;


    QStandardItem* protoitem = new QStandardItem();
    this->len = sizeof(pip_header->ip_p);
    setUserRoleData(protoitem);
    ipitem->appendRow(protoitem);
    this->offset += this->len;

    item = new QStandardItem();
    this->len = sizeof(pip_header->ip_sum);
    item->setText(QString("Header checksum: 0x%1").arg(ntohs(pip_header->ip_sum),0,16));
    setUserRoleData(item);
    ipitem->appendRow(item);
    this->offset += this->len;
    
    // ip Source and destionation
    item = new QStandardItem();
    this->len = sizeof(pip_header->ip_src);
    item->setText(QString("Source: %1").arg(inet_ntoa(pip_header->ip_src)));
    setUserRoleData(item);
    ipitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    this->len = sizeof(pip_header->ip_dst);
    item->setText(QString("Destination: %1").arg(inet_ntoa(pip_header->ip_dst)));
    setUserRoleData(item);
    ipitem->appendRow(item);
    this->offset += this->len;
    

    this->offset = orignalOffset + pip_header->ip_hl * 4;
    int type = pip_header->ip_p;

    switch(type)
    {
        case IPPROTO_TCP:
            protoitem->setText(QString("Type: TCP (0x%1)").arg(type,2,16,QLatin1Char('0')));
            this->model->setItem(this->irow++, 0, ipitem);   

            addTcpNode(protoInd+1);
            break;
        case IPPROTO_UDP:
            protoitem->setText(QString("Type: UDP (0x%1)").arg(type,2, 16,QLatin1Char('0')));
            this->model->setItem(this->irow++, 0, ipitem);   

            addUdpNode(protoInd+1);
            break;
        case IPPROTO_ICMP:
            protoitem->setText(QString("Type: ICMP (0x%1)").arg(type,2, 16,QLatin1Char('0')));
            this->model->setItem(this->irow++, 0, ipitem);   

            addIcmpNode(protoInd+1);
            break;
        case IPPROTO_IGMP:
            protoitem->setText(QString("Type: IGMP (0x%1)").arg(type,2, 16,QLatin1Char('0')));
            this->model->setItem(this->irow++, 0, ipitem);   

            addIgmpNode(protoInd+1);
            break;
        default:
            qDebug("Current the sniffer can not analysis the ethernet type:%0x", type);
            break;
    }
}
Example #24
0
void Project::addFile(QTreeView* treeView, QSortFilterProxyModel* sort, const QString &fileName)
{
    if (_files.contains(fileName))
        return;
    QFileInfo fi(fileName);
    QString absFileName = fi.absoluteFilePath();
    QString relFileName;
    if (!projectRoot.isEmpty()) {
        QDir projectDir(QFileInfo(projectRoot).absoluteDir());
        relFileName = projectDir.relativeFilePath(absFileName);
    } else {
        relFileName = absFileName;
    }

    QStringList path = relFileName.split(QDir::separator());
    while (path.first().isEmpty()) {
        path.pop_front();
    }
    QStandardItem* curItem;
    bool isMiniZinc = true;
    bool isCoursera = false;
    //if (fi.suffix()=="mzn") {
    //    curItem = mzn;
    if (fi.suffix()=="zinc") {
        curItem = zinc;
    } else if (fi.suffix()=="dzn") {
        curItem = dzn;
    } else if (fi.suffix()=="fzn") {
        return;
    } else {
        curItem = other;
        isMiniZinc = false;
        isCoursera = fi.completeBaseName()=="_coursera";
    }

    if (isCoursera) {
        if (_courseraProject) {
            QMessageBox::warning(treeView,"Zinc IDE",
                                "Cannot add second Coursera options file",
                                QMessageBox::Ok);
            return;
        }
        QFile metadata(absFileName);
        if (!metadata.open(QIODevice::ReadOnly)) {
            QMessageBox::warning(treeView,"Zinc IDE",
                                 "Cannot open Coursera options file",
                                 QMessageBox::Ok);
            return;
        }
        QTextStream in(&metadata);
        CourseraProject* cp = new CourseraProject;
        if (in.status() != QTextStream::Ok) {
            delete cp;
            goto coursera_done;
        }
        cp->course = in.readLine();
        if (in.status() != QTextStream::Ok) {
            delete cp;
            goto coursera_done;
        }
        cp->checkpwdSid= in.readLine();
        if (in.status() != QTextStream::Ok) {
            delete cp;
            goto coursera_done;
        }
        cp->name = in.readLine();
        QString nSolutions_s = in.readLine();
        int nSolutions = nSolutions_s.toInt();
        for (int i=0; i<nSolutions; i++) {
            if (in.status() != QTextStream::Ok) {
                delete cp;
                goto coursera_done;
            }
            QString line = in.readLine();
            QStringList tokens = line.split(", ");
            if (tokens.size() < 5) {
                delete cp;
                goto coursera_done;
            }
            CourseraItem item(tokens[0].trimmed(),tokens[1].trimmed(),tokens[2].trimmed(),
                              tokens[3].trimmed(),tokens[4].trimmed());
            cp->problems.append(item);
        }
        if (in.status() != QTextStream::Ok) {
            delete cp;
            goto coursera_done;
        }
        nSolutions_s = in.readLine();
        nSolutions = nSolutions_s.toInt();
        for (int i=0; i<nSolutions; i++) {
            if (in.status() != QTextStream::Ok) {
                delete cp;
                goto coursera_done;
            }
            QString line = in.readLine();
            QStringList tokens = line.split(", ");
            if (tokens.size() < 3) {
                delete cp;
                goto coursera_done;
            }
            CourseraItem item(tokens[0].trimmed(),tokens[1].trimmed(),tokens[2].trimmed());
            cp->models.append(item);
        }
        _courseraProject = cp;
        ui->actionSubmit_to_Coursera->setVisible(true);
    }
coursera_done:

    setModified(true, true);
    QStandardItem* prevItem = curItem;
    treeView->expand(sort->mapFromSource(curItem->index()));
    curItem = curItem->child(0);
    int i=0;
    while (curItem != NULL) {
        if (curItem->text() == path.first()) {
            path.pop_front();
            treeView->expand(sort->mapFromSource(curItem->index()));
            prevItem = curItem;
            curItem = curItem->child(0);
            i = 0;
        } else {
            i += 1;
            curItem = curItem->parent()->child(i);
        }
    }
    for (int i=0; i<path.size(); i++) {
        QStandardItem* newItem = new QStandardItem(path[i]);
        prevItem->appendRow(newItem);
        if (i<path.size()-1) {
            newItem->setIcon(QIcon(":/icons/images/folder.png"));
        } else {
            _files.insert(absFileName,newItem->index());
            if (isMiniZinc) {
                newItem->setIcon(QIcon(":/images/mznicon.png"));
            }
        }
        treeView->expand(sort->mapFromSource(newItem->index()));
        prevItem = newItem;
    }
}
Example #25
0
void AnalysisThread::addTcpNode(int protoInd)
{
    struct tcphdr* ptcp_header = (struct tcphdr *)this->snifferData.protocalVec.at(protoInd)->pProtocal;

    QStandardItem* tcpitem = new QStandardItem();
    this->len = ptcp_header->doff * 4;
    setUserRoleData(tcpitem);

    // For the bottom manage the tcp header
    int tcpoffset = this->offset + ptcp_header->doff * 4;

    QStandardItem* item = new QStandardItem();
    u_int16_t src_port = ntohs(ptcp_header->source);
    this->len = sizeof(src_port);
    item->setText(QString("Source port: %1").arg(src_port));
    setUserRoleData(item);
    tcpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    u_int16_t dst_port = ntohs(ptcp_header->dest);
    this->len = sizeof(dst_port);
    item->setText(QString("Destination port: %1").arg(dst_port));
    setUserRoleData(item);
    tcpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    u_int32_t seq = ntohl(ptcp_header->seq);
    this->len = sizeof(seq);
    item->setText(QString("Sequence number: %1    (absolute sequence number)")
            .arg(seq));
    setUserRoleData(item);
    tcpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    u_int32_t ack_seq = ntohl(ptcp_header->ack_seq);
    this->len = sizeof(ack_seq);
    item->setText(QString("Acknowledgment number: %1    (absolute ack number)")
            .arg(ack_seq));
    setUserRoleData(item);
    tcpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    this->len = 1; // The header length
    item->setText(QString("Header length: %1 bytes")
            .arg(ptcp_header->doff * 4)); // The four bit multi 4 is the bytes
    setUserRoleData(item);
    tcpitem->appendRow(item);

    // The flag
    item = new QStandardItem();
    this->len = 2;
    setUserRoleData(item);
    QStringList flag; // The flag such as ack fin

    QStandardItem* childitem = new QStandardItem();
    this->len = 1;
    setUserRoleData(childitem);
    childitem->setText(QString("0000 00.. .... = Reserved: Not set"));
    item->appendRow(childitem);
    this->offset += this->len;

    childitem = new QStandardItem();
    setUserRoleData(childitem);
    if (ptcp_header->urg)
    {
        childitem->setText(".... ..1. .... = Urgent: Set");
        flag << "urg";
    }
    else
    {
        childitem->setText(".... ..0. .... = Urgent: Set");
    }
    item->appendRow(childitem);

    childitem = new QStandardItem();
    setUserRoleData(childitem);
    if (ptcp_header->ack)
    {
        childitem->setText(".... ...1 .... = Acknowledgment: Set");
        flag << "ack";
    }
    else
    {
        childitem->setText(".... ...0 .... = Acknowledgment: Not set");
    }
    item->appendRow(childitem);

    childitem = new QStandardItem();
    setUserRoleData(childitem);
    if (ptcp_header->psh)
    {
        childitem->setText(".... .... 1... = Push: Set");
        flag << "push";
    }
    else
    {
        childitem->setText(".... .... 0... = Push: Not set");
    }
    item->appendRow(childitem);

    childitem = new QStandardItem();
    setUserRoleData(childitem);
    if (ptcp_header->rst)
    {
        childitem->setText(".... .... .1.. = Reset: Set");
        flag << "reset";
    }
    else
    {
        childitem->setText(".... .... .0.. = Reset: Not set");
    }
    item->appendRow(childitem);

    childitem = new QStandardItem();
    setUserRoleData(childitem);
    if (ptcp_header->syn)
    {
        childitem->setText(".... .... .1.. = Reset: Set");
        flag << "syn";
    }
    else
    {
        childitem->setText(".... .... .0.. = Reset: Not set");
    }
    item->appendRow(childitem);

    childitem = new QStandardItem();
    setUserRoleData(childitem);
    if (ptcp_header->fin)
    {
        childitem->setText(".... .... ...1 = Fin: Set");
        flag << "fin";
    }
    else
    {
        childitem->setText(".... .... ...0 = Fin: Not set");
    }
    item->appendRow(childitem);
    
    item->setText(QString("Flags: %1")
            .arg(flag.join("/")));

    tcpitem->appendRow(item);
    this->offset += this->len;
    // The flag end
    
    item = new QStandardItem();
    u_int16_t window = ntohs(ptcp_header->window);
    this->len = sizeof(window);
    item->setText(QString("Window size value: %1").arg(window));
    setUserRoleData(item);
    tcpitem->appendRow(item);
    this->offset += this->len;

    item = new QStandardItem();
    this->len = sizeof(ptcp_header->check);
    item->setText(QString("Checksum: 0x%1 [validation disabled]")
            .arg(ntohs(ptcp_header->check),4, 16));
    setUserRoleData(item);
    tcpitem->appendRow(item);
    this->offset += this->len;

    tcpitem->setText(QString("Transmission Control Protocol, Src Port: %1, Dst Port: %2, Seq: %3, Ack: %4")
            .arg(src_port)
            .arg(dst_port)
            .arg(seq)
            .arg(ack_seq));
    this->model->setItem(this->irow++, 0, tcpitem); 

    // Analysis the application data
    //
    this->offset = tcpoffset;
    ApplicationData* pad = NULL;
    try{
        pad = static_cast<ApplicationData*>(this->snifferData.
               protocalVec.at(protoInd+1)->pProtocal);
    } catch(std::exception)
    {
        return;
    }
    if (pad == NULL)
    {
        return;
    }
    if (pad->strProtocal == SnifferType::HTTP_PROTOCAL)
    {
        addHttpNode(pad);
    }
}
Example #26
0
void MidiInstrument::populatePatchModel(QStandardItemModel* model, int chan, MidiType songType)
{
    model->clear();
    int mask = 0;
    bool drumchan = chan == 9;
    switch (songType)
    {
        case MIDI_TYPE_XG:
            mask = 4;
            break;
        case MIDI_TYPE_GS:
            mask = 2;
            break;
        case MIDI_TYPE_GM:
            if (drumchan)
                return;
            mask = 1;
            break;
        case MIDI_TYPE_NULL:
            mask = 7;
            break;
    }
    if (pg.size() > 1)
    {
        for (ciPatchGroup i = pg.begin(); i != pg.end(); ++i)
        {
            PatchGroup* pgp = *i;
            QList<QStandardItem*> folder;
            QStandardItem* noop = new QStandardItem("");
            QStandardItem *dir = new QStandardItem(pgp->name);
            QFont f = dir->font();
            f.setBold(true);
            dir->setFont(f);
            const PatchList& pl = pgp->patches;
            for (ciPatch ipl = pl.begin(); ipl != pl.end(); ++ipl)
            {
                const Patch* mp = *ipl;
                if (mp->typ & mask)
                {
                    int id = ((mp->hbank & 0xff) << 16) + ((mp->lbank & 0xff) << 8) + (mp->prog & 0xff);
                    QList<QStandardItem*> row;
                    QString strId = QString::number(id);
                    QStandardItem* idItem = new QStandardItem(strId);
                    QStandardItem* nItem = new QStandardItem(mp->name);
                    nItem->setToolTip(QString(pgp->name+":\n    "+mp->name));
                    row.append(nItem);
                    row.append(idItem);
                    dir->appendRow(row);
                }

            }
            folder.append(dir);
            folder.append(noop);
            model->appendRow(folder);
        }
    }
    else if (pg.size() == 1)
    {
        // no groups
        const PatchList& pl = pg.front()->patches;
        QStandardItem* root = model->invisibleRootItem();
        for (ciPatch ipl = pl.begin(); ipl != pl.end(); ++ipl)
        {
            const Patch* mp = *ipl;
            if (mp->typ & mask)
            {
                int id = ((mp->hbank & 0xff) << 16) + ((mp->lbank & 0xff) << 8) + (mp->prog & 0xff);
                QList<QStandardItem*> row;
                QString strId = QString::number(id);
                QStandardItem* idItem = new QStandardItem(strId);
                QStandardItem* nItem = new QStandardItem(mp->name);
                nItem->setToolTip(QString(mp->name));
                row.append(nItem);
                row.append(idItem);
                root->appendRow(row);
            }
        }
    }
}
Example #27
0
void AnalysisThread::addIgmpNode(int protoInd)
{
    struct igmp* pigmp_header = (struct igmp *)this->snifferData.protocalVec.at(protoInd)->pProtocal;

    int version = 1;
    QString type = "membership report";
    QString maxrestime = "";

    switch (pigmp_header->igmp_type)
    {
        case IGMP_MEMBERSHIP_QUERY:
        {
            type = "membership query";
            break;
        }
        case IGMP_V1_MEMBERSHIP_REPORT:
        {
            break;
        }
        case IGMP_V2_MEMBERSHIP_REPORT:
        {
            version = 2;
            maxrestime = QString("Max Response Time: %1 sec (0x%2)")
                .arg(pigmp_header->igmp_code / 10.0)
                .arg(pigmp_header->igmp_code,2,16,QLatin1Char('0'));
            break;
        }
        case IGMP_V2_LEAVE_GROUP:
        {
            type = "Leave-group message";
            break;
        }
        case 0x22:
        {
            version = 3;
            break;
        }
        default:
        {
            break;
        }
    }

    QStandardItem* igmpitem = new QStandardItem();
    this->len = sizeof(struct igmp);
    setUserRoleData(igmpitem);
    igmpitem->setText("Internet Group Management Protocol");
    
    QStandardItem* item = new QStandardItem();
    item->setText(QString("IGMP Version: %1").arg(version));
    igmpitem->appendRow(item);

    item = new QStandardItem();
    item->setText(QString("Type: %1 (0x%2)")
            .arg(type)
            .arg(pigmp_header->igmp_type,2,16));
    this->len = sizeof(pigmp_header->igmp_type);
    setUserRoleData(item);
    igmpitem->appendRow(item);
    this->offset += this->len;

    if (maxrestime != "")
    {
        item = new QStandardItem();
        this->len = 1;
        item->setText(maxrestime);
        setUserRoleData(item);
        igmpitem->appendRow(item);
    }
    this->offset += 1;

    item = new QStandardItem();
    this->len = sizeof(pigmp_header->igmp_cksum);
    item->setText(QString("Header checksum: 0x%1")
            .arg(ntohs(pigmp_header->igmp_cksum),4,16));
    setUserRoleData(item);
    igmpitem->appendRow(item);
    this->offset += this->len;
    
    item = new QStandardItem();
    this->len = sizeof(pigmp_header->igmp_group); 
    item->setText(QString("Multicast Address: %1")
            .arg(SnifferUtil::netToIp(pigmp_header->igmp_group)));
    setUserRoleData(item);
    igmpitem->appendRow(item);
    this->offset += this->len;

    this->model->setItem(this->irow++, 0, igmpitem);   

}
Example #28
0
//创建目录树
void MainWindow::createMenuTree()
{
    QSqlQuery fstMenuQuery;//对firstmenus搜索
    QSqlQuery secMenuQuery;//对secondmenus搜索
    QSqlQuery thdMenuQuery;//对thirdmenus搜索
    if(fstMenuQuery.exec("SELECT menuitem, id FROM firstmenus;"))//判断搜索数据库中一级目录
    {
        int fstNumRows = 0;//定义搜索返回的行数
        if(db.driver()->hasFeature(QSqlDriver::QuerySize))//判断驱动是否包含QuerySize
        {
            fstNumRows = fstMenuQuery.size();//将返回的行数赋于fstNumRows
        }
        else
        {
            fstMenuQuery.last();//移至最后一行
            fstNumRows = fstMenuQuery.at()+1;//将返回的行数赋于fstNumRows
            fstMenuQuery.seek(-1);//返回第一行
        }
        if(fstNumRows>0)//判断搜索得到的结果是否大于0
        {
            menuTree = new QTreeView();//建立目录树
            treeModel = new QStandardItemModel(fstNumRows,1);//设置目录的大小
            treeModel->setHeaderData(0,Qt::Horizontal,tr("目录"));//设置目录头
            int fstInt = 0;
            while(fstMenuQuery.next())//加载一级目录
            {
                QStandardItem *fstItem = new QStandardItem(fstMenuQuery.value(0).toString());//新建一级目录各子项
                fstItem->setData(1,Qt::UserRole);//设置目录阶数
                treeModel->setItem(fstInt,fstItem);//将一级目录加载到目录树中
                fstInt++;//fstInt自加

                if(secMenuQuery.exec("SELECT menuitem, id FROM secondmenus WHERE parentid = "+ fstMenuQuery.value(1).toString()))//判断是否有二级目录
                {
                    int secNumRows = 0;//定义搜索返回的行数
                    if(db.driver()->hasFeature(QSqlDriver::QuerySize))
                    {
                        secNumRows = secMenuQuery.size();
                    }
                    else
                    {
                        secMenuQuery.last();
                        secNumRows = secMenuQuery.at()+1;
                        secMenuQuery.seek(-1);
                    }
                    if(secNumRows>0)//判断搜索得到的结果是否大于0
                    {
                        while(secMenuQuery.next())//加载二级目录
                        {
                            QStandardItem *secItem = new QStandardItem(secMenuQuery.value(0).toString());//新建二级目录各子项
                            secItem->setData(2,Qt::UserRole);//设置目录阶数为2
                            fstItem->appendRow(secItem);//加载二级目录

                            if(thdMenuQuery.exec("SELECT menuitem, id FROM thirdmenus WHERE parentid = "+ secMenuQuery.value(1).toString()))
                            {
                                int thdNumRows = 0;
                                if(db.driver()->hasFeature(QSqlDriver::QuerySize))
                                {
                                    thdNumRows = thdMenuQuery.size();
                                }
                                else
                                {
                                    thdMenuQuery.last();
                                    thdNumRows = thdMenuQuery.at()+1;
                                    thdMenuQuery.seek(-1);
                                }
                                if(thdNumRows>0)
                                {
                                    while(thdMenuQuery.next())//加载三级目录
                                    {
                                        QStandardItem *thdItem = new QStandardItem(thdMenuQuery.value(0).toString());//新建三级目录各子项
                                        thdItem->setData(3,Qt::UserRole);//设置目录阶数为3
                                        secItem->appendRow(thdItem);//加载三级目录
                                    }
                                }
                            }
                        }
                    }
                }
            }
            menuTree->setModel(treeModel);//设置目录树的MODEL
            menuTree->setEditTriggers(QAbstractItemView::NoEditTriggers);//设置为不可编辑
            menuTree->resizeColumnToContents(0);//设置树的宽度
            mainSplitter->addWidget(menuTree);//将目录加载到主面板中

            connect(menuTree,SIGNAL(clicked(QModelIndex)),this,SLOT(menuTreeClick(QModelIndex)));//当用户点击树目录时,启动menuTreeClick函数
        }
    }
}
Example #29
0
int Schedule::init(QFile *file) {
	QString line;
	int basicBlock = 0;
	int beginState = 0;
	int endState = 0;
  int insnCount = 0;
	QString insn;
  if(!file)
    return 0;
	QTextStream in(file);
	Function * function = NULL;

  clear();
	m_functions.clear();

	Block * block = NULL;
	while (!in.atEnd()) {
		int pos = 0;
		int posEqual;
		line = in.readLine();
		QRegExp rxStartFunc("^Start Function: (\\w+)");
		QRegExp rxEndFunc("^End Function: (\\w+)");
		QRegExp rxFunctionCall("call.*@(\\w+)\\(");
		QRegExp rxLoad("load");
		QRegExp rxStateBegin("^state.*BB_?(\\d+)_(\\d+)$");
		QRegExp rxStateEnd("^(.*)\\(endState.*_(\\d+)\\)");
		QRegExp rxRegisters("%([0-9a-zA-Z_]+)");
		QRegExp rxEqual("=");
		QRegExp rxBr("br label %(\\d+)");
    

		if (rxStartFunc.indexIn(line, 0) != -1) {
			QString functionName = rxStartFunc.cap(1);
			function = new Function(functionName);
			m_functions.push_back(function);
			//qDebug() << functionName << endl;
		}
    else if (rxStateBegin.indexIn(line, 0) != -1) {
			//assert(function!=NULL);
      if(function == NULL){
        continue;
      }
			basicBlock = rxStateBegin.cap(1).toInt();
			beginState = rxStateBegin.cap(2).toInt();
			block = function->findBlock(basicBlock);
			if (block == NULL) {
				block = new Block(basicBlock);
				function->insertBlock(block);
			}
		}
    
    else if (rxStateEnd.indexIn(line, 0) != -1) {
			//assert(block != NULL);
      if(block == NULL){
        continue;
      }
			insn = rxStateEnd.cap(1).trimmed();
			//int BBNum = rxStateEnd.cap(2).toInt();
			//assert(BBNum == basicBlock);
      endState = rxStateEnd.cap(2).toInt();
      if (rxLoad.indexIn(line, 0) != -1) {
        //special case for load instruction
        endState -- ;
      }
			if (!insn.isEmpty()) {
        insnCount ++;
				Task *task = new Task(insn, basicBlock, beginState, endState);
				block->insertTask(task);

        if (rxFunctionCall.indexIn(line, 0) != -1) {
          /*function calls*/
					//qDebug << "function " << function->m_name<< " is calling "
           // << rxFunctionCall.cap(1)<< endl;
          task->m_type = CALL;
					function->m_callee.push_back(rxFunctionCall.cap(1));
        }
        else if (rxBr.indexIn(line, 0) != -1) {
          /*branch instructions*/
          //qDebug() << "branch destination of instruction " << function->m_name << line<< " is " << rxBr.cap(1) << endl;
          task->m_type = BR;
          block->m_branch = rxBr.cap(1).toInt();
        }
        posEqual = rxEqual.indexIn(line, 0);

        /*checking dependencies*/
				while ((pos = rxRegisters.indexIn(line, pos)) != -1) {
          if (pos < posEqual){
            //qDebug() << "output " << rxRegisters.cap(1) << endl;
            QString destination = rxRegisters.cap(1);
            task->m_destination = destination;
          }
					else{
            //case where a register appear on the right side of
            //an equal size: this is a source operand
            //qDebug() << "input for instruction" 
             // << line << " is "
              //<< rxRegisters.cap(1)<< endl;
            QString source = rxRegisters.cap(1);
            task->m_sources.push_back(source);
          }

					pos += rxRegisters.matchedLength();

				}
			}

		}
    else if (rxEndFunc.indexIn(line, 0) != -1) {
		}
    else {
      //qDebug() << line << endl;
    }
	}


	/*construct control flow graph*/
	for (int k = 0; k < m_functions.size(); k++) {
			Function * function = m_functions[k];
			for(int j = 0; j < (int)function->m_blocks.size(); j++)
			{
				Block * block = function->m_blocks[j];
				assert(block);
				for(int i = 0; i < (int)function->m_blocks.size(); i++)
				{
					if(i == j || function->m_blocks[i]->m_tasks.empty())
						continue;
					//printf("trying to match branch %d to register %d\n",function->m_blocks[j]->m_branch,
						//	function->m_blocks[i]->m_tasks[0]->m_destination);
          bool ok;
					if(function->m_blocks[i]->m_tasks[0]->m_destination.toInt(&ok)
							== block->m_branch+1 && ok){
            //TODO get rid of this hack after branch destination
            //block is available
						block->m_targetBlock = function->m_blocks[i];
						//printf("destination match:  from BB %d to BB %d for function %s", block->m_index,
								//function->m_blocks[i]->m_index, function->m_name.toStdString().c_str());
            //printf("because the branch destination is %d, and the output register of the current BB is %d\n",
                //block->m_branch, function->m_blocks[i]->m_tasks[0]->m_destination);
					}
				}
			}
	}

	/*construct data model*/
  /* now, ScheduleItem inherts QStandardItem.
  * Function, Block both inherts ScheduleItem,
  * so we do not need to create new object for these items,
  * just use them */
	QStandardItem *rootItem = invisibleRootItem();
	for (int k = 0; k < m_functions.size(); k++) {
		Function * function = m_functions[k];
		//QStandardItem *functionItem = new ScheduleItem(function->getName());
		QStandardItem *functionItem = function;
		functionItem->setFlags(functionItem->flags() & ~Qt::ItemIsEditable);
		rootItem->appendRow(functionItem);
		//QStandardItem *parentItem = item;
		for (int i = 0; i < (int)function->m_blocks.size(); i++) {
			Block *block = function->m_blocks[i];
			QStandardItem *blockItem;
			//blockItem= new ScheduleItem(block->text());
			blockItem= block; 
			blockItem->setFlags(blockItem->flags() & ~Qt::ItemIsEditable);
			functionItem->appendRow(blockItem);
			//cout << "Basic Block: " << block->getIndex() << endl;
      /* we don't need to create child task item anymore since
       * 1. we don't need to display them in the explorer
       * 2. tasks can be accessed through the m_tasks member variable
       */

			/*for (int j = 0; j < block->getNumTasks(); j++) {
				QStandardItem *taskItem_insn = new ScheduleItem(
						block->getTask(j)->m_insn);
				QStandardItem *taskItem_begin = new ScheduleItem(
						QString::number(block->getTask(j)->m_beginState));
				QStandardItem *taskItem_end = new ScheduleItem(
						QString::number(block->getTask(j)->m_endState));
				QList<QStandardItem *> list;
				list << taskItem_insn << taskItem_begin << taskItem_end;
				blockItem->appendRow(list);
				//taskItem->setFlags(taskItem->flags() & ~Qt::ItemIsEditable);
				//qDebug() << "\tInstruction: "
				//	<< block->getTask(j)->m_insn
				//<< "column count" << blockItem->columnCount() << endl;
			}
      */
		}
	}

  //process instruction dependencies
	for (int k = 0; k < m_functions.size(); k++) {
			Function * function = m_functions[k];
			for(int j = 0; j < (int)function->m_blocks.size(); j++)
			{
				Block * block = function->m_blocks[j];
        for(int k = 0; k < (int)block->m_tasks.size(); k++){
          for(int m = 0; m < (int)block->m_tasks.size(); m++){
            if(k == m) continue;
            if(block->m_tasks[m]->m_sources.contains(block->m_tasks[k]->m_destination)){
              block->m_tasks[k]->m_dependent.push_back(block->m_tasks[m]);
              block->m_tasks[m]->m_depending.push_back(block->m_tasks[k]);
            }

          }
        }
      }
  }

	setHeaderData(0, Qt::Horizontal, "Explorer");
	return 0;
}
Example #30
0
void ParseTreeLablerForm::readTree(char * treeFile)
{
    std::ifstream fileI;
    std::string line;
    standardModel = new QStandardItemModel ;
    rootNode = standardModel->invisibleRootItem();

    set<int> segsWithLabel;
    fileI.open(treeFile);
    getline(fileI, line);
    assert(line.substr(0,7)=="digraph");
    
    if (fileI.is_open())
    {
        while (fileI.good())
        {
            getline(fileI, line); 
            if (line.at(0) == '}')
                break;

            
            vector<string> toks;
            getTokens(line, toks,"\t ->;");
//            for(vector<string>::iterator it=toks.begin();it!=toks.end();it++)
//            {
//                if((*it).size()!=0)
//                        cout<<*it<<",,";
//            }
//            cout<<endl;
            if (toks.size() == 1)
            {
                //orphan
                string name = toks.at(0);
                updateTypeCounts(name);
                QStandardItem *item = new QStandardItem(name.data());
                nameToTreeNode[name] = item;

                rootNode->appendRow(item);

            }
            else if (toks.size() == 2)
            {
                // with a parent
                string name = toks.at(1);
                updateTypeCounts(name);
                QStandardItem *item = new QStandardItem(name.data());
                nameToTreeNode[name] = item;
                QStandardItem *parent = nameToTreeNode[toks.at(0)];
                assert(parent != NULL);
                parent->appendRow(item);

            }
            else
            {
                assert(false);
            }
        }
            widget.treeView->setModel(standardModel);
        
    }
    else
    {
        cout << "could not open the gt LabelMap file you specified ..exiting\n";
        exit(-1);
    }
}