void QgsProjectionSelectionTreeWidget::loadCrsList( QSet<QString> *crsFilter )
{
  if ( mProjListDone )
    return;

  // convert our Coordinate Reference System filter into the SQL expression
  QString sqlFilter = ogcWmsCrsFilterAsSqlExpression( crsFilter );

  // Create the top-level nodes for the list view of projections
  // Make in an italic font to distinguish them from real projections
  //
  // Geographic coordinate system node
  mGeoList = new QTreeWidgetItem( lstCoordinateSystems, QStringList( tr( "Geographic Coordinate Systems" ) ) );

  QFont fontTemp = mGeoList->font( 0 );
  fontTemp.setItalic( true );
  fontTemp.setBold( true );
  mGeoList->setFont( 0, fontTemp );
  mGeoList->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconProjectionEnabled.svg" ) ) );

  // Projected coordinate system node
  mProjList = new QTreeWidgetItem( lstCoordinateSystems, QStringList( tr( "Projected Coordinate Systems" ) ) );

  fontTemp = mProjList->font( 0 );
  fontTemp.setItalic( true );
  fontTemp.setBold( true );
  mProjList->setFont( 0, fontTemp );
  mProjList->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/transformed.svg" ) ) );

  //bail out in case the projections db does not exist
  //this is necessary in case the pc is running linux with a
  //read only filesystem because otherwise sqlite will try
  //to create the db file on the fly

  if ( !QFileInfo::exists( mSrsDatabaseFileName ) )
  {
    mProjListDone = true;
    return;
  }

  // open the database containing the spatial reference data
  sqlite3 *database = nullptr;
  int rc = sqlite3_open_v2( mSrsDatabaseFileName.toUtf8().data(), &database, SQLITE_OPEN_READONLY, nullptr );
  if ( rc )
  {
    // XXX This will likely never happen since on open, sqlite creates the
    //     database if it does not exist.
    showDBMissingWarning( mSrsDatabaseFileName );
    return;
  }

  const char *tail = nullptr;
  sqlite3_stmt *stmt = nullptr;
  // Set up the query to retrieve the projection information needed to populate the list
  //note I am giving the full field names for clarity here and in case someone
  //changes the underlying view TS
  QString sql = QStringLiteral( "select description, srs_id, upper(auth_name||':'||auth_id), is_geo, name, parameters, deprecated from vw_srs where %1 order by name,description" )
                .arg( sqlFilter );

  rc = sqlite3_prepare( database, sql.toUtf8(), sql.toUtf8().length(), &stmt, &tail );
  // XXX Need to free memory from the error msg if one is set
  if ( rc == SQLITE_OK )
  {
    QTreeWidgetItem *newItem = nullptr;
    // Cache some stuff to speed up creating of the list of projected
    // spatial reference systems
    QString previousSrsType;
    QTreeWidgetItem *previousSrsTypeNode = nullptr;

    while ( sqlite3_step( stmt ) == SQLITE_ROW )
    {
      // check to see if the srs is geographic
      int isGeo = sqlite3_column_int( stmt, 3 );
      if ( isGeo )
      {
        // this is a geographic coordinate system
        // Add it to the tree (field 0)
        newItem = new QTreeWidgetItem( mGeoList, QStringList( QString::fromUtf8( ( char * )sqlite3_column_text( stmt, 0 ) ) ) );

        // display the authority name (field 2) in the second column of the list view
        newItem->setText( AuthidColumn, QString::fromUtf8( ( char * )sqlite3_column_text( stmt, 2 ) ) );

        // display the qgis srs_id (field 1) in the third column of the list view
        newItem->setText( QgisCrsIdColumn, QString::fromUtf8( ( char * )sqlite3_column_text( stmt, 1 ) ) );
      }
      else
      {
        // This is a projected srs
        QTreeWidgetItem *node = nullptr;
        QString srsType = QString::fromUtf8( ( char * )sqlite3_column_text( stmt, 4 ) );
        // Find the node for this type and add the projection to it
        // If the node doesn't exist, create it
        if ( srsType == previousSrsType )
        {
          node = previousSrsTypeNode;
        }
        else
        {
          // Different from last one, need to search
          QList<QTreeWidgetItem *> nodes = lstCoordinateSystems->findItems( srsType, Qt::MatchExactly | Qt::MatchRecursive, NameColumn );
          if ( nodes.isEmpty() )
          {
            // the node doesn't exist -- create it
            // Make in an italic font to distinguish them from real projections
            node = new QTreeWidgetItem( mProjList, QStringList( srsType ) );
            QFont fontTemp = node->font( 0 );
            fontTemp.setItalic( true );
            node->setFont( 0, fontTemp );
          }
          else
          {
            node = nodes.first();
          }
          // Update the cache.
          previousSrsType = srsType;
          previousSrsTypeNode = node;
        }
        // add the item, setting the projection name in the first column of the list view
        newItem = new QTreeWidgetItem( node, QStringList( QString::fromUtf8( ( char * )sqlite3_column_text( stmt, 0 ) ) ) );
        // display the authority id (field 2) in the second column of the list view
        newItem->setText( AuthidColumn, QString::fromUtf8( ( char * )sqlite3_column_text( stmt, 2 ) ) );
        // display the qgis srs_id (field 1) in the third column of the list view
        newItem->setText( QgisCrsIdColumn, QString::fromUtf8( ( char * )sqlite3_column_text( stmt, 1 ) ) );
        // expand also parent node
        newItem->parent()->setExpanded( true );
      }

      // display the qgis deprecated in the user data of the item
      newItem->setData( 0, RoleDeprecated, QString::fromUtf8( ( char * )sqlite3_column_text( stmt, 6 ) ) );
      newItem->setHidden( cbxHideDeprecated->isChecked() );
    }
    mProjList->setExpanded( true );
  }

  // close the sqlite3 statement
  sqlite3_finalize( stmt );
  // close the database
  sqlite3_close( database );

  mProjListDone = true;
}
Example #2
0
void Wizard::checkMltComponents()
{
    m_mltCheck.programList->setColumnCount(2);
    m_mltCheck.programList->setRootIsDecorated(false);
    m_mltCheck.programList->setHeaderHidden(true);
    QSize itemSize(20, fontMetrics().height() * 2.5);
    m_mltCheck.programList->setColumnWidth(0, 30);
    m_mltCheck.programList->setIconSize(QSize(24, 24));


    QTreeWidgetItem *mltitem = new QTreeWidgetItem(m_mltCheck.programList);

    QTreeWidgetItem *meltitem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("Melt") + " (" + KdenliveSettings::rendererpath() + ')');
    meltitem->setData(1, Qt::UserRole, i18n("Required for rendering (part of MLT package)"));
    meltitem->setSizeHint(0, itemSize);
    meltitem->setIcon(0, m_okIcon);

    // Check MLT's installed producers
    QProcess checkProcess;
    checkProcess.start(KdenliveSettings::rendererpath(), QStringList() << "-query" << "producer");
    if (!checkProcess.waitForStarted()) {
        meltitem->setIcon(0, m_badIcon);
        meltitem->setData(1, Qt::UserRole, i18n("Error starting MLT's command line player (melt)"));
        button(QWizard::NextButton)->setEnabled(false);
    } else {
        checkProcess.waitForFinished();
        QByteArray result = checkProcess.readAllStandardError();

        // Check MLT avformat module
        QTreeWidgetItem *avformatItem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("Avformat module (FFmpeg)"));
        avformatItem->setData(1, Qt::UserRole, i18n("Required to work with various video formats (hdv, mpeg, flash, ...)"));
        avformatItem->setSizeHint(0, itemSize);
        if (!result.contains("- avformat")) {
            avformatItem->setIcon(0, m_badIcon);
            m_mltCheck.tabWidget->setTabEnabled(1, false);
        } else {
            avformatItem->setIcon(0, m_okIcon);
            // Make sure we have MLT > 0.3.4
            bool recentMlt = false;
            int version = 0;
            QString mltVersion;
            QString exepath = KStandardDirs::findExe("pkg-config");
            if (!exepath.isEmpty()) {
                checkProcess.start(exepath, QStringList() << "--variable=version" << "mlt++");
                if (!checkProcess.waitForStarted()) {
                    kDebug() << "// Error querying MLT's version";
                } else {
                    checkProcess.waitForFinished();
                    mltVersion = checkProcess.readAllStandardOutput();
                    version = 100 * mltVersion.section('.', 0, 0).toInt() + 10 * mltVersion.section('.', 1, 1).toInt() + mltVersion.section('.', 2, 2).toInt();
                    kDebug() << "// FOUND MLT's pkgconfig version: " << version;
                    if (version > 34) recentMlt = true;
                }
            }
            if (version == 0) {
                checkProcess.start(KdenliveSettings::rendererpath(), QStringList() << "--version");
                if (!checkProcess.waitForStarted()) {
                    kDebug() << "// Error querying MLT's version";
                } else {
                    checkProcess.waitForFinished();
                    mltVersion = checkProcess.readAllStandardError();
                    mltVersion = mltVersion.section('\n', 0, 0).simplified();
                    mltVersion = mltVersion.section(' ', -1).simplified();
                    version = 100 * mltVersion.section('.', 0, 0).toInt() + 10 * mltVersion.section('.', 1, 1).toInt() + mltVersion.section('.', 2, 2).toInt();
                    kDebug() << "// FOUND MLT version: " << version;
                    if (version >= 40) recentMlt = true;
                }
            }

            mltitem->setText(1, i18n("MLT version: %1", mltVersion.simplified()));
            mltitem->setSizeHint(0, itemSize);
            if (version < recommendedMltVersion) {
                mltitem->setData(1, Qt::UserRole, i18n("Please upgrade to the latest MLT version"));
                mltitem->setIcon(0, m_badIcon);
            } else {
                mltitem->setData(1, Qt::UserRole, i18n("MLT version is correct"));
                mltitem->setIcon(0, m_okIcon);
            }

            if (recentMlt) {
                // Check installed audio codecs
                QProcess checkProcess2;
                checkProcess2.start(KdenliveSettings::rendererpath(), QStringList() << "noise:" << "-consumer" << "avformat" << "acodec=list");
                if (!checkProcess2.waitForStarted()) {
                    m_mltCheck.tabWidget->setTabEnabled(1, false);
                    kDebug() << "// Error parsing MLT's avformat codecs";
                } else {
                    checkProcess2.waitForFinished();
                    QByteArray codecList = checkProcess2.readAllStandardError();
                    QString acodecList(codecList);
                    QStringList result;
                    QStringList alist = acodecList.split('\n', QString::SkipEmptyParts);
                    for (int i = 0; i < alist.count(); i++) {
                        if (alist.at(i).contains("- ")) result.append(alist.at(i).section("- ", 1).simplified().toLower());
                    }
                    m_mltCheck.acodecs_list->addItems(result);
                    KdenliveSettings::setAudiocodecs(result);
                    //kDebug()<<"// FOUND LIST:\n\n"<<m_audioCodecs<<"\n\n++++++++++++++++++++";
                }
                // Check video codecs
                checkProcess2.start(KdenliveSettings::rendererpath(), QStringList() << "noise:" << "-consumer" << "avformat" << "vcodec=list");
                if (!checkProcess2.waitForStarted()) {
                    kDebug() << "// Error parsing MLT's avformat codecs";
                } else {
                    checkProcess2.waitForFinished();
                    QByteArray codecList = checkProcess2.readAllStandardError();
                    QString vcodecList(codecList);
                    QStringList result;
                    QStringList vlist = vcodecList.split('\n', QString::SkipEmptyParts);
                    for (int i = 0; i < vlist.count(); i++) {
                        if (vlist.at(i).contains("- ")) result.append(vlist.at(i).section("- ", 1).simplified().toLower());
                    }
                    m_mltCheck.vcodecs_list->addItems(result);
                    KdenliveSettings::setVideocodecs(result);
                    //kDebug()<<"// FOUND LIST:\n\n"<<m_videoCodecs<<"\n\n++++++++++++++++++++";
                }
                // Check formats
                checkProcess2.start(KdenliveSettings::rendererpath(), QStringList() << "noise:" << "-consumer" << "avformat" << "f=list");
                if (!checkProcess2.waitForStarted()) {
                    kDebug() << "// Error parsing MLT's avformat codecs";
                } else {
                    checkProcess2.waitForFinished();
                    QByteArray codecList = checkProcess2.readAllStandardError();
                    QString vcodecList(codecList);
                    QStringList result;
                    QStringList vlist = vcodecList.split('\n', QString::SkipEmptyParts);
                    for (int i = 0; i < vlist.count(); i++) {
                        if (vlist.at(i).contains("- ")) {
                            QString format = vlist.at(i).section("- ", 1).simplified().toLower();
                            if (format.contains(',')) {
                                QStringList sub = format.split(',', QString::SkipEmptyParts);
                                for (int j = 0; j < sub.count(); j++)
                                    result.append(sub.at(j));
                            } else result.append(format);
                        }
                    }
                    m_mltCheck.formats_list->addItems(result);
                    KdenliveSettings::setSupportedformats(result);
                    //kDebug()<<"// FOUND LIST:\n\n"<<m_videoCodecs<<"\n\n++++++++++++++++++++";
                }
            }

        }

        // Check MLT dv module
        QTreeWidgetItem *dvItem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("DV module (libdv)"));
        dvItem->setData(1, Qt::UserRole, i18n("Required to work with dv files if avformat module is not installed"));
        dvItem->setSizeHint(0, itemSize);
        if (!result.contains("- libdv")) {
            dvItem->setIcon(0, m_badIcon);
        } else {
            dvItem->setIcon(0, m_okIcon);
        }

        // Check MLT image format module
        QTreeWidgetItem *imageItem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("QImage module"));
        imageItem->setData(1, Qt::UserRole, i18n("Required to work with images"));
        imageItem->setSizeHint(0, itemSize);
        if (!result.contains("- qimage")) {
            imageItem->setIcon(0, m_badIcon);
            imageItem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("Pixbuf module"));
            imageItem->setData(1, Qt::UserRole, i18n("Required to work with images"));
            imageItem->setSizeHint(0, itemSize);
            if (!result.contains("- pixbuf")) imageItem->setIcon(0, m_badIcon);
            else imageItem->setIcon(0, m_okIcon);
        } else {
            imageItem->setIcon(0, m_okIcon);
        }
    }
}
Example #3
0
CommitImpl::CommitImpl(Git* g, bool amend) : git(g) {

	// adjust GUI
	setAttribute(Qt::WA_DeleteOnClose);
	setupUi(this);
	textEditMsg->setFont(TYPE_WRITER_FONT);

	QVector<QSplitter*> v(1, splitter);
	QGit::restoreGeometrySetting(CMT_GEOM_KEY, this, &v);

	QSettings settings;
	QString templ(settings.value(CMT_TEMPL_KEY, CMT_TEMPL_DEF).toString());
	QString msg;
	QDir d;
	if (d.exists(templ))
		readFromFile(templ, msg);

	// set-up files list
	const RevFile* f = git->getFiles(ZERO_SHA);
	for (int i = 0; f && i < f->count(); ++i) { // in case of amend f could be null

		bool inIndex = f->statusCmp(i, RevFile::IN_INDEX);
		bool isNew = (f->statusCmp(i, RevFile::NEW) || f->statusCmp(i, RevFile::UNKNOWN));
		QColor myColor = QPalette().color(QPalette::WindowText);
		if (isNew)
			myColor = Qt::darkGreen;
		else if (f->statusCmp(i, RevFile::DELETED))
			myColor = Qt::red;

		QTreeWidgetItem* item = new QTreeWidgetItem(treeWidgetFiles);
		item->setText(0, git->filePath(*f, i));
		item->setText(1, inIndex ? "Updated in index" : "Not updated in index");
		item->setCheckState(0, inIndex || !isNew ? Qt::Checked : Qt::Unchecked);
		item->setForeground(0, myColor);
	}
	treeWidgetFiles->resizeColumnToContents(0);

	// compute cursor offsets. Take advantage of fixed width font
	textEditMsg->setPlainText("\nx\nx"); // cursor doesn't move on empty text
	textEditMsg->moveCursor(QTextCursor::Start);
	textEditMsg->verticalScrollBar()->setValue(0);
	textEditMsg->horizontalScrollBar()->setValue(0);
	int y0 = textEditMsg->cursorRect().y();
	int x0 = textEditMsg->cursorRect().x();
	textEditMsg->moveCursor(QTextCursor::Down);
	textEditMsg->moveCursor(QTextCursor::Right);
	textEditMsg->verticalScrollBar()->setValue(0);
	int y1 = textEditMsg->cursorRect().y();
	int x1 = textEditMsg->cursorRect().x();
	ofsX = x1 - x0;
	ofsY = y1 - y0;
	textEditMsg->moveCursor(QTextCursor::Start);
	textEditMsg_cursorPositionChanged();

	if (lastMsgBeforeError.isEmpty()) {
		// setup textEditMsg with old commit message to be amended
		QString status("");
		if (amend)
			status = git->getLastCommitMsg();

		// setup textEditMsg with default value if user opted to do so (default)
		if (testFlag(USE_CMT_MSG_F, FLAGS_KEY))
			status += git->getNewCommitMsg();

		msg = status.trimmed();
	} else
		msg = lastMsgBeforeError;

	textEditMsg->setPlainText(msg);
	textEditMsg->setFocus();

	// if message is not changed we avoid calling refresh
	// to change patch name in stgCommit()
	origMsg = msg;

	// setup button functions
	if (amend) {
		if (git->isStGITStack()) {
			pushButtonOk->setText("&Add to top");
			pushButtonOk->setShortcut(QKeySequence("Alt+A"));
			pushButtonOk->setToolTip("Refresh top stack patch");
		} else {
			pushButtonOk->setText("&Amend");
			pushButtonOk->setShortcut(QKeySequence("Alt+A"));
			pushButtonOk->setToolTip("Amend latest commit");
		}
		connect(pushButtonOk, SIGNAL(clicked()),
			this, SLOT(pushButtonAmend_clicked()));
	} else {
		if (git->isStGITStack()) {
			pushButtonOk->setText("&New patch");
			pushButtonOk->setShortcut(QKeySequence("Alt+N"));
			pushButtonOk->setToolTip("Create a new patch");
		}
		connect(pushButtonOk, SIGNAL(clicked()),
			this, SLOT(pushButtonCommit_clicked()));
	}
	connect(treeWidgetFiles, SIGNAL(customContextMenuRequested(const QPoint&)),
	        this, SLOT(contextMenuPopup(const QPoint&)));
	connect(textEditMsg, SIGNAL(cursorPositionChanged()),
	        this, SLOT(textEditMsg_cursorPositionChanged()));

    textEditMsg->installEventFilter(this);
}
Example #4
0
void MainWindow::updateFrames() {
    if (core == NULL)
        return;

    static bool first_time = true;
    if (first_time) {
        setup_mem();
        this->add_output(" > Adding binary information to notepad");
        notepadDock->setText("# Binary information\n\n" + core->cmd("i") +
                             "\n" + core->cmd("ie") + "\n" + core->cmd("iM") + "\n");
        //first_time = false;
    } else {
        refreshMem("");
    }

    refreshFlagspaces();

    auto spi = QAbstractItemView::ScrollPerItem;
    auto spp = QAbstractItemView::ScrollPerPixel;

    // TODO: make this configurable by the user?
    const bool use_scrollperpixel = true;
    if (use_scrollperpixel) {
        this->flagsDock->flagsTreeWidget->setVerticalScrollMode(spp);
        this->symbolsDock->symbolsTreeWidget->setVerticalScrollMode(spp);
        this->importsDock->importsTreeWidget->setVerticalScrollMode(spp);
        this->functionsDock->functionsTreeWidget->setVerticalScrollMode(spp);
        this->stringsDock->stringsTreeWidget->setVerticalScrollMode(spp);
        this->relocsDock->relocsTreeWidget->setVerticalScrollMode(spp);
        this->memoryDock->xreFromTreeWidget_2->setVerticalScrollMode(spp);
        this->memoryDock->xrefToTreeWidget_2->setVerticalScrollMode(spp);
    } else {
        this->flagsDock->flagsTreeWidget->setVerticalScrollMode(spi);
        this->symbolsDock->symbolsTreeWidget->setVerticalScrollMode(spi);
        this->importsDock->importsTreeWidget->setVerticalScrollMode(spi);
        this->functionsDock->functionsTreeWidget->setVerticalScrollMode(spi);
        this->stringsDock->stringsTreeWidget->setVerticalScrollMode(spi);
        this->relocsDock->relocsTreeWidget->setVerticalScrollMode(spi);
        this->memoryDock->xreFromTreeWidget_2->setVerticalScrollMode(spi);
        this->memoryDock->xrefToTreeWidget_2->setVerticalScrollMode(spi);
    }

    this->functionsDock->fillFunctions();

    this->importsDock->fillImports();

    // FIXME, doesn't work bc it sorts strings, not numbers... sigh
    /*
      Use QListWidgetItem::setData() not the constructor to set your value. Then all will work like you expect it to work.

      int yourIntValue = 123456;
      QListWidgetItem *item = new QListWidgetItem;
      item->setData(Qt::DisplayRole, yourIntValue);
    */
    //this->importsDock->importsTreeWidget->sortByColumn(1, Qt::DescendingOrder);

    adjustColumns(this->importsDock->importsTreeWidget);

    this->relocsDock->relocsTreeWidget->clear();
    for (auto i: core->getList ("bin","relocs")) {
        QStringList pieces = i.split (",");
        if (pieces.length()==3)
            appendRow(this->relocsDock->relocsTreeWidget, pieces[0], pieces[1], pieces[2]);
    }
    adjustColumns(this->relocsDock->relocsTreeWidget);

    this->symbolsDock->fillSymbols();

    this->stringsDock->stringsTreeWidget->clear();
    for (auto i : core->getList ("bin", "strings")) {
        QStringList pieces = i.split (",");
        if (pieces.length () == 2)
            appendRow(this->stringsDock->stringsTreeWidget, pieces[0], pieces[1]);
    }
    adjustColumns(this->stringsDock->stringsTreeWidget);

    this->commentsDock->commentsTreeWidget->clear();
    QList<QList<QString>> comments = this->core->getComments();
    for (QList<QString> comment: comments) {
        /*
        QString name;
        //this->add_debug_output("Comment: " + comment[1] + ": " + comment[0]);
        RAnalFunction *fcn = this->core->functionAt(comment[1].toLongLong(0, 16));
        if (fcn != NULL) {
            name = fcn->name;
        } else {
            name = "";
        }
        */
        QString fcn_name = this->core->cmdFunctionAt(comment[1]);
        appendRow(this->commentsDock->commentsTreeWidget, comment[1], fcn_name, comment[0].remove('"'));
    }
    adjustColumns(this->commentsDock->commentsTreeWidget);

    // Add nested comments
    QMap<QString, QList<QList<QString>>> cmts = this->core->getNestedComments();
    for(auto cmt : cmts.keys()) {
        QTreeWidgetItem *item = new QTreeWidgetItem(this->commentsDock->nestedCommentsTreeWidget);
        item->setText(0, cmt);
        QList<QList<QString>> meow = cmts.value(cmt);
        for (int i = 0; i < meow.size(); ++i) {
            QList<QString> tmp = meow.at(i);
            QTreeWidgetItem *it = new QTreeWidgetItem();
            it->setText(0, tmp[1]);
            it->setText(1, tmp[0].remove('"'));
            item->addChild(it);
        }
        this->commentsDock->nestedCommentsTreeWidget->addTopLevelItem(item);
    }
    adjustColumns(this->commentsDock->nestedCommentsTreeWidget);

    // TODO: FIXME: Remove the check for first_time;
    if (first_time) {
        sectionsWidget->tree->clear();
        int row = 0;
        for (auto i: core->getList("bin","sections")) {
            QStringList a = i.split (",");
            if (a.length()>2) {
                // Fix to work with ARM bins
                //if (a[4].startsWith(".")) {
                if (a[4].contains(".")) {
                    QString addr = a[1];
                    QString addr_end = "0x0"+core->itoa(core->math(a[1]+"+"+a[2]));
                    QString size = QString::number(core->math(a[2]));
                    QString name = a[4];
                    this->sectionsWidget->fillSections(row, name, size, addr, addr_end);

                    // Used to select a color for the sections graph
                    if (row == 10) {
                        row = 0;
                    } else {
                        row++;
                    }
                }
            }
        }
        //adjustColumns(sectionsWidget->tree);
        sectionsWidget->adjustColumns();

        first_time = false;

        this->dashboardDock->updateContents();
    }
}
Example #5
0
void CreateCircleDialog::loadIdentities(uint32_t token)
{
#ifdef DEBUG_CREATE_CIRCLE_DIALOG 
	std::cerr << "CreateCircleDialog::loadIdentities(" << token << ")";
	std::cerr << std::endl;
#endif

	QTreeWidget *tree = ui.treeWidget_IdList;

	tree->clear();

	bool acceptAnonymous = ui.radioButton_ListAll->isChecked();
	bool acceptAllPGP = ui.radioButton_ListAllPGP->isChecked();
	//bool acceptKnownPGP = ui.radioButton_ListKnownPGP->isChecked();

	RsGxsIdGroup data;
	std::vector<RsGxsIdGroup> datavector;
	std::vector<RsGxsIdGroup>::iterator vit;
	if (!rsIdentity->getGroupData(token, datavector)) {
		std::cerr << "CreateCircleDialog::insertIdentities() Error getting GroupData";
		std::cerr << std::endl;
		return;
	}

    for(vit = datavector.begin(); vit != datavector.end(); ++vit) 
    {
	    data = (*vit);

	    /* do filtering */
	    bool ok = false;
	    if (acceptAnonymous) 
		    ok = true;
	    else if (acceptAllPGP) 
		    ok = data.mMeta.mGroupFlags & RSGXSID_GROUPFLAG_REALID ;
	    else if (data.mPgpKnown)
		    ok = data.mMeta.mGroupFlags & RSGXSID_GROUPFLAG_REALID ;

	    if (!ok) {
#ifdef DEBUG_CREATE_CIRCLE_DIALOG 
		    std::cerr << "CreateCircleDialog::insertIdentities() Skipping ID: " << data.mMeta.mGroupId;
		    std::cerr << std::endl;
#endif
		    continue;
	    }

	    QString  keyId = QString::fromStdString(data.mMeta.mGroupId.toStdString());
	    QString  nickname = QString::fromUtf8(data.mMeta.mGroupName.c_str());
	    QString  idtype = tr("Anon Id");
	    
	    QPixmap pixmap ;

    if(data.mImage.mSize == 0 || !pixmap.loadFromData(data.mImage.mData, data.mImage.mSize, "PNG"))
        pixmap = QPixmap::fromImage(GxsIdDetails::makeDefaultIcon(RsGxsId(data.mMeta.mGroupId))) ;

	    if (data.mMeta.mGroupFlags & RSGXSID_GROUPFLAG_REALID) 
        	{
		    if (data.mPgpKnown) {
			    RsPeerDetails details;
			    rsPeers->getGPGDetails(data.mPgpId, details);
			    idtype = QString::fromUtf8(details.name.c_str());
		    } 
	    		else 
			    idtype = tr("PGP Linked Id");
		    
	    }

	    QTreeWidgetItem *item = new QTreeWidgetItem();
	    item->setText(RSCIRCLEID_COL_NICKNAME, nickname);
        item->setIcon(RSCIRCLEID_COL_NICKNAME, QIcon(pixmap));
	    item->setText(RSCIRCLEID_COL_KEYID, keyId);
	    item->setText(RSCIRCLEID_COL_IDTYPE, idtype);
	    tree->addTopLevelItem(item);

	    // External Circle.
	    if (mIsExistingCircle) 
	    {
		    // check if its in the circle.

		    // We use an explicit cast
		    //

		    if ( mCircleGroup.mInvitedMembers.find(RsGxsId(data.mMeta.mGroupId)) != mCircleGroup.mInvitedMembers.end())  /* found it */
			    addMember(keyId, idtype, nickname);
	    }
    }
}
void DbStructureModel::reloadData(DBBrowserDB* db)
{
    // Save pointer to DB object
    m_db = db;

    beginResetModel();

    // Remove all data except for the root item
    while(rootItem->childCount())
    {
        delete rootItem->child(0);
        rootItem->removeChild(rootItem->child(0));
    }

    // Create the nodes for tables, indices, views and triggers
    QMap<QString, QTreeWidgetItem*> typeToParentItem;
    QTreeWidgetItem* itemTables = new QTreeWidgetItem(rootItem);
    itemTables->setIcon(0, QIcon(QString(":/icons/table")));
    itemTables->setText(0, tr("Tables (%1)").arg(db->objMap.values("table").count()));
    typeToParentItem.insert("table", itemTables);
    QTreeWidgetItem* itemIndices = new QTreeWidgetItem(rootItem);
    itemIndices->setIcon(0, QIcon(QString(":/icons/index")));
    itemIndices->setText(0, tr("Indices (%1)").arg(db->objMap.values("index").count()));
    typeToParentItem.insert("index", itemIndices);
    QTreeWidgetItem* itemViews = new QTreeWidgetItem(rootItem);
    itemViews->setIcon(0, QIcon(QString(":/icons/view")));
    itemViews->setText(0, tr("Views (%1)").arg(db->objMap.values("view").count()));
    typeToParentItem.insert("view", itemViews);
    QTreeWidgetItem* itemTriggers = new QTreeWidgetItem(rootItem);
    itemTriggers->setIcon(0, QIcon(QString(":/icons/trigger")));
    itemTriggers->setText(0, tr("Triggers (%1)").arg(db->objMap.values("trigger").count()));
    typeToParentItem.insert("trigger", itemTriggers);

    // Get all database objects and sort them by their name
    QMultiMap<QString, DBBrowserObject> dbobjs;
    for(objectMap::ConstIterator it=db->objMap.begin(); it != db->objMap.end(); ++it)
        dbobjs.insert((*it).getname(), (*it));

    // Add the actual table objects
    for(QMultiMap<QString, DBBrowserObject>::ConstIterator it=dbobjs.begin(); it != dbobjs.end(); ++it)
    {
        // Object node
        QTreeWidgetItem *tableItem = new QTreeWidgetItem(typeToParentItem.value((*it).gettype()));
        tableItem->setIcon(0, QIcon(QString(":/icons/%1").arg((*it).gettype())));
        tableItem->setText(0, (*it).getname());
        tableItem->setText(1, (*it).gettype());
        tableItem->setText(3, (*it).getsql());

        // If it is a table or view add the field Nodes
        if((*it).gettype() == "table" || (*it).gettype() == "view")
        {
            for(int i=0; i < it->fldmap.size(); ++i)
            {
                QTreeWidgetItem *fldItem = new QTreeWidgetItem(tableItem);
                fldItem->setText(0, (*it).fldmap.at(i)->name());
                fldItem->setText(1, "field");
                fldItem->setText(2, (*it).fldmap.at(i)->type());
                fldItem->setIcon(0, QIcon(":/icons/field"));
            }
        }
    }

    // Refresh the view
    endResetModel();
}
Example #7
0
void DetailsDialog::ShowArchiveList()
{
	// show list of files in given archive-file
	
	QString szFile = m_pParentDigestList->GetFullPathToEntry(m_pCurrentEntry);
	setWindowTitle(szFile);
	
	if (m_pCurrentEntry->m_FileType.m_enFileType == HEADERTYPE_LZX)
	{
		if (m_pLzxLib == nullptr)
		{
			m_pLzxLib = new QLZXLib(this);
		}
		
		try
		{
			QLZXLib::tEntryInfoList lstArchiveInfo;
			
			// set given file as archive
			m_pLzxLib->SetArchive(szFile);
		
			// collect list of files
			m_pLzxLib->List(lstArchiveInfo);
			
			// note: following is temp listing..
			
			QTreeWidgetItem *pTopItem = new QTreeWidgetItem((QTreeWidgetItem*)0);
			pTopItem->setText(0, szFile);
			ui->archiveList->addTopLevelItem(pTopItem);
			
			auto it = lstArchiveInfo.begin();
			auto itEnd = lstArchiveInfo.end();
			while (it != itEnd)
			{
				QLZXLib::CEntryInfo &Entry = (*it);
				if (Entry.m_szFileName.length() < 1)
				{
					++it;
					continue;
				}
				
				QTreeWidgetItem *pSubItem = new QTreeWidgetItem(pTopItem);
				pSubItem->setText(0, Entry.m_szFileName);
				pSubItem->setText(1, QString::number(Entry.m_ulUnpackedSize)); // always given
				
				// TODO: need to extract files to get hashes..
				//
				// also, add each extracted file to our list
				// so we can lookup hash-matches:
				// set current archive as parent of each of those
				//
				//CFileEntry *pEntry = new CFileEntry();
				//pEntry->m_pParentEntry = m_pCurrentEntry;
				//m_DigestList.m_FileData.AddFoundFile();
				
				pTopItem->addChild(pSubItem);
				++it;
			}
			
			ui->archiveList->resizeColumnToContents(0);
		}
		catch (std::exception &exp)
		{
			QMessageBox::warning(this, "Error viewing",
								 QString::fromLocal8Bit(exp.what()),
								 QMessageBox::Ok);
								 
			//ui->lblDecrunch->setText(QString::fromLocal8Bit(exp.what()));
		}
	}
	else if (m_pCurrentEntry->m_FileType.m_enFileType == HEADERTYPE_LHA)
	{
		if (m_pLhaLib == nullptr)
		{
			m_pLhaLib = new QLhALib(this);
		}
		
		try
		{
			QLhALib::tArchiveEntryList lstArchiveInfo;
			
			// set given file as archive
			m_pLhaLib->SetArchive(szFile);
		
			// collect list of files
			m_pLhaLib->List(lstArchiveInfo);

			// note: following is temp listing..
			
			QTreeWidgetItem *pTopItem = new QTreeWidgetItem((QTreeWidgetItem*)0);
			pTopItem->setText(0, szFile);
			ui->archiveList->addTopLevelItem(pTopItem);
			
			auto it = lstArchiveInfo.begin();
			auto itEnd = lstArchiveInfo.end();
			while (it != itEnd)
			{
				QLhALib::CArchiveEntry &Entry = (*it);
				if (Entry.m_szFileName.length() < 1)
				{
					++it;
					continue;
				}
				
				QTreeWidgetItem *pSubItem = new QTreeWidgetItem(pTopItem);
				pSubItem->setText(0, Entry.m_szFileName);
				pSubItem->setText(1, QString::number(Entry.m_ulUnpackedSize)); // always given
				
				// TODO: need to extract files to get hashes..
				//
				// also, add each extracted file to our list
				// so we can lookup hash-matches:
				// set current archive as parent of each of those
				//
				//CFileEntry *pEntry = new CFileEntry();
				//pEntry->m_pParentEntry = m_pCurrentEntry;
				//m_DigestList.m_FileData.AddFoundFile();
				
				pTopItem->addChild(pSubItem);
				++it;
			}
			
			ui->archiveList->resizeColumnToContents(0);
		}
		catch (std::exception &exp)
		{
			QMessageBox::warning(this, "Error viewing",
								 QString::fromLocal8Bit(exp.what()),
								 QMessageBox::Ok);
								 
			//ui->lblDecrunch->setText(QString::fromLocal8Bit(exp.what()));
		}
	}
}
Example #8
0
void qtDLGPEEditor::InsertSections()
{
	QList<IMAGE_SECTION_HEADER> sections = m_pEManager->getSections(m_currentFile);
	if(sections.size() <= 0) return;

	QTreeWidgetItem *topElement;

	topElement = new QTreeWidgetItem();
	topElement->setText(0,"Sections");
	topElement->setText(1,"VA");
	topElement->setText(2,"Virtual Size");
	topElement->setText(3,"Ptr. Raw Data");
	topElement->setText(4,"Size of Raw");
	topElement->setText(5,"Characteristics");
	treePE->addTopLevelItem(topElement);

	for(int i = 0; i < sections.size(); i++)
	{
		QTreeWidgetItem *sectionElement;

		sectionElement = new QTreeWidgetItem(topElement);
		sectionElement->setText(0,QString::fromAscii((char*)sections.at(i).Name, sizeof(sections.at(i).Name)));
		sectionElement->setText(1,QString("%1").arg(sections.at(i).VirtualAddress,8,16,QChar('0')));
		sectionElement->setText(2,QString("%1").arg(sections.at(i).Misc.VirtualSize,8,16,QChar('0')));
		sectionElement->setText(3,QString("%1").arg(sections.at(i).PointerToRawData,8,16,QChar('0')));
		sectionElement->setText(4,QString("%1").arg(sections.at(i).SizeOfRawData,8,16,QChar('0')));
		sectionElement->setText(5,QString("%1").arg(sections.at(i).Characteristics,8,16,QChar('0')));
	}
}
Example #9
0
void qtDLGPEEditor::InsertHeaderData(QTreeWidgetItem *topElement,QString ValueName,quint64 dwValue)
{
	QTreeWidgetItem *dataElement = new QTreeWidgetItem(topElement);
	dataElement->setText(0,ValueName);
	dataElement->setText(1,QString("%1").arg(dwValue,16,16,QChar('0')));
}
Example #10
0
void MainWindow::addToList() {
    QTextStream out(stdout);
    if(gameRunning) {
        if(ui->newWord->text().length() > 0) {
            //            *wordList << ui->newWord->text().toUpper();
            if(ui->newWord->text().length() > 2) {
                if(Hunspell_spell(spellChecker,ui->newWord->text().toAscii())) {
                    //                out << "correct spelling\n";
                    out.flush();

                    if(validWord()) {
                        bool isNewWord = true;
                        for(int i=0;i<letterItems[ui->newWord->text().length()]->childCount();i++) {
                            if(letterItems[ui->newWord->text().length()]->child(i)->text(0) == ui->newWord->text().toLower()) {
                                isNewWord = false;
                            }
                        }
                        if(isNewWord) {
                            QTreeWidgetItem *newItem = new QTreeWidgetItem(letterItems[ui->newWord->text().length()]);
                            newItem->setText(0,ui->newWord->text().toLower());
                            ui->wordTree->scrollToItem(newItem);
                            ui->wordTree->clearSelection();
                            newItem->setSelected(true);
                        }
                    }
                    else {
                        QTreeWidgetItem *newItem = new QTreeWidgetItem(letterItems[1]);
                        newItem->setText(0,ui->newWord->text().toLower());
                        ui->wordTree->scrollToItem(newItem);
                        ui->wordTree->clearSelection();
                        newItem->setSelected(true);
                    }
                }
                else {
                    //                out << "incorrect spelling\n";
                    out.flush();
                    QTreeWidgetItem *newItem = new QTreeWidgetItem(letterItems[0]);
                    newItem->setText(0,ui->newWord->text().toLower());
                    ui->wordTree->scrollToItem(newItem);
                    ui->wordTree->clearSelection();
                    newItem->setSelected(true);
                }
            }
            ui->wordTree->expandAll();
            //            ui->wordTable->setRowCount(10);
            //            ui->wordTable->setColumnCount(1);
            //            QTableWidgetItem *newItem = new QTableWidgetItem(ui->newWord->text());
            //            ui->wordTable->setItem(1,1,newItem);
            //            wordListModel->setStringList(*wordList);
            //            ui->wordList->scrollToBottom();
            //ui->wordList->itemDelegateForRow(0)->setProperty("color",QColor(255,0,0));
        }
    }
    int score = 0;
    int words = 0;
    int lettersScore[18] = {-1,-1,0,1,1,2,3,5,8,8,8,8,8,8,8,8,8,8};
    for(int i = 0; i<18; i++) {
        if(i != 2) {
            score += letterItems[i]->childCount()*lettersScore[i];
        }
        if(i > 2) {
            words += letterItems[i]->childCount();
        }
    }
    ui->score->display(score);
    ui->numWords->display(words);
    
    ui->newWord->setText("");
    for(int i = 0;i<16;i++) {
        button[i]->setStyleSheet("* { color: black;} ");
    }
    ui->newWord->setFocus();
}
Example #11
0
void qtDLGPEEditor::InsertOptionalHeader()
{
	QTreeWidgetItem *topElement;
	topElement = new QTreeWidgetItem();
	topElement->setText(0,"IMAGE_OPTIONAL_HEADER");

	if(m_pEManager->is64BitFile(m_currentFile))
	{
		IMAGE_NT_HEADERS64 currentFileHeader = m_pEManager->getNTHeader64(m_currentFile);

		treePE->addTopLevelItem(topElement);
		InsertHeaderData(topElement,"AddressOfEntryPoint",currentFileHeader.OptionalHeader.AddressOfEntryPoint);
		InsertHeaderData(topElement,"BaseOfCode",currentFileHeader.OptionalHeader.BaseOfCode);
		InsertHeaderData(topElement,"CheckSum",currentFileHeader.OptionalHeader.CheckSum);
		//InsertHeaderData(topElement,"DataDirectory",currentFileHeader.OptionalHeader.DataDirectory);
		InsertHeaderData(topElement,"DllCharacteristics",currentFileHeader.OptionalHeader.DllCharacteristics);
		InsertHeaderData(topElement,"FileAlignment",currentFileHeader.OptionalHeader.FileAlignment);
		InsertHeaderData(topElement,"ImageBase",currentFileHeader.OptionalHeader.ImageBase);
		InsertHeaderData(topElement,"LoaderFlags",currentFileHeader.OptionalHeader.LoaderFlags);
		InsertHeaderData(topElement,"Magic",currentFileHeader.OptionalHeader.Magic);
		InsertHeaderData(topElement,"MajorImageVersion",currentFileHeader.OptionalHeader.MajorImageVersion);
		InsertHeaderData(topElement,"MajorLinkerVersion",currentFileHeader.OptionalHeader.MajorLinkerVersion);
		InsertHeaderData(topElement,"MajorOperatingSystemVersion",currentFileHeader.OptionalHeader.MajorOperatingSystemVersion);
		InsertHeaderData(topElement,"MajorSubsystemVersion",currentFileHeader.OptionalHeader.MajorSubsystemVersion);
		InsertHeaderData(topElement,"MinorImageVersion",currentFileHeader.OptionalHeader.MinorImageVersion);
		InsertHeaderData(topElement,"MinorLinkerVersion",currentFileHeader.OptionalHeader.MinorLinkerVersion);
		InsertHeaderData(topElement,"MinorOperatingSystemVersion",currentFileHeader.OptionalHeader.MinorOperatingSystemVersion);
		InsertHeaderData(topElement,"MinorSubsystemVersion",currentFileHeader.OptionalHeader.MinorSubsystemVersion);
		InsertHeaderData(topElement,"NumberOfRvaAndSizes",currentFileHeader.OptionalHeader.NumberOfRvaAndSizes);
		InsertHeaderData(topElement,"SectionAlignment",currentFileHeader.OptionalHeader.SectionAlignment);
		InsertHeaderData(topElement,"SizeOfCode",currentFileHeader.OptionalHeader.SizeOfCode);
		InsertHeaderData(topElement,"SizeOfHeaders",currentFileHeader.OptionalHeader.SizeOfHeaders);
		InsertHeaderData(topElement,"SizeOfHeapCommit",currentFileHeader.OptionalHeader.SizeOfHeapCommit);
		InsertHeaderData(topElement,"SizeOfHeapReserve",currentFileHeader.OptionalHeader.SizeOfHeapReserve);
		InsertHeaderData(topElement,"SizeOfImage",currentFileHeader.OptionalHeader.SizeOfImage);
		InsertHeaderData(topElement,"SizeOfInitializedData",currentFileHeader.OptionalHeader.SizeOfInitializedData);
		InsertHeaderData(topElement,"SizeOfStackCommit",currentFileHeader.OptionalHeader.SizeOfStackCommit);
		InsertHeaderData(topElement,"SizeOfStackReserve",currentFileHeader.OptionalHeader.SizeOfStackReserve);
		InsertHeaderData(topElement,"SizeOfUninitializedData",currentFileHeader.OptionalHeader.SizeOfUninitializedData);
		InsertHeaderData(topElement,"Subsystem",currentFileHeader.OptionalHeader.Subsystem);
		InsertHeaderData(topElement,"Win32VersionValue",currentFileHeader.OptionalHeader.Win32VersionValue);
	}
	else
	{
		IMAGE_NT_HEADERS32 currentFileHeader = m_pEManager->getNTHeader32(m_currentFile);

		treePE->addTopLevelItem(topElement);
		InsertHeaderData(topElement,"AddressOfEntryPoint",currentFileHeader.OptionalHeader.AddressOfEntryPoint);
		InsertHeaderData(topElement,"BaseOfCode",currentFileHeader.OptionalHeader.BaseOfCode);
		InsertHeaderData(topElement,"CheckSum",currentFileHeader.OptionalHeader.CheckSum);
		//InsertHeaderData(topElement,"DataDirectory",currentFileHeader.OptionalHeader.DataDirectory);
		InsertHeaderData(topElement,"DllCharacteristics",currentFileHeader.OptionalHeader.DllCharacteristics);
		InsertHeaderData(topElement,"FileAlignment",currentFileHeader.OptionalHeader.FileAlignment);
		InsertHeaderData(topElement,"ImageBase",currentFileHeader.OptionalHeader.ImageBase);
		InsertHeaderData(topElement,"LoaderFlags",currentFileHeader.OptionalHeader.LoaderFlags);
		InsertHeaderData(topElement,"Magic",currentFileHeader.OptionalHeader.Magic);
		InsertHeaderData(topElement,"MajorImageVersion",currentFileHeader.OptionalHeader.MajorImageVersion);
		InsertHeaderData(topElement,"MajorLinkerVersion",currentFileHeader.OptionalHeader.MajorLinkerVersion);
		InsertHeaderData(topElement,"MajorOperatingSystemVersion",currentFileHeader.OptionalHeader.MajorOperatingSystemVersion);
		InsertHeaderData(topElement,"MajorSubsystemVersion",currentFileHeader.OptionalHeader.MajorSubsystemVersion);
		InsertHeaderData(topElement,"MinorImageVersion",currentFileHeader.OptionalHeader.MinorImageVersion);
		InsertHeaderData(topElement,"MinorLinkerVersion",currentFileHeader.OptionalHeader.MinorLinkerVersion);
		InsertHeaderData(topElement,"MinorOperatingSystemVersion",currentFileHeader.OptionalHeader.MinorOperatingSystemVersion);
		InsertHeaderData(topElement,"MinorSubsystemVersion",currentFileHeader.OptionalHeader.MinorSubsystemVersion);
		InsertHeaderData(topElement,"NumberOfRvaAndSizes",currentFileHeader.OptionalHeader.NumberOfRvaAndSizes);
		InsertHeaderData(topElement,"SectionAlignment",currentFileHeader.OptionalHeader.SectionAlignment);
		InsertHeaderData(topElement,"SizeOfCode",currentFileHeader.OptionalHeader.SizeOfCode);
		InsertHeaderData(topElement,"SizeOfHeaders",currentFileHeader.OptionalHeader.SizeOfHeaders);
		InsertHeaderData(topElement,"SizeOfHeapCommit",currentFileHeader.OptionalHeader.SizeOfHeapCommit);
		InsertHeaderData(topElement,"SizeOfHeapReserve",currentFileHeader.OptionalHeader.SizeOfHeapReserve);
		InsertHeaderData(topElement,"SizeOfImage",currentFileHeader.OptionalHeader.SizeOfImage);
		InsertHeaderData(topElement,"SizeOfInitializedData",currentFileHeader.OptionalHeader.SizeOfInitializedData);
		InsertHeaderData(topElement,"SizeOfStackCommit",currentFileHeader.OptionalHeader.SizeOfStackCommit);
		InsertHeaderData(topElement,"SizeOfStackReserve",currentFileHeader.OptionalHeader.SizeOfStackReserve);
		InsertHeaderData(topElement,"SizeOfUninitializedData",currentFileHeader.OptionalHeader.SizeOfUninitializedData);
		InsertHeaderData(topElement,"Subsystem",currentFileHeader.OptionalHeader.Subsystem);
		InsertHeaderData(topElement,"Win32VersionValue",currentFileHeader.OptionalHeader.Win32VersionValue);
	}
}
Example #12
0
void EditDrumset::nameChanged(const QString& name)
      {
      QTreeWidgetItem* item = pitchList->currentItem();
      if (item)
            item->setText(COL_NAME, name);
      }
Example #13
0
void
ViewHelpMenu::generalInfo()
{
  std::string text2 = getPGLVersionString();
  QString text;
  ViewSysInfo a (this,__glwidget,(tr("PlantGL Viewer")+" "+QString(text2.c_str())).toAscii(),true);
  QTreeWidgetItem * itemF = a.addItem(tr("PlantGL Library"));
  QTreeWidgetItem *item = new QTreeWidgetItem( itemF );
  item->setText( 0, tr( "Version" ) );
  item->setText( 1, QString(text2.c_str()) );
  item = new QTreeWidgetItem( itemF, item );
  item->setText( 0, tr( "Binary Format Version" ) );
  item->setText( 1, QString::number(BinaryPrinter::BINARY_FORMAT_VERSION) );
  item = new QTreeWidgetItem( itemF, item );
  item->setText( 0, tr( "Real Type Precision" ) );
#ifdef PGL_USE_DOUBLE
  text = "Double";
#else
  text = "Simple";
#endif
  item->setText( 1, text  );
  item = new QTreeWidgetItem( itemF, item );
  item->setText( 0, tr( "Using Threads" ) );
  if(ViewGeomSceneGL::useThread()) text = "True";
  else text = "False";
  item->setText( 1, tr( text.toAscii() ) );

  item = new QTreeWidgetItem( itemF, item );
  item->setText( 0, tr( "PGL Namespace" ) );
#ifndef PGL_NAMESPACE_NAME
  text = "False";
#else
  text = "True";
#endif
  item->setText( 1, tr( text.toAscii() ) );
  item = new QTreeWidgetItem( itemF, item );
  item->setText( 0, tr( "PGL Debug" ) );
#ifdef PGL_DEBUG
  text = "True";
#else
  text = "False";
#endif
  item->setText( 1, tr( text.toAscii() ) );
#ifdef _WIN32
  item = new QTreeWidgetItem( itemF, item );
  item->setText( 0, tr( "PGL DLLs" ) );
#ifdef VIEW_DLL
  text = "True";
#else
  text = "False";
#endif
  item->setText( 1, tr( text.toAscii() ) );
#endif
  item = new QTreeWidgetItem( itemF, item );
  item->setText( 0, tr( "Using Glut" ) );
#ifdef WITH_GLUT
  text = "True";
#else
  text = "False";
#endif
  item->setText( 1, tr( text.toAscii() ) );
  itemF = a.addItem(tr("Tools Library"));
  item = new QTreeWidgetItem( itemF );
  item->setText( 0, tr( "Tools Namespace" ) );
#ifndef TOOLS_NAMESPACE_NAME
  text = "False";
#else
  text = "True";
#endif
  item->setText( 1, tr( text.toAscii() ) );
  //itemF = a.addItem(tr("PlantGL"));
  //item = new QTreeWidgetItem( itemF );
  //item->setText( 0, tr( "Install Path" ) );
  //string p = TOOLS(getPlantGLDir());
  //if(!p.empty())item->setText( 1, QString(p.c_str()) );
  itemF = a.addItem(tr("Flex"));
  item = new QTreeWidgetItem( itemF );
  item->setText( 0, tr( "Version" ) );
  item->setText( 1, QString(lexerVersion().c_str())  );
  a.exec();
}
Example #14
0
void DialogMsgManage::init()
{
    setWindowFlags(Qt::Dialog | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
    setAttribute(Qt::WA_DeleteOnClose);
    //加载qss
    QFile file(":/qss/Dialog.qss");
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << file.errorString() << __FILE__ << __LINE__;
    } else {
        setStyleSheet(file.readAll());
    }
    file.close();    
    connect(g_msgbox, SIGNAL(signMsgChanged(int,int,int))
            , this, SLOT(slotProcessMsgChange(int,int,int)), Qt::QueuedConnection);
    
    ui->btnFirstPage->setEnabled(false);
    ui->btnPrevPage->setEnabled(false);
    ui->btnNextPage->setEnabled(false);
    ui->btnLastPage->setEnabled(false);

    m_valid.setRange(0, 0);
    ui->lineEditCurPage->setValidator(&m_valid);
    ui->lineEditCurPage->setText("0");
    ui->lineEditCurPage->setAlignment(Qt::AlignCenter);
    ui->labelPageNum->setAlignment(Qt::AlignCenter);
    
    //信息列表菜单
    m_actRead = new QAction(this);
    connect(m_actRead, SIGNAL(triggered()), this, SLOT(slotActionRead()));
    m_actStopRead = new QAction(this);
    connect(m_actStopRead, SIGNAL(triggered()), this, SLOT(slotActionStopRead()));
    m_actForwarding = new QAction(this);
    connect(m_actForwarding, SIGNAL(triggered()), this, SLOT(slotActionForwarding()));
    m_actReply = new QAction(this);
    connect(m_actReply, SIGNAL(triggered()), this, SLOT(slotActionReply()));
//    m_actMoveToInbox = new QAction(this);
//    connect(m_actMoveToInbox, SIGNAL(triggered()), this, SLOT(slotActionMoveToInbox()));
//    m_actMoveToOutbox = new QAction(this);
//    connect(m_actMoveToOutbox, SIGNAL(triggered()), this, SLOT(slotActionMoveToOutbox()));
//    m_actMoveToDraftbox = new QAction(this);
//    connect(m_actMoveToDraftbox, SIGNAL(triggered()), this, SLOT(slotActionMoveToDraftbox()));
//    m_actMoveToDustbin = new QAction(this);
//    connect(m_actMoveToDustbin, SIGNAL(triggered()), this, SLOT(slotActionMoveToDustbin()));
    m_actRestore = new QAction(this);
    connect(m_actRestore, SIGNAL(triggered()), this, SLOT(slotActionRestore()));
    m_actAddIntoPhoneBook = new QAction(this);
    connect(m_actAddIntoPhoneBook, SIGNAL(triggered()), this, SLOT(slotActionAddIntoPhoneBook()));
    m_actDelete = new QAction(this);
    connect(m_actDelete, SIGNAL(triggered()), this, SLOT(slotActionDelete()));
    m_menuMsgList = new QMenu(this);
    m_menuMsgList->addAction(m_actRead);
    m_menuMsgList->addAction(m_actStopRead);
    m_menuMsgList->addAction(m_actForwarding);
    m_menuMsgList->addAction(m_actReply);
    m_menuMsgList->addSeparator();
    m_menuMsgList->addAction(m_actAddIntoPhoneBook);
    m_menuMsgList->addSeparator();
//    m_menuMsgList->addAction(m_actMoveToInbox);
//    m_menuMsgList->addAction(m_actMoveToOutbox);
//    m_menuMsgList->addAction(m_actMoveToDraftbox);
//    m_menuMsgList->addAction(m_actMoveToDustbin);
    m_menuMsgList->addAction(m_actRestore);
    m_menuMsgList->addSeparator();
    m_menuMsgList->addAction(m_actDelete);
    ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    
    m_actSetAllRead = new QAction(this);
    connect(m_actSetAllRead, SIGNAL(triggered()), this, SLOT(slotActionSetAllRead()));
    m_actViewUnread = new QAction(this);
    connect(m_actViewUnread, SIGNAL(triggered()), this, SLOT(slotActionViewUnread()));
    m_actExport = new QAction(this);
    connect(m_actExport, SIGNAL(triggered()), this, SLOT(slotActionExport()));
    m_actDeleteAll = new QAction(this);
    connect(m_actDeleteAll, SIGNAL(triggered()), this, SLOT(slotActionDeleteAll()));
    m_actDeleteMoreSetting = new QAction(this);
    connect(m_actDeleteMoreSetting, SIGNAL(triggered()), this, SLOT(slotActionDeleteMoreSetting()));
    m_menuTree = new QMenu(this);
    m_menuTree->addAction(m_actViewUnread);
    m_menuTree->addAction(m_actSetAllRead);
    m_menuTree->addSeparator();
    m_menuTree->addAction(m_actExport);
    m_menuTree->addSeparator();
    m_menuTree->addAction(m_actDeleteAll);
    m_menuTree->addAction(m_actDeleteMoreSetting);
    ui->treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);

    ui->treeWidget->header()->hide();
    m_msgBoxTopItem = new QTreeWidgetItem(ui->treeWidget);
    m_msgBoxTopItem->setSizeHint(0, QSize(0, cons_tree_item_height));
    for (int i=0; i<=Message::Box_Dustbin; i++) {
        QTreeWidgetItem *twItem = new QTreeWidgetItem(m_msgBoxTopItem);
        twItem->setData(0, Qt::UserRole + DataIndex_Type, DataType_MessageBox);
        twItem->setData(0, Qt::UserRole + DataIndex_Value, i);
        twItem->setSizeHint(0, QSize(0, cons_tree_item_height));
        m_msgBoxItems << twItem;
    }
    m_phoneBookItem = new QTreeWidgetItem(ui->treeWidget);
    m_phoneBookItem->setSizeHint(0, QSize(0, cons_tree_item_height));
    for (int i=0; i<=Contact::Type_Stranger; i++) {
        QTreeWidgetItem *twItem = new QTreeWidgetItem(m_phoneBookItem);
        twItem->setSizeHint(0, QSize(0, cons_tree_item_height));
        QList<Contact> contacts = g_phoneBook->getContactsOfType((Contact::Type)i);
        foreach (Contact contact, contacts) {
            QTreeWidgetItem *twItemT = new QTreeWidgetItem(twItem);
            twItemT->setText(0, QString("%1(%2)").arg(contact.name).arg(contact.phonenum));
            twItemT->setData(0, Qt::UserRole + DataIndex_Type, DataType_PhoneBook);
            twItemT->setData(0, Qt::UserRole + DataIndex_Value, QVariant::fromValue<Contact>(contact));
            twItemT->setSizeHint(0, QSize(0, cons_tree_item_height));
        }
        m_contactTypeItems << twItem;
    }
void MainWindow::pluginTestFinished(PluginTest *test)
{
	QTreeWidgetItem *item = treeItemFromPluginTest(test);
	//
	if (item != NULL)
	{
		QFont font = item->font(0);
		font.setBold(true);
		// is test ok?
		if (test->isTestOk())
		{
			item->setText(1, "[Ok]");
			item->setFont(1, font);
		}
		else // test failed
		{
			item->setText(1, "[Failed!]");
			item->setFont(0, font);
		}
		// update info
		item->child(2)->child(0)->setText(1, test->getCaption());
		item->child(3)->child(0)->setText(1, test->getFlvUrl());
		item->child(3)->child(1)->child(0)->setText(1, QString("%1").arg(test->getSize()));
		// update info results
		if (!test->isFlvOk())
		{
			item->child(3)->setText(1, "[Failed!]");
			item->child(3)->setFont(0, font);
			// is flvurl empty?
			if (test->getFlvUrl().isEmpty())
			{
				item->child(3)->child(0)->setText(1, "Empty Url!");
				item->child(3)->child(0)->setFont(0, font);
			}
			// is size?
			if (test->getSize() != test->getExpectedSize())
			{
				item->child(3)->child(1)->setText(1,"[Failed!]");
				item->child(3)->child(1)->setFont(0, font);
			}
			else // size ok
			{
				item->child(3)->child(1)->setText(1,"[Ok]");
				item->child(3)->child(1)->setFont(1, font);
			}
		}
		else // flv ok
		{
			// flv
			item->child(3)->setText(1, "[Ok]");
			item->child(3)->setFont(1, font);
			// size flv
			item->child(3)->child(1)->setText(1,"[Ok]");
			item->child(3)->child(1)->setFont(1, font);
		}
		//
		if (!test->isCaptionOk())
		{
			item->child(2)->setText(1, "[Failed!]");
			item->child(2)->setFont(0, font);
		}
		else // caption ok
		{
			item->child(2)->setText(1, "[Ok]");
			item->child(2)->setFont(1, font);
		}
	}
}
Example #16
0
QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* parent )
    : QWidget( parent )
{
  mLayer = layer;

  if ( !layer )
  {
    return;
  }

  setupUi( this );

  int tabIdx = QSettings().value( "/Windows/VectorLayerProperties/diagram/tab", 0 ).toInt();

  mDiagramPropertiesTabWidget->setCurrentIndex( tabIdx );

  mBackgroundColorButton->setColorDialogTitle( tr( "Background color" ) );
  mBackgroundColorButton->setColorDialogOptions( QColorDialog::ShowAlphaChannel );
  mDiagramPenColorButton->setColorDialogTitle( tr( "Pen color" ) );
  mDiagramPenColorButton->setColorDialogOptions( QColorDialog::ShowAlphaChannel );

  mValueLineEdit->setValidator( new QDoubleValidator( mValueLineEdit ) );
  mMinimumDiagramScaleLineEdit->setValidator( new QDoubleValidator( mMinimumDiagramScaleLineEdit ) );
  mMaximumDiagramScaleLineEdit->setValidator( new QDoubleValidator( mMaximumDiagramScaleLineEdit ) );

  mDiagramUnitComboBox->insertItem( 0, tr( "mm" ), QgsDiagramSettings::MM );
  mDiagramUnitComboBox->insertItem( 1, tr( "Map units" ), QgsDiagramSettings::MapUnits );

  QGis::GeometryType layerType = layer->geometryType();
  if ( layerType == QGis::UnknownGeometry || layerType == QGis::NoGeometry )
  {
    mDisplayDiagramsGroupBox->setChecked( false );
    mDisplayDiagramsGroupBox->setEnabled( false );
  }

  //insert placement options

  if ( layerType == QGis::Point || layerType == QGis::Polygon )
  {
    mPlacementComboBox->addItem( tr( "Around Point" ), QgsDiagramLayerSettings::AroundPoint );
    mPlacementComboBox->addItem( tr( "Over Point" ), QgsDiagramLayerSettings::OverPoint );
  }

  if ( layerType == QGis::Line || layerType == QGis::Polygon )
  {
    mPlacementComboBox->addItem( tr( "Line" ), QgsDiagramLayerSettings::Line );
    mPlacementComboBox->addItem( tr( "Horizontal" ), QgsDiagramLayerSettings::Horizontal );
  }

  if ( layerType == QGis::Polygon )
  {
    mPlacementComboBox->addItem( tr( "Free" ), QgsDiagramLayerSettings::Free );
  }

  if ( layerType == QGis::Line )
  {
    mLineOptionsComboBox->addItem( tr( "On line" ), QgsDiagramLayerSettings::OnLine );
    mLineOptionsComboBox->addItem( tr( "Above line" ), QgsDiagramLayerSettings::AboveLine );
    mLineOptionsComboBox->addItem( tr( "Below Line" ), QgsDiagramLayerSettings::BelowLine );
    mLineOptionsComboBox->addItem( tr( "Map orientation" ), QgsDiagramLayerSettings::MapOrientation );
  }
  else
  {
    mLineOptionsComboBox->setVisible( false );
    mLineOptionsLabel->setVisible( false );
  }

  QPixmap pix = QgsApplication::getThemePixmap( "pie-chart" );
  mDiagramTypeComboBox->addItem( pix, tr( "Pie chart" ), DIAGRAM_NAME_PIE );
  pix = QgsApplication::getThemePixmap( "text" );
  mDiagramTypeComboBox->addItem( pix, tr( "Text diagram" ), DIAGRAM_NAME_TEXT );
  pix = QgsApplication::getThemePixmap( "histogram" );
  mDiagramTypeComboBox->addItem( pix, tr( "Histogram" ), DIAGRAM_NAME_HISTOGRAM );

  mLabelPlacementComboBox->addItem( tr( "Height" ), QgsDiagramSettings::Height );
  mLabelPlacementComboBox->addItem( tr( "x-height" ), QgsDiagramSettings::XHeight );

  mScaleDependencyComboBox->addItem( tr( "Area" ), true );
  mScaleDependencyComboBox->addItem( tr( "Diameter" ), false );

  mDataDefinedXComboBox->addItem( tr( "None" ), -1 );
  mDataDefinedYComboBox->addItem( tr( "None" ), -1 );

  mAngleOffsetComboBox->addItem( tr( "Top" ), 90 * 16 );
  mAngleOffsetComboBox->addItem( tr( "Right" ), 0 );
  mAngleOffsetComboBox->addItem( tr( "Bottom" ), 270 * 16 );
  mAngleOffsetComboBox->addItem( tr( "Left" ), 180 * 16 );

  //insert all attributes into the combo boxes
  const QgsFields& layerFields = layer->pendingFields();
  for ( int idx = 0; idx < layerFields.count(); ++idx )
  {
    QTreeWidgetItem *newItem = new QTreeWidgetItem( mAttributesTreeWidget );
    QString name = QString( "\"%1\"" ).arg( layerFields[idx].name() );
    newItem->setText( 0,  name );
    newItem->setData( 0, Qt::UserRole, name );
    newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled );
    if ( layerFields[idx].type() != QVariant::String )
    {
      mSizeAttributeComboBox->addItem( layerFields[idx].name(), idx );
    }

    mDataDefinedXComboBox->addItem( layerFields[idx].name(), idx );
    mDataDefinedYComboBox->addItem( layerFields[idx].name(), idx );
  }
  mAvailableAttributes = mSizeAttributeComboBox->count();

  const QgsDiagramRendererV2* dr = layer->diagramRenderer();
  if ( !dr ) //no diagram renderer yet, insert reasonable default
  {
    mDisplayDiagramsGroupBox->setChecked( false );
    mFixedSizeCheckBox->setChecked( true );
    mDiagramUnitComboBox->setCurrentIndex( mDiagramUnitComboBox->findText( tr( "mm" ) ) );
    mLabelPlacementComboBox->setCurrentIndex( mLabelPlacementComboBox->findText( tr( "x-height" ) ) );
    mDiagramSizeSpinBox->setValue( 30 );
    mBarWidthSpinBox->setValue( 5 );
    mVisibilityGroupBox->setChecked( layer->hasScaleBasedVisibility() );
    mMaximumDiagramScaleLineEdit->setText( QString::number( layer->maximumScale() ) );
    mMinimumDiagramScaleLineEdit->setText( QString::number( layer->minimumScale() ) );

    switch ( layerType )
    {
      case QGis::Point:
        mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 0 ) );
        break;
      case QGis::Line:
        mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 3 ) );
        mLineOptionsComboBox->setCurrentIndex( mLineOptionsComboBox->findData( 2 ) );
        break;
      case QGis::Polygon:
        mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 0 ) );
        break;
      case QGis::UnknownGeometry:
      case QGis::NoGeometry:
        break;
    }
    mBackgroundColorButton->setColor( QColor( 255, 255, 255, 255 ) );
  }
  else // already a diagram renderer present
  {
    mDisplayDiagramsGroupBox->setChecked( true );

    //single category renderer or interpolated one?
    mFixedSizeCheckBox->setChecked( dr->rendererName() == "SingleCategory" );

    //assume single category or linearly interpolated diagram renderer for now
    QList<QgsDiagramSettings> settingList = dr->diagramSettings();
    if ( settingList.size() > 0 )
    {
      mDiagramFont = settingList.at( 0 ).font;
      QSizeF size = settingList.at( 0 ).size;
      mBackgroundColorButton->setColor( settingList.at( 0 ).backgroundColor );
      mTransparencySlider->setValue( settingList.at( 0 ).transparency );
      mDiagramPenColorButton->setColor( settingList.at( 0 ).penColor );
      mPenWidthSpinBox->setValue( settingList.at( 0 ).penWidth );
      mDiagramSizeSpinBox->setValue(( size.width() + size.height() ) / 2.0 );
      mMinimumDiagramScaleLineEdit->setText( QString::number( settingList.at( 0 ).minScaleDenominator, 'f' ) );
      mMaximumDiagramScaleLineEdit->setText( QString::number( settingList.at( 0 ).maxScaleDenominator, 'f' ) );
      mVisibilityGroupBox->setChecked( settingList.at( 0 ).minScaleDenominator != -1 &&
                                       settingList.at( 0 ).maxScaleDenominator != -1 );
      if ( settingList.at( 0 ).sizeType == QgsDiagramSettings::MM )
      {
        mDiagramUnitComboBox->setCurrentIndex( 0 );
      }
      else
      {
        mDiagramUnitComboBox->setCurrentIndex( 1 );
      }

      if ( settingList.at( 0 ).labelPlacementMethod == QgsDiagramSettings::Height )
      {
        mLabelPlacementComboBox->setCurrentIndex( 0 );
      }
      else
      {
        mLabelPlacementComboBox->setCurrentIndex( 1 );
      }

      mAngleOffsetComboBox->setCurrentIndex( mAngleOffsetComboBox->findData( settingList.at( 0 ).angleOffset ) );

      mOrientationLeftButton->setProperty( "direction", QgsDiagramSettings::Left );
      mOrientationRightButton->setProperty( "direction", QgsDiagramSettings::Right );
      mOrientationUpButton->setProperty( "direction", QgsDiagramSettings::Up );
      mOrientationDownButton->setProperty( "direction", QgsDiagramSettings::Down );
      switch ( settingList.at( 0 ).diagramOrientation )
      {
        case QgsDiagramSettings::Left:
          mOrientationLeftButton->setChecked( true );
          break;

        case QgsDiagramSettings::Right:
          mOrientationRightButton->setChecked( true );
          break;

        case QgsDiagramSettings::Up:
          mOrientationUpButton->setChecked( true );
          break;

        case QgsDiagramSettings::Down:
          mOrientationDownButton->setChecked( true );
          break;
      }

      mBarWidthSpinBox->setValue( settingList.at( 0 ).barWidth );

      mIncreaseSmallDiagramsGroupBox->setChecked( settingList.at( 0 ).minimumSize != 0 );
      mIncreaseMinimumSizeSpinBox->setValue( settingList.at( 0 ).minimumSize );

      if ( settingList.at( 0 ).scaleByArea )
      {
        mScaleDependencyComboBox->setCurrentIndex( 0 );
      }
      else
      {
        mScaleDependencyComboBox->setCurrentIndex( 1 );
      }

      QList< QColor > categoryColors = settingList.at( 0 ).categoryColors;
      QList< QString > categoryAttributes = settingList.at( 0 ).categoryAttributes;
      QList< QString >::const_iterator catIt = categoryAttributes.constBegin();
      QList< QColor >::const_iterator coIt = categoryColors.constBegin();
      for ( ; catIt != categoryAttributes.constEnd(); ++catIt, ++coIt )
      {
        QTreeWidgetItem *newItem = new QTreeWidgetItem( mDiagramAttributesTreeWidget );
        newItem->setText( 0, *catIt );
        newItem->setData( 0, Qt::UserRole, *catIt );
        newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled );
        QColor col( *coIt );
        col.setAlpha( 255 );
        newItem->setBackground( 1, QBrush( col ) );
      }
    }

    if ( dr->rendererName() == "LinearlyInterpolated" )
    {
      const QgsLinearlyInterpolatedDiagramRenderer* lidr = dynamic_cast<const QgsLinearlyInterpolatedDiagramRenderer*>( dr );
      if ( lidr )
      {
        mDiagramSizeSpinBox->setEnabled( false );
        mValueLineEdit->setText( QString::number( lidr->upperValue(), 'f' ) );
        mSizeSpinBox->setValue(( lidr->upperSize().width() + lidr->upperSize().height() ) / 2 );
        if ( lidr->classificationAttributeIsExpression() )
        {
          mSizeAttributeComboBox->addItem( lidr->classificationAttributeExpression() );
          mSizeAttributeComboBox->setCurrentIndex( mSizeAttributeComboBox->count() - 1 );
        }
        else
        {
          mSizeAttributeComboBox->setCurrentIndex( mSizeAttributeComboBox->findData( lidr->classificationAttribute() ) );
        }
      }
    }

    const QgsDiagramLayerSettings *dls = layer->diagramLayerSettings();
    if ( dls )
    {
      mDiagramDistanceSpinBox->setValue( dls->dist );
      mPrioritySlider->setValue( dls->priority );
      mDataDefinedXComboBox->setCurrentIndex( mDataDefinedXComboBox->findData( dls->xPosColumn ) );
      mDataDefinedYComboBox->setCurrentIndex( mDataDefinedYComboBox->findData( dls->yPosColumn ) );
      if ( dls->xPosColumn != -1 || dls->yPosColumn != -1 )
      {
        mDataDefinedPositionGroupBox->setChecked( true );
      }
      mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( dls->placement ) );
      mLineOptionsComboBox->setCurrentIndex( mLineOptionsComboBox->findData( dls->placementFlags ) );
    }

    if ( dr->diagram() )
    {
      QString diagramName = dr->diagram()->diagramName();
      mDiagramTypeComboBox->setCurrentIndex( mDiagramTypeComboBox->findData( diagramName ) );
      if ( mDiagramTypeComboBox->currentIndex() == -1 )
      {
        QMessageBox::warning( this, tr( "Unknown diagram type." ),
                              tr( "The diagram type '%1' is unknown. A default type is selected for you." ).arg( diagramName ), QMessageBox::Ok );
        mDiagramTypeComboBox->setCurrentIndex( mDiagramTypeComboBox->findData( DIAGRAM_NAME_PIE ) );
      }
    }
  } // if ( !dr )

  // Trigger a clicked event, so all the items get properly enabled and disabled
  on_mDisplayDiagramsGroupBox_toggled( mDisplayDiagramsGroupBox->isChecked() );

  connect( mSizeAttributeExpression, SIGNAL( clicked() ), this, SLOT( showSizeAttributeExpressionDialog() ) );
  connect( mAddAttributeExpression, SIGNAL( clicked() ), this, SLOT( showAddAttributeExpressionDialog() ) );
}
Example #17
0
void MainWindow::updateResultMctrl(struct mctrlResult *mctrlRes, int com)
{
	bool dtr = mctrlRes->dtr;
	bool rts = mctrlRes->rts;
	bool cts = mctrlRes->cts;
	bool dcd = mctrlRes->dcd;
	bool dsr = mctrlRes->dsr;
	bool ri = mctrlRes->ri;
	QTreeWidgetItem *mctrl = ui->treeWidget->topLevelItem(com-1)->child(6);
	QTreeWidgetItem *DTR = mctrl->child(0);
	QTreeWidgetItem *RTS = mctrl->child(1);
	QTreeWidgetItem *CTS = mctrl->child(2);
	QTreeWidgetItem *DCD = mctrl->child(3);
	QTreeWidgetItem *DSR = mctrl->child(4);
	QTreeWidgetItem *RNG = mctrl->child(5);
	QTreeWidgetItem *round = ui->treeWidget->topLevelItem(com-1)->child(0);
	QTreeWidgetItem *txlen = ui->treeWidget->topLevelItem(com-1)->child(1);
	QTreeWidgetItem *rxlen = ui->treeWidget->topLevelItem(com-1)->child(2);
	QTreeWidgetItem *err = ui->treeWidget->topLevelItem(com-1)->child(3);
	QTreeWidgetItem *ecerr = ui->treeWidget->topLevelItem(com-1)->child(4);

	if(!txlen->isHidden()){
		txlen->setHidden(true);
	}
	if(!rxlen->isHidden()){
		rxlen->setHidden(true);
	}
	if(!err->isHidden()){
		err->setHidden(true);
	}
	if(!ecerr->isHidden()){
		ecerr->setHidden(true);
	}
	if(mctrl->isHidden()){
		mctrl->setHidden(false);
	}
	
	round->setText(1, QString::number(mctrlRes->round));
	
	if(dtr){
		DTR->setText(1, "O");
		DTR->setForeground(1, QBrush(QColor(0, 255, 0)));
	}else{
		DTR->setText(1, "X");
		DTR->setForeground(1, QBrush(QColor(255, 0, 0)));
	}

	if(rts){
		RTS->setText(1, "O");
		RTS->setForeground(1, QBrush(QColor(0, 255, 0)));
	}else{
		RTS->setText(1, "X");
		RTS->setForeground(1, QBrush(QColor(255, 0, 0)));
	}

	if(cts){
		CTS->setText(1, "O");
		CTS->setForeground(1, QBrush(QColor(0, 255, 0)));
	}else{
		CTS->setText(1, "X");
		CTS->setForeground(1, QBrush(QColor(255, 0, 0)));
	}

	if(dcd){
		DCD->setText(1, "O");
		DCD->setForeground(1, QBrush(QColor(0, 255, 0)));
	}else{
		DCD->setText(1, "X");
		DCD->setForeground(1, QBrush(QColor(255, 0, 0)));
	}

	if(dsr){
		DSR->setText(1, "O");
		DSR->setForeground(1, QBrush(QColor(0, 255, 0)));
	}else{
		DSR->setText(1, "X");
		DSR->setForeground(1, QBrush(QColor(255, 0, 0)));
	}

	if(ri){
		RNG->setText(1, "O");
		RNG->setForeground(1, QBrush(QColor(0, 255, 0)));
	}else{
		RNG->setText(1, "X");
		RNG->setForeground(1, QBrush(QColor(255, 0, 0)));
	}
}
Example #18
0
void MainWindow::openFile() {
    int i;

    QString qstr;

    if(_filename.empty()) {
        qstr = QFileDialog::getOpenFileName(this,"Choose ROOT file","/","*.root");
        _filename = qstr.toStdString();
    }
    else {
        qstr = QFileDialog::getOpenFileName(this,"Choose ROOT file",QString::fromStdString(_filename),"*.root");
        _filename = qstr.toStdString();
    }

    if(_filename.empty()) {
        return;
    }

    setWindowTitle(QString::fromStdString("AmViewer (" + _filename + ")"));

    TFile *f = new TFile(_filename.c_str());
    f->ReadAll();

    TAmRun *amRun = NULL;

    amRun = AMBER::GetRunFromFile(f);

    // will use this as indicator for whether or not in 'analysis mode' in other parts of program
    _state->recon_tree = NULL;

    if(amRun == NULL) {
        // Means that this is a root file which contains candidate events. So we're in 'analysis mode'

        _analysisDrop->setEnabled(true);
        _saveMenu->setEnabled(true);

        _state->recon_tree = (TTree*)f->Get("recon_tree"); // cast might be superfluous
        _state->amevTree = (TAmEvTree*)f->Get("candidate_tree");

        int totalEvents = _state->amevTree->GetEntries();

        // clear tree widget
        _eventList->clear();

        // create a dynamic array based on upper bound of number of runs
        QTreeWidgetItem *run_source[totalEvents];

        // variables for putting events under the correct run number
        unsigned int prev_run = 0;
        int j = 0;

        QTreeWidgetItem *event;
        stringstream out,out2;

        string runtitle;

        for(i=0; i<totalEvents; i++) {
            // OK, SHIT. REMEMBER eventNum is the number according to the FILE **not** AMBER
            _state->eventNum = i;
            _state->update_recon();

            if(_state->run_num == prev_run) {
                event = new QTreeWidgetItem(run_source[j-1]);
                out.str("");
                out2.str("");
                out << setprecision(8) << setw(8) << _state->event_num;
                out2 << i;
                event->setText(0,QString::fromStdString(out.str()));
                event->setText(1,QString::fromStdString(out2.str()));
                prev_run = _state->run_num;
            }
            else {
                run_source[j] = new QTreeWidgetItem(_eventList);
                out.str("");
                out << setprecision(8) << setw(8) << _state->run_num;
                runtitle = "Run" + out.str();
                run_source[j]->setText(0,QString::fromStdString(runtitle));
                event = new QTreeWidgetItem(run_source[j]);
                out.str("");
                out2.str("");
                out << setprecision(8) << setw(8) << _state->event_num;
                out2 << i;
                event->setText(0,QString::fromStdString(out.str()));
                event->setText(1,QString::fromStdString(out2.str()));
                j++;
                prev_run = _state->run_num;
            }
        }

        _eventList->sortItems(0,Qt::AscendingOrder); //maybe check that 2nd arg
        _eventList->setColumnHidden(1,true);

        _eventList->setHeaderLabel("Candidate Events");

        connect(_eventList,SIGNAL(itemClicked(QTreeWidgetItem*,int)),this,SLOT(getEvent(QTreeWidgetItem*)));

        // make an info window, if one doesn't exist
        if(_infoWindow==NULL) {
            _infoWindow = new InfoWindow(_state);
        }
    }
Example #19
0
void MainWindow::fillStateForFrame()
{
    if (!m_selectedEvent || !m_selectedEvent->hasState()) {
        return;
    }

    if (m_nonDefaultsLookupEvent) {
        m_ui.nonDefaultsCB->blockSignals(true);
        m_ui.nonDefaultsCB->setChecked(true);
        m_ui.nonDefaultsCB->blockSignals(false);
    }

    bool nonDefaults = m_ui.nonDefaultsCB->isChecked();
    QVariantMap defaultParams;
    if (nonDefaults) {
        ApiTraceState defaultState = m_trace->defaultState();
        defaultParams = defaultState.parameters();
    }

    const ApiTraceState &state = *m_selectedEvent->state();
    m_ui.stateTreeWidget->clear();
    QList<QTreeWidgetItem *> items;
    variantMapToItems(state.parameters(), defaultParams, items);
    m_ui.stateTreeWidget->insertTopLevelItems(0, items);

    QMap<QString, QString> shaderSources = state.shaderSources();
    if (shaderSources.isEmpty()) {
        m_sourcesWidget->setShaders(shaderSources);
    } else {
        m_sourcesWidget->setShaders(shaderSources);
    }

    m_ui.uniformsTreeWidget->clear();
    QList<QTreeWidgetItem *> uniformsItems;
    variantMapToItems(state.uniforms(), QVariantMap(), uniformsItems);
    m_ui.uniformsTreeWidget->insertTopLevelItems(0, uniformsItems);

    const QList<ApiTexture> &textures =
        state.textures();
    const QList<ApiFramebuffer> &fbos =
        state.framebuffers();

    m_ui.surfacesTreeWidget->clear();
    if (textures.isEmpty() && fbos.isEmpty()) {
        m_ui.surfacesTab->setDisabled(false);
    } else {
        m_ui.surfacesTreeWidget->setIconSize(QSize(THUMBNAIL_SIZE, THUMBNAIL_SIZE));
        if (!textures.isEmpty()) {
            QTreeWidgetItem *textureItem =
                new QTreeWidgetItem(m_ui.surfacesTreeWidget);
            textureItem->setText(0, tr("Textures"));
            if (textures.count() <= 6) {
                textureItem->setExpanded(true);
            }

            for (int i = 0; i < textures.count(); ++i) {
                const ApiTexture &texture =
                    textures[i];
                addSurfaceItem(texture, texture.label(),
                               textureItem,
                               m_ui.surfacesTreeWidget);
            }
        }
        if (!fbos.isEmpty()) {
            QTreeWidgetItem *fboItem =
                new QTreeWidgetItem(m_ui.surfacesTreeWidget);
            fboItem->setText(0, tr("Framebuffers"));
            if (fbos.count() <= 6) {
                fboItem->setExpanded(true);
            }

            for (int i = 0; i < fbos.count(); ++i) {
                const ApiFramebuffer &fbo =
                    fbos[i];
                addSurfaceItem(fbo, fbo.type(),
                               fboItem,
                               m_ui.surfacesTreeWidget);
            }
        }
        m_ui.surfacesTab->setEnabled(true);
    }
    m_ui.stateDock->show();
}
Example #20
0
void ObjectWindow::update() {
    if (!level) return;

    QList<QTreeWidgetItem*> children;

    // update enemies
    children = enemyRoot.takeChildren();
    for (int i = 0; i < children.size(); i++) {
        delete children[i];
    }
    enemyRoot.setText(0, QString("Enemies (%1)").arg(level->enemies.size()));
    for (int i = 0; i < level->enemies.size(); i++) {
        QTreeWidgetItem *item = new QTreeWidgetItem(&enemyRoot);
        const enemy_t &enemy = level->enemies[i];
        const enemytype_t &type = level->enemyTypes[enemy.type];
        item->setText(0, QString("(%1, %2) %3 (%4)")
                      .arg(enemy.x).arg(enemy.y)
                      .arg(type.name).arg(type.state));
        item->setData(1, 0, i);
    }

    // update enemy types
    children = typeRoot.takeChildren();
    for (int i = 0; i < children.size(); i++) {
        delete children[i];
    }
    typeRoot.setText(0, QString("Enemy Types (%1)").arg(level->enemyTypes.size()));
    for (int i = 0; i < level->enemyTypes.size(); i++) {
        QTreeWidgetItem *item = new QTreeWidgetItem(&typeRoot);
        const enemytype_t &type = level->enemyTypes[i];
        item->setText(0, QString("%1 (%2)")
                       .arg(type.name).arg(type.state));
        item->setData(1, 0, i);
    }

    // update objects
    children = objectRoot.takeChildren();
    for (int i = 0; i < children.size(); i++) {
        delete children[i];
    }
    objectRoot.setText(0, QString("Objects (%1)").arg(level->objects.size()));
    for (int i = 0; i < level->objects.size(); i++) {
        QTreeWidgetItem *item = new QTreeWidgetItem(&objectRoot);
        const object_t &object = level->objects[i];
        QString name = "invalid";
        if (object.type < level->objectNames.size())
            name = level->objectNames[object.type];

        item->setText(0, QString("(%1, %2) %3")
                      .arg(object.x).arg(object.y).arg(name));
        item->setData(1, 0, i);
    }

    // update items
    children = itemRoot.takeChildren();
    for (int i = 0; i < children.size(); i++) {
        delete children[i];
    }
    itemRoot.setText(0, QString("Items (%1)").arg(level->items.size()));
    for (int i = 0; i < level->items.size(); i++) {
        QTreeWidgetItem *item = new QTreeWidgetItem(&itemRoot);
        const item_t &theItem = level->items[i];
        item->setText(0, QString("(%1, %2) Item")
                      .arg(theItem.x).arg(theItem.y));
        item->setData(1, 0, i);
    }
}
Example #21
0
void K3b::AudioRippingDialog::setupGui()
{
    QWidget *frame = mainWidget();
    QGridLayout* Form1Layout = new QGridLayout( frame );
    Form1Layout->setContentsMargins( 0, 0, 0, 0 );

    QTreeWidgetItem* header = new QTreeWidgetItem;
    header->setText( 0, i18n( "Filename") );
    header->setText( 1, i18n( "Length") );
    header->setText( 2, i18n( "File Size") );
    header->setText( 3, i18n( "Type") );

    d->viewTracks = new QTreeWidget( frame );
    d->viewTracks->setSortingEnabled( false );
    d->viewTracks->setAllColumnsShowFocus( true );
    d->viewTracks->setHeaderItem( header );
    d->viewTracks->setRootIsDecorated( false );
    d->viewTracks->setSelectionMode( QAbstractItemView::NoSelection );
    d->viewTracks->setFocusPolicy( Qt::NoFocus );
    d->viewTracks->header()->setStretchLastSection( false );
    d->viewTracks->header()->setSectionResizeMode( 0, QHeaderView::Stretch );
    d->viewTracks->header()->setSectionResizeMode( 1, QHeaderView::ResizeToContents );
    d->viewTracks->header()->setSectionResizeMode( 2, QHeaderView::ResizeToContents );
    d->viewTracks->header()->setSectionResizeMode( 3, QHeaderView::ResizeToContents );

    QTabWidget* mainTab = new QTabWidget( frame );

    m_optionWidget = new K3b::AudioConvertingOptionWidget( mainTab );
    mainTab->addTab( m_optionWidget, i18n("Settings") );


    // setup filename pattern page
    // -------------------------------------------------------------------------------------------
    m_patternWidget = new K3b::CddbPatternWidget( mainTab );
    mainTab->addTab( m_patternWidget, i18n("File Naming") );
    connect( m_patternWidget, SIGNAL(changed()), this, SLOT(refresh()) );


    // setup advanced page
    // -------------------------------------------------------------------------------------------
    QWidget* advancedPage = new QWidget( mainTab );
    QGridLayout* advancedPageLayout = new QGridLayout( advancedPage );
    mainTab->addTab( advancedPage, i18n("Advanced") );

    m_comboParanoiaMode = K3b::StdGuiItems::paranoiaModeComboBox( advancedPage );
    m_spinRetries = new QSpinBox( advancedPage );
    m_checkIgnoreReadErrors = new QCheckBox( i18n("Ignore read errors"), advancedPage );
    m_checkUseIndex0 = new QCheckBox( i18n("Do not read pregaps"), advancedPage );

    advancedPageLayout->addWidget( new QLabel( i18n("Paranoia mode:"), advancedPage ), 0, 0 );
    advancedPageLayout->addWidget( m_comboParanoiaMode, 0, 1 );
    advancedPageLayout->addWidget( new QLabel( i18n("Read retries:"), advancedPage ), 1, 0 );
    advancedPageLayout->addWidget( m_spinRetries, 1, 1 );
    advancedPageLayout->addWidget( m_checkIgnoreReadErrors, 2, 0, 0, 1 );
    advancedPageLayout->addWidget( m_checkUseIndex0, 3, 0, 0, 1 );
    advancedPageLayout->setRowStretch( 4, 1 );
    advancedPageLayout->setColumnStretch( 2, 1 );

    // -------------------------------------------------------------------------------------------


    Form1Layout->addWidget( d->viewTracks, 0, 0 );
    Form1Layout->addWidget( mainTab, 1, 0 );
    Form1Layout->setRowStretch( 0, 1 );

    setStartButtonText( i18n( "Start Ripping" ), i18n( "Starts copying the selected tracks") );

    connect( m_checkUseIndex0, SIGNAL(toggled(bool)), this, SLOT(refresh()) );
    connect( m_optionWidget, SIGNAL(changed()), this, SLOT(refresh()) );
}
Example #22
0
QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* parent )
    : QWidget( parent )
{
  mLayer = layer;

  if ( !layer )
  {
    return;
  }

  setupUi( this );

  // get rid of annoying outer focus rect on Mac
  mDiagramOptionsListWidget->setAttribute( Qt::WA_MacShowFocusRect, false );

  connect( mEnableDiagramsCheckBox, SIGNAL( toggled( bool ) ), mDiagramTypeFrame, SLOT( setEnabled( bool ) ) );
  connect( mEnableDiagramsCheckBox, SIGNAL( toggled( bool ) ), mDiagramFrame, SLOT( setEnabled( bool ) ) );

  mScaleRangeWidget->setMapCanvas( QgisApp::instance()->mapCanvas() );

  mBackgroundColorButton->setColorDialogTitle( tr( "Select background color" ) );
  mBackgroundColorButton->setAllowAlpha( true );
  mBackgroundColorButton->setContext( "symbology" );
  mBackgroundColorButton->setShowNoColor( true );
  mBackgroundColorButton->setNoColorString( tr( "Transparent background" ) );
  mDiagramPenColorButton->setColorDialogTitle( tr( "Select pen color" ) );
  mDiagramPenColorButton->setAllowAlpha( true );
  mDiagramPenColorButton->setContext( "symbology" );
  mDiagramPenColorButton->setShowNoColor( true );
  mDiagramPenColorButton->setNoColorString( tr( "Transparent outline" ) );

  mMaxValueSpinBox->setShowClearButton( false );

  mDiagramUnitComboBox->insertItem( 0, tr( "mm" ), QgsDiagramSettings::MM );
  mDiagramUnitComboBox->insertItem( 1, tr( "Map units" ), QgsDiagramSettings::MapUnits );

  QGis::GeometryType layerType = layer->geometryType();
  if ( layerType == QGis::UnknownGeometry || layerType == QGis::NoGeometry )
  {
    mEnableDiagramsCheckBox->setChecked( false );
    mEnableDiagramsCheckBox->setEnabled( false );
    mDiagramTypeFrame->setEnabled( false );
    mDiagramFrame->setEnabled( false );
  }

  //insert placement options
  mPlacementComboBox->blockSignals( true );
  switch ( layerType )
  {
    case QGis::Point:
      mPlacementComboBox->addItem( tr( "Around Point" ), QgsDiagramLayerSettings::AroundPoint );
      mPlacementComboBox->addItem( tr( "Over Point" ), QgsDiagramLayerSettings::OverPoint );
      mLinePlacementFrame->setVisible( false );
      break;
    case QGis::Line:
      mPlacementComboBox->addItem( tr( "Around Line" ), QgsDiagramLayerSettings::Line );
      mPlacementComboBox->addItem( tr( "Over Line" ), QgsDiagramLayerSettings::Horizontal );
      mLinePlacementFrame->setVisible( true );
      break;
    case QGis::Polygon:
      mPlacementComboBox->addItem( tr( "Around Centroid" ), QgsDiagramLayerSettings::AroundPoint );
      mPlacementComboBox->addItem( tr( "Over Centroid" ), QgsDiagramLayerSettings::OverPoint );
      mPlacementComboBox->addItem( tr( "Perimeter" ), QgsDiagramLayerSettings::Line );
      mPlacementComboBox->addItem( tr( "Inside Polygon" ), QgsDiagramLayerSettings::Horizontal );
      mLinePlacementFrame->setVisible( false );
      break;
    default:
      break;
  }
  mPlacementComboBox->blockSignals( false );

  mDiagramTypeComboBox->blockSignals( true );
  QPixmap pix = QgsApplication::getThemePixmap( "pie-chart" );
  mDiagramTypeComboBox->addItem( pix, tr( "Pie chart" ), DIAGRAM_NAME_PIE );
  pix = QgsApplication::getThemePixmap( "text" );
  mDiagramTypeComboBox->addItem( pix, tr( "Text diagram" ), DIAGRAM_NAME_TEXT );
  pix = QgsApplication::getThemePixmap( "histogram" );
  mDiagramTypeComboBox->addItem( pix, tr( "Histogram" ), DIAGRAM_NAME_HISTOGRAM );
  mDiagramTypeComboBox->blockSignals( false );

  mLabelPlacementComboBox->addItem( tr( "Height" ), QgsDiagramSettings::Height );
  mLabelPlacementComboBox->addItem( tr( "x-height" ), QgsDiagramSettings::XHeight );

  mScaleDependencyComboBox->addItem( tr( "Area" ), true );
  mScaleDependencyComboBox->addItem( tr( "Diameter" ), false );

  mDataDefinedXComboBox->addItem( tr( "None" ), -1 );
  mDataDefinedYComboBox->addItem( tr( "None" ), -1 );

  mAngleOffsetComboBox->addItem( tr( "Top" ), 90 * 16 );
  mAngleOffsetComboBox->addItem( tr( "Right" ), 0 );
  mAngleOffsetComboBox->addItem( tr( "Bottom" ), 270 * 16 );
  mAngleOffsetComboBox->addItem( tr( "Left" ), 180 * 16 );

  QSettings settings;

  // reset horiz strech of left side of options splitter (set to 1 for previewing in Qt Designer)
  QSizePolicy policy( mDiagramOptionsListFrame->sizePolicy() );
  policy.setHorizontalStretch( 0 );
  mDiagramOptionsListFrame->setSizePolicy( policy );
  if ( !settings.contains( QString( "/Windows/Diagrams/OptionsSplitState" ) ) )
  {
    // set left list widget width on intial showing
    QList<int> splitsizes;
    splitsizes << 115;
    mDiagramOptionsSplitter->setSizes( splitsizes );
  }

  // restore dialog, splitters and current tab
  mDiagramOptionsSplitter->restoreState( settings.value( QString( "/Windows/Diagrams/OptionsSplitState" ) ).toByteArray() );
  mDiagramOptionsListWidget->setCurrentRow( settings.value( QString( "/Windows/Diagrams/Tab" ), 0 ).toInt() );

  // field combo and expression button
  mSizeFieldExpressionWidget->setLayer( mLayer );
  QgsDistanceArea myDa;
  myDa.setSourceCrs( mLayer->crs().srsid() );
  myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() );
  myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) );
  mSizeFieldExpressionWidget->setGeomCalculator( myDa );

  //insert all attributes into the combo boxes
  const QgsFields& layerFields = layer->pendingFields();
  for ( int idx = 0; idx < layerFields.count(); ++idx )
  {
    QTreeWidgetItem *newItem = new QTreeWidgetItem( mAttributesTreeWidget );
    QString name = QString( "\"%1\"" ).arg( layerFields[idx].name() );
    newItem->setText( 0, name );
    newItem->setData( 0, Qt::UserRole, name );
    newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled );

    mDataDefinedXComboBox->addItem( layerFields[idx].name(), idx );
    mDataDefinedYComboBox->addItem( layerFields[idx].name(), idx );
  }

  const QgsDiagramRendererV2* dr = layer->diagramRenderer();
  if ( !dr ) //no diagram renderer yet, insert reasonable default
  {
    mEnableDiagramsCheckBox->setChecked( false );
    mDiagramTypeFrame->setEnabled( false );
    mDiagramFrame->setEnabled( false );
    mFixedSizeRadio->setChecked( true );
    mDiagramUnitComboBox->setCurrentIndex( mDiagramUnitComboBox->findText( tr( "mm" ) ) );
    mLabelPlacementComboBox->setCurrentIndex( mLabelPlacementComboBox->findText( tr( "x-height" ) ) );
    mDiagramSizeSpinBox->setEnabled( true );
    mDiagramSizeSpinBox->setValue( 15 );
    mLinearScaleFrame->setEnabled( false );
    mIncreaseMinimumSizeSpinBox->setEnabled( false );
    mIncreaseMinimumSizeLabel->setEnabled( false );
    mBarWidthSpinBox->setValue( 5 );
    mScaleVisibilityGroupBox->setChecked( layer->hasScaleBasedVisibility() );
    mScaleRangeWidget->setScaleRange( 1.0 / layer->maximumScale(), 1.0 / layer->minimumScale() ); // caution: layer uses scale denoms, widget uses true scales
    mShowAllCheckBox->setChecked( true );

    switch ( layerType )
    {
      case QGis::Point:
        mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( QgsDiagramLayerSettings::AroundPoint ) );
        break;
      case QGis::Line:
        mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( QgsDiagramLayerSettings::Line ) );
        chkLineAbove->setChecked( true );
        chkLineBelow->setChecked( false );
        chkLineOn->setChecked( false );
        chkLineOrientationDependent->setChecked( false );
        break;
      case QGis::Polygon:
        mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( QgsDiagramLayerSettings::AroundPoint ) );
        break;
      case QGis::UnknownGeometry:
      case QGis::NoGeometry:
        break;
    }
    mBackgroundColorButton->setColor( QColor( 255, 255, 255, 255 ) );
    mDiagramTypeComboBox->blockSignals( true );
    mDiagramTypeComboBox->setCurrentIndex( 0 );
    mDiagramTypeComboBox->blockSignals( false );
    //force a refresh of widget status to match diagram type
    on_mDiagramTypeComboBox_currentIndexChanged( mDiagramTypeComboBox->currentIndex() );
  }
  else // already a diagram renderer present
  {
    //single category renderer or interpolated one?
    if ( dr->rendererName() == "SingleCategory" )
    {
      mFixedSizeRadio->setChecked( true );
    }
    else
    {
      mAttributeBasedScalingRadio->setChecked( true );
    }
    mDiagramSizeSpinBox->setEnabled( mFixedSizeRadio->isChecked() );
    mLinearScaleFrame->setEnabled( mAttributeBasedScalingRadio->isChecked() );

    //assume single category or linearly interpolated diagram renderer for now
    QList<QgsDiagramSettings> settingList = dr->diagramSettings();
    if ( settingList.size() > 0 )
    {
      mEnableDiagramsCheckBox->setChecked( settingList.at( 0 ).enabled );
      mDiagramTypeFrame->setEnabled( mEnableDiagramsCheckBox->isChecked() );
      mDiagramFrame->setEnabled( mEnableDiagramsCheckBox->isChecked() );
      mDiagramFont = settingList.at( 0 ).font;
      QSizeF size = settingList.at( 0 ).size;
      mBackgroundColorButton->setColor( settingList.at( 0 ).backgroundColor );
      mTransparencySpinBox->setValue( settingList.at( 0 ).transparency * 100.0 / 255.0 );
      mDiagramPenColorButton->setColor( settingList.at( 0 ).penColor );
      mPenWidthSpinBox->setValue( settingList.at( 0 ).penWidth );
      mDiagramSizeSpinBox->setValue(( size.width() + size.height() ) / 2.0 );
      // caution: layer uses scale denoms, widget uses true scales
      mScaleRangeWidget->setScaleRange( 1.0 / ( settingList.at( 0 ).maxScaleDenominator > 0 ? settingList.at( 0 ).maxScaleDenominator : layer->maximumScale() ),
                                        1.0 / ( settingList.at( 0 ).minScaleDenominator > 0 ? settingList.at( 0 ).minScaleDenominator : layer->minimumScale() ) );
      mScaleVisibilityGroupBox->setChecked( settingList.at( 0 ).scaleBasedVisibility );
      if ( settingList.at( 0 ).sizeType == QgsDiagramSettings::MM )
      {
        mDiagramUnitComboBox->setCurrentIndex( 0 );
      }
      else
      {
        mDiagramUnitComboBox->setCurrentIndex( 1 );
      }

      if ( settingList.at( 0 ).labelPlacementMethod == QgsDiagramSettings::Height )
      {
        mLabelPlacementComboBox->setCurrentIndex( 0 );
      }
      else
      {
        mLabelPlacementComboBox->setCurrentIndex( 1 );
      }

      mAngleOffsetComboBox->setCurrentIndex( mAngleOffsetComboBox->findData( settingList.at( 0 ).angleOffset ) );

      mOrientationLeftButton->setProperty( "direction", QgsDiagramSettings::Left );
      mOrientationRightButton->setProperty( "direction", QgsDiagramSettings::Right );
      mOrientationUpButton->setProperty( "direction", QgsDiagramSettings::Up );
      mOrientationDownButton->setProperty( "direction", QgsDiagramSettings::Down );
      switch ( settingList.at( 0 ).diagramOrientation )
      {
        case QgsDiagramSettings::Left:
          mOrientationLeftButton->setChecked( true );
          break;

        case QgsDiagramSettings::Right:
          mOrientationRightButton->setChecked( true );
          break;

        case QgsDiagramSettings::Up:
          mOrientationUpButton->setChecked( true );
          break;

        case QgsDiagramSettings::Down:
          mOrientationDownButton->setChecked( true );
          break;
      }

      mBarWidthSpinBox->setValue( settingList.at( 0 ).barWidth );

      mIncreaseSmallDiagramsCheck->setChecked( settingList.at( 0 ).minimumSize != 0 );
      mIncreaseMinimumSizeSpinBox->setEnabled( mIncreaseSmallDiagramsCheck->isChecked() );
      mIncreaseMinimumSizeLabel->setEnabled( mIncreaseSmallDiagramsCheck->isChecked() );

      mIncreaseMinimumSizeSpinBox->setValue( settingList.at( 0 ).minimumSize );

      if ( settingList.at( 0 ).scaleByArea )
      {
        mScaleDependencyComboBox->setCurrentIndex( 0 );
      }
      else
      {
        mScaleDependencyComboBox->setCurrentIndex( 1 );
      }

      QList< QColor > categoryColors = settingList.at( 0 ).categoryColors;
      QList< QString > categoryAttributes = settingList.at( 0 ).categoryAttributes;
      QList< QString > categoryLabels = settingList.at( 0 ).categoryLabels;
      QList< QString >::const_iterator catIt = categoryAttributes.constBegin();
      QList< QColor >::const_iterator coIt = categoryColors.constBegin();
      QList< QString >::const_iterator labIt = categoryLabels.constBegin();
      for ( ; catIt != categoryAttributes.constEnd(); ++catIt, ++coIt, ++labIt )
      {
        QTreeWidgetItem *newItem = new QTreeWidgetItem( mDiagramAttributesTreeWidget );
        newItem->setText( 0, *catIt );
        newItem->setData( 0, Qt::UserRole, *catIt );
        newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled );
        QColor col( *coIt );
        col.setAlpha( 255 );
        newItem->setBackground( 1, QBrush( col ) );
        newItem->setText( 2, *labIt );
        newItem->setFlags( newItem->flags() | Qt::ItemIsEditable );
      }
    }

    if ( dr->rendererName() == "LinearlyInterpolated" )
    {
      const QgsLinearlyInterpolatedDiagramRenderer* lidr = dynamic_cast<const QgsLinearlyInterpolatedDiagramRenderer*>( dr );
      if ( lidr )
      {
        mDiagramSizeSpinBox->setEnabled( false );
        mLinearScaleFrame->setEnabled( true );
        mMaxValueSpinBox->setValue( lidr->upperValue() );
        mSizeSpinBox->setValue(( lidr->upperSize().width() + lidr->upperSize().height() ) / 2 );
        if ( lidr->classificationAttributeIsExpression() )
        {
          mSizeFieldExpressionWidget->setField( lidr->classificationAttributeExpression() );
        }
        else
        {
          mSizeFieldExpressionWidget->setField( mLayer->pendingFields().at( lidr->classificationAttribute() ).name() );
        }
      }
    }

    const QgsDiagramLayerSettings *dls = layer->diagramLayerSettings();
    if ( dls )
    {
      mDiagramDistanceSpinBox->setValue( dls->dist );
      mPrioritySlider->setValue( dls->priority );
      mDataDefinedXComboBox->setCurrentIndex( mDataDefinedXComboBox->findData( dls->xPosColumn ) );
      mDataDefinedYComboBox->setCurrentIndex( mDataDefinedYComboBox->findData( dls->yPosColumn ) );
      if ( dls->xPosColumn != -1 || dls->yPosColumn != -1 )
      {
        mDataDefinedPositionGroupBox->setChecked( true );
      }
      mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( dls->placement ) );

      chkLineAbove->setChecked( dls->placementFlags & QgsDiagramLayerSettings::AboveLine );
      chkLineBelow->setChecked( dls->placementFlags & QgsDiagramLayerSettings::BelowLine );
      chkLineOn->setChecked( dls->placementFlags & QgsDiagramLayerSettings::OnLine );
      if ( !( dls->placementFlags & QgsDiagramLayerSettings::MapOrientation ) )
        chkLineOrientationDependent->setChecked( true );

      mShowAllCheckBox->setChecked( dls->showAll );
    }

    if ( dr->diagram() )
    {
      QString diagramName = dr->diagram()->diagramName();
      mDiagramTypeComboBox->blockSignals( true );
      mDiagramTypeComboBox->setCurrentIndex( mDiagramTypeComboBox->findData( diagramName ) );
      mDiagramTypeComboBox->blockSignals( false );
      //force a refresh of widget status to match diagram type
      on_mDiagramTypeComboBox_currentIndexChanged( mDiagramTypeComboBox->currentIndex() );
      if ( mDiagramTypeComboBox->currentIndex() == -1 )
      {
        QMessageBox::warning( this, tr( "Unknown diagram type." ),
                              tr( "The diagram type '%1' is unknown. A default type is selected for you." ).arg( diagramName ), QMessageBox::Ok );
        mDiagramTypeComboBox->setCurrentIndex( mDiagramTypeComboBox->findData( DIAGRAM_NAME_PIE ) );
      }
    }
  } // if ( !dr )

  connect( mAddAttributeExpression, SIGNAL( clicked() ), this, SLOT( showAddAttributeExpressionDialog() ) );
  connect( mTransparencySlider, SIGNAL( valueChanged( int ) ), mTransparencySpinBox, SLOT( setValue( int ) ) );
  connect( mTransparencySpinBox, SIGNAL( valueChanged( int ) ), mTransparencySlider, SLOT( setValue( int ) ) );
}
Example #23
0
void InputOutputPatchEditor::fillMappingTree()
{
    /* Disable check state change tracking when the tree is filled */
    disconnect(m_mapTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
               this, SLOT(slotMapItemChanged(QTreeWidgetItem*, int)));

    m_mapTree->clear();

    qDebug() << "[InputOutputPatchEditor] Fill tree for universe: " << m_universe;

    // Build a complete list of Input/Output plugins
    QStringList IOplugins = m_ioMap->inputPluginNames();
    foreach (QString out, m_ioMap->outputPluginNames())
        if (IOplugins.contains(out) == false)
            IOplugins.append(out);

    // cycle through available plugins
    foreach (QString pluginName, IOplugins)
    {
        quint32 inputId = 0;
        quint32 outputId = 0;
        QStringList inputs = m_ioMap->pluginInputs(pluginName);
        QStringList outputs = m_ioMap->pluginOutputs(pluginName);
        bool hasFeedback = m_ioMap->pluginSupportsFeedback(pluginName);
        QLCIOPlugin *plugin = m_doc->ioPluginCache()->plugin(pluginName);

        // 1st case: this plugin has no input or output
        if (inputs.length() == 0 && outputs.length() == 0)
        {
            QTreeWidgetItem* pitem = new QTreeWidgetItem(m_mapTree);
            pitem->setText(KMapColumnPluginName, pluginName);
            pitem->setText(KMapColumnDeviceName, KInputNone);
            pitem->setText(KMapColumnInputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
            pitem->setText(KMapColumnOutputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
        }
        else
        {
            // 2nd case: plugin with an input and maybe an output
            for (int l = 0; l < inputs.length(); l++)
            {
                quint32 uni = m_ioMap->inputMapping(pluginName, inputId);
                //qDebug() << "Plugin: " << pluginName << ", input: " << id << ", universe:" << uni;
                if (uni == InputOutputMap::invalidUniverse() ||
                   (uni == m_universe || plugin->capabilities() & QLCIOPlugin::Infinite))
                {
                    QTreeWidgetItem* pitem = new QTreeWidgetItem(m_mapTree);
                    pitem->setText(KMapColumnPluginName, pluginName);
                    pitem->setText(KMapColumnDeviceName, inputs.at(l));
                    pitem->setFlags(pitem->flags() | Qt::ItemIsUserCheckable);
                    if (m_currentInputPluginName == pluginName && m_currentInput == inputId)
                        pitem->setCheckState(KMapColumnHasInput, Qt::Checked);
                    else
                        pitem->setCheckState(KMapColumnHasInput, Qt::Unchecked);
                    pitem->setTextAlignment(KMapColumnHasInput, Qt::AlignHCenter);
                    pitem->setText(KMapColumnInputLine, QString("%1").arg(inputId));
                    pitem->setText(KMapColumnOutputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
                    // check if this plugin has also an output
                    if (outputs.contains(inputs.at(l)))
                    {
                        quint32 outUni = m_ioMap->outputMapping(pluginName, outputId);
                        if (outUni == InputOutputMap::invalidUniverse() ||
                           (outUni == m_universe || plugin->capabilities() & QLCIOPlugin::Infinite))
                        {
                            if (m_currentOutputPluginName == pluginName && m_currentOutput == outputId)
                                pitem->setCheckState(KMapColumnHasOutput, Qt::Checked);
                            else
                                pitem->setCheckState(KMapColumnHasOutput, Qt::Unchecked);
                            pitem->setText(KMapColumnOutputLine, QString("%1").arg(outputId));
                            // add feedback
                            if (hasFeedback)
                            {
                                if (m_currentFeedbackPluginName == pluginName && m_currentFeedback == outputId)
                                    pitem->setCheckState(KMapColumnHasFeedback, Qt::Checked);
                                else
                                    pitem->setCheckState(KMapColumnHasFeedback, Qt::Unchecked);
                            }
                        }
                        outputId++;
                    }
                }
                inputId++;
            }
            // 3rd case: output only plugins
            for (int o = 0; o < outputs.length(); o++)
            {
                if (inputs.contains(outputs.at(o)) == false)
                {
                    quint32 outUni = m_ioMap->outputMapping(pluginName, outputId);
                    if (outUni == InputOutputMap::invalidUniverse() ||
                        (outUni == m_universe || plugin->capabilities() & QLCIOPlugin::Infinite))
                    {
                        //qDebug() << "Plugin: " << pluginName << ", output: " << id << ", universe:" << outUni;
                        QTreeWidgetItem* pitem = new QTreeWidgetItem(m_mapTree);
                        pitem->setText(KMapColumnPluginName, pluginName);
                        pitem->setText(KMapColumnDeviceName, outputs.at(o));
                        pitem->setFlags(pitem->flags() | Qt::ItemIsUserCheckable);
                        if (m_currentOutputPluginName == pluginName && m_currentOutput == outputId)
                            pitem->setCheckState(KMapColumnHasOutput, Qt::Checked);
                        else
                            pitem->setCheckState(KMapColumnHasOutput, Qt::Unchecked);
                        // add feedback
                        if (hasFeedback)
                        {
                            if (m_currentFeedbackPluginName == pluginName && m_currentFeedback == outputId)
                                pitem->setCheckState(KMapColumnHasFeedback, Qt::Checked);
                            else
                                pitem->setCheckState(KMapColumnHasFeedback, Qt::Unchecked);
                        }
                        pitem->setText(KMapColumnOutputLine, QString("%1").arg(outputId));
                        pitem->setText(KMapColumnInputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
                    }
                    outputId++;
                }
            }
        }
    }
int DicomImageSet::readDatasetFile(const QString &datasetFileName, QTreeWidget *treeWidget)
{
    HRESULT hr = S_OK;
    IXMLDOMDocument *pXMLDom = NULL;
    IXMLDOMNodeList *pPatients = NULL;
    IXMLDOMNode *pPatient = NULL;
	DOMNodeType nodeType;
    VARIANT_BOOL varStatus;
    VARIANT varFileName;
	VARIANT varValue;
	BSTR bstrQuery;

    VariantInit(&varFileName);
    VariantInit(&varValue);

	QString queryPatient, queryDate, queryProtocol, queryCollection;

    CHK_HR(CreateAndInitDOM(&pXMLDom));

	CHK_HR(VariantFromString(datasetFileName.toStdWString().c_str(), varFileName));
    CHK_HR(pXMLDom->load(varFileName, &varStatus));
    if (varStatus != VARIANT_TRUE)
    {
        CHK_HR(ReportParseError(pXMLDom, "Failed to load DOM from stocks.xml."));
    }

	treeWidget->clear();
	treeWidget->setColumnCount(1);
	CHK_HR(pXMLDom->getElementsByTagName(L"Patient", &pPatients));
	if (pPatients)
	{
		long nPatients;
		CHK_HR(pPatients->get_length(&nPatients));
		for (long i=0; i<nPatients; ++i)
		{
			CHK_HR(pPatients->get_item(i, &pPatient));
			CHK_HR(GetAttributeFromNode(pPatient, L"patients_name", &varValue));
			queryPatient = QString::fromWCharArray(_bstr_t(varValue));
			QTreeWidgetItem * patientItem = new QTreeWidgetItem(treeWidget, QStringList(queryPatient));
			patientItem->setExpanded(true);

			IXMLDOMNodeList * pDates = NULL;
			CHK_HR(pPatient->get_childNodes(&pDates));
			long nDates;
			CHK_HR(pDates->get_length(&nDates));
			for (long j=0; j<nDates; ++j)
			{
				IXMLDOMNode * pDate = NULL;
				CHK_HR(pDates->get_item(j, &pDate));
				CHK_HR(pDate->get_nodeType(&nodeType));
				if(nodeType!=NODE_ELEMENT)
				{
					continue;
				}
				CHK_HR(GetAttributeFromNode(pDate, L"acquisition_date", &varValue));
				queryDate = QString::fromWCharArray(_bstr_t(varValue));
				int intDate = queryDate.toInt();
				QDate date = (QDate::fromString("1900-01-01", "yyyy-MM-dd")).addDays(intDate-693962);
				QTreeWidgetItem * dateItem = new QTreeWidgetItem(patientItem, QStringList(date.toString("yyyy-MM-dd")));
				dateItem->setExpanded(true);

				IXMLDOMNodeList * pProtocols = NULL;
				CHK_HR(pDate->get_childNodes(&pProtocols));
				long nProtocols;
				CHK_HR(pProtocols->get_length(&nProtocols));
				for (long j=0; j<nProtocols; ++j)
				{
					IXMLDOMNode * pProtocol = NULL;
					CHK_HR(pProtocols->get_item(j, &pProtocol));
					CHK_HR(pProtocol->get_nodeType(&nodeType));
					if(nodeType!=NODE_ELEMENT)
					{
						continue;
					}
					CHK_HR(GetAttributeFromNode(pProtocol, L"protocol_name", &varValue));
					queryProtocol = QString::fromWCharArray(_bstr_t(varValue));
					QTreeWidgetItem * protocolItem = new QTreeWidgetItem(dateItem, QStringList(queryProtocol));
					protocolItem->setExpanded(true);

					IXMLDOMNodeList * pCollections = NULL;
					CHK_HR(pProtocol->get_childNodes(&pCollections));
					long nCollections;
					CHK_HR(pCollections->get_length(&nCollections));
					for (long j=0; j<nCollections; ++j)
					{
						IXMLDOMNode * pCollection = NULL;
						CHK_HR(pCollections->get_item(j, &pCollection));
						CHK_HR(pCollection->get_nodeType(&nodeType));
						if(nodeType!=NODE_ELEMENT)
						{
							continue;
						}
						CHK_HR(GetAttributeFromNode(pCollection, L"acquisition_number", &varValue));
						queryCollection = QString::fromWCharArray(_bstr_t(varValue));
						QTreeWidgetItem * collectionItem = new QTreeWidgetItem(protocolItem);
						QString queryStr = QString("root/Patient[@patients_name = '%1']/Date[@acquisition_date = '%2']/Protocol[@protocol_name = '%3']/Collection[@acquisition_number = '%4']")
							.arg(queryPatient).arg(queryDate).arg(queryProtocol).arg(queryCollection);

						IXMLDOMElement * pDtiNode = NULL;
						bstrQuery = SysAllocString(QString(queryStr+"/DTI").toStdWString().c_str());
						CHK_ALLOC(bstrQuery);
						CHK_HR(pXMLDom->selectSingleNode(bstrQuery, (IXMLDOMNode**)&pDtiNode));
						SysFreeString(bstrQuery);
						if (pDtiNode)
						{
							collectionItem->setText(0,queryCollection+"*");
						} else
						{
							collectionItem->setText(0, queryCollection);
						}

						collectionItem->setData(0, Qt::UserRole, queryStr);
						collectionItem->setExpanded(true);


						protocolItem->addChild(collectionItem);
						SAFE_RELEASE(pCollection);
					}

					dateItem->addChild(protocolItem);
					SAFE_RELEASE(pProtocol);
				}

				patientItem->addChild(dateItem);
				SAFE_RELEASE(pDate);
			}
			treeWidget->insertTopLevelItem(i, patientItem);
			SAFE_RELEASE(pPatient);
		}
	}

CleanUp:
    SAFE_RELEASE(pXMLDom);
    SAFE_RELEASE(pPatients);
    SAFE_RELEASE(pPatient);
    VariantClear(&varFileName);

	return SUCCEEDED(hr);
}
/* FUNCTION: setupSimulationResultsTree */
void ResultsWindow::setupSimulationResultsTree(void)
{
    NXDataStoreInfo *dataStoreInfo = entityManager->getDataStoreInfo();
    QWidget *tab1Widget = tabWidget->widget(0);
    resultsTree = dynamic_cast<QTreeWidget*>(tab1Widget);
    resultsTree->clear();
	QTreeWidgetItem* rootNode = new QTreeWidgetItem(resultsTree);
	rootNode->setText(0, userFriendlyCurrentFile());
	rootNode->setIcon(0, nh5FileIcon);
	rootNode->setFlags(Qt::ItemIsEnabled);
	rootNode->setExpanded(true);
	resultsTree->addTopLevelItem(rootNode);
    
    // input parameters
	NXProperties *inputParameters = dataStoreInfo->getInputParameters();
	if (inputParameters != NULL) {
		DataWindowTreeItem* inputParametersItem =
			new InputParametersTreeItem(this, rootNode);
		inputParametersItem->setIcon(0, inputParametersIcon);
		inputParametersItem->setText(0, tr("Input parameters"));
		inputParametersItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    }
    
    // input files
    vector<string> inputFileNames = dataStoreInfo->getInputFileNames();
    if (inputFileNames.size() > 0) {
        QTreeWidgetItem *inputFilesItem = new QTreeWidgetItem(rootNode);
        inputFilesItem->setIcon(0, inputFilesIcon);
        inputFilesItem->setText(0, tr("Input files"));
		inputFilesItem->setFlags(Qt::ItemIsEnabled);
		inputFilesItem->setExpanded(true);
        
        vector<string>::const_iterator inputFileNameIter;
        for (inputFileNameIter = inputFileNames.begin();
            inputFileNameIter != inputFileNames.end();
            ++inputFileNameIter)
        {
            QTreeWidgetItem *inputFileItem = new QTreeWidgetItem(inputFilesItem);
            inputFileItem->setIcon(0, inputFileIcon);
            inputFileItem->setText
				(0, strippedName(QString(inputFileNameIter->c_str())));
			inputFileItem->setFlags(Qt::ItemIsEnabled);
            // inputFilesItem->addChild(inputFileItem);
			
			if(isMMPFile(*inputFileNameIter)) {
				int mmpFileFrameSetId = 
					dataStoreInfo->getInputStructureId(*inputFileNameIter);
				if (mmpFileFrameSetId > -1) {
					NXMoleculeSet *rootMoleculeSet = 
						entityManager->getRootMoleculeSet(mmpFileFrameSetId, 0);
					setupMoleculeSetResultsSubtree(rootMoleculeSet,
					                               inputFileItem);
				} else {
                    // TODO: handle this
				}
            }

        }
    }
    
    // Results
	
	NXProperties *resultsSummary = dataStoreInfo->getResultsSummary();
	vector<string> trajectoryNames = dataStoreInfo->getTrajectoryNames();
	
    // don't create if no children
    if (resultsSummary == NULL && trajectoryNames.size()==0) return;
    
    QTreeWidgetItem *resultsItem = new QTreeWidgetItem(rootNode);
    resultsItem->setIcon(0, resultsIcon);
    resultsItem->setText(0, tr("Results"));
	resultsItem->setFlags(Qt::ItemIsEnabled);
	resultsItem->setExpanded(true);
    
    // Results -> Summary
	DataWindowTreeItem* resultsSummaryItem = NULL;
	if (resultsSummary != NULL) {
		resultsSummaryItem = new ResultsSummaryTreeItem(this, resultsItem);
		resultsSummaryItem->setText(0, tr("Summary"));
		resultsSummaryItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
	}
	
    // Results -> Trajectories
	if (trajectoryNames.size() > 0) {
		QTreeWidgetItem *trajectoryItem = new QTreeWidgetItem(resultsItem);
		trajectoryItem->setIcon(0, resultsTrajectoriesIcon);
		trajectoryItem->setText(0, tr("Trajectories"));
		trajectoryItem->setFlags(Qt::ItemIsEnabled);
		trajectoryItem->setExpanded(true);
        
        vector<string>::const_iterator trajectoryNameIter;
        for (trajectoryNameIter = trajectoryNames.begin();
            trajectoryNameIter != trajectoryNames.end();
            ++trajectoryNameIter)
        {
            TrajectoryGraphicsTreeItem* trajectoryNameItem =
                new TrajectoryGraphicsTreeItem(*trajectoryNameIter,
											   this,
											   trajectoryItem);
            trajectoryNameItem->setIcon(0, resultsTrajectoriesIcon);
            trajectoryNameItem->setText(0, QString(trajectoryNameIter->c_str()));
			trajectoryNameItem->setFlags(Qt::ItemIsSelectable |
			                             Qt::ItemIsEnabled);
            // trajectoryItem->addChild(trajectoryNameItem);
			
            // Show some graphics right away
			if (trajectoryNameIter == trajectoryNames.begin())
				trajectoryNameItem->showWindow();
			
            // Signal the results summary window once the data store is
            // complete so it can refresh itself
			int trajectoryId =
				dataStoreInfo->getTrajectoryId(*trajectoryNameIter);
			if ((resultsSummaryItem != NULL) &&
			    (!dataStoreInfo->storeIsComplete(trajectoryId)))
			{
				/// @todo: This code will need to be a little smarter once we support multiple
				/// trajectories and such. As it stands, it would make multiple identical signal-
				/// slot connections.
				
				    QObject::connect(entityManager,
				                     SIGNAL(dataStoreComplete()),
				                     resultsSummaryItem,
				                     SLOT(refresh()));
				    ((ResultsSummaryTreeItem*)resultsSummaryItem)
					    ->setTrajectoryId(trajectoryId);
				    resultsSummaryItem->refresh();
			    }
		}
	}
}
Example #26
0
void ChannelsJoinDialog::fillListView()
{
	m_pTreeWidget->clear();

	m_pTreeWidget->header()->hide();

	// Registered channels go first

	QTreeWidgetItem * par = new QTreeWidgetItem(m_pTreeWidget, HeaderItem);
	par->setText(0,__tr2qs("Registered Channels"));
	par->setExpanded(true);

	QHash<QString,KviRegisteredChannelList *> * d = g_pRegisteredChannelDataBase->channelDict();
	if(d)
	{
		for(QHash<QString,KviRegisteredChannelList *>::Iterator it = d->begin();it != d->end();++it)
		{
			QTreeWidgetItem * chld = new QTreeWidgetItem(par, RegisteredChannelItem);
			chld->setText(0,it.key());
			chld->setIcon(0,*(g_pIconManager->getSmallIcon(KviIconManager::Channel)));
		}
	}

	par->sortChildren(0, Qt::AscendingOrder);

	par = new QTreeWidgetItem(m_pTreeWidget, HeaderItem);
	par->setText(0,__tr2qs("Recent Channels"));
	par->setExpanded(true);

	QTreeWidgetItem * chld;

	bool bGotChanOnCurrentNetwork = false;

	QTreeWidgetItem * hdr;

	if(m_pConsole)
	{
		QStringList * pList = g_pApp->recentChannelsForNetwork(m_pConsole->currentNetworkName());
		if(pList)
		{
			if(pList->count() > 0)
			{
				bGotChanOnCurrentNetwork = true;

				hdr = new QTreeWidgetItem(par, HeaderItem);
				hdr->setText(0,__tr2qs("Current Network"));
				hdr->setExpanded(true);

				for(QStringList::Iterator it = pList->begin(); it != pList->end(); ++it)
				{
					chld = new QTreeWidgetItem(hdr, RecentChannelItem);
					chld->setText(0,*it);
					chld->setIcon(0,*(g_pIconManager->getSmallIcon(KviIconManager::Channel)));
				}
				hdr->sortChildren(0, Qt::AscendingOrder);
			}
		}
	}

	KviPointerHashTable<QString,QStringList> * pDict = g_pApp->recentChannels();
	if(!pDict)
		return;

	hdr = new QTreeWidgetItem(par, HeaderItem);
	hdr->setText(0,__tr2qs("All Networks"));

	if(!bGotChanOnCurrentNetwork)
		hdr->setExpanded(true); // expand this one instead

	QHash<QString,int> hNoDuplicates;

	for(QStringList * pChans = pDict->first();pChans;pChans = pDict->next())
	{
		for(QStringList::Iterator it = pChans->begin(); it != pChans->end(); ++it)
		{
			QString chan = *it;
			if(hNoDuplicates.contains(chan.toLower()))
				continue;
			hNoDuplicates.insert(chan.toLower(),1);
			chld = new QTreeWidgetItem(hdr, RecentChannelItem);
			chld->setText(0,chan);
			chld->setIcon(0,*(g_pIconManager->getSmallIcon(KviIconManager::Channel)));
		}
	}
	hdr->sortChildren(0, Qt::AscendingOrder);
}
Example #27
0
SiteInfo::SiteInfo(WebView* view, QWidget* parent)
    : QDialog(parent)
    , ui(new Ui::SiteInfo)
    , m_certWidget(0)
    , m_view(view)
{
    setAttribute(Qt::WA_DeleteOnClose);
    ui->setupUi(this);

    ui->listWidget->item(0)->setIcon(QIcon::fromTheme("document-properties", QIcon(":/icons/preferences/document-properties.png")));
    ui->listWidget->item(1)->setIcon(QIcon::fromTheme("applications-graphics", QIcon(":/icons/preferences/applications-graphics.png")));
    ui->listWidget->item(2)->setIcon(QIcon::fromTheme("text-x-sql", QIcon(":/icons/preferences/text-x-sql.png")));
    ui->listWidget->item(3)->setIcon(QIcon::fromTheme("dialog-password", QIcon(":/icons/preferences/dialog-password.png")));
    ui->listWidget->item(0)->setSelected(true);

    WebPage* webPage = view->page();
    QWebFrame* frame = view->page()->mainFrame();
    QString title = view->title();
    QSslCertificate cert = webPage->sslCertificate();
    m_baseUrl = frame->baseUrl();

    //GENERAL
    ui->heading->setText(QString("<b>%1</b>:").arg(title));
    ui->siteAddress->setText(view->url().toString());
    ui->sizeLabel->setText(qz_fileSizeToString(webPage->totalBytes()));
    QString encoding;

    //Meta
    QWebElementCollection meta = frame->findAllElements("meta");
    for (int i = 0; i < meta.count(); i++) {
        QWebElement element = meta.at(i);

        QString content = element.attribute("content");
        QString name = element.attribute("name");
        if (name.isEmpty()) {
            name = element.attribute("http-equiv");
        }
        if (!element.attribute("charset").isEmpty()) {
            encoding = element.attribute("charset");
        }
        if (content.contains(QLatin1String("charset="))) {
            encoding = content.mid(content.indexOf(QLatin1String("charset=")) + 8);
        }

        if (content.isEmpty() || name.isEmpty()) {
            continue;
        }
        QTreeWidgetItem* item = new QTreeWidgetItem(ui->treeTags);
        item->setText(0, name);
        item->setText(1, content);
        ui->treeTags->addTopLevelItem(item);
    }
    if (encoding.isEmpty()) {
        encoding = mApp->webSettings()->defaultTextEncoding();
    }
    ui->encodingLabel->setText(encoding.toUpper());

    //MEDIA
    QWebElementCollection img = frame->findAllElements("img");
    for (int i = 0; i < img.count(); i++) {
        QWebElement element = img.at(i);

        QString src = element.attribute("src");
        QString alt = element.attribute("alt");
        if (alt.isEmpty()) {
            if (src.indexOf(QLatin1Char('/')) == -1) {
                alt = src;
            }
            else {
                int pos = src.lastIndexOf(QLatin1Char('/'));
                alt = src.mid(pos);
                alt.remove(QLatin1Char('/'));
            }
        }
        if (src.isEmpty() || alt.isEmpty()) {
            continue;
        }
        QTreeWidgetItem* item = new QTreeWidgetItem(ui->treeImages);
        item->setText(0, alt);
        item->setText(1, src);
        ui->treeImages->addTopLevelItem(item);
    }

    //DATABASES
    const QList<QWebDatabase> &databases = frame->securityOrigin().databases();

    int counter = 0;
    foreach(const QWebDatabase & b, databases) {
        QListWidgetItem* item = new QListWidgetItem(ui->databaseList);
        item->setText(b.displayName());
        item->setData(Qt::UserRole + 10, counter);

        ++counter;
    }
void MainWindow::pluginTestRunning(PluginTest *test)
{
	QTreeWidgetItem *item = treeItemFromPluginTest(test);
	if (item != NULL) item->setText(1, "[Testing...]");
}
void
GenerateHeatMapDialog::generateNow()
{

    double minLat = 999;
    double maxLat = -999;
    double minLon = 999;
    double maxLon = -999;
    QHash<QString, int> hash;

    // loop through the table and export all selected
    for(int i=0; i<files->invisibleRootItem()->childCount(); i++) {

        // give user a chance to abort..
        QApplication::processEvents();

        // did they?
        if (aborted == true) return; // user aborted!

        QTreeWidgetItem *current = files->invisibleRootItem()->child(i);

        // is it selected
        if (static_cast<QCheckBox*>(files->itemWidget(current,0))->isChecked()) {

            files->setCurrentItem(current); QApplication::processEvents();

            // this one then
            current->setText(4, tr("Reading...")); QApplication::processEvents();

            // open it..
            QStringList errors;
            QList<RideFile*> rides;
            QFile thisfile(QString(context->athlete->home->activities().absolutePath()+"/"+current->text(1)));
            RideFile *ride = RideFileFactory::instance().openRideFile(context, thisfile, errors, &rides);

            // open success?
            if (ride) {
                current->setText(4, tr("Writing...")); QApplication::processEvents();

                if (ride->areDataPresent()->lat == true && ride->areDataPresent()->lon == true) {
                    int lastDistance = 0;
                    foreach(const RideFilePoint *point, ride->dataPoints()) {

                        if (lastDistance < (int) (point->km * 1000) &&
                           (point->lon!=0 || point->lat!=0)) {

                            // Pick up a point max every 15m
                            lastDistance = (int) (point->km * 1000) + 15;
                            //outhtml << "  new google.maps.LatLng("<<point->lat<<", "<<point->lon<<"),\n";
                            QString lonlat = QString("%1,%2").arg(floorf(point->lat*100000)/100000).arg(floorf(point->lon*100000)/100000);
                            if (hash.contains(lonlat)) {
                                hash[lonlat] = hash[lonlat] + 1;
                            } else {
                                hash[lonlat] = 1;
                            }

                            if (minLon > point->lon) minLon = point->lon;
                            if (minLat > point->lat) minLat = point->lat;
                            if (maxLon < point->lon) maxLon = point->lon;
                            if (maxLat < point->lat) maxLat = point->lat;

                        }

                    }
                }

                delete ride; // free memory!
            // open failed
            } else {
void QgsProjectionSelectionTreeWidget::loadUserCrsList( QSet<QString> *crsFilter )
{
  if ( mUserProjListDone )
    return;

  QgsDebugMsgLevel( "Fetching user projection list...", 4 );

  // convert our Coordinate Reference System filter into the SQL expression
  QString sqlFilter = ogcWmsCrsFilterAsSqlExpression( crsFilter );

  // User defined coordinate system node
  // Make in an italic font to distinguish them from real projections
  mUserProjList = new QTreeWidgetItem( lstCoordinateSystems, QStringList( tr( "User Defined Coordinate Systems" ) ) );

  QFont fontTemp = mUserProjList->font( 0 );
  fontTemp.setItalic( true );
  fontTemp.setBold( true );
  mUserProjList->setFont( 0, fontTemp );
  mUserProjList->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/user.svg" ) ) );

  //determine where the user proj database lives for this user. If none is found an empty
  //now only will be shown
  QString databaseFileName = QgsApplication::qgisUserDatabaseFilePath();
  // first we look for ~/.qgis/qgis.db
  // if it doesn't exist we copy it in from the global resources dir

  //return straight away if the user has not created any custom projections
  if ( !QFileInfo::exists( databaseFileName ) )
  {
    QgsDebugMsg( "Users qgis.db not found...skipping" );
    mUserProjListDone = true;
    return;
  }

  sqlite3      *database = nullptr;
  const char   *tail = nullptr;
  sqlite3_stmt *stmt = nullptr;
  //check the db is available
  int result = sqlite3_open_v2( databaseFileName.toUtf8().constData(), &database, SQLITE_OPEN_READONLY, nullptr );
  if ( result )
  {
    // XXX This will likely never happen since on open, sqlite creates the
    //     database if it does not exist. But we checked earlier for its existence
    //     and aborted in that case. This is because we may be running from read only
    //     media such as live cd and don't want to force trying to create a db.
    showDBMissingWarning( databaseFileName );
    return;
  }

  // Set up the query to retrieve the projection information needed to populate the list
  QString sql = QStringLiteral( "select description, srs_id from vw_srs where %1" ).arg( sqlFilter );

  result = sqlite3_prepare( database, sql.toUtf8(), sql.toUtf8().length(), &stmt, &tail );
  // XXX Need to free memory from the error msg if one is set
  if ( result == SQLITE_OK )
  {
    QTreeWidgetItem *newItem = nullptr;
    while ( sqlite3_step( stmt ) == SQLITE_ROW )
    {
      newItem = new QTreeWidgetItem( mUserProjList, QStringList( QString::fromUtf8( ( char * )sqlite3_column_text( stmt, 0 ) ) ) );
      // EpsgCrsId for user projections is not always defined in some dbases.
      // It's also not written from customprojections dialog.
      // display the epsg (field 2) in the second column of the list view
      // newItem->setText( EPSG_COLUMN, QString::fromUtf8(( char * )sqlite3_column_text( stmt, 2 ) ) );
      // display the qgis srs_id (field 1) in the third column of the list view
      newItem->setText( QgisCrsIdColumn, QString::fromUtf8( ( char * )sqlite3_column_text( stmt, 1 ) ) );
      newItem->setText( AuthidColumn, QStringLiteral( "USER:%1" ).arg( QString::fromUtf8( ( char * )sqlite3_column_text( stmt, 1 ) ).toInt() ) );
    }
  }
  // close the sqlite3 statement
  sqlite3_finalize( stmt );
  sqlite3_close( database );

  mUserProjListDone = true;
}