QWidget* PathChooserDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &) const
{
    QTreeWidgetItem *item = tree_->currentItem();
    if (!item) {
        return NULL;
    }
    path_item_ = item;

    path_editor_ = new QWidget(parent);
    QHBoxLayout *hbox = new QHBoxLayout(path_editor_);
    path_editor_->setLayout(hbox);
    path_le_ = new QLineEdit(path_editor_);
    QPushButton *pb = new QPushButton(path_editor_);

    path_le_->setText(item->text(col_p_pipe_));
    pb->setText(QString(tr("Browse" UTF8_HORIZONTAL_ELLIPSIS)));

    hbox->setContentsMargins(0, 0, 0, 0);
    hbox->addWidget(path_le_);
    hbox->addWidget(pb);
    hbox->setSizeConstraint(QLayout::SetMinimumSize);

    // Grow the item to match the editor. According to the QAbstractItemDelegate
    // documenation we're supposed to reimplement sizeHint but this seems to work.
    QSize size = option.rect.size();
    size.setHeight(qMax(option.rect.height(), hbox->sizeHint().height()));
    item->setData(col_p_pipe_, Qt::SizeHintRole, size);

    path_le_->selectAll();
    path_editor_->setFocusProxy(path_le_);
    path_editor_->setFocusPolicy(path_le_->focusPolicy());

    connect(path_le_, SIGNAL(destroyed()), this, SLOT(stopEditor()));
    connect(pb, SIGNAL(pressed()), this, SLOT(browse_button_clicked()));
    return path_editor_;
}
Exemple #2
0
void Scene_polylines_item::change_corner_radii(double r) {
    if(r >= 0) {
        d->spheres_drawn_radius = r;
        d->draw_extremities = (r > 0);
        if(r>0 && !spheres)
        {
          spheres = new Scene_spheres_item(this, false);
          spheres->setName("Corner spheres");
          spheres->setRenderingMode(Gouraud);
          connect(spheres, SIGNAL(destroyed()), this, SLOT(reset_spheres()));
          scene->addItem(spheres);
          scene->changeGroup(spheres, this);
          lockChild(spheres);
          computeSpheres();
          spheres->invalidateOpenGLBuffers();
        }
        else if (r<=0 && spheres!=NULL)
        {
          unlockChild(spheres);
          scene->erase(scene->item_id(spheres));
        }
    Q_EMIT itemChanged();
    }
}
void tst_QPluginLoader::reloadPlugin()
{
    QPluginLoader loader;
    loader.setFileName( sys_qualifiedLibraryName("theplugin"));     //a plugin
    loader.load(); // not recommended, instance() should do the job.
    PluginInterface *instance = qobject_cast<PluginInterface*>(loader.instance());
    QVERIFY(instance);
    QCOMPARE(instance->pluginName(), QLatin1String("Plugin ok"));

    QSignalSpy spy(loader.instance(), SIGNAL(destroyed()));
    QVERIFY(spy.isValid());
    QVERIFY(loader.unload());   // refcount reached 0, did really unload
    QCOMPARE(spy.count(), 1);

    // reload plugin
    QVERIFY(loader.load());
    QVERIFY(loader.isLoaded());

    PluginInterface *instance2 = qobject_cast<PluginInterface*>(loader.instance());
    QVERIFY(instance2);
    QCOMPARE(instance2->pluginName(), QLatin1String("Plugin ok"));

    QVERIFY(loader.unload());
}
Exemple #4
0
void KBinaryClock::toggleCalendar()
{
	if (_calendar && !_disableCalendar) {
		// calls slotCalendarDeleted which does the cleanup for us
		_calendar->close();
		return;
	}
	if (_calendar || _disableCalendar){
		return;
	}
	_calendar = new DatePicker(this, QDateTime::currentDateTime().date());
	connect( _calendar, SIGNAL( destroyed() ), SLOT( slotCalendarDeleted() ));

	// some extra spacing is included if aligned on a desktop edge
	QPoint c = mapToGlobal(QPoint(0,0));

	int w = _calendar->sizeHint().width() + 28;
															// Added 28 px. to size poperly as said in API
	int h = _calendar->sizeHint().height();

	switch (position()) {
	case KPanelApplet::pLeft:	c.setX(c.x()+width()+2);	break;
	case KPanelApplet::pRight:	c.setX(c.x()-w-2);		break;
	case KPanelApplet::pTop:	c.setY(c.y()+height()+2);	break;
	case KPanelApplet::pBottom:	c.setY(c.y()-h-2);		break;
		}

		// make calendar fully visible
		QRect deskR = KGlobalSettings::desktopGeometry(QPoint(0,0));

		if (c.y()+h > deskR.bottom())	c.setY(deskR.bottom()-h-1);
		if (c.x()+w > deskR.right())				c.setX(deskR.right()-w-1);

		_calendar->move(c);
		_calendar->show();
}
void FindReplaceDialog::setExtendedScintilla(ExtendedScintilla* scintilla)
{
    m_scintilla = scintilla;

    // Create indicator for find-all and replace-all occurrences
    foundIndicatorNumber = m_scintilla->indicatorDefine(QsciScintilla::StraightBoxIndicator);
    m_scintilla->setIndicatorForegroundColor(Qt::magenta, foundIndicatorNumber);
    m_scintilla->setIndicatorDrawUnder(true, foundIndicatorNumber);

    bool isWriteable = ! m_scintilla->isReadOnly();
    ui->replaceWithText->setEnabled(isWriteable);
    ui->replaceButton->setEnabled(isWriteable);
    ui->replaceAllButton->setEnabled(isWriteable);

    connect(m_scintilla, SIGNAL(destroyed()), this, SLOT(hide()));
    connect(ui->findText, SIGNAL(editingFinished()), this, SLOT(cancelFind()));
    connect(ui->regexpCheckBox, &QCheckBox::toggled, this, &FindReplaceDialog::cancelFind);
    connect(ui->caseCheckBox, &QCheckBox::toggled, this, &FindReplaceDialog::cancelFind);
    connect(ui->wholeWordsCheckBox, &QCheckBox::toggled, this, &FindReplaceDialog::cancelFind);
    connect(ui->wrapCheckBox, &QCheckBox::toggled, this, &FindReplaceDialog::cancelFind);
    connect(ui->backwardsCheckBox, &QCheckBox::toggled, this, &FindReplaceDialog::cancelFind);
    connect(ui->selectionCheckBox, &QCheckBox::toggled, this, &FindReplaceDialog::cancelFind);
    connect(ui->selectionCheckBox, &QCheckBox::toggled, ui->wrapCheckBox, &QCheckBox::setDisabled);
}
void SongLoaderInserter::Load(Playlist* destination, int row, bool play_now,
                              bool enqueue, const QList<QUrl>& urls) {
  destination_ = destination;
  row_ = row;
  play_now_ = play_now;
  enqueue_ = enqueue;

  connect(destination, SIGNAL(destroyed()), SLOT(DestinationDestroyed()));
  connect(this, SIGNAL(PreloadFinished()), SLOT(InsertSongs()));
  connect(this, SIGNAL(EffectiveLoadFinished(const SongList&)), destination,
          SLOT(UpdateItems(const SongList&)));

  for (const QUrl& url : urls) {
    SongLoader* loader = new SongLoader(library_, player_, this);

    SongLoader::Result ret = loader->Load(url);

    if (ret == SongLoader::BlockingLoadRequired) {
      pending_.append(loader);
      continue;
    }

    if (ret == SongLoader::Success)
      songs_ << loader->songs();
    else
      emit Error(tr("Error loading %1").arg(url.toString()));
    delete loader;
  }

  if (pending_.isEmpty()) {
    InsertSongs();
    deleteLater();
  } else {
    QtConcurrent::run(this, &SongLoaderInserter::AsyncLoad);
  }
}
void NetworkAccessManager::handleAuthenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator)
{
	if (m_widget)
	{
		AuthenticationDialog *authenticationDialog = new AuthenticationDialog(reply->url(), authenticator, m_widget);
		authenticationDialog->setButtonsVisible(false);

		ContentsDialog dialog(Utils::getIcon(QLatin1String("dialog-password")), authenticationDialog->windowTitle(), QString(), QString(), (QDialogButtonBox::Ok | QDialogButtonBox::Cancel), authenticationDialog, m_widget);

		connect(&dialog, SIGNAL(accepted()), authenticationDialog, SLOT(accept()));

		QEventLoop eventLoop;

		m_widget->showDialog(&dialog);

		connect(&dialog, SIGNAL(closed(bool,QDialogButtonBox::StandardButton)), &eventLoop, SLOT(quit()));
		connect(this, SIGNAL(destroyed()), &eventLoop, SLOT(quit()));

		eventLoop.exec();

		m_widget->hideDialog(&dialog);
	}
	else
	{
void medViewContainer::setView(medAbstractView *view)
{
    if(d->view)
    {
        d->view->viewWidget()->hide();
        this->removeInternView();
    }
    if(view)
    {
        d->view = view;
        connect(d->view, SIGNAL(destroyed()), this, SLOT(removeInternView()));
        connect(d->view, SIGNAL(selectedRequest(bool)), this, SLOT(setSelected(bool)));

        if(medAbstractLayeredView* layeredView = dynamic_cast<medAbstractLayeredView*>(view))
        {
            connect(layeredView, SIGNAL(currentLayerChanged()), this, SIGNAL(currentLayerChanged()));
            connect(layeredView, SIGNAL(currentLayerChanged()), this, SLOT(updateToolBar()));
            connect(layeredView, SIGNAL(layerAdded(uint)), this, SIGNAL(viewContentChanged()));
            connect(layeredView, SIGNAL(layerRemoved(uint)), this, SIGNAL(viewContentChanged()));
        }

        if (medAbstractImageView* imageView = dynamic_cast <medAbstractImageView*> (view))
        {
            if (!d->userSplittable)
                imageView->fourViewsParameter()->hide();
        }
        
        d->maximizedAction->setEnabled(true);
        d->defaultWidget->hide();
        d->mainLayout->addWidget(d->view->viewWidget(), 2, 0, 1, 1);
        d->view->viewWidget()->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::MinimumExpanding);
        d->view->viewWidget()->show();

        emit viewChanged();
    }
}
Exemple #9
0
/*!
  \internal

  Creates a new script in \a project with the name \a name,
  context \a context and code \a code.
*/
QSScript::QSScript(QSProject *project,
                   const QString &name,
                   const QString &code,
                   QObject *context)
  :
  QObject(project, name.local8Bit())
{
  d = new QSScriptPrivate;
#ifndef AQ_ENABLE_SCRIPTCACHE
  d->code = code;
#else
  d->code = aqSha1(code);
  aqDiskCacheInsert(d->code, code);
#endif

  d->name = name;
  d->project = project;

  if (context) {
    d->context = context;
    connect(context, SIGNAL(destroyed()),
            this, SLOT(objectDestroyed()));
  }
}
Exemple #10
0
void PukeController::insertPObject(int fd, int iWinId, WidgetS *obj){ /*FOLD00*/
  // If no widget list exists for this fd, create one
  if(WidgetList[fd] == NULL){
    QIntDict<WidgetS> *qidWS = new("QIntDict<WidgetS>") QIntDict<WidgetS>;
    qidWS->setAutoDelete(TRUE);
    WidgetList.insert(fd, qidWS);
  }
  // Set main widget structure list
  WidgetList[fd]->insert(iWinId, obj);

  // Set reverse list used durring delete to remove the widget
  widgetId *pwi = new("widgetId") widgetId;
  pwi->fd = fd;
  pwi->iWinId = iWinId;
  char key[keySize];
  memset(key, 0, keySize);
  sprintf(key, "%p", obj->pwidget);
  revWidgetList.insert(key, pwi);

  // Now connect to the destroyed signal so we can remove the object from the lists
  // Once it is deleted
  connect(obj->pwidget, SIGNAL(destroyed()),
          this, SLOT(pobjectDestroyed()));
}
Exemple #11
0
Bus::~Bus()
{
  emit destroyed();
}
//!
//! Destructor of the ClusteringLayouterNode class.
//!
//! Defined virtual to guarantee that the destructor of a derived class
//! will be called if the instance of the derived class is saved in a
//! variable of its parent class type.
//!
ClusteringLayouterNode::~ClusteringLayouterNode ()
{
	emit destroyed();
    DEC_INSTANCE_COUNTER
    Log::info(QString("ClusteringLayouterNode destroyed."), "ClusteringLayouterNode::~ClusteringLayouterNode");
}
QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWidget *parent, Qt::WindowFlags flags )
    : QDialog( parent, flags ), mDock( NULL )
{
  mLayer = theLayer;

  setupUi( this );

  setAttribute( Qt::WA_DeleteOnClose );

  QSettings settings;
  restoreGeometry( settings.value( "/Windows/BetterAttributeTable/geometry" ).toByteArray() );

  mView->setLayer( mLayer );
  mFilterModel = ( QgsAttributeTableFilterModel * ) mView->model();
  mModel = ( QgsAttributeTableModel * )(( QgsAttributeTableFilterModel * )mView->model() )->sourceModel();

  mQuery = query;
  mColumnBox = columnBox;
  columnBoxInit();

  bool myDockFlag = settings.value( "/qgis/dockAttributeTable", false ).toBool();
  if ( myDockFlag )
  {
    mDock = new QgsAttributeTableDock( tr( "Attribute table - %1 (%n Feature(s))", "feature count", mModel->rowCount() ).arg( mLayer->name() ), QgisApp::instance() );
    mDock->setAllowedAreas( Qt::BottomDockWidgetArea | Qt::TopDockWidgetArea );
    mDock->setWidget( this );
    connect( this, SIGNAL( destroyed() ), mDock, SLOT( close() ) );
    QgisApp::instance()->addDockWidget( Qt::BottomDockWidgetArea, mDock );
  }

  updateTitle();

  mRemoveSelectionButton->setIcon( QgisApp::getThemeIcon( "/mActionUnselectAttributes.png" ) );
  mSelectedToTopButton->setIcon( QgisApp::getThemeIcon( "/mActionSelectedToTop.png" ) );
  mCopySelectedRowsButton->setIcon( QgisApp::getThemeIcon( "/mActionCopySelected.png" ) );
  mZoomMapToSelectedRowsButton->setIcon( QgisApp::getThemeIcon( "/mActionZoomToSelected.png" ) );
  mInvertSelectionButton->setIcon( QgisApp::getThemeIcon( "/mActionInvertSelection.png" ) );
  mToggleEditingButton->setIcon( QgisApp::getThemeIcon( "/mActionToggleEditing.png" ) );
  mSaveEditsButton->setIcon( QgisApp::getThemeIcon( "/mActionSaveEdits.png" ) );
  mDeleteSelectedButton->setIcon( QgisApp::getThemeIcon( "/mActionDeleteSelected.png" ) );
  mOpenFieldCalculator->setIcon( QgisApp::getThemeIcon( "/mActionCalculateField.png" ) );
  mAddAttribute->setIcon( QgisApp::getThemeIcon( "/mActionNewAttribute.png" ) );
  mRemoveAttribute->setIcon( QgisApp::getThemeIcon( "/mActionDeleteAttribute.png" ) );

  // toggle editing
  bool canChangeAttributes = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeAttributeValues;
  bool canDeleteFeatures = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::DeleteFeatures;
  bool canAddAttributes = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::AddAttributes;
  bool canDeleteAttributes = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::DeleteAttributes;
  bool canAddFeatures = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::AddFeatures;

  mToggleEditingButton->setCheckable( true );
  mToggleEditingButton->setChecked( mLayer->isEditable() );
  mToggleEditingButton->setEnabled( canChangeAttributes && !mLayer->isReadOnly() );

  mSaveEditsButton->setEnabled( canChangeAttributes && mLayer->isEditable() );
  mOpenFieldCalculator->setEnabled( canChangeAttributes && mLayer->isEditable() );
  mDeleteSelectedButton->setEnabled( canDeleteFeatures && mLayer->isEditable() );
  mAddAttribute->setEnabled( canAddAttributes && mLayer->isEditable() );
  mRemoveAttribute->setEnabled( canDeleteAttributes && mLayer->isEditable() );
  mAddFeature->setEnabled( canAddFeatures && mLayer->isEditable() && mLayer->geometryType() == QGis::NoGeometry );
  mAddFeature->setHidden( !canAddFeatures || mLayer->geometryType() != QGis::NoGeometry );

  // info from table to application
  connect( this, SIGNAL( editingToggled( QgsMapLayer * ) ), QgisApp::instance(), SLOT( toggleEditing( QgsMapLayer * ) ) );
  connect( this, SIGNAL( saveEdits( QgsMapLayer * ) ), QgisApp::instance(), SLOT( saveEdits( QgsMapLayer * ) ) );

  // info from layer to table
  connect( mLayer, SIGNAL( editingStarted() ), this, SLOT( editingToggled() ) );
  connect( mLayer, SIGNAL( editingStopped() ), this, SLOT( editingToggled() ) );

  connect( searchButton, SIGNAL( clicked() ), this, SLOT( search() ) );
  connect( mAddFeature, SIGNAL( clicked() ), this, SLOT( addFeature() ) );

  connect( mLayer, SIGNAL( selectionChanged() ), this, SLOT( updateSelectionFromLayer() ) );
  connect( mLayer, SIGNAL( layerDeleted() ), this, SLOT( close() ) );
  connect( mView->verticalHeader(), SIGNAL( sectionClicked( int ) ), this, SLOT( updateRowSelection( int ) ) );
  connect( mView->verticalHeader(), SIGNAL( sectionPressed( int ) ), this, SLOT( updateRowPressed( int ) ) );
  connect( mModel, SIGNAL( modelChanged() ), this, SLOT( updateSelection() ) );

  if ( settings.value( "/qgis/attributeTableBehaviour", 0 ).toInt() == 2 )
  {
    connect( QgisApp::instance()->mapCanvas(), SIGNAL( extentsChanged() ), mModel, SLOT( layerModified() ) );
  }

  mLastClickedHeaderIndex = 0;
  mSelectionModel = new QItemSelectionModel( mFilterModel );
  updateSelectionFromLayer();

  //make sure to show all recs on first load
  on_cbxShowSelectedOnly_toggled( false );
}
YTLocalVideoData::~YTLocalVideoData()
{
    Q_ASSERT(_videoFile.isNull());
    Q_ASSERT(_status != YTLocalVideo::Loading);
    emit destroyed(_videoId);
}
BufferView::~BufferView()
{
    emit destroyed(this);
}
Exemple #16
0
bool Servatrice::initServer()
{
    serverName = settings->value("server/name").toString();
    serverId = settings->value("server/id", 0).toInt();
    bool regServerOnly = settings->value("server/regonly", 0).toBool();
        
    const QString authenticationMethodStr = settings->value("authentication/method").toString();
    if (authenticationMethodStr == "sql") {
        authenticationMethod = AuthenticationSql;
    } else {
        if (regServerOnly) {
            qDebug() << "Registration only server enabled but no DB Connection : Error.";
            return false;   
        }
        authenticationMethod = AuthenticationNone;
    }
    
    QString dbTypeStr = settings->value("database/type").toString();
    if (dbTypeStr == "mysql")
        databaseType = DatabaseMySql;
    else
        databaseType = DatabaseNone;
    
    servatriceDatabaseInterface = new Servatrice_DatabaseInterface(-1, this);
    setDatabaseInterface(servatriceDatabaseInterface);
    
    if (databaseType != DatabaseNone) {
        settings->beginGroup("database");
        dbPrefix = settings->value("prefix").toString();
        servatriceDatabaseInterface->initDatabase("QMYSQL",
                              settings->value("hostname").toString(),
                              settings->value("database").toString(),
                              settings->value("user").toString(),
                              settings->value("password").toString());
        settings->endGroup();
        
        updateServerList();
        
        qDebug() << "Clearing previous sessions...";
        servatriceDatabaseInterface->clearSessionTables();
    }
    
    const QString roomMethod = settings->value("rooms/method").toString();
    if (roomMethod == "sql") {
        QSqlQuery query(servatriceDatabaseInterface->getDatabase());
        query.prepare("select id, name, descr, auto_join, join_message from " + dbPrefix + "_rooms order by id asc");
        servatriceDatabaseInterface->execSqlQuery(query);
        while (query.next()) {
            QSqlQuery query2(servatriceDatabaseInterface->getDatabase());
            query2.prepare("select name from " + dbPrefix + "_rooms_gametypes where id_room = :id_room");
            query2.bindValue(":id_room", query.value(0).toInt());
            servatriceDatabaseInterface->execSqlQuery(query2);
            QStringList gameTypes;
            while (query2.next())
                gameTypes.append(query2.value(0).toString());
            
            addRoom(new Server_Room(query.value(0).toInt(),
                                    query.value(1).toString(),
                                    query.value(2).toString(),
                                    query.value(3).toInt(),
                                    query.value(4).toString(),
                                    gameTypes,
                                    this
            ));
        }
    } else {
        int size = settings->beginReadArray("rooms/roomlist");
        for (int i = 0; i < size; ++i) {
            settings->setArrayIndex(i);
            
            QStringList gameTypes;
            int size2 = settings->beginReadArray("game_types");
                for (int j = 0; j < size2; ++j) {
                settings->setArrayIndex(j);
                gameTypes.append(settings->value("name").toString());
            }
            settings->endArray();
                
            Server_Room *newRoom = new Server_Room(
                i,
                settings->value("name").toString(),
                settings->value("description").toString(),
                settings->value("autojoin").toBool(),
                settings->value("joinmessage").toString(),
                gameTypes,
                this
            );
            addRoom(newRoom);
        }
        settings->endArray();
    }
    
    updateLoginMessage();
    
    maxGameInactivityTime = settings->value("game/max_game_inactivity_time").toInt();
    maxPlayerInactivityTime = settings->value("game/max_player_inactivity_time").toInt();
    
    maxUsersPerAddress = settings->value("security/max_users_per_address").toInt();
    messageCountingInterval = settings->value("security/message_counting_interval").toInt();
    maxMessageCountPerInterval = settings->value("security/max_message_count_per_interval").toInt();
    maxMessageSizePerInterval = settings->value("security/max_message_size_per_interval").toInt();
    maxGamesPerUser = settings->value("security/max_games_per_user").toInt();

	try { if (settings->value("servernetwork/active", 0).toInt()) {
		qDebug() << "Connecting to ISL network.";
		const QString certFileName = settings->value("servernetwork/ssl_cert").toString();
		const QString keyFileName = settings->value("servernetwork/ssl_key").toString();
		qDebug() << "Loading certificate...";
		QFile certFile(certFileName);
		if (!certFile.open(QIODevice::ReadOnly))
			throw QString("Error opening certificate file: %1").arg(certFileName);
		QSslCertificate cert(&certFile);
#if QT_VERSION < 0x050000
		if (!cert.isValid())
			throw(QString("Invalid certificate."));
#else
		const QDateTime currentTime = QDateTime::currentDateTime();
		if(currentTime < cert.effectiveDate() ||
			currentTime > cert.expiryDate() ||
			cert.isBlacklisted())
			throw(QString("Invalid certificate."));
#endif
		qDebug() << "Loading private key...";
		QFile keyFile(keyFileName);
		if (!keyFile.open(QIODevice::ReadOnly))
			throw QString("Error opening private key file: %1").arg(keyFileName);
		QSslKey key(&keyFile, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey);
		if (key.isNull())
			throw QString("Invalid private key.");
		
		QMutableListIterator<ServerProperties> serverIterator(serverList);
		while (serverIterator.hasNext()) {
			const ServerProperties &prop = serverIterator.next();
			if (prop.cert == cert) {
				serverIterator.remove();
				continue;
			}
			
			QThread *thread = new QThread;
			thread->setObjectName("isl_" + QString::number(prop.id));
			connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
			
			IslInterface *interface = new IslInterface(prop.id, prop.hostname, prop.address.toString(), prop.controlPort, prop.cert, cert, key, this);
			interface->moveToThread(thread);
			connect(interface, SIGNAL(destroyed()), thread, SLOT(quit()));
			
			thread->start();
			QMetaObject::invokeMethod(interface, "initClient", Qt::BlockingQueuedConnection);
		}
			
		const int networkPort = settings->value("servernetwork/port", 14747).toInt();
		qDebug() << "Starting ISL server on port" << networkPort;
		
		islServer = new Servatrice_IslServer(this, cert, key, this);
		if (islServer->listen(QHostAddress::Any, networkPort))
			qDebug() << "ISL server listening.";
		else
			throw QString("islServer->listen()");
	} } catch (QString error) {
		qDebug() << "ERROR --" << error;
		return false;
	}
	
	pingClock = new QTimer(this);
	connect(pingClock, SIGNAL(timeout()), this, SIGNAL(pingClockTimeout()));
	pingClock->start(1000);
	
	int statusUpdateTime = settings->value("server/statusupdate").toInt();
	statusUpdateClock = new QTimer(this);
	connect(statusUpdateClock, SIGNAL(timeout()), this, SLOT(statusUpdate()));
	if (statusUpdateTime != 0) {
		qDebug() << "Starting status update clock, interval " << statusUpdateTime << " ms";
		statusUpdateClock->start(statusUpdateTime);
	}
	
	const int numberPools = settings->value("server/number_pools", 1).toInt();
	gameServer = new Servatrice_GameServer(this, numberPools, servatriceDatabaseInterface->getDatabase(), this);
	gameServer->setMaxPendingConnections(1000);
	const int gamePort = settings->value("server/port", 4747).toInt();
	qDebug() << "Starting server on port" << gamePort;
	if (gameServer->listen(QHostAddress::Any, gamePort))
		qDebug() << "Server listening.";
	else {
		qDebug() << "gameServer->listen(): Error.";
		return false;
	}
	return true;
}
Exemple #17
0
AccountEditWidget *GaduProtocolFactory::newEditAccountWidget(Account account, QWidget *parent)
{
    auto result = m_pluginInjectedFactory->makeInjected<GaduEditAccountWidget>(m_gaduServersManager, account, parent);
    connect(this, SIGNAL(destroyed()), result, SLOT(deleteLater()));
    return result;
}
Exemple #18
0
	void menu_item_widget::init()
	{
		set_margins(neogfx::margins{});
		iLayout.set_margins(neogfx::margins{ iGap, 0.0, iGap * (iMenu.type() == i_menu::Popup ? 2.0 : 1.0), 0.0 });
		iLayout.set_spacing(size{ iGap, 0.0 });
		if (iMenu.type() == i_menu::Popup)
			iIcon.set_fixed_size(size{ iIconSize, iIconSize });
		else
			iIcon.set_fixed_size(size{});
		iSpacer.set_minimum_size(size{ 0.0, 0.0 });
		auto text_updated = [this]()
		{
			auto m = mnemonic_from_text(iText.text());
			if (!m.empty())
				app::instance().add_mnemonic(*this);
			else
				app::instance().remove_mnemonic(*this);
		};
		iText.text_changed(text_updated, this);
		text_updated();
		if (iMenuItem.type() == i_menu_item::Action)
		{
			auto action_changed = [this]()
			{
				iIcon.set_image(iMenuItem.action().is_unchecked() ? iMenuItem.action().image() : iMenuItem.action().checked_image());
				if (!iIcon.image().is_empty())
					iIcon.set_fixed_size(size{ iIconSize, iIconSize });
				else if (iMenu.type() == i_menu::MenuBar)
					iIcon.set_fixed_size(size{});
				iText.set_text(iMenuItem.action().menu_text());
				if (iMenu.type() != i_menu::MenuBar)
					iShortcutText.set_text(iMenuItem.action().shortcut() != boost::none ? iMenuItem.action().shortcut()->as_text() : std::string());
				iSpacer.set_minimum_size(size{ iMenuItem.action().shortcut() != boost::none && iMenu.type() != i_menu::MenuBar ? iGap * 2.0 : 0.0, 0.0 });
				enable(iMenuItem.action().is_enabled());
			};
			iMenuItem.action().changed(action_changed, this);
			iMenuItem.action().checked(action_changed, this);
			iMenuItem.action().unchecked(action_changed, this);
			iMenuItem.action().enabled(action_changed, this);
			iMenuItem.action().disabled(action_changed, this);
			action_changed();
		}
		else
		{
			iMenuItem.sub_menu().opened([this]() {update(); }, this);
			iMenuItem.sub_menu().closed([this]() {update(); }, this);
			auto menu_changed = [this]() 
			{ 
				iIcon.set_image(iMenuItem.sub_menu().image());
				iText.set_text(iMenuItem.sub_menu().title());
			};
			iMenuItem.sub_menu().menu_changed(menu_changed, this);
			menu_changed();
		}
		iMenuItem.selected([this]()
		{
			if (iMenuItem.type() == i_menu_item::SubMenu && iMenu.type() == i_menu::Popup)
			{
				iSubMenuOpener = std::make_unique<neolib::callback_timer>(app::instance(), [this](neolib::callback_timer&)
				{
					if (!iMenuItem.sub_menu().is_open())
					{
						destroyed_flag destroyed(*this);
						iMenu.open_sub_menu.trigger(iMenuItem.sub_menu());
						if (!destroyed)
							update();
					}
				}, 250);
			}
		}, this);
		iMenuItem.deselected([this]()
		{
			iSubMenuOpener.reset();
		}, this);
	}
Exemple #19
0
AccountAddWidget *GaduProtocolFactory::newAddAccountWidget(bool showButtons, QWidget *parent)
{
    auto result = m_pluginInjectedFactory->makeInjected<GaduAddAccountWidget>(showButtons, parent);
    connect(this, SIGNAL(destroyed()), result, SLOT(deleteLater()));
    return result;
}
Exemple #20
0
void GLC_Context::openGLContextDestroyed()
{
    m_ContextSharedData.clear();
    emit destroyed(this);
}
Exemple #21
0
void ScriptableWorker::run()
{
    if ( hasLogLevel(LogDebug) ) {
        bool isEval = m_args.length() == Arguments::Rest + 2
                && m_args.at(Arguments::Rest) == "eval";

        for (int i = Arguments::Rest + (isEval ? 1 : 0); i < m_args.length(); ++i) {
            QString indent = isEval ? QString("EVAL:")
                                    : (QString::number(i - Arguments::Rest + 1) + " ");
            foreach (const QByteArray &line, m_args.at(i).split('\n')) {
                SCRIPT_LOG( indent + getTextData(line) );
                indent = "  ";
            }
        }
    }

    bool hasData;
    const quintptr id = m_args.at(Arguments::ActionId).toULongLong(&hasData);
    QVariantMap data;
    if (hasData)
        data = Action::data(id);

    const QString currentPath = getTextData(m_args.at(Arguments::CurrentPath));

    QScriptEngine engine;
    ScriptableProxy proxy(m_wnd, data);
    Scriptable scriptable(&proxy);
    scriptable.initEngine(&engine, currentPath, data);

    if (m_socket) {
        QObject::connect( proxy.signaler(), SIGNAL(sendMessage(QByteArray,int)),
                          m_socket, SLOT(sendMessage(QByteArray,int)) );

        QObject::connect( &scriptable, SIGNAL(sendMessage(QByteArray,int)),
                          m_socket, SLOT(sendMessage(QByteArray,int)) );
        QObject::connect( m_socket, SIGNAL(messageReceived(QByteArray,int)),
                          &scriptable, SLOT(setInput(QByteArray)) );

        QObject::connect( m_socket, SIGNAL(disconnected()),
                          &scriptable, SLOT(abort()) );
        QObject::connect( &scriptable, SIGNAL(destroyed()),
                          m_socket, SLOT(deleteAfterDisconnected()) );

        if ( m_socket->isClosed() ) {
            SCRIPT_LOG("TERMINATED");
            return;
        }

        m_socket->start();
    }

    QObject::connect( &scriptable, SIGNAL(requestApplicationQuit()),
                      qApp, SLOT(quit()) );

    QByteArray response;
    int exitCode;

    if ( m_args.length() <= Arguments::Rest ) {
        SCRIPT_LOG("Error: bad command syntax");
        exitCode = CommandBadSyntax;
    } else {
        const QString cmd = getTextData( m_args.at(Arguments::Rest) );

#ifdef HAS_TESTS
        if ( cmd == "flush" && m_args.length() == Arguments::Rest + 2 ) {
            log( "flush ID: " + getTextData(m_args.at(Arguments::Rest + 1)), LogAlways );
            scriptable.sendMessageToClient(QByteArray(), CommandFinished);
            return;
        }
#endif

        QScriptValue fn = engine.globalObject().property(cmd);
        if ( !fn.isFunction() ) {
            SCRIPT_LOG("Error: unknown command");
            const QString msg =
                    Scriptable::tr("Name \"%1\" doesn't refer to a function.").arg(cmd);
            response = createLogMessage(msg, LogError).toUtf8();
            exitCode = CommandError;
        } else {
            /* Special arguments:
             * "-"  read this argument from stdin
             * "--" read all following arguments without control sequences
             */
            QScriptValueList fnArgs;
            bool readRaw = false;
            for ( int i = Arguments::Rest + 1; i < m_args.length(); ++i ) {
                const QByteArray &arg = m_args.at(i);
                if (!readRaw && arg == "--") {
                    readRaw = true;
                } else {
                    const QScriptValue value = readRaw || arg != "-"
                            ? scriptable.newByteArray(arg)
                            : scriptable.input();
                    fnArgs.append(value);
                }
            }

            engine.evaluate(m_pluginScript);
            QScriptValue result = fn.call(QScriptValue(), fnArgs);

            if ( engine.hasUncaughtException() ) {
                const QString exceptionText =
                        QString("%1\n--- backtrace ---\n%2\n--- end backtrace ---")
                        .arg( engine.uncaughtException().toString(),
                              engine.uncaughtExceptionBacktrace().join("\n") );

                SCRIPT_LOG( QString("Error: Exception in command \"%1\": %2")
                             .arg(cmd, exceptionText) );

                response = createLogMessage(exceptionText, LogError).toUtf8();
                exitCode = CommandError;
            } else {
                response = serializeScriptValue(result);
                exitCode = CommandFinished;
            }
        }
    }

    if (exitCode == CommandFinished && hasData)
        Action::setData(id, scriptable.data());

    scriptable.sendMessageToClient(response, exitCode);

    SCRIPT_LOG("DONE");
}
Exemple #22
0
Database::~Database()
{
    Database::removeDatabase(this);
    emit destroyed(this);
}
void PluginCreator::runClicked()
      {
      log->clear();
      QQmlEngine* qml = Ms::MScore::qml();
      connect(qml, SIGNAL(warnings(const QList<QQmlError>&)),
         SLOT(qmlWarnings(const QList<QQmlError>&)));

      item = 0;
      QQmlComponent component(qml);
      component.setData(textEdit->toPlainText().toUtf8(), QUrl());
      QObject* obj = component.create();
      if (obj == 0) {
            msg("creating component failed\n");
            foreach(QQmlError e, component.errors())
                  msg(QString("   line %1: %2\n").arg(e.line()).arg(e.description()));
            stop->setEnabled(false);
            return;
            }
      qInstallMsgHandler(qmlMsgHandler);
      stop->setEnabled(true);
      run->setEnabled(false);

      item = qobject_cast<QmlPlugin*>(obj);

      if (item->pluginType() == "dock" || item->pluginType() == "dialog") {
            view = new QQuickView(qml, 0);
            view->setTitle(item->menuPath().mid(item->menuPath().lastIndexOf(".") + 1));
            view->setColor(QApplication::palette().color(QPalette::Window));
            view->setResizeMode(QQuickView::SizeRootObjectToView);
            view->setWidth(item->width());
            view->setHeight(item->height());
            item->setParentItem(view->contentItem());

            if (item->pluginType() == "dock") {
                  dock = new QDockWidget("Plugin", 0);
                  dock->setAttribute(Qt::WA_DeleteOnClose);
                  dock->setWidget(QWidget::createWindowContainer(view));
                  dock->widget()->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
                  Qt::DockWidgetArea area = Qt::RightDockWidgetArea;
                  if (item->dockArea() == "left")
                        area = Qt::LeftDockWidgetArea;
                  else if (item->dockArea() == "top")
                        area = Qt::TopDockWidgetArea;
                  else if (item->dockArea() == "bottom")
                        area = Qt::BottomDockWidgetArea;
                  addDockWidget(area, dock);
                  connect(dock, SIGNAL(destroyed()), SLOT(closePlugin()));
                  dock->widget()->setAttribute(Qt::WA_DeleteOnClose);
                  }
            view->show();
            view->raise();
            connect(view, SIGNAL(destroyed()), SLOT(closePlugin()));
            }

      connect(qml,  SIGNAL(quit()), SLOT(closePlugin()));

      if (mscore->currentScore() && item->pluginType() != "dock")
            mscore->currentScore()->startCmd();
      item->runPlugin();
      if (mscore->currentScore() && item->pluginType() != "dock")
            mscore->currentScore()->endCmd();
      mscore->endCmd();
      }
Exemple #24
0
bool BreEnemy::takeDamage(sf::Vector2f position, int damageType, int damageAmount)
{
    if (damageType >= 0)
        return false;
    if (invulnerability > 0)
        return true;

    if (state != BS_FlyIn)
    {
        if (shieldStrength > 0)
        {
            shieldStrength -= damageAmount;
            damageAmount = 0;
            if (shieldStrength <= 0)
            {
                setCollisionRadius(50);
                damageAmount = -shieldStrength;
                shieldStrength = 0;
            }
        }
        shieldCharge = 0.0;
        health -= damageAmount;
    }
    if (health < maxHealth / 2 && !moneyshieldDeployed)
    {
        moneyshieldDeployed = true;
        P<Transmission> t = new Transmission();
        t->setText("Deploying corperate|money shield");
        t->top();
        
        if (difficulty < 2)
        {
            for(float f=0; f<=360; f+=20)
            {
                new MoneyShield(this, f, 100, false);
                new MoneyShield(this, f, 80, true);
            }
        }else{
            for(float f=0; f<=360; f+=20)
            {
                new MoneyShield(this, f, 110, false);
                new MoneyShield(this, f, 90, true);
                new MoneyShield(this, f, 70, false);
            }
        }
    }

    if (health <= 0)
    {
        health = 0;
        destroy();
        destroyed();
        for(unsigned int n=0; n<4; n++)
        {
            new BreDeath(getPosition(), n);
        }
        foreach(BasicEnemyBase, e, enemyList)
            e->destroy();
        P<ScoreManager>(engine->getObject("score"))->add(500);
        if (difficulty > 1)
            P<ScoreManager>(engine->getObject("score"))->add(200);
        for(unsigned int n=0; n<30; n++)
            new Explosion(sprite.getPosition() + sf::Vector2f(random(-60, 60), random(-80, 80)), 15);
    }
    invulnerability = 0.10;
    return true;
}
QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWidget *parent, Qt::WindowFlags flags )
    : QDialog( parent, flags )
    , mDock( nullptr )
    , mLayer( theLayer )
    , mRubberBand( nullptr )
    , mCurrentSearchWidgetWrapper( nullptr )
{
  setupUi( this );

  // Fix selection color on loosing focus (Windows)
  setStyleSheet( QgisApp::instance()->styleSheet() );

  setAttribute( Qt::WA_DeleteOnClose );

  QSettings settings;

  // Initialize the window geometry
  restoreGeometry( settings.value( "/Windows/BetterAttributeTable/geometry" ).toByteArray() );

  QgsAttributeEditorContext context;

  myDa = new QgsDistanceArea();

  myDa->setSourceCrs( mLayer->crs() );
  myDa->setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() );
  myDa->setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) );

  context.setDistanceArea( *myDa );
  context.setVectorLayerTools( QgisApp::instance()->vectorLayerTools() );

  QgsFeatureRequest r;
  if ( mLayer->geometryType() != QGis::NoGeometry &&
       settings.value( "/qgis/attributeTableBehaviour", QgsAttributeTableFilterModel::ShowAll ).toInt() == QgsAttributeTableFilterModel::ShowVisible )
  {
    QgsMapCanvas *mc = QgisApp::instance()->mapCanvas();
    QgsRectangle extent( mc->mapSettings().mapToLayerCoordinates( theLayer, mc->extent() ) );
    r.setFilterRect( extent );

    QgsGeometry *g = QgsGeometry::fromRect( extent );
    mRubberBand = new QgsRubberBand( mc, QGis::Polygon );
    mRubberBand->setToGeometry( g, theLayer );
    delete g;

    mActionShowAllFilter->setText( tr( "Show All Features In Initial Canvas Extent" ) );
  }

  // Initialize dual view
  mMainView->init( mLayer, QgisApp::instance()->mapCanvas(), r, context );

  // Initialize filter gui elements
  mFilterActionMapper = new QSignalMapper( this );
  mFilterColumnsMenu = new QMenu( this );
  mActionFilterColumnsMenu->setMenu( mFilterColumnsMenu );
  mApplyFilterButton->setDefaultAction( mActionApplyFilter );

  // Set filter icon in a couple of places
  QIcon filterIcon = QgsApplication::getThemeIcon( "/mActionFilter.svg" );
  mActionShowAllFilter->setIcon( filterIcon );
  mActionAdvancedFilter->setIcon( filterIcon );
  mActionSelectedFilter->setIcon( filterIcon );
  mActionVisibleFilter->setIcon( filterIcon );
  mActionEditedFilter->setIcon( filterIcon );

  // Connect filter signals
  connect( mActionAdvancedFilter, SIGNAL( triggered() ), SLOT( filterExpressionBuilder() ) );
  connect( mActionShowAllFilter, SIGNAL( triggered() ), SLOT( filterShowAll() ) );
  connect( mActionSelectedFilter, SIGNAL( triggered() ), SLOT( filterSelected() ) );
  connect( mActionVisibleFilter, SIGNAL( triggered() ), SLOT( filterVisible() ) );
  connect( mActionEditedFilter, SIGNAL( triggered() ), SLOT( filterEdited() ) );
  connect( mFilterActionMapper, SIGNAL( mapped( QObject* ) ), SLOT( filterColumnChanged( QObject* ) ) );
  connect( mFilterQuery, SIGNAL( returnPressed() ), SLOT( filterQueryAccepted() ) );
  connect( mActionApplyFilter, SIGNAL( triggered() ), SLOT( filterQueryAccepted() ) );
  connect( mSetStyles, SIGNAL( pressed() ), SLOT( openConditionalStyles() ) );

  // info from layer to table
  connect( mLayer, SIGNAL( editingStarted() ), this, SLOT( editingToggled() ) );
  connect( mLayer, SIGNAL( editingStopped() ), this, SLOT( editingToggled() ) );
  connect( mLayer, SIGNAL( layerDeleted() ), this, SLOT( close() ) );
  connect( mLayer, SIGNAL( selectionChanged() ), this, SLOT( updateTitle() ) );
  connect( mLayer, SIGNAL( featureAdded( QgsFeatureId ) ), this, SLOT( updateTitle() ) );
  connect( mLayer, SIGNAL( featuresDeleted( QgsFeatureIds ) ), this, SLOT( updateTitle() ) );
  connect( mLayer, SIGNAL( attributeAdded( int ) ), this, SLOT( columnBoxInit() ) );
  connect( mLayer, SIGNAL( attributeDeleted( int ) ), this, SLOT( columnBoxInit() ) );

  // connect table info to window
  connect( mMainView, SIGNAL( filterChanged() ), this, SLOT( updateTitle() ) );

  // info from table to application
  connect( this, SIGNAL( saveEdits( QgsMapLayer * ) ), QgisApp::instance(), SLOT( saveEdits( QgsMapLayer * ) ) );

  bool myDockFlag = settings.value( "/qgis/dockAttributeTable", false ).toBool();
  if ( myDockFlag )
  {
    mDock = new QgsAttributeTableDock( tr( "Attribute table - %1 (%n Feature(s))", "feature count", mMainView->featureCount() ).arg( mLayer->name() ), QgisApp::instance() );
    mDock->setAllowedAreas( Qt::BottomDockWidgetArea | Qt::TopDockWidgetArea );
    mDock->setWidget( this );
    connect( this, SIGNAL( destroyed() ), mDock, SLOT( close() ) );
    QgisApp::instance()->addDockWidget( Qt::BottomDockWidgetArea, mDock );
  }

  columnBoxInit();
  updateTitle();

  mRemoveSelectionButton->setIcon( QgsApplication::getThemeIcon( "/mActionUnselectAttributes.png" ) );
  mSelectedToTopButton->setIcon( QgsApplication::getThemeIcon( "/mActionSelectedToTop.png" ) );
  mCopySelectedRowsButton->setIcon( QgsApplication::getThemeIcon( "/mActionCopySelected.png" ) );
  mZoomMapToSelectedRowsButton->setIcon( QgsApplication::getThemeIcon( "/mActionZoomToSelected.svg" ) );
  mPanMapToSelectedRowsButton->setIcon( QgsApplication::getThemeIcon( "/mActionPanToSelected.svg" ) );
  mInvertSelectionButton->setIcon( QgsApplication::getThemeIcon( "/mActionInvertSelection.png" ) );
  mToggleEditingButton->setIcon( QgsApplication::getThemeIcon( "/mActionToggleEditing.svg" ) );
  mSaveEditsButton->setIcon( QgsApplication::getThemeIcon( "/mActionSaveEdits.svg" ) );
  mDeleteSelectedButton->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteSelected.svg" ) );
  mOpenFieldCalculator->setIcon( QgsApplication::getThemeIcon( "/mActionCalculateField.png" ) );
  mAddAttribute->setIcon( QgsApplication::getThemeIcon( "/mActionNewAttribute.png" ) );
  mRemoveAttribute->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteAttribute.png" ) );
  mTableViewButton->setIcon( QgsApplication::getThemeIcon( "/mActionOpenTable.png" ) );
  mAttributeViewButton->setIcon( QgsApplication::getThemeIcon( "/mActionPropertyItem.png" ) );
  mExpressionSelectButton->setIcon( QgsApplication::getThemeIcon( "/mIconExpressionSelect.svg" ) );
  mAddFeature->setIcon( QgsApplication::getThemeIcon( "/mActionNewTableRow.png" ) );

  // toggle editing
  bool canChangeAttributes = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeAttributeValues;
  bool canDeleteFeatures = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::DeleteFeatures;
  bool canAddAttributes = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::AddAttributes;
  bool canDeleteAttributes = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::DeleteAttributes;
  bool canAddFeatures = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::AddFeatures;

  mToggleEditingButton->blockSignals( true );
  mToggleEditingButton->setCheckable( true );
  mToggleEditingButton->setChecked( mLayer->isEditable() );
  mToggleEditingButton->setEnabled(( canChangeAttributes || canDeleteFeatures || canAddAttributes || canDeleteAttributes || canAddFeatures ) && !mLayer->isReadOnly() );
  mToggleEditingButton->blockSignals( false );

  mSaveEditsButton->setEnabled( mToggleEditingButton->isEnabled() && mLayer->isEditable() );
  mReloadButton->setEnabled( ! mLayer->isEditable() );
  mAddAttribute->setEnabled(( canChangeAttributes || canAddAttributes ) && mLayer->isEditable() );
  mDeleteSelectedButton->setEnabled( canDeleteFeatures && mLayer->isEditable() );
  mAddFeature->setEnabled( canAddFeatures && mLayer->isEditable() );
  mAddFeature->setHidden( !canAddFeatures );

  mMainViewButtonGroup->setId( mTableViewButton, QgsDualView::AttributeTable );
  mMainViewButtonGroup->setId( mAttributeViewButton, QgsDualView::AttributeEditor );

  // Load default attribute table filter
  QgsAttributeTableFilterModel::FilterMode defaultFilterMode = ( QgsAttributeTableFilterModel::FilterMode ) settings.value( "/qgis/attributeTableBehaviour", QgsAttributeTableFilterModel::ShowAll ).toInt();

  switch ( defaultFilterMode )
  {
    case QgsAttributeTableFilterModel::ShowVisible:
      filterVisible();
      break;

    case QgsAttributeTableFilterModel::ShowSelected:
      filterSelected();
      break;

    case QgsAttributeTableFilterModel::ShowAll:
    default:
      filterShowAll();
      break;
  }

  mUpdateExpressionText->registerGetExpressionContextCallback( &_getExpressionContext, mLayer );

  mFieldModel = new QgsFieldModel( this );
  mFieldModel->setLayer( mLayer );
  mFieldCombo->setModel( mFieldModel );
  connect( mRunFieldCalc, SIGNAL( clicked() ), this, SLOT( updateFieldFromExpression() ) );
  connect( mRunFieldCalcSelected, SIGNAL( clicked() ), this, SLOT( updateFieldFromExpressionSelected() ) );
  // NW TODO Fix in 2.6 - Doesn't work with field model for some reason.
//  connect( mUpdateExpressionText, SIGNAL( returnPressed() ), this, SLOT( updateFieldFromExpression() ) );
  connect( mUpdateExpressionText, SIGNAL( fieldChanged( QString, bool ) ), this, SLOT( updateButtonStatus( QString, bool ) ) );
  mUpdateExpressionText->setLayer( mLayer );
  mUpdateExpressionText->setLeftHandButtonStyle( true );

  mMainView->setView( QgsDualView::AttributeTable );

  editingToggled();
}
void ColumnPreferencesFrame::on_columnTreeWidget_itemActivated(QTreeWidgetItem *item, int column)
{
    if (!item || cur_line_edit_ || cur_combo_box_) return;

    QWidget *editor = NULL;
    cur_column_ = column;
    saved_combo_idx_ = item->data(type_col_, Qt::UserRole).toInt();

    switch (column) {
    case title_col_:
    {
        cur_line_edit_ = new QLineEdit();
        cur_column_ = column;
        saved_col_string_ = item->text(title_col_);
        connect(cur_line_edit_, SIGNAL(editingFinished()), this, SLOT(columnTitleEditingFinished()));
        editor = cur_line_edit_;
        break;
    }
    case type_col_:
    {
        cur_combo_box_ = new QComboBox();
        for (int i = 0; i < NUM_COL_FMTS; i++) {
            cur_combo_box_->addItem(col_format_desc(i), QVariant(i));
            if (i == saved_combo_idx_) {
                cur_combo_box_->setCurrentIndex(i);
            }
        }
        connect(cur_combo_box_, SIGNAL(currentIndexChanged(int)), this, SLOT(columnTypeCurrentIndexChanged(int)));
        editor = cur_combo_box_;
        break;
    }
    case custom_field_col_:
    {
        SyntaxLineEdit *syntax_edit = new SyntaxLineEdit();
        saved_col_string_ = item->text(custom_field_col_);
        connect(syntax_edit, SIGNAL(textChanged(QString)),
                syntax_edit, SLOT(checkFieldName(QString)));
        connect(syntax_edit, SIGNAL(editingFinished()), this, SLOT(customFieldEditingFinished()));
        editor = cur_line_edit_ = syntax_edit;

        saved_combo_idx_ = item->data(type_col_, Qt::UserRole).toInt();
        item->setText(type_col_, col_format_desc(COL_CUSTOM));
        item->setData(type_col_, Qt::UserRole, QVariant(COL_CUSTOM));
        break;
    }
    case custom_occurrence_col_:
    {
        SyntaxLineEdit *syntax_edit = new SyntaxLineEdit();
        saved_col_string_ = item->text(custom_occurrence_col_);
        connect(syntax_edit, SIGNAL(textChanged(QString)),
                this, SLOT(customOccurrenceTextChanged(QString)));
        connect(syntax_edit, SIGNAL(editingFinished()), this, SLOT(customOccurrenceEditingFinished()));
        editor = cur_line_edit_ = syntax_edit;

        saved_combo_idx_ = item->data(type_col_, Qt::UserRole).toInt();
        item->setText(type_col_, col_format_desc(COL_CUSTOM));
        item->setData(type_col_, Qt::UserRole, QVariant(COL_CUSTOM));
        break;
    }
    default:
        return;
    }

    if (cur_line_edit_) {
        cur_line_edit_->setText(saved_col_string_);
        cur_line_edit_->selectAll();
        connect(cur_line_edit_, SIGNAL(destroyed()), this, SLOT(lineEditDestroyed()));
    }
    if (cur_combo_box_) {
        connect(cur_combo_box_, SIGNAL(destroyed()), this, SLOT(comboDestroyed()));
    }
    if (editor) {
        QFrame *edit_frame = new QFrame();
        QHBoxLayout *hb = new QHBoxLayout();
        QSpacerItem *spacer = new QSpacerItem(5, 10);

        hb->addWidget(editor, 0);
        hb->addSpacerItem(spacer);
        hb->setStretch(1, 1);
        hb->setContentsMargins(0, 0, 0, 0);

        edit_frame->setLineWidth(0);
        edit_frame->setFrameStyle(QFrame::NoFrame);
        // The documentation suggests setting autoFillbackground. That looks silly
        // so we clear the item text instead.
        item->setText(cur_column_, "");
        edit_frame->setLayout(hb);
        ui->columnTreeWidget->setItemWidget(item, cur_column_, edit_frame);
        editor->setFocus();
    }
}
void ObjectEditorWidget::updateData(Object *obj)
{
    if (obj == mCurrentObject)
        return;

    if (mCurrentObject)
        mCurrentObject->disconnect(this);

    mCurrentObject = obj;
    if (! mCurrentObject)
        return;

    connect(mCurrentObject, SIGNAL(dataChanged(const QVariantMap&)), this, SLOT(onObjectDataChanged(const QVariantMap&)));
    connect(mCurrentObject, SIGNAL(destroyed()), this, SLOT(onCurrentObjectDestroyed()));

    mBorderColorButton->blockSignals(true);

    ////mChooseObjectComboBox->clear();
    mObjectsHierarchy.clear();

    if (mCurrentObject->resource()) {
        //mChooseObjectComboBox->addItem(mCurrentObject->resource()->objectName() + tr("(resource)"));
        mObjectsHierarchy.append(mCurrentObject->resource());
    }

    //mChooseObjectComboBox->addItem(mCurrentObject->objectName() + tr("(copy)"));
    mObjectsHierarchy.append(mCurrentObject);

    mBorderWidthSpinBox->setValue(mCurrentObject->borderWidth());
    mBorderColorButton->setColor(mCurrentObject->borderColor());
    mColorButton->setText(obj->backgroundColor().name());
    mColorButton->setColor(obj->backgroundColor());
    mOpacitySlider->setValue(obj->backgroundOpacity());
    mNameEdit->setText(mCurrentObject->objectName());
    mNameEdit->setStyleSheet("");
    mNameEdit->setEnabled(mCurrentObject->editableName());
    mXSpin->setRange(-mCurrentObject->width(), Scene::width());
    mXSpin->setValue(mCurrentObject->x());
    mYSpin->setRange(-mCurrentObject->height(), Scene::height());
    mYSpin->setValue(mCurrentObject->y());
    if (mCurrentObject->percentWidth())
        mWidthEditor->setText(QString::number(mCurrentObject->percentWidth()));
    else
        mWidthEditor->setText(QString::number(mCurrentObject->width()));
    if (mCurrentObject->percentWidth())
        mHeightEditor->setText(QString::number(mCurrentObject->percentHeight()));
    else
        mHeightEditor->setText(QString::number(mCurrentObject->height()));


    QList<Action*> actions;
    QObject *object;

    mMousePressComboBox->clear();
    actions = mCurrentObject->actionsForEvent(Interaction::MousePress);
    for(int i=0; i < actions.size(); i++) {
        object = actions[i];
        mMousePressComboBox->addItem(actions[i]->icon(), actions[i]->toString(), qVariantFromValue(object));
    }

    mMouseReleaseComboBox->clear();
    actions = mCurrentObject->actionsForEvent(Interaction::MouseRelease);
    for(int i=0; i < actions.size(); i++) {
        object = actions[i];
        mMouseReleaseComboBox->addItem(actions[i]->icon(), actions[i]->toString(), qVariantFromValue(object));
    }

    mMouseMoveComboBox->clear();
    actions = mCurrentObject->actionsForEvent(Interaction::MouseMove);
    for(int i=0; i < actions.size(); i++) {
        object = actions[i];
        mMouseMoveComboBox->addItem(actions[i]->icon(), actions[i]->toString(), qVariantFromValue(object));
    }

    mRoundedRectCheckBox->setChecked(mCurrentObject->roundedRect());
    mXRadiusSpinBox->setValue(mCurrentObject->xRadius());
    mYRadiusSpinBox->setValue(mCurrentObject->yRadius());

    mVisibleCheckbox->setChecked(mCurrentObject->visible());

    mBorderColorButton->blockSignals(false);

}
Exemple #28
0
/*virtual*/
void AbstractItemView::setModel(QAbstractItemModel *model, AbstractViewItem *prototype)
{
    if( m_model == model || !model)
        return;

    if (m_model) {
        disconnect(m_model, SIGNAL(destroyed()),
                   this, SLOT(_q_modelDestroyed()));
        disconnect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
                   this, SLOT( dataChanged(QModelIndex,QModelIndex)));
        disconnect(m_model, SIGNAL(rowsInserted(QModelIndex,int,int)),
                   this, SLOT(rowsInserted(QModelIndex,int,int)));
        disconnect(m_model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
                   this, SLOT(rowsRemoved(QModelIndex,int,int)));
        disconnect(m_model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
                   this, SLOT(rowsAboutToBeRemoved(QModelIndex,int,int)));
        disconnect(m_model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
                   this, SLOT(rowsAboutToBeInserted(QModelIndex,int,int)));
        disconnect(m_model, SIGNAL(columnsInserted(QModelIndex,int,int)),
                   this, SLOT(columnsInserted(QModelIndex,int,int)));
        disconnect(m_model, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
                   this, SLOT(columnsAboutToBeInserted(QModelIndex,int,int)));
        disconnect(m_model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
                   this, SLOT(columnsRemoved(QModelIndex,int,int)));
        disconnect(m_model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
                   this, SLOT(columnsAboutToBeRemoved(QModelIndex,int,int)));
        disconnect(m_model, SIGNAL(modelReset()), this, SLOT(reset()));
        disconnect(m_model, SIGNAL(layoutChanged()), this, SLOT(_q_layoutChanged()));

        m_model = 0;
    }

    setSelectionModel(0);

    m_currentIndex = QModelIndex();
    m_rootIndex = QModelIndex();

    m_model = model;

    Q_ASSERT_X(m_model->index(0,0) == m_model->index(0,0),
               "AbstractItemView::setModel",
               "A model should return the exact same index "
               "(including its internal id/pointer) when asked for it twice in a row.");
    Q_ASSERT_X(m_model->index(0,0).parent() == QModelIndex(),
               "AbstractItemView::setModel",
               "The parent of a top level index should be invalid");


    connect(m_model, SIGNAL(destroyed()), this, SLOT(modelDestroyed()));
    connect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
            this, SLOT( dataChanged(QModelIndex,QModelIndex)));
    connect(m_model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
            this, SLOT(rowsAboutToBeInserted(QModelIndex,int,int)));
    connect(m_model, SIGNAL(rowsInserted(QModelIndex,int,int)),
            this, SLOT(rowsInserted(QModelIndex,int,int)));
    connect(m_model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
            this, SLOT(rowsAboutToBeRemoved(QModelIndex,int,int)));
    connect(m_model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
            this, SLOT(rowsRemoved(QModelIndex,int,int)));
    connect(m_model, SIGNAL(modelReset()), this, SLOT(reset()));
    connect(m_model, SIGNAL(layoutChanged()), this, SLOT(layoutChanged()));

    setSelectionModel(new QItemSelectionModel(m_model));

    if (prototype && m_container) {
        m_container->setItemPrototype(prototype);
        m_container->reset();
    }
}
Exemple #29
0
QHostInfoLookupManager::QHostInfoLookupManager() : mutex(QMutex::Recursive), wasDeleted(false)
{
    moveToThread(QCoreApplicationPrivate::mainThread());
    connect(QCoreApplication::instance(), SIGNAL(destroyed()), SLOT(waitForThreadPoolDone()), Qt::DirectConnection);
    threadPool.setMaxThreadCount(5); // do 5 DNS lookups in parallel
}
Exemple #30
0
void MainWindow::overallStatistics()
{
    QuestionItem *q_item;
    QTableWidgetItem *tw_item;
    QWidget *stats_widget = new QWidget(this, Qt::Dialog /*| Qt::WindowMaximizeButtonHint*/);
    stats_widget->setWindowModality(Qt::WindowModal);
    stats_widget->setAttribute(Qt::WA_DeleteOnClose);
#ifdef Q_OS_MAC
    stats_widget->setWindowTitle(tr("%1 - Overall statistics").arg(currentDatabaseName()));
#else
    stats_widget->setWindowTitle(tr("%1 - Overall statistics - iTest").arg(currentDatabaseName()));
#endif
    stats_widget->setMinimumSize(QSize(300, 200));
    QGridLayout *stats_glayout = new QGridLayout(stats_widget);
    QLabel *stats_label = new QLabel(stats_widget);
    stats_glayout->addWidget(stats_label, 0, 0);
    QHBoxLayout *stats_hlayout_search = new QHBoxLayout(stats_widget);
    QLabel *stats_label_search = new QLabel(stats_widget);
    stats_label_search->setText(tr("Search:"));
    stats_hlayout_search->addWidget(stats_label_search);
    ExtendedLineEdit *stats_search = new ExtendedLineEdit(stats_widget);
    stats_hlayout_search->addWidget(stats_search);
    stats_glayout->addLayout(stats_hlayout_search, 1, 0);
    stats_tw = new MTTableWidget(stats_widget);
    QObject::connect(stats_search, SIGNAL(textChanged(QLineEdit *, const QString &)), stats_tw, SLOT(filterItems(QLineEdit *, const QString &)));
    stats_glayout->addWidget(stats_tw, 2, 0);
    QHBoxLayout *stats_hlayout = new QHBoxLayout(stats_widget);
    stats_hlayout->setMargin(0); stats_hlayout->setSpacing(6);
    stats_hlayout->addStretch();
    stats_btn_adjustall = new QPushButton (tr("Adjust all"), stats_widget);
    QObject::connect(stats_btn_adjustall, SIGNAL(released()), this, SLOT(statsAdjustAll()));
    stats_btn_adjustall->setEnabled(false);
    stats_hlayout->addWidget(stats_btn_adjustall);
    QPushButton *stats_btn_close = new QPushButton (tr("Close"), stats_widget);
    QObject::connect(stats_btn_close, SIGNAL(released()), stats_widget, SLOT(close()));
    QObject::connect(stats_widget, SIGNAL(destroyed()), this, SLOT(statsWidgetClosed()));
    stats_hlayout->addWidget(stats_btn_close);
    stats_glayout->addLayout(stats_hlayout, 3, 0);
    stats_glayout->setMargin(6); stats_glayout->setSpacing(6);
    btngrpStatsAdjust = new QButtonGroup(stats_widget);
    QObject::connect(btngrpStatsAdjust, SIGNAL(buttonReleased(QAbstractButton *)), this, SLOT(statsAdjust(QAbstractButton *)));
    int rows = 0;
    int row = 0;
    for (int i = 0; i < LQListWidget->count(); ++i) {
        if (current_db_questions.value(LQListWidget->item(i))->recommendedDifficulty() != -1) {
            rows++;
        }
    }
    stats_label->setText(tr("<b>%1 questions with statistics found</b>").arg(rows));
    if (rows == 0) {
        stats_widget->show();
        return;
    }
    stats_tw->setRowCount(rows);
    stats_tw->setColumnCount(6);
    tw_item = new QTableWidgetItem(tr("Question name"));
    stats_tw->setHorizontalHeaderItem(0, tw_item);
    tw_item = new QTableWidgetItem(tr("Difficulty"));
    stats_tw->setHorizontalHeaderItem(1, tw_item);
    tw_item = new QTableWidgetItem(tr("Calculated difficulty"));
    stats_tw->setHorizontalHeaderItem(2, tw_item);
    tw_item = new QTableWidgetItem(tr("Number of correct answers"));
    stats_tw->setHorizontalHeaderItem(3, tw_item);
    tw_item = new QTableWidgetItem(tr("Number of incorrect answers"));
    stats_tw->setHorizontalHeaderItem(4, tw_item);
    tw_item = new QTableWidgetItem(tr("Adjust difficulty"));
    stats_tw->setHorizontalHeaderItem(5, tw_item);
    stats_tw->verticalHeader()->hide();
    QFont font; font.setBold(true);
    for (int i = 0; i < LQListWidget->count(); ++i) {
        q_item = current_db_questions.value(LQListWidget->item(i));
        if (q_item->recommendedDifficulty() == -1)
            continue;
        tw_item = new QTableWidgetItem(q_item->group().isEmpty() ? q_item->name() : QString("[%1] %2").arg(q_item->group()).arg(q_item->name()));
        tw_item->setBackground(QBrush(backgroundColourForCategory(q_item->category())));
        tw_item->setForeground(QBrush(foregroundColourForCategory(q_item->category())));
        tw_item->setFont(font);
        stats_tw->setItem(row, 0, tw_item);
        tw_item = new QTableWidgetItem;
        switch (q_item->difficulty()) {
            case -1: tw_item->setText(tr("Unknown")); break;
            case 0: tw_item->setText(tr("Easy"));
                tw_item->setBackground(QBrush(QColor(197, 255, 120)));
                tw_item->setForeground(QBrush(QColor(0, 0, 0)));
                break;
            case 1: tw_item->setText(tr("Medium"));
                tw_item->setBackground(QBrush(QColor(255, 251, 0)));
                tw_item->setForeground(QBrush(QColor(0, 0, 0)));
                break;
            case 2: tw_item->setText(tr("Difficult"));
                tw_item->setBackground(QBrush(QColor(204, 109, 0)));
                tw_item->setForeground(QBrush(QColor(0, 0, 0)));
                break;
            default: tw_item->setText(tr("Unknown")); break;
        }
        stats_tw->setItem(row, 1, tw_item);
        tw_item = new QTableWidgetItem;
        switch (q_item->recommendedDifficulty()) {
            case -1: tw_item->setText(tr("Unknown")); break;
            case 0: tw_item->setText(tr("Easy"));
                tw_item->setBackground(QBrush(QColor(197, 255, 120)));
                tw_item->setForeground(QBrush(QColor(0, 0, 0)));
                break;
            case 1: tw_item->setText(tr("Medium"));
                tw_item->setBackground(QBrush(QColor(255, 251, 0)));
                tw_item->setForeground(QBrush(QColor(0, 0, 0)));
                break;
            case 2: tw_item->setText(tr("Difficult"));
                tw_item->setBackground(QBrush(QColor(204, 109, 0)));
                tw_item->setForeground(QBrush(QColor(0, 0, 0)));
                break;
            default: tw_item->setText(tr("Unknown")); break;
        }
        stats_tw->setItem(row, 2, tw_item);
        tw_item = new QTableWidgetItem(QString::number(q_item->correctAnsCount()));
        tw_item->setFont(font); tw_item->setForeground(QBrush(QColor(92, 163, 0)));
        stats_tw->setItem(row, 3, tw_item);
        tw_item = new QTableWidgetItem(QString::number(q_item->incorrectAnsCount()));
        tw_item->setFont(font); tw_item->setForeground(QBrush(QColor(204, 109, 0)));
        stats_tw->setItem(row, 4, tw_item);
        tw_item = new QTableWidgetItem;
        QPushButton *stats_btn_adjust = new QPushButton(tr("Adjust difficulty"), stats_tw);
        stats_tw->setCellWidget(row, 5, stats_btn_adjust);
        stats_btn_adjust->setEnabled(false);
        stats_qmap.insert(stats_btn_adjust, q_item);
        stats_twmap.insert(stats_btn_adjust, row);
        stats_lwmap.insert(stats_btn_adjust, i);
        btngrpStatsAdjust->addButton(stats_btn_adjust);
        if (q_item->difficulty() != q_item->recommendedDifficulty()) {
            stats_btn_adjustall->setEnabled(true);
            stats_btn_adjust->setEnabled(true);
        }
        row++;
    }
    stats_tw->resizeColumnsToContents(); stats_tw->resizeRowsToContents();
    stats_widget->resize(stats_tw->columnWidth(0) + stats_tw->columnWidth(1) + stats_tw->columnWidth(2) + stats_tw->columnWidth(3) + stats_tw->columnWidth(4) + stats_tw->columnWidth(5) + 40, 400);
    stats_widget->show();
}