void MScenePrivate::onDisplayChangeEvent(MOnDisplayChangeEvent *event)
{
    Q_Q(MScene);

    if (event->state() == MOnDisplayChangeEvent::FullyOnDisplay ||
            event->state() == MOnDisplayChangeEvent::FullyOffDisplay) {
        // Simple cases. Just forward the event as it is.
        sendEventToMWidgets(filterMWidgets(q->items()), event);
        return;
    }

    QList<MWidget *> fullyOnWidgets;
    QList<MWidget *> partiallyOnWidgets;
    QList<MWidget *> fullyOffWidgets;

    QList<MWidget *> intersectingWidgets = filterMWidgets(q->items(event->viewRect(),
            Qt::IntersectsItemBoundingRect));

    QList<MWidget *> allWidgets = filterMWidgets(q->items());

    // Find who is fully on, partially on and fully off

    QSet<MWidget *> fullyOffWidgetsSet = allWidgets.toSet().subtract(intersectingWidgets.toSet());
    fullyOffWidgets = fullyOffWidgetsSet.toList();

    int intersectingWidgetsCount = intersectingWidgets.count();
    MWidget *widget;
    for (int i = 0; i < intersectingWidgetsCount; i++) {
        widget = intersectingWidgets.at(i);
        if (event->viewRect().contains(widget->sceneBoundingRect())) {
            fullyOnWidgets << widget;
        } else {
            partiallyOnWidgets << widget;
        }
    }

    // Send the events to the corresponding MWidgets

    if (fullyOnWidgets.count() > 0) {
        MOnDisplayChangeEvent fullyOnEvent(MOnDisplayChangeEvent::FullyOnDisplay,
                                             event->viewRect());

        sendEventToMWidgets(fullyOnWidgets, &fullyOnEvent);
    }

    if (fullyOffWidgets.count() > 0) {
        MOnDisplayChangeEvent fullyOffEvent(MOnDisplayChangeEvent::FullyOffDisplay,
                                              event->viewRect());

        sendEventToMWidgets(fullyOffWidgets, &fullyOffEvent);
    }

    if (partiallyOnWidgets.count() > 0) {
        MOnDisplayChangeEvent partiallyOnEvent(MOnDisplayChangeEvent::PartiallyOnDisplay,
                event->viewRect());

        sendEventToMWidgets(partiallyOnWidgets, &partiallyOnEvent);
    }

}
void AutoProfileWatcher::clearProfileAssignments()
{
    QSet<AutoProfileInfo*> terminateProfiles;

    QListIterator<QList<AutoProfileInfo*> > iterDelete(appProfileAssignments.values());
    while (iterDelete.hasNext())
    {
        QList<AutoProfileInfo*> templist = iterDelete.next();
        terminateProfiles.unite(templist.toSet());
    }
    appProfileAssignments.clear();

    QListIterator<QList<AutoProfileInfo*> > iterClassDelete(windowClassProfileAssignments.values());
    while (iterClassDelete.hasNext())
    {
        QList<AutoProfileInfo*> templist = iterClassDelete.next();
        terminateProfiles.unite(templist.toSet());
    }
    windowClassProfileAssignments.clear();

    QListIterator<QList<AutoProfileInfo*> > iterNameDelete(windowNameProfileAssignments.values());
    while (iterNameDelete.hasNext())
    {
        QList<AutoProfileInfo*> templist = iterNameDelete.next();
        terminateProfiles.unite(templist.toSet());
    }
    windowNameProfileAssignments.clear();

    QSetIterator<AutoProfileInfo*> iterTerminate(terminateProfiles);
    while (iterTerminate.hasNext())
    {
        AutoProfileInfo *info = iterTerminate.next();
        if (info)
        {
            delete info;
            info = 0;
        }
    }

    QListIterator<AutoProfileInfo*> iterDefaultsDelete(defaultProfileAssignments.values());
    while (iterDefaultsDelete.hasNext())
    {
        AutoProfileInfo *info = iterDefaultsDelete.next();
        if (info)
        {
            delete info;
            info = 0;
        }
    }
    defaultProfileAssignments.clear();

    allDefaultInfo = 0;
    guidSet.clear();
}
Example #3
0
void AnchorTool::itemsAboutToRemoved(const QList<FormEditorItem*> &removedItems)
{
    QList<FormEditorItem*> newItemList = items().toSet().subtract(removedItems.toSet()).toList();
    setItems(newItemList);
    m_anchorIndicator.setItems(newItemList);
    m_anchorLineIndicator.clear();
}
Example #4
0
    void shouldCallHandlersWithJob()
    {
        // GIVEN
        int callCount = 0;
        QList<KJob*> seenJobs;

        auto handlerWithJob = [&](KJob *job) {
            callCount++;
            seenJobs << job;
        };

        FakeJob *job1 = new FakeJob(this);
        FakeJob *job2 = new FakeJob(this);
        CompositeJob *compositeJob = new CompositeJob(this);
        compositeJob->setAutoDelete(false);
        QVERIFY(compositeJob->install(job1, handlerWithJob));
        QVERIFY(compositeJob->install(job2, handlerWithJob));

        // WHEN
        compositeJob->start();
        QTest::qWait(FakeJob::DURATION + 10);

        // THEN
        QCOMPARE(callCount, 2);
        QCOMPARE(seenJobs.toSet(), QSet<KJob*>() << job1 << job2);
        QVERIFY(!compositeJob->error());
        delete compositeJob;
    }
Example #5
0
MessageFilter::MessageFilter(MessageModel *source, const QList<BufferId> &buffers, QObject *parent)
    : QSortFilterProxyModel(parent),
    _validBuffers(buffers.toSet()),
    _messageTypeFilter(0)
{
    init();
    setSourceModel(source);
}
Example #6
0
void
KMixWindow::loadBaseConfig()
{
  KConfigGroup config(KGlobal::config(), "Global");

//  GlobalConfig& gcfg = GlobalConfig::instance();
  GlobalConfigData& gcd = GlobalConfig::instance().data;

  QList<QString> preferredMixersInSoundMenu;
  preferredMixersInSoundMenu = config.readEntry("Soundmenu.Mixers", preferredMixersInSoundMenu);
  GlobalConfig::instance().setMixersForSoundmenu(preferredMixersInSoundMenu.toSet());

  setBeepOnVolumeChange(gcd.volumeFeedback);
  m_startVisible = config.readEntry("Visible", false);
  m_multiDriverMode = config.readEntry("MultiDriver", false);
  m_defaultCardOnStart = config.readEntry("DefaultCardOnStart", "");
  m_configVersion = config.readEntry("ConfigVersion", 0);
  // WARNING Don't overwrite m_configVersion with the "correct" value, before having it
  // evaluated. Better only write that in saveBaseConfig()
  m_autouseMultimediaKeys = config.readEntry("AutoUseMultimediaKeys", true);
  QString mixerMasterCard = config.readEntry("MasterMixer", "");
  QString masterDev = config.readEntry("MasterMixerDevice", "");
  Mixer::setGlobalMaster(mixerMasterCard, masterDev, true);
  QString mixerIgnoreExpression = config.readEntry("MixerIgnoreExpression",
      "Modem");
  MixerToolBox::instance()->setMixerIgnoreExpression(mixerIgnoreExpression);

  // --- Advanced options, without GUI: START -------------------------------------
  QString volumePercentageStepString = config.readEntry("VolumePercentageStep");
  if (!volumePercentageStepString.isNull())
    {
      float volumePercentageStep = volumePercentageStepString.toFloat();
      if (volumePercentageStep > 0 && volumePercentageStep <= 100)
        Volume::VOLUME_STEP_DIVISOR = (100 / volumePercentageStep);
    }

  // --- Advanced options, without GUI: END -------------------------------------

  m_backendFilter = config.readEntry<>("Backends", QList<QString>());
  kDebug() << "Backends: " << m_backendFilter;

  // show/hide menu bar
  bool showMenubar = config.readEntry("Menubar", true);

  if (_actionShowMenubar)
    _actionShowMenubar->setChecked(showMenubar);
}
void LiveRubberBandSelectionManipulator::select(SelectionType selectionType)
{
    QDeclarativeViewInspectorPrivate *inspectorPrivate
        = QDeclarativeViewInspectorPrivate::get(m_editorView);
    QList<QGraphicsItem*> itemList
        = inspectorPrivate->selectableItems(m_selectionRectangleElement.rect(),
                                            Qt::IntersectsItemShape);
    QList<QGraphicsItem*> newSelectionList;

    foreach (QGraphicsItem* item, itemList) {
        if (item
                && item->parentItem()
                && !newSelectionList.contains(item)
                //&& m_beginFormEditorItem->childItems().contains(item) // TODO activate this test
           )
        {
            newSelectionList.append(item);
        }
    }

    if (newSelectionList.isEmpty() && m_beginFormEditorItem)
        newSelectionList.append(m_beginFormEditorItem);

    QList<QGraphicsItem*> resultList;

    switch(selectionType) {
    case AddToSelection: {
        resultList.append(m_oldSelectionList);
        resultList.append(newSelectionList);
    }
    break;
    case ReplaceSelection: {
        resultList.append(newSelectionList);
    }
    break;
    case RemoveFromSelection: {
        QSet<QGraphicsItem*> oldSelectionSet(m_oldSelectionList.toSet());
        QSet<QGraphicsItem*> newSelectionSet(newSelectionList.toSet());
        resultList.append(oldSelectionSet.subtract(newSelectionSet).toList());
    }
    }

    m_editorView->setSelectedItems(resultList);
}
Example #8
0
NewAccountDialog::NewAccountDialog(const QList<QString>& allKeychains, const QList<QString>& selectedKeychains, QWidget* parent)
    : QDialog(parent)
{
    if (allKeychains.isEmpty()) {
        throw std::runtime_error(tr("You must first create at least one keychain.").toStdString());
    }

    keychainSet = selectedKeychains.toSet();

    QList<QString> keychains = allKeychains;
    qSort(keychains.begin(), keychains.end());

    // Buttons
    QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
                                     | QDialogButtonBox::Cancel);
    okButton = buttonBox->button(QDialogButtonBox::Ok);
    okButton->setEnabled(false);

    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));

    // Account Name
    QLabel* nameLabel = new QLabel();
    nameLabel->setText(tr("Account Name:"));
    nameEdit = new QLineEdit();
    connect(nameEdit, &QLineEdit::textChanged, [this](const QString& /*text*/) { updateEnabled(); });

    QHBoxLayout* nameLayout = new QHBoxLayout();
    nameLayout->setSizeConstraint(QLayout::SetNoConstraint);
    nameLayout->addWidget(nameLabel);
    nameLayout->addWidget(nameEdit);

    // Keychain List Widget
    QLabel* selectionLabel = new QLabel(tr("Select keychains:"));
    keychainListWidget = new QListWidget();
    for (auto& keychain: keychains)
    {
        QCheckBox* checkBox = new QCheckBox(keychain);
        checkBox->setCheckState(selectedKeychains.count(keychain) ? Qt::Checked : Qt::Unchecked);
        connect(checkBox, &QCheckBox::stateChanged, [=](int state) { updateSelection(keychain, state); });
        QListWidgetItem* item = new QListWidgetItem();
        keychainListWidget->addItem(item);
        keychainListWidget->setItemWidget(item, checkBox);
    }

    // Minimum Signatures
    QLabel *minSigLabel = new QLabel();
    minSigLabel->setText(tr("Minimum Signatures:"));

    minSigComboBox = new QComboBox();
    minSigLineEdit = new QLineEdit();
    minSigLineEdit->setAlignment(Qt::AlignRight);
    minSigComboBox->setLineEdit(minSigLineEdit);

    QHBoxLayout* minSigLayout = new QHBoxLayout();
    minSigLayout->setSizeConstraint(QLayout::SetNoConstraint);
    minSigLayout->addWidget(minSigLabel);
    minSigLayout->addWidget(minSigComboBox);
    updateMinSigs();

    // Creation Time
    QDateTime localDateTime = QDateTime::currentDateTime();
    QLabel* creationTimeLabel = new QLabel(tr("Creation Time ") + "(" + localDateTime.timeZoneAbbreviation() + "):");
    creationTimeEdit = new QDateTimeEdit(QDateTime::currentDateTime());
    creationTimeEdit->setDisplayFormat("yyyy.MM.dd hh:mm:ss");
    creationTimeEdit->setCalendarPopup(true);
    calendarWidget = new QCalendarWidget(this);
    creationTimeEdit->setCalendarWidget(calendarWidget);

    QHBoxLayout* creationTimeLayout = new QHBoxLayout();
    creationTimeLayout->setSizeConstraint(QLayout::SetNoConstraint);
    creationTimeLayout->addWidget(creationTimeLabel);
    creationTimeLayout->addWidget(creationTimeEdit);

    // Main Layout 
    QVBoxLayout *mainLayout = new QVBoxLayout();
    mainLayout->setSizeConstraint(QLayout::SetNoConstraint);
    mainLayout->addLayout(nameLayout);
    mainLayout->addWidget(selectionLabel);
    mainLayout->addWidget(keychainListWidget);
    mainLayout->addLayout(minSigLayout);
    mainLayout->addLayout(creationTimeLayout);
    mainLayout->addWidget(buttonBox);
    setLayout(mainLayout);
}
/*!
    \internal
 */
QString QWebSocketHandshakeResponse::getHandshakeResponse(
        const QWebSocketHandshakeRequest &request,
        const QString &serverName,
        bool isOriginAllowed,
        const QList<QWebSocketProtocol::Version> &supportedVersions,
        const QList<QString> &supportedProtocols,
        const QList<QString> &supportedExtensions)
{
    QStringList response;
    m_canUpgrade = false;

    if (!isOriginAllowed) {
        if (!m_canUpgrade) {
            m_error = QWebSocketProtocol::CloseCodePolicyViolated;
            m_errorString = tr("Access forbidden.");
            response << QStringLiteral("HTTP/1.1 403 Access Forbidden");
        }
    } else {
        if (request.isValid()) {
            const QString acceptKey = calculateAcceptKey(request.key());
            const QList<QString> matchingProtocols =
                    supportedProtocols.toSet().intersect(request.protocols().toSet()).toList();
            //TODO: extensions must be kept in the order in which they arrive
            //cannot use set.intersect() to get the supported extensions
            const QList<QString> matchingExtensions =
                    supportedExtensions.toSet().intersect(request.extensions().toSet()).toList();
            QList<QWebSocketProtocol::Version> matchingVersions =
                    request.versions().toSet().intersect(supportedVersions.toSet()).toList();
            std::sort(matchingVersions.begin(), matchingVersions.end(),
                      std::greater<QWebSocketProtocol::Version>());    //sort in descending order

            if (Q_UNLIKELY(matchingVersions.isEmpty())) {
                m_error = QWebSocketProtocol::CloseCodeProtocolError;
                m_errorString = tr("Unsupported version requested.");
                m_canUpgrade = false;
            } else {
                response << QStringLiteral("HTTP/1.1 101 Switching Protocols") <<
                            QStringLiteral("Upgrade: websocket") <<
                            QStringLiteral("Connection: Upgrade") <<
                            QStringLiteral("Sec-WebSocket-Accept: ") % acceptKey;
                if (!matchingProtocols.isEmpty()) {
                    m_acceptedProtocol = matchingProtocols.first();
                    response << QStringLiteral("Sec-WebSocket-Protocol: ") % m_acceptedProtocol;
                }
                if (!matchingExtensions.isEmpty()) {
                    m_acceptedExtension = matchingExtensions.first();
                    response << QStringLiteral("Sec-WebSocket-Extensions: ") % m_acceptedExtension;
                }
                QString origin = request.origin().trimmed();
                if (origin.contains(QStringLiteral("\r\n")) ||
                        serverName.contains(QStringLiteral("\r\n"))) {
                    m_error = QWebSocketProtocol::CloseCodeAbnormalDisconnection;
                    m_errorString = tr("One of the headers contains a newline. " \
                                       "Possible attack detected.");
                    m_canUpgrade = false;
                } else {
                    if (origin.isEmpty())
                        origin = QStringLiteral("*");
                    response << QStringLiteral("Server: ") % serverName                      <<
                                QStringLiteral("Access-Control-Allow-Credentials: false")    <<
                                QStringLiteral("Access-Control-Allow-Methods: GET")          <<
                                QStringLiteral("Access-Control-Allow-Headers: content-type") <<
                                QStringLiteral("Access-Control-Allow-Origin: ") % origin     <<
                                QStringLiteral("Date: ") %
                                    QDateTime::currentDateTimeUtc()
                                        .toString(QStringLiteral("ddd, dd MMM yyyy hh:mm:ss 'GMT'"));

                    m_acceptedVersion = QWebSocketProtocol::currentVersion();
                    m_canUpgrade = true;
                }
            }
        } else {
            m_error = QWebSocketProtocol::CloseCodeProtocolError;
            m_errorString = tr("Bad handshake request received.");
            m_canUpgrade = false;
        }
        if (Q_UNLIKELY(!m_canUpgrade)) {
            response << QStringLiteral("HTTP/1.1 400 Bad Request");
            QStringList versions;
            Q_FOREACH (const QWebSocketProtocol::Version &version, supportedVersions)
                versions << QString::number(static_cast<int>(version));
            response << QStringLiteral("Sec-WebSocket-Version: ")
                                % versions.join(QStringLiteral(", "));
        }
    }
Example #10
0
void GameRule::onPhaseChange(ServerPlayer *player) const{
    Room *room = player->getRoom();
    switch(player->getPhase()){
    case Player::RoundStart:{
            break;
        }
    case Player::Start: {
            player->setMark("SlashCount", 0);

            if(room->getMode() == "05_2v3")
                if(player->isLord() || player->getRole() == "loyalist"){
                    int card_id = room->drawCard();
                    room->showCard(player, card_id);
                    room->getThread()->delay();
                    player->addToPile("Angers", card_id);
                    LogMessage log;
                    log.type = "$Juqi";
                    log.from = player;
                    log.card_str = QString::number(card_id);
                    room->sendLog(log);
                    if(player->getPile("Angers").length() > 4){
                        const QList<int> angs = player->getPile("Angers");
                        room->fillAG(angs, player);
                        int card_id = room->askForAG(player, angs, false, "cbangercollect");
                        if(card_id < 0)
                            card_id = player->getPile("Angers").first();
                        room->throwCard(card_id);
                        player->invoke("clearAG");
                    }
                }

            break;
        }
    case Player::Judge: {
            QList<const DelayedTrick *> tricks = player->delayedTricks();
            while(!tricks.isEmpty() && player->isAlive()){
                const DelayedTrick *trick = tricks.takeLast();
                bool on_effect = room->cardEffect(trick, NULL, player);
                if(!on_effect)
                    trick->onNullified(player);
            }

            break;
        }
    case Player::Draw: {
            int nUm = 2;
            if(room->getTag("FirstRound").toBool()){
                room->setTag("FirstRound", false);
                if(room->getMode() == "02_1v1")
                    nUm --;
            }

            QVariant num = nUm;
            room->getThread()->trigger(DrawNCards, player, num);
            int n = num.toInt();
            if(n > 0)
                player->drawCards(n, false);
            room->getThread()->trigger(DrawNCardsDone, player, num);
            break;
        }

    case Player::Play: {
            player->clearHistory();

            while(player->isAlive()){
                CardUseStruct card_use;
                room->activate(player, card_use);
                if(card_use.isValid()){
                    room->useCard(card_use);
                }else
                    break;
            }
            break;
        }

    case Player::Discard:{
            int discard_num = player->getHandcardNum() - player->getMaxCards();
            if(player->hasFlag("jilei")){
                QSet<const Card *> jilei_cards;
                QList<const Card *> handcards = player->getHandcards();
                foreach(const Card *card, handcards){
                    if(player->isJilei(card))
                        jilei_cards << card;
                }

                if(jilei_cards.size() > player->getMaxCards()){
                    // show all his cards
                    room->showAllCards(player);

                    DummyCard *dummy_card = new DummyCard;
                    foreach(const Card *card, handcards.toSet() - jilei_cards){
                        dummy_card->addSubcard(card);
                    }
                    room->throwCard(dummy_card, player);

                    return;
                }
            }

            if(discard_num > 0)
                room->askForDiscard(player, "gamerule", discard_num);
            break;
        }
Example #11
0
void GameRule::onPhaseChange(ServerPlayer *player) const{
    Room *room = player->getRoom();
    switch(player->getPhase()){
    case Player::RoundStart:{
            break;
        }
    case Player::Start: {
            player->setMark("SlashCount", 0);
            break;
        }
    case Player::Judge: {
            QList<const DelayedTrick *> tricks = player->delayedTricks();
            while(!tricks.isEmpty() && player->isAlive()){
                const DelayedTrick *trick = tricks.takeLast();
                bool on_effect = room->cardEffect(trick, NULL, player);
                if(!on_effect)
                    trick->onNullified(player);
            }

            break;
        }
    case Player::Draw: {
            QVariant num = 2;
            if(room->getTag("FirstRound").toBool()){
                room->setTag("FirstRound", false);
                if(room->getMode() == "02_1v1")
                    num = 1;
            }

            room->getThread()->trigger(DrawNCards, room, player, num);
            int n = num.toInt();
            if(n > 0)
                player->drawCards(n, false);

            break;
        }

    case Player::Play: {
            while(player->isAlive()){
                CardUseStruct card_use;
                room->activate(player, card_use);
                if(card_use.isValid()){
                    room->useCard(card_use);
                }else
                    break;
            }

            break;
        }

    case Player::Discard:{
        while (player->getHandcardNum() > player->getMaxCards())
        {
            int discard_num = player->getHandcardNum() - player->getMaxCards();
            if(player->hasFlag("jilei")){
                QSet<const Card *> jilei_cards;
                QList<const Card *> handcards = player->getHandcards();
                foreach(const Card *card, handcards){
                    if(player->isJilei(card))
                        jilei_cards << card;
                }

                if(jilei_cards.size() > player->getMaxCards()){
                    // show all his cards
                    room->showAllCards(player);

                    DummyCard *dummy_card = new DummyCard;
                    foreach(const Card *card, handcards.toSet() - jilei_cards){
                        dummy_card->addSubcard(card);
                    }
                    room->throwCard(dummy_card, player);

                    return;
                }
            }

            if(discard_num > 0)
                room->askForDiscard(player, "gamerule", discard_num, 1);
        }
        break;
    }
bool cRenderer::RenderImage()
{
	WriteLog("cRenderer::RenderImage()", 2);

	if (image->IsAllocated())
	{
		image->SetImageParameters(params->imageAdjustments);

		int progressiveSteps;
		if (data->configuration.UseProgressive())
			progressiveSteps =
				(int)(log((double)max(image->GetWidth(), image->GetHeight())) / log(2.0)) - 3;
		else
			progressiveSteps = 0;

		if (progressiveSteps < 0) progressiveSteps = 0;
		int progressive = pow(2.0, (double)progressiveSteps - 1);
		if (progressive == 0) progressive = 1;

		// prepare multiple threads
		QThread **thread = new QThread *[data->configuration.GetNumberOfThreads()];
		cRenderWorker::sThreadData *threadData =
			new cRenderWorker::sThreadData[data->configuration.GetNumberOfThreads()];
		cRenderWorker **worker = new cRenderWorker *[data->configuration.GetNumberOfThreads()];

		if (scheduler) delete scheduler;
		scheduler = new cScheduler(image->GetHeight(), progressive);

		cProgressText progressText;
		progressText.ResetTimer();

		for (int i = 0; i < data->configuration.GetNumberOfThreads(); i++)
		{
			threadData[i].id = i + 1;
			if (data->configuration.UseNetRender())
			{
				if (i < data->netRenderStartingPositions.size())
				{
					threadData[i].startLine = data->netRenderStartingPositions.at(i);
				}
				else
				{
					threadData[i].startLine = 0;
					qCritical() << "NetRender - Mising starting positions data";
				}
			}
			else
			{
				threadData[i].startLine = (image->GetHeight() / data->configuration.GetNumberOfThreads())
																	* i / scheduler->GetProgressiveStep()
																	* scheduler->GetProgressiveStep();
			}
			threadData[i].scheduler = scheduler;
		}

		QString statusText;
		QString progressTxt;

		QElapsedTimer timerRefresh;
		timerRefresh.start();
		qint64 lastRefreshTime = 0;
		QList<int> listToRefresh;
		QList<int> listToSend;

		QElapsedTimer timerProgressRefresh;
		timerProgressRefresh.start();

		WriteLog("Start rendering", 2);
		do
		{
			WriteLogDouble("Progressive loop", scheduler->GetProgressiveStep(), 2);
			for (int i = 0; i < data->configuration.GetNumberOfThreads(); i++)
			{
				WriteLog(QString("Thread ") + QString::number(i) + " create", 3);
				thread[i] = new QThread;
				worker[i] = new cRenderWorker(
					params, fractal, &threadData[i], data, image); // Warning! not needed to delete object
				worker[i]->moveToThread(thread[i]);
				QObject::connect(thread[i], SIGNAL(started()), worker[i], SLOT(doWork()));
				QObject::connect(worker[i], SIGNAL(finished()), thread[i], SLOT(quit()));
				QObject::connect(worker[i], SIGNAL(finished()), worker[i], SLOT(deleteLater()));
				thread[i]->setObjectName("RenderWorker #" + QString::number(i));
				thread[i]->start();
				WriteLog(QString("Thread ") + QString::number(i) + " started", 3);
			}

			while (!scheduler->AllLinesDone())
			{
				gApplication->processEvents();

				if (*data->stopRequest || progressText.getTime() > data->configuration.GetMaxRenderTime()
						|| systemData.globalStopRequest)
				{
					scheduler->Stop();
				}

				Wait(10); // wait 10ms

				if (data->configuration.UseRefreshRenderedList())
				{
					// get list of last rendered lines
					QList<int> list = scheduler->GetLastRenderedLines();
					// create list of lines for image refresh
					listToRefresh += list;
				}

				// status bar and progress bar
				double percentDone = scheduler->PercentDone();
				data->lastPercentage = percentDone;
				statusText = QObject::tr("Rendering image");
				progressTxt = progressText.getText(percentDone);
				data->statistics.time = progressText.getTime();

				if (timerProgressRefresh.elapsed() > 1000)
				{
					emit updateProgressAndStatus(statusText, progressTxt, percentDone);
					emit updateStatistics(data->statistics);
					timerProgressRefresh.restart();
				}

				// refresh image
				if (listToRefresh.size() > 0)
				{
					if (timerRefresh.elapsed() > lastRefreshTime
							&& (scheduler->GetProgressivePass() > 1 || !data->configuration.UseProgressive()))
					{
						timerRefresh.restart();

						emit updateProgressAndStatus(statusText, progressTxt, percentDone);
						emit updateStatistics(data->statistics);

						QSet<int> set_listToRefresh = listToRefresh.toSet(); // removing duplicates
						listToRefresh = set_listToRefresh.toList();
						qSort(listToRefresh);
						listToSend += listToRefresh;

						image->CompileImage(&listToRefresh);

						if (data->configuration.UseRenderTimeEffects())
						{
							if (params->ambientOcclusionEnabled
									&& params->ambientOcclusionMode == params::AOmodeScreenSpace)
							{
								cRenderSSAO rendererSSAO(params, data, image);
								rendererSSAO.setProgressive(scheduler->GetProgressiveStep());
								rendererSSAO.RenderSSAO(&listToRefresh);
							}
						}

						image->ConvertTo8bit();

						if (data->configuration.UseImageRefresh())
						{
							image->UpdatePreview(&listToRefresh);
							image->GetImageWidget()->update();
						}

						// sending rendered lines to NetRender server
						if (data->configuration.UseNetRender() && gNetRender->IsClient()
								&& gNetRender->GetStatus() == CNetRender::netRender_WORKING)
						{
							// If ACK was already received, then server is ready to take new data.
							if (netRenderAckReceived)
							{
								QList<QByteArray> renderedLinesData;
								for (int i = 0; i < listToSend.size(); i++)
								{
									// avoid sending already rendered lines
									if (scheduler->IsLineDoneByServer(listToSend.at(i)))
									{
										listToSend.removeAt(i);
										i--;
										continue;
									}
									// creating data set to send
									QByteArray lineData;
									CreateLineData(listToSend.at(i), &lineData);
									renderedLinesData.append(lineData);
								}
								// sending data
								if (listToSend.size() > 0)
								{
									emit sendRenderedLines(listToSend, renderedLinesData);
									emit NotifyClientStatus();
									netRenderAckReceived = false;
									listToSend.clear();
								}
							}
						}

						if (data->configuration.UseNetRender() && gNetRender->IsServer())
						{
							QList<int> toDoList = scheduler->CreateDoneList();
							if (toDoList.size() > data->configuration.GetNumberOfThreads())
							{
								for (int c = 0; c < gNetRender->GetClientCount(); c++)
								{
									emit SendToDoList(c, toDoList);
								}
							}
						}

						lastRefreshTime = timerRefresh.elapsed() * data->configuration.GetRefreshRate()
															/ (listToRefresh.size());

						if (lastRefreshTime < 100)
							lastRefreshTime = 100; // the shortest refresh time can be 100ms

						// do not refresh and send data too often
						if (data->configuration.UseNetRender())
						{
							if (lastRefreshTime < 500) lastRefreshTime = 500;
						}

						timerRefresh.restart();
						listToRefresh.clear();
					} // timerRefresh
				}		// isPreview
			}			// while scheduler

			for (int i = 0; i < data->configuration.GetNumberOfThreads(); i++)
			{
				while (thread[i]->isRunning())
				{
					gApplication->processEvents();
				};
				WriteLog(QString("Thread ") + QString::number(i) + " finished", 2);
				delete thread[i];
			}
		} while (scheduler->ProgressiveNextStep());

		// send last rendered lines
		if (data->configuration.UseNetRender() && gNetRender->IsClient()
				&& gNetRender->GetStatus() == CNetRender::netRender_WORKING)
		{
			if (netRenderAckReceived)
			{
				QList<QByteArray> renderedLinesData;
				for (int i = 0; i < listToSend.size(); i++)
				{
					// avoid sending already rendered lines
					if (scheduler->IsLineDoneByServer(listToSend.at(i)))
					{
						listToSend.removeAt(i);
						i--;
						continue;
					}
					QByteArray lineData;
					CreateLineData(listToSend.at(i), &lineData);
					renderedLinesData.append(lineData);
				}

				if (listToSend.size() > 0)
				{
					emit sendRenderedLines(listToSend, renderedLinesData);
					emit NotifyClientStatus();
					netRenderAckReceived = false;
					listToSend.clear();
				}
			}
		}

		if (data->configuration.UseNetRender())
		{
			if (gNetRender->IsClient())
			{
				gNetRender->SetStatus(CNetRender::netRender_READY);
				emit NotifyClientStatus();
			}

			if (gNetRender->IsServer())
			{
				emit StopAllClients();
			}
		}
		// refresh image at end
		WriteLog("image->CompileImage()", 2);
		image->CompileImage();

		if (!(gNetRender->IsClient() && data->configuration.UseNetRender()))
		{
			bool ssaoUsed = false;
			if (params->ambientOcclusionEnabled
					&& params->ambientOcclusionMode == params::AOmodeScreenSpace)
			{
				cRenderSSAO rendererSSAO(params, data, image);
				connect(&rendererSSAO,
					SIGNAL(updateProgressAndStatus(const QString &, const QString &, double)), this,
					SIGNAL(updateProgressAndStatus(const QString &, const QString &, double)));
				rendererSSAO.RenderSSAO();
				ssaoUsed = true;
			}
Example #13
0
void BtBookshelfModel::addModules(const QList<CSwordModuleInfo *> & modules) {
    addModules(modules.toSet());
}