void QmlProfilerStatisticsModel::loadData(qint64 rangeStart, qint64 rangeEnd) { clear(); qint64 qmlTime = 0; qint64 lastEndTime = 0; QHash <int, QVector<qint64> > durations; const bool checkRanges = (rangeStart != -1) && (rangeEnd != -1); const QVector<QmlProfilerDataModel::QmlEventData> &eventList = d->modelManager->qmlModel()->getEvents(); const QVector<QmlProfilerDataModel::QmlEventTypeData> &typesList = d->modelManager->qmlModel()->getEventTypes(); // used by binding loop detection QStack<const QmlProfilerDataModel::QmlEventData*> callStack; callStack.push(0); // artificial root for (int i = 0; i < eventList.size(); ++i) { const QmlProfilerDataModel::QmlEventData *event = &eventList[i]; const QmlProfilerDataModel::QmlEventTypeData *type = &typesList[event->typeIndex()]; if (!d->acceptedTypes.contains(type->rangeType)) continue; if (checkRanges) { if ((event->startTime() + event->duration() < rangeStart) || (event->startTime() > rangeEnd)) continue; } // update stats QmlEventStats *stats = &d->data[event->typeIndex()]; stats->duration += event->duration(); stats->durationSelf += event->duration(); if (event->duration() < stats->minTime) stats->minTime = event->duration(); if (event->duration() > stats->maxTime) stats->maxTime = event->duration(); stats->calls++; // for median computing durations[event->typeIndex()].append(event->duration()); // qml time computation if (event->startTime() > lastEndTime) { // assume parent event if starts before last end qmlTime += event->duration(); lastEndTime = event->startTime() + event->duration(); } // // binding loop detection // const QmlProfilerDataModel::QmlEventData *potentialParent = callStack.top(); while (potentialParent && !(potentialParent->startTime() + potentialParent->duration() > event->startTime())) { callStack.pop(); potentialParent = callStack.top(); } // check whether event is already in stack for (int ii = 1; ii < callStack.size(); ++ii) { if (callStack.at(ii)->typeIndex() == event->typeIndex()) { d->eventsInBindingLoop.insert(event->typeIndex()); break; } } if (callStack.count() > 1) d->data[callStack.top()->typeIndex()].durationSelf -= event->duration(); callStack.push(event); d->modelManager->modelProxyCountUpdated(d->modelId, i, eventList.count()*2); } // post-process: calc mean time, median time, percentoftime int i = d->data.size(); int total = i * 2; for (QHash<int, QmlEventStats>::iterator it = d->data.begin(); it != d->data.end(); ++it) { QmlEventStats* stats = &it.value(); if (stats->calls > 0) stats->timePerCall = stats->duration / (double)stats->calls; QVector<qint64> eventDurations = durations[it.key()]; if (!eventDurations.isEmpty()) { Utils::sort(eventDurations); stats->medianTime = eventDurations.at(eventDurations.count()/2); } stats->percentOfTime = stats->duration * 100.0 / qmlTime; stats->percentSelf = stats->durationSelf * 100.0 / qmlTime; d->modelManager->modelProxyCountUpdated(d->modelId, i++, total); } // set binding loop flag foreach (int typeIndex, d->eventsInBindingLoop) d->data[typeIndex].isBindingLoop = true; // insert root event QmlEventStats rootEvent; rootEvent.duration = rootEvent.minTime = rootEvent.maxTime = rootEvent.timePerCall = rootEvent.medianTime = qmlTime + 1; rootEvent.durationSelf = 1; rootEvent.calls = 1; rootEvent.percentOfTime = 100.0; rootEvent.percentSelf = 1.0 / rootEvent.duration; d->data.insert(-1, rootEvent); d->modelManager->modelProxyCountUpdated(d->modelId, 1, 1); emit dataAvailable(); }
bool GoForwardActionWidget::event(QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonDblClick || event->type() == QEvent::Wheel) { QList<GesturesManager::GesturesContext> contexts; contexts << GesturesManager::ToolBarGesturesContext << GesturesManager::GenericGesturesContext; if (GesturesManager::startGesture(this, event, contexts)) { return true; } } if (event->type() == QEvent::ContextMenu) { QContextMenuEvent *contextMenuEvent(static_cast<QContextMenuEvent*>(event)); if (contextMenuEvent) { if (contextMenuEvent->reason() == QContextMenuEvent::Mouse) { contextMenuEvent->accept(); return true; } event->accept(); Window *window(getWindow()); QMenu menu(this); menu.addAction(window ? window->getContentsWidget()->getAction(ActionsManager::ClearTabHistoryAction) : ActionsManager::getAction(ActionsManager::ClearTabHistoryAction, this)); menu.addAction(window ? window->getContentsWidget()->getAction(ActionsManager::PurgeTabHistoryAction) : ActionsManager::getAction(ActionsManager::PurgeTabHistoryAction, this)); ToolBarWidget *toolBar = qobject_cast<ToolBarWidget*>(parentWidget()); if (toolBar) { menu.addSeparator(); menu.addActions(ToolBarWidget::createCustomizationMenu(toolBar->getIdentifier(), QList<QAction*>(), &menu)->actions()); } menu.exec(contextMenuEvent->globalPos()); return true; } return false; } if (event->type() == QEvent::ToolTip) { QHelpEvent *helpEvent(dynamic_cast<QHelpEvent*>(event)); if (helpEvent) { const QVector<QKeySequence> shortcuts(ActionsManager::getActionDefinition(ActionsManager::GoForwardAction).shortcuts); QString toolTip(text() + (shortcuts.isEmpty() ? QString() : QLatin1String(" (") + shortcuts.at(0).toString(QKeySequence::NativeText) + QLatin1Char(')'))); if (getWindow()) { const WindowHistoryInformation history(getWindow()->getContentsWidget()->getHistory()); if (!history.entries.isEmpty() && history.index < (history.entries.count() - 1)) { QString title(history.entries.at(history.index + 1).title); title = (title.isEmpty() ? tr("(Untitled)") : title.replace(QLatin1Char('&'), QLatin1String("&&"))); toolTip = title + QLatin1String(" (") + text() + (shortcuts.isEmpty() ? QString() : QLatin1String(" - ") + shortcuts.at(0).toString(QKeySequence::NativeText)) + QLatin1Char(')'); } } QToolTip::showText(helpEvent->globalPos(), toolTip); } return true; } return ActionWidget::event(event); }
// genExpressionElements(QString input) // The parsing section of the calculator. // // Generates an QVector of expression elements from a QString input // This QVector can then be processed to give a quantitative value. QVector<ExpressionElement> StringCalculator::genExpressionElements(QString input) { // Declare our output vector, starting with size 0. QVector<ExpressionElement> expressionVector = QVector<ExpressionElement>(0); // Index that determines where to start when searching for the next operation int crawlIndex = 0; while(crawlIndex < input.length()) { //-------------------------------------------------------------------------------------------------------------------------------- // Operation handling //-------------------------------------------------------------------------------------------------------------------------------- // Check for operations if(input.at(crawlIndex) == QChar('[')) { int operationEnd = input.indexOf("]", crawlIndex); // Is there a closing bracket? if(operationEnd < 0) { // INTERNAL ERROR // No closing bracket for operation throw 103; } else { // Add a new expression element to the vector expressionVector.append(ExpressionElement(input.mid(crawlIndex, operationEnd + 1 - crawlIndex))); crawlIndex = operationEnd + 1; continue; } } //-------------------------------------------------------------------------------------------------------------------------------- // Subexpression handling //-------------------------------------------------------------------------------------------------------------------------------- if(input.at(crawlIndex) == QChar('(')) { // Turns out the below statement doesn't work. //int subexpressionEnd = input.indexOf(")", crawlIndex); int subexpressionEnd = crawlIndex+1; // A placeholder value for where the subexpression ends. int subexpressionCounter = 1; // Counts how many subexpressions we need to end. // Loop through the input, counting up all the open and close parens to find our matching one int parenI = subexpressionEnd; for(; parenI < input.size(); parenI++) { if(input.at(parenI) == QChar('(')) { subexpressionCounter++; } else if(input.at(parenI) == QChar(')')) { subexpressionCounter--; if(subexpressionCounter == 0) { // Stop incrementing parenI here. break; } } // We haven't found the close paren yet, increment parenI. } // We either found the closing paren or we didn't. // Assign it the value of the loop iterator. subexpressionEnd = parenI; if(subexpressionEnd < 0) { subexpressionEnd = input.size(); } double subexpressionNet = calculateQStringInput(input.mid(crawlIndex + 1, subexpressionEnd - 1 - crawlIndex)); // Support stuff like 5(10) = 50 if(!expressionVector.isEmpty()) { if(expressionVector.at(expressionVector.size()-1).isNumber_) { expressionVector.append(ExpressionElement("[*]")); } } expressionVector.append(ExpressionElement(subexpressionNet)); crawlIndex = subexpressionEnd + 1; continue; } //-------------------------------------------------------------------------------------------------------------------------------- // Number handling //-------------------------------------------------------------------------------------------------------------------------------- // Not an operation, so it must be a number. // Check to see if last element is a number so that we can multiply it to this one if(!expressionVector.isEmpty()) // Insure that the vector isn't empty yet. { if(expressionVector.at(expressionVector.size()-1).isNumber_) { expressionVector.append(ExpressionElement("[*]")); // Support stuff like (10)5 = 50 } } int nextOperation = input.indexOf('[', crawlIndex); int nextSubexpression = input.indexOf("(", crawlIndex); if(nextOperation < 0) { nextOperation = input.size()+1; } if(nextSubexpression < 0) { nextSubexpression = input.size()+1; } // Get where the number should end, which is right up to next paren or bracket. int numberEnd = std::min(nextOperation, nextSubexpression); // Check to make sure we didn't somehow grab a close paren int closingBracketCheck = input.indexOf(')', crawlIndex); if(closingBracketCheck < numberEnd && closingBracketCheck >= 0) { // SYNTAX ERROR // Closing paren with no open paren. throw 104; } // Is there another operation? if(nextOperation < 0 && nextSubexpression < 0) { // No more operations or subexpressions. Append the last number. expressionVector.append(ExpressionElement(input.right(input.size() - crawlIndex))); break; } else { // More operations to go through! expressionVector.append(ExpressionElement(input.mid(crawlIndex, numberEnd - crawlIndex))); crawlIndex = numberEnd; continue; } crawlIndex++; // Just in case of infinite looping. Consider removing later. } return expressionVector; // return the expression vector output. }
void QWebFramePrivate::renderPrivate(QPainter *painter, QWebFrame::RenderLayer layer, const QRegion &clip) { if (!frame->view() || !frame->contentRenderer()) return; QVector<QRect> vector = clip.rects(); if (vector.isEmpty()) return; GraphicsContext context(painter); if (context.paintingDisabled() && !context.updatingControlTints()) return; WebCore::FrameView* view = frame->view(); view->layoutIfNeededRecursive(); for (int i = 0; i < vector.size(); ++i) { const QRect& clipRect = vector.at(i); QRect intersectedRect = clipRect.intersected(view->frameRect()); painter->save(); painter->setClipRect(clipRect, Qt::IntersectClip); int x = view->x(); int y = view->y(); if (layer & QWebFrame::ContentsLayer) { context.save(); int scrollX = view->scrollX(); int scrollY = view->scrollY(); QRect rect = intersectedRect; context.translate(x, y); rect.translate(-x, -y); context.translate(-scrollX, -scrollY); rect.translate(scrollX, scrollY); context.clip(view->visibleContentRect()); view->paintContents(&context, rect); context.restore(); } if (layer & QWebFrame::ScrollBarLayer && !view->scrollbarsSuppressed() && (view->horizontalScrollbar() || view->verticalScrollbar())) { context.save(); QRect rect = intersectedRect; context.translate(x, y); rect.translate(-x, -y); view->paintScrollbars(&context, rect); context.restore(); } if (layer & QWebFrame::PanIconLayer) view->paintPanScrollIcon(&context); painter->restore(); } }
int UIDnDHandler::retrieveDataInternal( Qt::DropAction dropAction, const QString &strMIMEType, QVector<uint8_t> &vecData) { LogFlowFunc(("Retrieving data as '%s', dropAction=%d\n", qPrintable(strMIMEType), dropAction)); int rc = VINF_SUCCESS; /* Indicate to the guest that we have dropped the data on the host. * The guest then will initiate the actual "drop" operation into our proxy on the guest. */ Assert(!m_dndSource.isNull()); CProgress progress = m_dndSource.Drop(strMIMEType, UIDnDHandler::toVBoxDnDAction(dropAction)); LogFlowFunc(("Source: isOk=%RTbool\n", m_dndSource.isOk())); if (m_dndSource.isOk()) { /* Send a mouse event with released mouse buttons into the guest that triggers * the "drop" event in our proxy window on the guest. */ AssertPtr(m_pSession); m_pSession->mouse().PutMouseEvent(0, 0, 0, 0, 0); msgCenter().showModalProgressDialog(progress, tr("Retrieving data ..."), ":/progress_dnd_gh_90px.png", m_pParent); LogFlowFunc(("Progress: fCanceled=%RTbool, fCompleted=%RTbool, isOk=%RTbool, hrc=%Rhrc\n", progress.GetCanceled(), progress.GetCompleted(), progress.isOk(), progress.GetResultCode())); if (!progress.GetCanceled()) { rc = ( progress.isOk() && progress.GetResultCode() == 0) ? VINF_SUCCESS : VERR_GENERAL_FAILURE; /** @todo Fudge; do a GetResultCode() to rc translation. */ if (RT_SUCCESS(rc)) { /* After we successfully retrieved data from the source we query it from Main. */ vecData = m_dndSource.ReceiveData(); /** @todo QVector.size() is "int" only!? */ if (m_dndSource.isOk()) { if (vecData.isEmpty()) rc = VERR_NO_DATA; } else { msgCenter().cannotDropDataToHost(m_dndSource, m_pParent); rc = VERR_GENERAL_FAILURE; /** @todo Fudge; do a GetResultCode() to rc translation. */ } } else msgCenter().cannotDropDataToHost(progress, m_pParent); } else /* Don't pop up a message. */ rc = VERR_CANCELLED; } else { msgCenter().cannotDropDataToHost(m_dndSource, m_pParent); rc = VERR_GENERAL_FAILURE; /** @todo Fudge; do a GetResultCode() to rc translation. */ } setOpMode(DNDMODE_UNKNOWN); LogFlowFuncLeaveRC(rc); return rc; }
PostingIterator* SearchStore::constructQuery(Transaction* tr, const Term& term) { Q_ASSERT(tr); if (term.operation() == Term::And || term.operation() == Term::Or) { QList<Term> subTerms = term.subTerms(); QVector<PostingIterator*> vec; vec.reserve(subTerms.size()); for (const Term& t : term.subTerms()) { vec << constructQuery(tr, t); } if (vec.isEmpty()) { return 0; } if (term.operation() == Term::And) { return new AndPostingIterator(vec); } else { return new OrPostingIterator(vec); } } if (term.value().isNull()) { return 0; } Q_ASSERT(term.value().isValid()); Q_ASSERT(term.comparator() != Term::Auto); Q_ASSERT(term.comparator() == Term::Contains ? term.value().type() == QVariant::String : true); const QVariant value = term.value(); const QByteArray property = term.property().toLower().toUtf8(); if (property == "type" || property == "kind") { EngineQuery q = constructTypeQuery(value.toString()); return tr->postingIterator(q); } else if (property == "includefolder") { const QByteArray folder = QFile::encodeName(value.toString()); Q_ASSERT(!folder.isEmpty()); Q_ASSERT(folder.startsWith('/')); quint64 id = filePathToId(folder); if (!id) { qDebug() << "Folder" << value.toString() << "does not exist"; return 0; } return tr->docUrlIter(id); } else if (property == "modified" || property == "mtime") { if (value.type() == QVariant::ByteArray) { QByteArray ba = value.toByteArray(); Q_ASSERT(ba.size() >= 4); int year = ba.mid(0, 4).toInt(); int month = ba.mid(4, 2).toInt(); int day = ba.mid(6, 2).toInt(); Q_ASSERT(year); // uses 0 to represent whole month or whole year month = month >= 0 && month <= 12 ? month : 0; day = day >= 0 && day <= 31 ? day : 0; QDate startDate(year, month ? month : 1, day ? day : 1); QDate endDate(startDate); if (month == 0) { endDate.setDate(endDate.year(), 12, 31); } else if (day == 0) { endDate.setDate(endDate.year(), endDate.month(), endDate.daysInMonth()); } return tr->mTimeRangeIter(QDateTime(startDate).toTime_t(), QDateTime(endDate, QTime(23, 59, 59)).toTime_t()); } else if (value.type() == QVariant::Date || value.type() == QVariant::DateTime) { const QDateTime dt = value.toDateTime(); return constructMTimeQuery(tr, dt, term.comparator()); } else { Q_ASSERT_X(0, "SearchStore::constructQuery", "modified property must contain date/datetime values"); } } else if (property == "rating") { bool okay = false; int rating = value.toInt(&okay); if (!okay) { qDebug() << "Rating comparisons must be with an integer"; return 0; } PostingDB::Comparator pcom; if (term.comparator() == Term::Greater || term.comparator() == Term::GreaterEqual) { pcom = PostingDB::GreaterEqual; if (term.comparator() == Term::Greater && rating) rating++; } else if (term.comparator() == Term::Less || term.comparator() == Term::LessEqual) { pcom = PostingDB::LessEqual; if (term.comparator() == Term::Less) rating--; } else if (term.comparator() == Term::Equal) { EngineQuery q = constructEqualsQuery("R", value.toString()); return tr->postingIterator(q); } else { Q_ASSERT(0); return 0; } const QByteArray prefix = "R"; const QByteArray val = QByteArray::number(rating); return tr->postingCompIterator(prefix, val, pcom); } QByteArray prefix; if (!property.isEmpty()) { prefix = fetchPrefix(property); if (prefix.isEmpty()) { return 0; } } auto com = term.comparator(); if (com == Term::Contains) { EngineQuery q = constructContainsQuery(prefix, value.toString()); return tr->postingIterator(q); } if (com == Term::Equal) { EngineQuery q = constructEqualsQuery(prefix, value.toString()); return tr->postingIterator(q); } QVariant val = term.value(); if (val.type() == QVariant::Int) { int intVal = value.toInt(); PostingDB::Comparator pcom; if (term.comparator() == Term::Greater || term.comparator() == Term::GreaterEqual) { pcom = PostingDB::GreaterEqual; if (term.comparator() == Term::Greater && intVal) intVal++; } else if (term.comparator() == Term::Less || term.comparator() == Term::LessEqual) { pcom = PostingDB::LessEqual; if (term.comparator() == Term::Less) intVal--; } else { Q_ASSERT(0); return 0; } return tr->postingCompIterator(prefix, QByteArray::number(intVal), pcom); } return 0; }
void QSymbianVGFontGlyphCache::cacheGlyphs(QVGPaintEnginePrivate *d, QFontEngine *fontEngine, const glyph_t *g, int count) { #ifdef QT_SYMBIAN_HARDWARE_GLYPH_CACHE QFontEngineS60 *s60fontEngine = static_cast<QFontEngineS60*>(fontEngine); if (s60fontEngine->m_activeFont->TypeUid() != KCFbsFontUid) return QVGFontGlyphCache::cacheGlyphs(d, fontEngine, g, count); QVector<glyph_t> uncachedGlyphs; while (count-- > 0) { // Skip this glyph if we have already cached it before. glyph_t glyph = *g++; if (((glyph < 256) && ((cachedGlyphsMask[glyph / 32] & (1 << (glyph % 32))) != 0)) || cachedGlyphs.contains(glyph)) continue; if (!uncachedGlyphs.contains(glyph)) uncachedGlyphs.append(glyph); } if (!uncachedGlyphs.isEmpty()) { CFbsFont *cfbsFont = static_cast<CFbsFont *>(s60fontEngine->m_activeFont); RFbsGlyphDataIterator iter; int err = iter.Open(*cfbsFont, (const unsigned int*)uncachedGlyphs.constData(), uncachedGlyphs.count()); if (err == KErrNotSupported || err == KErrInUse) { // Fallback in possibly supported error cases iter.Close(); qWarning("Falling back to default QVGFontGlyphCache"); return QVGFontGlyphCache::cacheGlyphs(d, fontEngine, g, count); } for (; err == KErrNone; err = iter.Next()) { const unsigned int glyph = iter.GlyphCode(); const RSgImage& image = iter.Image(); const TOpenFontCharMetrics& metrics = iter.Metrics(); TRect glyphBounds; metrics.GetHorizBounds(glyphBounds); VGImage vgImage = sgImageToVGImage(0, image); VGfloat origin[2]; VGfloat escapement[2]; origin[0] = -glyphBounds.iTl.iX; origin[1] = glyphBounds.iBr.iY; escapement[0] = 0; escapement[1] = 0; vgSetGlyphToImage(font, glyph, vgImage, origin, escapement); vgDestroyImage(vgImage); // Add to cache if (glyph < 256) cachedGlyphsMask[glyph / 32] |= (1 << (glyph % 32)); else cachedGlyphs.insert(glyph); } iter.Close(); if (err == KErrNoMemory || err == KErrNoGraphicsMemory) qWarning("Not enough memory to cache glyph"); else if (err != KErrNotFound) qWarning("Received error %d from glyph cache", err); } #else QVGFontGlyphCache::cacheGlyphs(d, fontEngine, g, count); #endif }
//------------------------------------------------------------------------------ // Name: do_find // Desc: //------------------------------------------------------------------------------ void DialogReferences::do_find() { bool ok = false; edb::address_t address; const edb::address_t page_size = edb::v1::debugger_core->page_size(); const QString text = ui->txtAddress->text(); if(!text.isEmpty()) { ok = edb::v1::eval_expression(text, &address); } if(ok) { edb::v1::memory_regions().sync(); const QList<IRegion::pointer> regions = edb::v1::memory_regions().regions(); int i = 0; for(const IRegion::pointer ®ion: regions) { // a short circut for speading things up if(region->accessible() || !ui->chkSkipNoAccess->isChecked()) { const edb::address_t page_count = region->size() / page_size; const QVector<quint8> pages = edb::v1::read_pages(region->start(), page_count); if(!pages.isEmpty()) { const quint8 *p = &pages[0]; const quint8 *const pages_end = &pages[0] + region->size(); while(p != pages_end) { if(pages_end - p < edb::v1::pointer_size()) { break; } const edb::address_t addr = p - &pages[0] + region->start(); edb::address_t test_address(0); memcpy(&test_address, p, edb::v1::pointer_size()); if(test_address == address) { auto item = new QListWidgetItem(edb::v1::format_pointer(addr)); item->setData(TypeRole, 'D'); item->setData(AddressRole, addr); ui->listWidget->addItem(item); } edb::Instruction inst(p, pages_end, addr); if(inst) { switch(inst.operation()) { case edb::Instruction::Operation::X86_INS_MOV: // instructions of the form: mov [ADDR], 0xNNNNNNNN Q_ASSERT(inst.operand_count() == 2); if(inst.operands()[0].general_type() == edb::Operand::TYPE_EXPRESSION) { if(inst.operands()[1].general_type() == edb::Operand::TYPE_IMMEDIATE && static_cast<edb::address_t>(inst.operands()[1].immediate()) == address) { auto item = new QListWidgetItem(edb::v1::format_pointer(addr)); item->setData(TypeRole, 'C'); item->setData(AddressRole, addr); ui->listWidget->addItem(item); } } break; case edb::Instruction::Operation::X86_INS_PUSH: // instructions of the form: push 0xNNNNNNNN Q_ASSERT(inst.operand_count() == 1); if(inst.operands()[0].general_type() == edb::Operand::TYPE_IMMEDIATE && static_cast<edb::address_t>(inst.operands()[0].immediate()) == address) { auto item = new QListWidgetItem(edb::v1::format_pointer(addr)); item->setData(TypeRole, 'C'); item->setData(AddressRole, addr); ui->listWidget->addItem(item); } break; default: if(is_jump(inst) || is_call(inst)) { if(inst.operands()[0].general_type() == edb::Operand::TYPE_REL) { if(inst.operands()[0].relative_target() == address) { auto item = new QListWidgetItem(edb::v1::format_pointer(addr)); item->setData(TypeRole, 'C'); item->setData(AddressRole, addr); ui->listWidget->addItem(item); } } } break; } } Q_EMIT updateProgress(util::percentage(i, regions.size(), p - &pages[0], region->size())); ++p; } } } else { Q_EMIT updateProgress(util::percentage(i, regions.size())); } ++i; } } }
void DownloadManager::timerEvent(QTimerEvent* e) { QVector<QTime> remTimes; QVector<int> progresses; QVector<double> speeds; if (e->timerId() == m_timer.timerId()) { if (!ui->list->count()) { ui->speedLabel->clear(); setWindowTitle(tr("Download Manager")); #ifdef Q_OS_WIN if (m_taskbarButton) { m_taskbarButton->progress()->hide(); } #endif return; } for (int i = 0; i < ui->list->count(); i++) { DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i))); if (!downItem || downItem->isCancelled() || !downItem->isDownloading()) { continue; } progresses.append(downItem->progress()); remTimes.append(downItem->remainingTime()); speeds.append(downItem->currentSpeed()); } if (remTimes.isEmpty()) { return; } QTime remaining; foreach (const QTime &time, remTimes) { if (time > remaining) { remaining = time; } } int progress = 0; foreach (int prog, progresses) { progress += prog; } progress = progress / progresses.count(); double speed = 0.00; foreach (double spee, speeds) { speed += spee; } #ifndef Q_OS_WIN ui->speedLabel->setText(tr("%1% of %2 files (%3) %4 remaining").arg(QString::number(progress), QString::number(progresses.count()), DownloadItem::currentSpeedToString(speed), DownloadItem::remaingTimeToString(remaining))); #endif setWindowTitle(tr("%1% - Download Manager").arg(progress)); #ifdef Q_OS_WIN if (m_taskbarButton) { m_taskbarButton->progress()->show(); m_taskbarButton->progress()->setValue(progress); } #endif } QWidget::timerEvent(e); }
void JCurveGroupWidget::updateCurve(JCurveWidget *curveView) { if (!curveView) { return; } // 清空旧数据 curveView->clearCurve(); // 获取横、纵坐标信号量 const QString suffix = curveView->property("suffix").toString().replace('-', '_'); const QString nameX = curveView->property("nameX").toString(); const QString nameY = curveView->property("nameY").toString(); QString sectionX = nameX.section(" (", 0, 0); QString sectionY = nameY.section(" (", 0, 0); // QString legendTitle = nameY % " (" % suffix % ")"; JCurveWidget::AxisXYType axisXYType = curveView->axisXYType(); // 获取M-H信号名称 QString machSection, heightSection; if (!JFlyRecord::instance()->readSignalMHSection( JSqlDataMgr::instance()->signalTableNamePrefix().append(suffix), machSection, heightSection)) { return; } // 生成数据表名称 const QString recordTableName = JSqlDataMgr::instance()->recordTableNamePrefix().append(suffix); // if (axisXYType == JCurveWidget::AxisXY_Value_Value) { // 获取记录数据 QVector<QPointF> data; QListIterator<QRectF> citerSiftAreas(q_siftAreas); while (citerSiftAreas.hasNext()) { const QRectF &range = citerSiftAreas.next(); // QVector<QPointF> tempData; if (JSqlDataMgr::instance()->readRecordDataV(recordTableName, sectionX, sectionY, machSection, heightSection, range, tempData)) { data << tempData; } } // 检测是否有数据需要处理 if (data.isEmpty()) { return; // 无数据需要绘制 } // curveView->updateData(curveView->addCurve(legendTitle), data); } else { // 获取记录数据 if (axisXYType == JCurveWidget::AxisXY_Value_Time) { qSwap(sectionX, sectionY); } // QList<QPair<QTime, qreal> > data; QListIterator<QRectF> citerSiftAreas(q_siftAreas); while (citerSiftAreas.hasNext()) { const QRectF &range = citerSiftAreas.next(); // QList<QPair<QTime, qreal> > tempData; if (JSqlDataMgr::instance()->readRecordDataV(recordTableName, sectionX, sectionY, machSection, heightSection, range, tempData)) { data.append(tempData); } } // 检测是否有数据需要处理 if (data.isEmpty()) { return; // 无数据需要绘制 } // curveView->updateData(curveView->addCurve(legendTitle), data); } }
void QtWebEnginePage::handlePageLoaded(const QString &result) { if (m_widget) { const QVector<int> profiles(ContentBlockingManager::getProfileList(m_widget->getOption(QLatin1String("Content/BlockingProfiles"), url()).toStringList())); if (!profiles.isEmpty()) { const QStringList domainList(ContentBlockingManager::createSubdomainList(url().host())); QStringList styleSheetBlackList(ContentBlockingManager::getStyleSheet(profiles)); QStringList styleSheetWhiteList; for (int i = 0; i < domainList.count(); ++i) { styleSheetBlackList += ContentBlockingManager::getStyleSheetBlackList(domainList.at(i), profiles); styleSheetWhiteList += ContentBlockingManager::getStyleSheetWhiteList(domainList.at(i), profiles); } QFile file(QLatin1String(":/modules/backends/web/qtwebengine/resources/hideElements.js")); if (file.open(QIODevice::ReadOnly)) { runJavaScript(QString(file.readAll()).arg(createJavaScriptList(styleSheetWhiteList)).arg(createJavaScriptList(styleSheetBlackList))); file.close(); } } const QStringList blockedRequests(qobject_cast<QtWebEngineWebBackend*>(m_widget->getBackend())->getBlockedElements(url().host())); if (!blockedRequests.isEmpty()) { QFile file(QLatin1String(":/modules/backends/web/qtwebengine/resources/hideBlockedRequests.js")); if (file.open(QIODevice::ReadOnly)) { runJavaScript(QString(file.readAll()).arg(createJavaScriptList(blockedRequests))); file.close(); } } } QString string(url().toString()); string.truncate(1000); const QRegularExpressionMatch match(QRegularExpression(QStringLiteral(">(<img style=\"-webkit-user-select: none;(?: cursor: zoom-in;)?\"|<video controls=\"\" autoplay=\"\" name=\"media\"><source) src=\"%1").arg(QRegularExpression::escape(string))).match(result)); const bool isViewingMedia(match.hasMatch()); if (isViewingMedia && match.captured().startsWith(QLatin1String("><img"))) { settings()->setAttribute(QWebEngineSettings::AutoLoadImages, true); settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, true); QFile file(QLatin1String(":/modules/backends/web/qtwebengine/resources/imageViewer.js")); file.open(QIODevice::ReadOnly); runJavaScript(file.readAll()); file.close(); } if (isViewingMedia != m_isViewingMedia) { m_isViewingMedia = isViewingMedia; emit viewingMediaChanged(m_isViewingMedia); } }
const StackedTile* StackedTileLoader::loadTile( TileId const & stackedTileId ) { // check if the tile is in the hash d->m_cacheLock.lockForRead(); StackedTile * stackedTile = d->m_tilesOnDisplay.value( stackedTileId, 0 ); d->m_cacheLock.unlock(); if ( stackedTile ) { stackedTile->setUsed( true ); return stackedTile; } // here ends the performance critical section of this method d->m_cacheLock.lockForWrite(); // has another thread loaded our tile due to a race condition? stackedTile = d->m_tilesOnDisplay.value( stackedTileId, 0 ); if ( stackedTile ) { stackedTile->setUsed( true ); d->m_cacheLock.unlock(); return stackedTile; } mDebug() << "StackedTileLoader::loadTile" << stackedTileId.toString(); // the tile was not in the hash so check if it is in the cache stackedTile = d->m_tileCache.take( stackedTileId ); if ( stackedTile ) { stackedTile->setUsed( true ); d->m_tilesOnDisplay[ stackedTileId ] = stackedTile; d->m_cacheLock.unlock(); return stackedTile; } // tile (valid) has not been found in hash or cache, so load it from disk // and place it in the hash from where it will get transferred to the cache // mDebug() << "load Tile from Disk: " << stackedTileId.toString(); QVector<QSharedPointer<TextureTile> > tiles; QVector<GeoSceneTexture const *> const textureLayers = d->findRelevantTextureLayers( stackedTileId ); QVector<GeoSceneTexture const *>::const_iterator pos = textureLayers.constBegin(); QVector<GeoSceneTexture const *>::const_iterator const end = textureLayers.constEnd(); for (; pos != end; ++pos ) { GeoSceneTexture const * const textureLayer = *pos; TileId const tileId( textureLayer->sourceDir(), stackedTileId.zoomLevel(), stackedTileId.x(), stackedTileId.y() ); mDebug() << "StackedTileLoader::loadTile: tile" << textureLayer->sourceDir() << tileId.toString() << textureLayer->tileSize(); const QImage tileImage = d->m_tileLoader->loadTile( tileId, DownloadBrowse ); const Blending *blending = d->m_blendingFactory.findBlending( textureLayer->blending() ); if ( blending == 0 && !textureLayer->blending().isEmpty() ) { mDebug() << Q_FUNC_INFO << "could not find blending" << textureLayer->blending(); } QSharedPointer<TextureTile> tile( new TextureTile( tileId, tileImage, blending ) ); tiles.append( tile ); } Q_ASSERT( !tiles.isEmpty() ); const QImage resultImage = d->m_layerDecorator.merge( stackedTileId, tiles ); stackedTile = new StackedTile( stackedTileId, resultImage, tiles ); stackedTile->setUsed( true ); d->m_tilesOnDisplay[ stackedTileId ] = stackedTile; d->m_cacheLock.unlock(); return stackedTile; }
QVector<QgsDataItem *> QgsWMSConnectionItem::createChildren() { QVector<QgsDataItem *> children; QgsDataSourceUri uri; uri.setEncodedUri( mUri ); QgsDebugMsg( "mUri = " + mUri ); QgsWmsSettings wmsSettings; if ( !wmsSettings.parseUri( mUri ) ) { children.append( new QgsErrorItem( this, tr( "Failed to parse WMS URI" ), mPath + "/error" ) ); return children; } bool res = mCapabilitiesDownload->downloadCapabilities( wmsSettings.baseUrl(), wmsSettings.authorization() ); if ( !res ) { children.append( new QgsErrorItem( this, tr( "Failed to download capabilities" ), mPath + "/error" ) ); return children; } QgsWmsCapabilities caps; if ( !caps.parseResponse( mCapabilitiesDownload->response(), wmsSettings.parserSettings() ) ) { children.append( new QgsErrorItem( this, tr( "Failed to parse capabilities" ), mPath + "/error" ) ); return children; } // Attention: supportedLayers() gives tree leafs, not top level QVector<QgsWmsLayerProperty> layerProperties = caps.supportedLayers(); if ( !layerProperties.isEmpty() ) { QgsWmsCapabilitiesProperty capabilitiesProperty = caps.capabilitiesProperty(); const QgsWmsCapabilityProperty &capabilityProperty = capabilitiesProperty.capability; for ( const QgsWmsLayerProperty &layerProperty : qgis::as_const( capabilityProperty.layers ) ) { // Attention, the name may be empty QgsDebugMsg( QString::number( layerProperty.orderId ) + ' ' + layerProperty.name + ' ' + layerProperty.title ); QString pathName = layerProperty.name.isEmpty() ? QString::number( layerProperty.orderId ) : layerProperty.name; QgsWMSLayerItem *layer = new QgsWMSLayerItem( this, layerProperty.title, mPath + '/' + pathName, capabilitiesProperty, uri, layerProperty ); children << layer; } } QList<QgsWmtsTileLayer> tileLayers = caps.supportedTileLayers(); if ( !tileLayers.isEmpty() ) { QHash<QString, QgsWmtsTileMatrixSet> tileMatrixSets = caps.supportedTileMatrixSets(); const auto constTileLayers = tileLayers; for ( const QgsWmtsTileLayer &l : constTileLayers ) { QString title = l.title.isEmpty() ? l.identifier : l.title; QgsDataItem *layerItem = l.styles.size() == 1 ? this : new QgsDataCollectionItem( this, title, mPath + '/' + l.identifier ); if ( layerItem != this ) { layerItem->setCapabilities( layerItem->capabilities2() & ~QgsDataItem::Fertile ); layerItem->setState( QgsDataItem::Populated ); layerItem->setToolTip( title ); children << layerItem; } for ( const QgsWmtsStyle &style : qgis::as_const( l.styles ) ) { QString styleName = style.title.isEmpty() ? style.identifier : style.title; if ( layerItem == this ) styleName = title; // just one style so no need to display it QgsDataItem *styleItem = l.setLinks.size() == 1 ? layerItem : new QgsDataCollectionItem( layerItem, styleName, layerItem->path() + '/' + style.identifier ); if ( styleItem != layerItem ) { styleItem->setCapabilities( styleItem->capabilities2() & ~QgsDataItem::Fertile ); styleItem->setState( QgsDataItem::Populated ); styleItem->setToolTip( styleName ); if ( layerItem == this ) children << styleItem; else layerItem->addChildItem( styleItem ); } for ( const QgsWmtsTileMatrixSetLink &setLink : qgis::as_const( l.setLinks ) ) { QString linkName = setLink.tileMatrixSet; if ( styleItem == layerItem ) linkName = styleName; // just one link so no need to display it QgsDataItem *linkItem = l.formats.size() == 1 ? styleItem : new QgsDataCollectionItem( styleItem, linkName, styleItem->path() + '/' + setLink.tileMatrixSet ); if ( linkItem != styleItem ) { linkItem->setCapabilities( linkItem->capabilities2() & ~QgsDataItem::Fertile ); linkItem->setState( QgsDataItem::Populated ); linkItem->setToolTip( linkName ); if ( styleItem == this ) children << linkItem; else styleItem->addChildItem( linkItem ); } for ( const QString &format : qgis::as_const( l.formats ) ) { QString name = format; if ( linkItem == styleItem ) name = linkName; // just one format so no need to display it QgsDataItem *tileLayerItem = new QgsWMTSLayerItem( linkItem, name, linkItem->path() + '/' + name, uri, l.identifier, format, style.identifier, setLink.tileMatrixSet, tileMatrixSets[ setLink.tileMatrixSet ].crs, title ); tileLayerItem->setToolTip( name ); if ( linkItem == this ) children << tileLayerItem; else linkItem->addChildItem( tileLayerItem ); } } } } } return children; }
void SyncEngine::startSync() { if (_journal->exists()) { QVector< SyncJournalDb::PollInfo > pollInfos = _journal->getPollInfos(); if (!pollInfos.isEmpty()) { qDebug() << "Finish Poll jobs before starting a sync"; CleanupPollsJob *job = new CleanupPollsJob(pollInfos, _account, _journal, _localPath, this); connect(job, SIGNAL(finished()), this, SLOT(startSync())); connect(job, SIGNAL(aborted(QString)), this, SLOT(slotCleanPollsJobAborted(QString))); job->start(); return; } } Q_ASSERT(!_syncRunning); _syncRunning = true; Q_ASSERT(_csync_ctx); if (!QDir(_localPath).exists()) { // No _tr, it should only occur in non-mirall emit csyncError("Unable to find local sync directory."); finalize(); return; } _syncedItems.clear(); _syncItemMap.clear(); _needsUpdate = false; csync_resume(_csync_ctx); int fileRecordCount = -1; if (!_journal->exists()) { qDebug() << "=====sync looks new (no DB exists)"; } else { qDebug() << "=====sync with existing DB"; } qDebug() << "=====Using Qt" << qVersion(); #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) qDebug() << "=====Using SSL library version" << QSslSocket::sslLibraryVersionString().toUtf8().data(); #endif fileRecordCount = _journal->getFileRecordCount(); // this creates the DB if it does not exist yet if( fileRecordCount == -1 ) { qDebug() << "No way to create a sync journal!"; emit csyncError(tr("Unable to initialize a sync journal.")); finalize(); return; // database creation error! } _csync_ctx->read_remote_from_db = true; // This tells csync to never read from the DB if it is empty // thereby speeding up the initial discovery significantly. _csync_ctx->db_is_empty = (fileRecordCount == 0); auto selectiveSyncBlackList = _journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList); bool usingSelectiveSync = (!selectiveSyncBlackList.isEmpty()); qDebug() << (usingSelectiveSync ? "====Using Selective Sync" : "====NOT Using Selective Sync"); if (fileRecordCount >= 0 && fileRecordCount < 50 && !usingSelectiveSync) { qDebug() << "===== Activating recursive PROPFIND (currently" << fileRecordCount << "file records)"; bool no_recursive_propfind = false; csync_set_module_property(_csync_ctx, "no_recursive_propfind", &no_recursive_propfind); } else { bool no_recursive_propfind = true; csync_set_module_property(_csync_ctx, "no_recursive_propfind", &no_recursive_propfind); } csync_set_userdata(_csync_ctx, this); _account->credentials()->syncContextPreStart(_csync_ctx); // csync_set_auth_callback( _csync_ctx, getauth ); //csync_set_log_level( 11 ); don't set the loglevel here, it shall be done by folder.cpp or owncloudcmd.cpp int timeout = OwncloudPropagator::httpTimeout(); csync_set_module_property(_csync_ctx, "timeout", &timeout); _stopWatch.start(); qDebug() << "#### Discovery start #################################################### >>"; _discoveryMainThread = new DiscoveryMainThread(account()); _discoveryMainThread->setParent(this); connect(this, SIGNAL(finished()), _discoveryMainThread, SLOT(deleteLater())); connect(_discoveryMainThread, SIGNAL(etagConcatenation(QString)), this, SLOT(slotRootEtagReceived(QString))); DiscoveryJob *discoveryJob = new DiscoveryJob(_csync_ctx); discoveryJob->_selectiveSyncBlackList = selectiveSyncBlackList; discoveryJob->_selectiveSyncWhiteList = _journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList); discoveryJob->_newSharedFolderSizeLimit = _newSharedFolderSizeLimit; discoveryJob->moveToThread(&_thread); connect(discoveryJob, SIGNAL(finished(int)), this, SLOT(slotDiscoveryJobFinished(int))); connect(discoveryJob, SIGNAL(folderDiscovered(bool,QString)), this, SIGNAL(folderDiscovered(bool,QString))); connect(discoveryJob, SIGNAL(newSharedFolder(QString)), this, SIGNAL(newSharedFolder(QString))); // This is used for the DiscoveryJob to be able to request the main thread/ // to read in directory contents. qDebug() << Q_FUNC_INFO << _remotePath << _remoteUrl; _discoveryMainThread->setupHooks( discoveryJob, _remotePath); // Starts the update in a seperate thread QMetaObject::invokeMethod(discoveryJob, "start", Qt::QueuedConnection); }
void QtWebEngineUrlRequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo &request) { if (!m_contentBlockingProfiles.contains(request.firstPartyUrl().host())) { m_contentBlockingProfiles[request.firstPartyUrl().host()] = ContentBlockingManager::getProfileList(SettingsManager::getValue(QLatin1String("Content/BlockingProfiles"), request.firstPartyUrl()).toStringList()); } const QVector<int> contentBlockingProfiles(m_contentBlockingProfiles.value(request.firstPartyUrl().host())); if (contentBlockingProfiles.isEmpty()) { const NetworkManagerFactory::DoNotTrackPolicy doNotTrackPolicy(NetworkManagerFactory::getDoNotTrackPolicy()); if (doNotTrackPolicy != NetworkManagerFactory::SkipTrackPolicy) { request.setHttpHeader(QStringLiteral("DNT").toLatin1(), ((doNotTrackPolicy == NetworkManagerFactory::DoNotAllowToTrackPolicy) ? QStringLiteral("1") : QStringLiteral("0")).toLatin1()); } return; } ContentBlockingManager::ResourceType resourceType(ContentBlockingManager::OtherType); switch (request.resourceType()) { case QWebEngineUrlRequestInfo::ResourceTypeMainFrame: resourceType = ContentBlockingManager::MainFrameType; break; case QWebEngineUrlRequestInfo::ResourceTypeSubFrame: resourceType = ContentBlockingManager::SubFrameType; break; case QWebEngineUrlRequestInfo::ResourceTypeStylesheet: resourceType = ContentBlockingManager::StyleSheetType; break; case QWebEngineUrlRequestInfo::ResourceTypeScript: resourceType = ContentBlockingManager::ScriptType; break; case QWebEngineUrlRequestInfo::ResourceTypeImage: resourceType = ContentBlockingManager::ImageType; break; case QWebEngineUrlRequestInfo::ResourceTypeObject: case QWebEngineUrlRequestInfo::ResourceTypeMedia: resourceType = ContentBlockingManager::ObjectType; break; case QWebEngineUrlRequestInfo::ResourceTypeXhr: resourceType = ContentBlockingManager::XmlHttpRequestType; break; default: break; } const ContentBlockingManager::CheckResult result(ContentBlockingManager::checkUrl(contentBlockingProfiles, request.firstPartyUrl(), request.requestUrl(), resourceType)); if (result.isBlocked) { Console::addMessage(QCoreApplication::translate("main", "Blocked request"), Otter::NetworkMessageCategory, LogMessageLevel, request.requestUrl().toString(), -1); request.block(true); } }
VertexSpec* CmodLoader::loadVertexSpec() { if (readCmodToken() != CmodVertexDesc) { setError("Missing vertex description in submesh"); return NULL; } QVector<VertexAttribute> attributes; bool done = false; while (!done && !error()) { quint16 token = 0; *m_inputStream >> token; if (token == CmodEndVertexDesc) { done = true; } else { VertexAttribute::Semantic semantic = VertexAttribute::InvalidAttributeSemantic; switch (token) { case 0: semantic = VertexAttribute::Position; break; case 1: semantic = VertexAttribute::Color; break; case 2: setError("color1 is not a supported vertex attribute"); break; case 3: semantic = VertexAttribute::Normal; break; case 4: semantic = VertexAttribute::Tangent; break; case 5: semantic = VertexAttribute::TextureCoord; break; case 6: setError("texture1 is not a supported vertex attribute"); break; case 7: setError("texture2 is not a supported vertex attribute"); break; case 8: setError("texture3 is not a supported vertex attribute"); break; case 9: semantic = VertexAttribute::PointSize; break; default: setError("Unrecognized vertex attribute semantic"); break; } VertexAttribute::Format format = VertexAttribute::InvalidAttributeFormat; quint16 formatIndex = 0; *m_inputStream >> formatIndex; switch (formatIndex) { case 0: format = VertexAttribute::Float1; break; case 1: format = VertexAttribute::Float2; break; case 2: format = VertexAttribute::Float3; break; case 3: format = VertexAttribute::Float4; break; case 4: format = VertexAttribute::UByte4; break; default: setError("Unrecognized vertex attribute format"); break; } if (format != VertexAttribute::InvalidAttributeFormat && semantic != VertexAttribute::InvalidAttributeSemantic) { attributes << VertexAttribute(semantic, format); } } } if (attributes.isEmpty()) { setError("Submesh has an empty vertex description"); return NULL; } return new VertexSpec(attributes.size(), attributes.data()); }
void PainterThread::drawAttrib(QPainter *p, Attributes *attrib) { if (attrib->getType() == TObsAgent) return; //---- Desenha o atributo p->begin(attrib->getImage()); p->setPen(Qt::NoPen); //defaultPen); //@RAIAN: Desenhando a vizinhanca if (attrib->getType() == TObsNeighborhood) { QColor color(Qt::white); QVector<QMap<QString, QList<double> > > *neighborhoods = attrib->getNeighValues(); QVector<ObsLegend> *vecLegend = attrib->getLegend(); QPen pen = p->pen(); pen.setStyle(Qt::SolidLine); pen.setWidth(attrib->getWidth()); // int random = qrand() % 256; double xCell = -1.0, yCell = -1.0; for (int pos = 0; pos < neighborhoods->size(); pos++) { QMap<QString, QList<double> > neigh = neighborhoods->at(pos); xCell = attrib->getXsValue()->at(pos); yCell = attrib->getYsValue()->at(pos); if ((xCell >= 0) && (yCell >=0)) { QMap<QString, QList<double> >::Iterator itNeigh = neigh.begin(); while (itNeigh != neigh.end()) { QString neighID = itNeigh.key(); QList<double> neighbor = itNeigh.value(); double xNeigh = neighbor.at(0); double yNeigh = neighbor.at(1); double weight = neighbor.at(2); if (vecLegend->isEmpty()) { weight = weight - attrib->getMinValue(); double c = weight * attrib->getVal2Color(); if (c >= 0 && c <= 255) { color.setRgb(c, c, c); } else { color.setRgb(255, 255, 255); } pen.setColor(color); } else { for (int j = 0; j < vecLegend->size(); j++) { ObsLegend leg = vecLegend->at(j); if (attrib->getGroupMode() == 3) { if (weight == leg.getTo().toDouble()) { pen.setColor(leg.getColor()); break; } } else { if ((leg.getFrom().toDouble() <= weight) && (weight < leg.getTo().toDouble())) { pen.setColor(leg.getColor()); break; } } } } p->setPen(pen); if ((xNeigh >= 0) && (yNeigh >= 0)) { drawNeighborhood(p, xCell, yCell, xNeigh, yNeigh); } itNeigh++; } } } } //@RAIAN: FIM else { if (attrib->getDataType() == TObsNumber) { QColor color(Qt::white); QVector<double> *values = attrib->getNumericValues(); QVector<ObsLegend> *vecLegend = attrib->getLegend(); double x = -1.0, y = -1.0, v = 0.0; int vSize = values->size(); int xSize = attrib->getXsValue()->size(); int ySize = attrib->getYsValue()->size(); for (int pos = 0; (pos < vSize && pos < xSize && pos < ySize); pos++) { v = values->at(pos); // Corrige o bug gerando quando um agente morre if (attrib->getXsValue()->isEmpty() || attrib->getXsValue()->size() == pos) break; x = attrib->getXsValue()->at(pos); y = attrib->getYsValue()->at(pos); if (vecLegend->isEmpty()) { v = v - attrib->getMinValue(); double c = v * attrib->getVal2Color(); if ((c >= 0) && (c <= 255)) { color.setRgb(c, c, c); } else { color.setRgb(255, 255, 255); } p->setBrush(color); } else { for (int j = 0; j < vecLegend->size(); j++) { p->setBrush(Qt::white); const ObsLegend &leg = vecLegend->at(j); if (attrib->getGroupMode() == TObsUniqueValue) // valor ?nico 3 { if (v == leg.getToNumber()) { p->setBrush(leg.getColor()); break; } } else { if ((leg.getFromNumber() <= v) && (v < leg.getToNumber())) { p->setBrush(leg.getColor()); break; } } } } if ((x >= 0) && (y >= 0)) draw(p, attrib->getType(), x, y); } } else if (attrib->getDataType() == TObsText) { QVector<QString> *values = attrib->getTextValues(); QVector<ObsLegend> *vecLegend = attrib->getLegend(); int random = qrand() % 256; double x = -1.0, y = -1.0; int vSize = values->size(); int xSize = attrib->getXsValue()->size(); int ySize = attrib->getYsValue()->size(); for (int pos = 0; (pos < vSize && pos < xSize && pos < ySize); pos++) { const QString & v = values->at(pos); // Corrige o bug gerando quando um agente morre if (attrib->getXsValue()->isEmpty() || attrib->getXsValue()->size() == pos) break; x = attrib->getXsValue()->at(pos); y = attrib->getYsValue()->at(pos); if (vecLegend->isEmpty()) { p->setBrush(QColor(random, random, random)); } else { p->setBrush(Qt::white); for (int j = 0; j < vecLegend->size(); j++) { const ObsLegend &leg = vecLegend->at(j); if (v == leg.getFrom()) { p->setBrush(leg.getColor()); break; } } } if ((x >= 0) && (y >= 0)) draw(p, attrib->getType(), x, y); } } } p->end(); }
void Qt5InformationNodeInstanceServer::collectItemChangesAndSendChangeCommands() { static bool inFunction = false; if (!inFunction) { inFunction = true; QSet<ServerNodeInstance> informationChangedInstanceSet; QVector<InstancePropertyPair> propertyChangedList; bool adjustSceneRect = false; if (sgView()) { foreach (QSGItem *item, allItems()) { if (item && hasInstanceForObject(item)) { ServerNodeInstance instance = instanceForObject(item); DesignerSupport::DirtyType informationsDirty = DesignerSupport::DirtyType(DesignerSupport::TransformUpdateMask | DesignerSupport::Visible | DesignerSupport::ZValue | DesignerSupport::OpacityValue); if (DesignerSupport::dirty(item, informationsDirty)) informationChangedInstanceSet.insert(instance); if (DesignerSupport::dirty(item, DesignerSupport::ParentChanged)) { m_parentChangedSet.insert(instance); informationChangedInstanceSet.insert(instance); } // if (d->geometryChanged) { // if (instance.isRootNodeInstance()) // declarativeView()->scene()->setSceneRect(item->boundingRect()); // } } } foreach (const InstancePropertyPair& property, changedPropertyList()) { const ServerNodeInstance instance = property.first; const QString propertyName = property.second; if (instance.isValid()) { if (instance.isRootNodeInstance() && (propertyName == "width" || propertyName == "height")) adjustSceneRect = true; if (propertyName.contains("anchors")) informationChangedInstanceSet.insert(instance); propertyChangedList.append(property); } } resetAllItems(); clearChangedPropertyList(); sendTokenBack(); if (!informationChangedInstanceSet.isEmpty()) nodeInstanceClient()->informationChanged(createAllInformationChangedCommand(informationChangedInstanceSet.toList())); if (!propertyChangedList.isEmpty()) nodeInstanceClient()->valuesChanged(createValuesChangedCommand(propertyChangedList)); if (!m_parentChangedSet.isEmpty()) { sendChildrenChangedCommand(m_parentChangedSet.toList()); m_parentChangedSet.clear(); } // if (adjustSceneRect) { // QRectF boundingRect = rootNodeInstance().boundingRect(); // if (boundingRect.isValid()) { // declarativeView()->setSceneRect(boundingRect); // } // } if (!m_completedComponentList.isEmpty()) { nodeInstanceClient()->componentCompleted(createComponentCompletedCommand(m_completedComponentList)); m_completedComponentList.clear(); } slowDownRenderTimer(); nodeInstanceClient()->flush(); nodeInstanceClient()->synchronizeWithClientProcess(); } inFunction = false; }
void PropertySyncer::handleMessage(const GammaRay::Message& msg) { Q_ASSERT(msg.address() == m_address); switch (msg.type()) { case Protocol::PropertySyncRequest: { Protocol::ObjectAddress addr; msg.payload() >> addr; Q_ASSERT(addr != Protocol::InvalidObjectAddress); const auto it = std::find_if(m_objects.constBegin(), m_objects.constEnd(), [addr](const ObjectInfo &info) { return info.addr == addr; }); if (it == m_objects.constEnd()) break; QVector<QPair<QString, QVariant> > values; const auto propCount = (*it).obj->metaObject()->propertyCount(); values.reserve(propCount); for (int i = qobjectPropertyOffset(); i < propCount; ++i) { const auto prop = (*it).obj->metaObject()->property(i); values.push_back(qMakePair(QString(prop.name()), prop.read((*it).obj))); } Q_ASSERT(!values.isEmpty()); Message msg(m_address, Protocol::PropertyValuesChanged); msg.payload() << addr << (quint32)values.size(); foreach (const auto &value, values) msg.payload() << value.first << value.second; emit message(msg); break; } case Protocol::PropertyValuesChanged: { Protocol::ObjectAddress addr; quint32 changeSize; msg.payload() >> addr >> changeSize; Q_ASSERT(addr != Protocol::InvalidObjectAddress); Q_ASSERT(changeSize > 0); auto it = std::find_if(m_objects.begin(), m_objects.end(), [addr](const ObjectInfo &info) { return info.addr == addr; }); if (it == m_objects.end()) break; for (quint32 i = 0; i < changeSize; ++i) { QString propName; QVariant propValue; msg.payload() >> propName >> propValue; (*it).recursionLock = true; (*it).obj->setProperty(propName.toUtf8(), propValue); // it can be invalid if as a result of the above call new objects have been registered for example it = std::find_if(m_objects.begin(), m_objects.end(), [addr](const ObjectInfo &info) { return info.addr == addr; }); Q_ASSERT(it != m_objects.end()); (*it).recursionLock = false; } break; } default: Q_ASSERT(!"We should not get here!"); } }
void QgsOverlayUtils::difference( const QgsFeatureSource &sourceA, const QgsFeatureSource &sourceB, QgsFeatureSink &sink, QgsProcessingContext &context, QgsProcessingFeedback *feedback, int &count, int totalCount, QgsOverlayUtils::DifferenceOutput outputAttrs ) { QgsFeatureRequest requestB; requestB.setSubsetOfAttributes( QgsAttributeList() ); if ( outputAttrs != OutputBA ) requestB.setDestinationCrs( sourceA.sourceCrs(), context.transformContext() ); QgsSpatialIndex indexB( sourceB.getFeatures( requestB ), feedback ); int fieldsCountA = sourceA.fields().count(); int fieldsCountB = sourceB.fields().count(); QgsAttributes attrs; attrs.resize( outputAttrs == OutputA ? fieldsCountA : ( fieldsCountA + fieldsCountB ) ); if ( totalCount == 0 ) totalCount = 1; // avoid division by zero QgsFeature featA; QgsFeatureRequest requestA; if ( outputAttrs == OutputBA ) requestA.setDestinationCrs( sourceB.sourceCrs(), context.transformContext() ); QgsFeatureIterator fitA = sourceA.getFeatures( requestA ); while ( fitA.nextFeature( featA ) ) { if ( feedback->isCanceled() ) break; if ( featA.hasGeometry() ) { QgsGeometry geom( featA.geometry() ); QgsFeatureIds intersects = indexB.intersects( geom.boundingBox() ).toSet(); QgsFeatureRequest request; request.setFilterFids( intersects ); request.setSubsetOfAttributes( QgsAttributeList() ); if ( outputAttrs != OutputBA ) request.setDestinationCrs( sourceA.sourceCrs(), context.transformContext() ); std::unique_ptr< QgsGeometryEngine > engine; if ( !intersects.isEmpty() ) { // use prepared geometries for faster intersection tests engine.reset( QgsGeometry::createGeometryEngine( geom.constGet() ) ); engine->prepareGeometry(); } QVector<QgsGeometry> geometriesB; QgsFeature featB; QgsFeatureIterator fitB = sourceB.getFeatures( request ); while ( fitB.nextFeature( featB ) ) { if ( feedback->isCanceled() ) break; if ( engine->intersects( featB.geometry().constGet() ) ) geometriesB << featB.geometry(); } if ( !geometriesB.isEmpty() ) { QgsGeometry geomB = QgsGeometry::unaryUnion( geometriesB ); geom = geom.difference( geomB ); } if ( !sanitizeDifferenceResult( geom ) ) continue; const QgsAttributes attrsA( featA.attributes() ); switch ( outputAttrs ) { case OutputA: attrs = attrsA; break; case OutputAB: for ( int i = 0; i < fieldsCountA; ++i ) attrs[i] = attrsA[i]; break; case OutputBA: for ( int i = 0; i < fieldsCountA; ++i ) attrs[i + fieldsCountB] = attrsA[i]; break; } QgsFeature outFeat; outFeat.setGeometry( geom ); outFeat.setAttributes( attrs ); sink.addFeature( outFeat, QgsFeatureSink::FastInsert ); } else { // TODO: should we write out features that do not have geometry? sink.addFeature( featA, QgsFeatureSink::FastInsert ); } ++count; feedback->setProgress( count / ( double ) totalCount * 100. ); } }
/******************************************************************************\ * Device handling * \******************************************************************************/ QString CSoundBase::SetDev ( const int iNewDev ) { // init return parameter with "no error" QString strReturn = ""; // first check if valid input parameter if ( iNewDev >= lNumDevs ) { // we should actually never get here... return tr ( "Invalid device selection." ); } // check if an ASIO driver was already initialized if ( lCurDev != INVALID_SNC_CARD_DEVICE ) { // a device was already been initialized and is used, first clean up // driver UnloadCurrentDriver(); const QString strErrorMessage = LoadAndInitializeDriver ( iNewDev ); if ( !strErrorMessage.isEmpty() ) { if ( iNewDev != lCurDev ) { // loading and initializing the new driver failed, go back to // original driver and display error message LoadAndInitializeDriver ( lCurDev ); } else { // the same driver is used but the driver properties seems to // have changed so that they are not compatible to our // software anymore QMessageBox::critical ( 0, APP_NAME, QString ( tr ( "The audio driver properties " "have changed to a state which is incompatible to this " "software. The selected audio device could not be used " "because of the following error: <b>" ) ) + strErrorMessage + QString ( tr ( "</b><br><br>Please restart the software." ) ), "Close", 0 ); _exit ( 0 ); } // store error return message strReturn = strErrorMessage; } } else { // init flag for "load any driver" bool bTryLoadAnyDriver = false; if ( iNewDev != INVALID_SNC_CARD_DEVICE ) { // This is the first time a driver is to be initialized, we first // try to load the selected driver, if this fails, we try to load // the first available driver in the system. If this fails, too, we // throw an error that no driver is available -> it does not make // sense to start the llcon software if no audio hardware is // available. if ( !LoadAndInitializeDriver ( iNewDev ).isEmpty() ) { // loading and initializing the new driver failed, try to find // at least one usable driver bTryLoadAnyDriver = true; } } else { // try to find one usable driver (select the first valid driver) bTryLoadAnyDriver = true; } if ( bTryLoadAnyDriver ) { // try to load and initialize any valid driver QVector<QString> vsErrorList = LoadAndInitializeFirstValidDriver(); if ( !vsErrorList.isEmpty() ) { // create error message with all details QString sErrorMessage = tr ( "<b>No usable " ) + strSystemDriverTechniqueName + tr ( " audio device " "(driver) found.</b><br><br>" "In the following there is a list of all available drivers " "with the associated error message:<ul>" ); for ( int i = 0; i < lNumDevs; i++ ) { sErrorMessage += "<li><b>" + GetDeviceName ( i ) + "</b>: " + vsErrorList[i] + "</li>"; } sErrorMessage += "</ul>"; throw CGenErr ( sErrorMessage ); } } } return strReturn; }
void QgsGeomColumnTypeThread::run() { QgsDataSourceUri uri = QgsPostgresConn::connUri( mName ); mConn = QgsPostgresConnPool::instance()->acquireConnection( uri.connectionInfo( false ) ); if ( !mConn ) { QgsDebugMsg( "Connection failed - " + uri.connectionInfo( false ) ); return; } mStopped = false; bool dontResolveType = QgsPostgresConn::dontResolveType( mName ); emit progressMessage( tr( "Retrieving tables of %1..." ).arg( mName ) ); QVector<QgsPostgresLayerProperty> layerProperties; if ( !mConn->supportedLayers( layerProperties, QgsPostgresConn::geometryColumnsOnly( mName ), QgsPostgresConn::publicSchemaOnly( mName ), mAllowGeometrylessTables ) || layerProperties.isEmpty() ) { QgsPostgresConnPool::instance()->releaseConnection( mConn ); mConn = nullptr; return; } int i = 0, n = layerProperties.size(); for ( QVector<QgsPostgresLayerProperty>::iterator it = layerProperties.begin(), end = layerProperties.end(); it != end; ++it ) { QgsPostgresLayerProperty &layerProperty = *it; if ( !mStopped ) { emit progress( i++, n ); emit progressMessage( tr( "Scanning column %1.%2.%3..." ) .arg( layerProperty.schemaName, layerProperty.tableName, layerProperty.geometryColName ) ); if ( !layerProperty.geometryColName.isNull() && ( layerProperty.types.value( 0, QgsWkbTypes::Unknown ) == QgsWkbTypes::Unknown || layerProperty.srids.value( 0, INT_MIN ) == INT_MIN ) ) { if ( dontResolveType ) { QgsDebugMsg( QString( "skipping column %1.%2 without type constraint" ).arg( layerProperty.schemaName, layerProperty.tableName ) ); continue; } mConn->retrieveLayerTypes( layerProperty, mUseEstimatedMetadata ); } } if ( mStopped ) { layerProperty.types.clear(); layerProperty.srids.clear(); break; } // Now tell the layer list dialog box... emit setLayerType( layerProperty ); } emit progress( 0, 0 ); emit progressMessage( mStopped ? tr( "Table retrieval stopped." ) : tr( "Table retrieval finished." ) ); QgsPostgresConnPool::instance()->releaseConnection( mConn ); mConn = nullptr; }
void SyncEngine::startSync() { if (_journal->exists()) { QVector< SyncJournalDb::PollInfo > pollInfos = _journal->getPollInfos(); if (!pollInfos.isEmpty()) { qDebug() << "Finish Poll jobs before starting a sync"; CleanupPollsJob *job = new CleanupPollsJob(pollInfos, _account, _journal, _localPath, this); connect(job, SIGNAL(finished()), this, SLOT(startSync())); connect(job, SIGNAL(aborted(QString)), this, SLOT(slotCleanPollsJobAborted(QString))); job->start(); return; } } Q_ASSERT(!_syncRunning); _syncRunning = true; Q_ASSERT(_csync_ctx); if (!QDir(_localPath).exists()) { // No _tr, it should only occur in non-mirall emit csyncError("Unable to find local sync folder."); finalize(false); return; } // Check free size on disk first. const qint64 minFree = criticalFreeSpaceLimit(); const qint64 freeBytes = Utility::freeDiskSpace(_localPath); if (freeBytes >= 0) { qDebug() << "There are" << freeBytes << "bytes available at" << _localPath << "and at least" << minFree << "are required"; if (freeBytes < minFree) { emit csyncError(tr("Only %1 are available, need at least %2 to start", "Placeholders are postfixed with file sizes using Utility::octetsToString()").arg( Utility::octetsToString(freeBytes), Utility::octetsToString(minFree))); finalize(false); return; } } else { qDebug() << "Could not determine free space available at" << _localPath; } _syncedItems.clear(); _syncItemMap.clear(); _needsUpdate = false; csync_resume(_csync_ctx); int fileRecordCount = -1; if (!_journal->exists()) { qDebug() << "=====sync looks new (no DB exists)"; } else { qDebug() << "=====sync with existing DB"; } qDebug() << "=====Using Qt" << qVersion(); #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) qDebug() << "=====Using SSL library version" << QSslSocket::sslLibraryVersionString().toUtf8().data(); #endif fileRecordCount = _journal->getFileRecordCount(); // this creates the DB if it does not exist yet if( fileRecordCount == -1 ) { qDebug() << "No way to create a sync journal!"; emit csyncError(tr("Unable to initialize a sync journal.")); finalize(false); return; // database creation error! } _csync_ctx->read_remote_from_db = true; // This tells csync to never read from the DB if it is empty // thereby speeding up the initial discovery significantly. _csync_ctx->db_is_empty = (fileRecordCount == 0); auto selectiveSyncBlackList = _journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList); bool usingSelectiveSync = (!selectiveSyncBlackList.isEmpty()); qDebug() << (usingSelectiveSync ? "====Using Selective Sync" : "====NOT Using Selective Sync"); csync_set_userdata(_csync_ctx, this); // Set up checksumming hook _csync_ctx->callbacks.checksum_hook = &CSyncChecksumHook::hook; _csync_ctx->callbacks.checksum_userdata = &_checksum_hook; _stopWatch.start(); qDebug() << "#### Discovery start #################################################### >>"; _discoveryMainThread = new DiscoveryMainThread(account()); _discoveryMainThread->setParent(this); connect(this, SIGNAL(finished(bool)), _discoveryMainThread, SLOT(deleteLater())); qDebug() << "=====Server" << account()->serverVersion() << QString("rootEtagChangesNotOnlySubFolderEtags=%1").arg(account()->rootEtagChangesNotOnlySubFolderEtags()); if (account()->rootEtagChangesNotOnlySubFolderEtags()) { connect(_discoveryMainThread, SIGNAL(etag(QString)), this, SLOT(slotRootEtagReceived(QString))); } else { connect(_discoveryMainThread, SIGNAL(etagConcatenation(QString)), this, SLOT(slotRootEtagReceived(QString))); } DiscoveryJob *discoveryJob = new DiscoveryJob(_csync_ctx); discoveryJob->_selectiveSyncBlackList = selectiveSyncBlackList; discoveryJob->_selectiveSyncWhiteList = _journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList); discoveryJob->_newBigFolderSizeLimit = _newBigFolderSizeLimit; discoveryJob->moveToThread(&_thread); connect(discoveryJob, SIGNAL(finished(int)), this, SLOT(slotDiscoveryJobFinished(int))); connect(discoveryJob, SIGNAL(folderDiscovered(bool,QString)), this, SIGNAL(folderDiscovered(bool,QString))); connect(discoveryJob, SIGNAL(newBigFolder(QString)), this, SIGNAL(newBigFolder(QString))); // This is used for the DiscoveryJob to be able to request the main thread/ // to read in directory contents. qDebug() << Q_FUNC_INFO << _remotePath << _remoteUrl; _discoveryMainThread->setupHooks( discoveryJob, _remotePath); // Starts the update in a seperate thread QMetaObject::invokeMethod(discoveryJob, "start", Qt::QueuedConnection); }
void BaseSqlTableModel::select() { if (!m_bInitialized) { return; } // We should be able to detect when a select() would be a no-op. The DAO's // do not currently broadcast signals for when common things happen. In the // future, we can turn this check on and avoid a lot of needless // select()'s. rryan 9/2011 // if (!m_bDirty) { // if (sDebug) { // qDebug() << this << "Skipping non-dirty select()"; // } // return; // } if (sDebug) { qDebug() << this << "select()"; } PerformanceTimer time; time.start(); // Prepare query for id and all columns not in m_trackSource QString queryString = QString("SELECT %1 FROM %2 %3") .arg(m_tableColumnsJoined, m_tableName, m_tableOrderBy); if (sDebug) { qDebug() << this << "select() executing:" << queryString; } QSqlQuery query(m_database); // This causes a memory savings since QSqlCachedResult (what QtSQLite uses) // won't allocate a giant in-memory table that we won't use at all. query.setForwardOnly(true); query.prepare(queryString); if (!query.exec()) { LOG_FAILED_QUERY(query); return; } // Remove all the rows from the table. We wait to do this until after the // table query has succeeded. See Bug #1090888. // TODO(rryan) we could edit the table in place instead of clearing it? if (!m_rowInfo.isEmpty()) { beginRemoveRows(QModelIndex(), 0, m_rowInfo.size() - 1); m_rowInfo.clear(); m_trackIdToRows.clear(); endRemoveRows(); } // sqlite does not set size and m_rowInfo was just cleared //if (sDebug) { // qDebug() << "Rows returned" << rows << m_rowInfo.size(); //} QVector<RowInfo> rowInfo; QSet<TrackId> trackIds; while (query.next()) { TrackId trackId(query.value(kIdColumn)); trackIds.insert(trackId); RowInfo thisRowInfo; thisRowInfo.trackId = trackId; // save rows where this currently track id is located thisRowInfo.order = rowInfo.size(); // Get all the table columns and store them in the hash for this // row-info section. thisRowInfo.metadata.reserve(m_tableColumns.size()); for (int i = 0; i < m_tableColumns.size(); ++i) { thisRowInfo.metadata << query.value(i); } rowInfo.push_back(thisRowInfo); } if (sDebug) { qDebug() << "Rows actually received:" << rowInfo.size(); } if (m_trackSource) { m_trackSource->filterAndSort(trackIds, m_currentSearch, m_currentSearchFilter, m_trackSourceOrderBy, m_trackSourceSortColumn, m_trackSourceSortOrder, &m_trackSortOrder); // Re-sort the track IDs since filterAndSort can change their order or mark // them for removal (by setting their row to -1). for (QVector<RowInfo>::iterator it = rowInfo.begin(); it != rowInfo.end(); ++it) { // If the sort is not a track column then we will sort only to // separate removed tracks (order == -1) from present tracks (order == // 0). Otherwise we sort by the order that filterAndSort returned to us. if (m_trackSourceOrderBy.isEmpty()) { it->order = m_trackSortOrder.contains(it->trackId) ? 0 : -1; } else { it->order = m_trackSortOrder.value(it->trackId, -1); } } } // RowInfo::operator< sorts by the order field, except -1 is placed at the // end so we can easily slice off rows that are no longer present. Stable // sort is necessary because the tracks may be in pre-sorted order so we // should not disturb that if we are only removing tracks. qStableSort(rowInfo.begin(), rowInfo.end()); m_trackIdToRows.clear(); for (int i = 0; i < rowInfo.size(); ++i) { const RowInfo& row = rowInfo[i]; if (row.order == -1) { // We've reached the end of valid rows. Resize rowInfo to cut off // this and all further elements. rowInfo.resize(i); break; } QLinkedList<int>& rows = m_trackIdToRows[row.trackId]; rows.push_back(i); } // We're done! Issue the update signals and replace the master maps. if (!rowInfo.isEmpty()) { beginInsertRows(QModelIndex(), 0, rowInfo.size() - 1); m_rowInfo = rowInfo; endInsertRows(); } qDebug() << this << "select() took" << time.elapsed().formatMillisWithUnit() << rowInfo.size(); }
// ==== DELETE ==== // Delete type void MainWindow::deleteType(){ QVector<int> ids = utilities::getSelectedTableViewIds(ui->typesTable); // No rows if (ids.isEmpty()) { return; } int numRows = ids.size(); QString deleteConfirmMessage = ""; QString statusBarMessage = ""; // Get all the machines that are about to be deleted QVector<TypeSystem> typesToBeDeleted; for(int i = 0; i < numRows;i++){ // An empty machine TypeSystem ts; // Set machine ID to the ID of the row ts.setId(ids[i]); // Get the machine info by ID if(!servicesLayer.getTypeSystem(ts, 1, error)){ checkError(); return; } // Add to vector typesToBeDeleted.push_back(ts); } // Single row if(numRows == 1){ deleteConfirmMessage = "Are you sure you want to delete " + typesToBeDeleted[0].getName() + "?"; statusBarMessage = typesToBeDeleted[0].getName() + " deleted"; } // Rows less than 11 else if(numRows > 1 && numRows < 11){ deleteConfirmMessage = "Are you sure you want to delete:\n"; // Loop over names for(int i = 0; i < numRows;i++){ deleteConfirmMessage += typesToBeDeleted[i].getName() + "\n"; } statusBarMessage = QString::number(numRows) + " entries deleted"; } // More than 10 else{ deleteConfirmMessage = "Are you sure you want to delete these " + QString::number(numRows) + " entries?"; statusBarMessage = QString::number(numRows) + " entries deleted"; } // Confirmation window int ans = QMessageBox::question(this, "Confirmation", deleteConfirmMessage, QMessageBox::Yes|QMessageBox::No, QMessageBox::No); // Check answer if (ans == QMessageBox::Yes) { // Delete if(!servicesLayer.deleteTypeSystem(typesToBeDeleted, 1, error)){ checkError(); return; } // Disable Person edit and delete buttons disableEditDeleteTypeButtons(); // Status bar update ui->statusBar->showMessage(statusBarMessage, constants::STATUSBAR_MESSAGE_TIME); // Re-display checkTypeSearch(); displayMachinesTable(); displayConnectionsTable(); } }
void PainterThread::drawAttrib(QPainter *p, Attributes *attrib) { if (attrib->getType() == TObsAgent) return; //---- Desenha o atributo p->begin(attrib->getImage()); p->setPen(Qt::NoPen); //defaultPen); //@RAIAN: Desenhando a vizinhanca if(attrib->getType() == TObsNeighborhood) { QColor color(Qt::white); QVector<QMap<QString, QList<double> > > *neighborhoods = attrib->getNeighValues(); QVector<ObsLegend> *vecLegend = attrib->getLegend(); QPen pen = p->pen(); pen.setStyle(Qt::SolidLine); pen.setWidth(attrib->getWidth()); // int random = rand() % 256; double xCell = -1.0, yCell = -1.0; for(int pos = 0; pos < neighborhoods->size(); pos++) { QMap<QString, QList<double> > neigh = neighborhoods->at(pos); xCell = attrib->getXsValue()->at(pos); yCell = attrib->getYsValue()->at(pos); if((xCell >= 0) && (yCell >=0)) { QMap<QString, QList<double> >::Iterator itNeigh = neigh.begin(); while(itNeigh != neigh.end()) { QString neighID = itNeigh.key(); QList<double> neighbor = itNeigh.value(); double xNeigh = neighbor.at(0); double yNeigh = neighbor.at(1); double weight = neighbor.at(2); if(vecLegend->isEmpty()) { weight = weight - attrib->getMinValue(); double c = weight * attrib->getVal2Color(); if(c >= 0 && c <= 255) { color.setRgb(c, c, c); } else { if( !reconfigMaxMin ) { printf("C++ - Min value: %f\n", attrib->getMinValue()); printf("C++ - Max value: %f\n", attrib->getMaxValue()); printf("C++ - c value: %f\n", c); qWarning("Warning: Invalid color. You need to reconfigure the maximum " "and the minimum values of the \"%s\".", qPrintable(attrib->getName()) ); reconfigMaxMin = true; } color.setRgb(255, 255, 255); } pen.setColor(color); } else { for(int j = 0; j < vecLegend->size(); j++) { ObsLegend leg = vecLegend->at(j); if(attrib->getGroupMode() == 3) { if(weight == leg.getTo().toDouble()) { pen.setColor(leg.getColor()); break; } } else { if((leg.getFrom().toDouble() <= weight) && (weight < leg.getTo().toDouble())) { pen.setColor(leg.getColor()); break; } } } } p->setPen(pen); if((xNeigh >= 0) && (yNeigh >= 0)) { drawNeighborhood(p, xCell, yCell, xNeigh, yNeigh); } itNeigh++; } } } } //@RAIAN: FIM else { if (attrib->getDataType() == TObsNumber) { QColor color(Qt::white); QVector<double> *values = attrib->getNumericValues(); QVector<ObsLegend> *vecLegend = attrib->getLegend(); double x = -1.0, y = -1.0, v = 0.0; #ifdef DEBUG_OBSERVER // if (attrib->getType() != TObsCell) { qDebug() << "\n----TObsNumber\nattrib->getXsValue()->size(): " << attrib->getXsValue()->size(); qDebug() << "values->size(): " << values->size() << "\n----\n"; } #endif int vSize = values->size(); int xSize = attrib->getXsValue()->size(); int ySize = attrib->getYsValue()->size(); for(int pos = 0; (pos < vSize && pos < xSize && pos < ySize); pos++) { v = values->at(pos); // Corrige o bug gerando quando um agente morre if (attrib->getXsValue()->isEmpty() || attrib->getXsValue()->size() == pos) break; x = attrib->getXsValue()->at(pos); y = attrib->getYsValue()->at(pos); if (vecLegend->isEmpty()) { v = v - attrib->getMinValue(); double c = v * attrib->getVal2Color(); if ((c >= 0) && (c <= 255)) { color.setRgb(c, c, c); } else { if (! reconfigMaxMin) { if (! QUIET_MODE ) qWarning("Warning: Invalid color. You need to reconfigure the " "maximum and the minimum values of the attribute \"%s\".", qPrintable(attrib->getName()) ); reconfigMaxMin = true; } color.setRgb(255, 255, 255); } p->setBrush(color); } else { for(int j = 0; j < vecLegend->size(); j++) { p->setBrush(Qt::white); const ObsLegend &leg = vecLegend->at(j); if (attrib->getGroupMode() == TObsUniqueValue) // valor único 3 { if (v == leg.getToNumber()) { p->setBrush(leg.getColor()); break; } } else { if ((leg.getFromNumber() <= v) && (v < leg.getToNumber())) { p->setBrush(leg.getColor()); break; } } } } if ((x >= 0) && ( y >= 0)) draw(p, attrib->getType(), x, y); } } else if (attrib->getDataType() == TObsText) { QVector<QString> *values = attrib->getTextValues(); QVector<ObsLegend> *vecLegend = attrib->getLegend(); #ifdef DEBUG_OBSERVER if (attrib->getType() != TObsCell) { qDebug() << "\n----TObsNumber\nattrib->getXsValue()->size(): " << attrib->getXsValue()->size(); qDebug() << "values->size(): " << values->size() << "\n----\n"; } #endif int random = rand() % 256; double x = -1.0, y = -1.0; int vSize = values->size(); int xSize = attrib->getXsValue()->size(); int ySize = attrib->getYsValue()->size(); for (int pos = 0; (pos < vSize && pos < xSize && pos < ySize); pos++) { const QString & v = values->at(pos); // Corrige o bug gerando quando um agente morre if (attrib->getXsValue()->isEmpty() || attrib->getXsValue()->size() == pos) break; x = attrib->getXsValue()->at(pos); y = attrib->getYsValue()->at(pos); if (vecLegend->isEmpty()) { p->setBrush(QColor(random, random, random)); } else { p->setBrush(Qt::white); for(int j = 0; j < vecLegend->size(); j++) { const ObsLegend &leg = vecLegend->at(j); if (v == leg.getFrom()) { p->setBrush(leg.getColor()); break; } } } if ((x >= 0) && ( y >= 0)) draw(p, attrib->getType(), x, y); } } } p->end(); }
void QtWebEngineUrlRequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo &request) { if (!m_areImagesEnabled && request.resourceType() == QWebEngineUrlRequestInfo::ResourceTypeImage) { request.block(true); return; } if (!m_contentBlockingProfiles.contains(request.firstPartyUrl().host())) { if (SettingsManager::getOption(SettingsManager::ContentBlocking_EnableContentBlockingOption, request.firstPartyUrl()).toBool()) { m_contentBlockingProfiles[request.firstPartyUrl().host()] = ContentBlockingManager::getProfileList(SettingsManager::getOption(SettingsManager::ContentBlocking_ProfilesOption, request.firstPartyUrl()).toStringList()); } else { m_contentBlockingProfiles[request.firstPartyUrl().host()] = QVector<int>(); } } const QVector<int> contentBlockingProfiles(m_contentBlockingProfiles.value(request.firstPartyUrl().host())); if (contentBlockingProfiles.isEmpty()) { const NetworkManagerFactory::DoNotTrackPolicy doNotTrackPolicy(NetworkManagerFactory::getDoNotTrackPolicy()); if (doNotTrackPolicy != NetworkManagerFactory::SkipTrackPolicy) { request.setHttpHeader(QStringLiteral("DNT").toLatin1(), ((doNotTrackPolicy == NetworkManagerFactory::DoNotAllowToTrackPolicy) ? QStringLiteral("1") : QStringLiteral("0")).toLatin1()); } return; } NetworkManager::ResourceType resourceType(NetworkManager::OtherType); bool storeBlockedUrl(true); switch (request.resourceType()) { case QWebEngineUrlRequestInfo::ResourceTypeMainFrame: resourceType = NetworkManager::MainFrameType; break; case QWebEngineUrlRequestInfo::ResourceTypeSubFrame: resourceType = NetworkManager::SubFrameType; break; case QWebEngineUrlRequestInfo::ResourceTypeStylesheet: resourceType = NetworkManager::StyleSheetType; storeBlockedUrl = false; break; case QWebEngineUrlRequestInfo::ResourceTypeScript: resourceType = NetworkManager::ScriptType; storeBlockedUrl = false; break; case QWebEngineUrlRequestInfo::ResourceTypeImage: resourceType = NetworkManager::ImageType; break; case QWebEngineUrlRequestInfo::ResourceTypeObject: case QWebEngineUrlRequestInfo::ResourceTypeMedia: resourceType = NetworkManager::ObjectType; break; #if QT_VERSION >= 0x050700 case QWebEngineUrlRequestInfo::ResourceTypePluginResource: resourceType = NetworkManager::ObjectSubrequestType; storeBlockedUrl = false; break; #endif case QWebEngineUrlRequestInfo::ResourceTypeXhr: resourceType = NetworkManager::XmlHttpRequestType; break; default: break; } const ContentBlockingManager::CheckResult result(ContentBlockingManager::checkUrl(contentBlockingProfiles, request.firstPartyUrl(), request.requestUrl(), resourceType)); if (result.isBlocked) { if (storeBlockedUrl && !m_blockedElements.value(request.firstPartyUrl().host()).contains(request.requestUrl().url())) { m_blockedElements[request.firstPartyUrl().host()].append(request.requestUrl().url()); } Console::addMessage(QCoreApplication::translate("main", "Request blocked with rule: %1").arg(result.rule), Console::NetworkCategory, Console::LogLevel, request.requestUrl().toString(), -1); request.block(true); } }
void SongTest::testSearch1() { Echonest::Song::SearchParams params; params.append( Echonest::Song::SearchParamData( Echonest::Song::Artist, QLatin1String("Modest Mouse") ) ); params.append( Echonest::Song::SearchParamData( Echonest::Song::Title, QLatin1String("Float On") ) ); params.append( Echonest::Song::SearchParamData( Echonest::Song::Results, 2 ) ); QNetworkReply* reply = Echonest::Song::search( params, Echonest::SongInformation( Echonest::SongInformation::ArtistHotttnesss | Echonest::SongInformation::ArtistLocation | Echonest::SongInformation::ArtistFamiliarity ) ); qDebug() << "Test search:" << reply->url().toString(); QEventLoop loop; loop.connect( reply, SIGNAL(finished()), SLOT(quit()) ); loop.exec(); QVector< Echonest::Song > songs = Echonest::Song::parseSearch( reply ); qDebug() << songs << songs.size(); QVERIFY( !songs.isEmpty() ); for(int i = 0; i < songs.size(); i++) { Echonest::Song song = songs.value(i); QLatin1String title = QLatin1String( "float on" ); QCOMPARE( song.title().toLower(), title ); QCOMPARE( song.artistName().toLower(), QLatin1String( "modest mouse" ) ); QVERIFY( !song.artistLocation().location.isEmpty() ); QCOMPARE( song.hotttnesss(), -1. ); qDebug() << song.hotttnesss() << song.artistHotttnesss() << song.artistFamiliarity() << song.artistLocation(); // now fetch some more info and make sure everything is still sane QNetworkReply* moreInfo = song.fetchInformation( Echonest::SongInformation( Echonest::SongInformation::Hotttnesss ) ); QEventLoop loop; loop.connect( moreInfo, SIGNAL(finished()), SLOT(quit()) ); loop.exec(); song.parseInformation( moreInfo ); QCOMPARE( song.title().toLower(), title ); QCOMPARE( song.artistName().toLower(), QLatin1String( "modest mouse" ) ); QVERIFY( !song.artistLocation().location.isEmpty() ); // make sure we got the new info QVERIFY( song.hotttnesss() != -1 ); } params.clear(); params.append( Echonest::Song::SearchParamData( Echonest::Song::Artist, QLatin1String("The Tallest Man On Earth") ) ); params.append( Echonest::Song::SearchParamData( Echonest::Song::Title, QLatin1String("The King of Spain") ) ); params.append( Echonest::Song::SearchParamData( Echonest::Song::Results, 3 ) ); Echonest::SongInformation info( Echonest::SongInformation( Echonest::SongInformation::AudioSummaryInformation | Echonest::SongInformation::Tracks | Echonest::SongInformation::Hotttnesss ) ); info.setIdSpaces( QStringList() << QLatin1String( "musicbrainz" ) << QLatin1String( "playme" ) ); reply = Echonest::Song::search( params, info); qDebug() << "QUERY:" << reply->url().toString(); loop.connect( reply, SIGNAL(finished()), SLOT(quit()) ); loop.exec(); songs = Echonest::Song::parseSearch( reply ); qDebug() << songs << songs.size(); foreach( const Echonest::Song& song, songs ) { // qDebug() << "SONG TRACKS:" << song.tracks(); foreach( const Echonest::Track& track, song.tracks() ) { // qDebug() << track.catalog() << track.foreignId(); QVERIFY( !track.catalog().isEmpty() ); QVERIFY( !track.foreignId().isEmpty() ); } }
void QmlProfilerEventsModelProxy::loadData(qint64 rangeStart, qint64 rangeEnd) { clear(); qint64 qmlTime = 0; qint64 lastEndTime = 0; QHash <QString, QVector<qint64> > durations; const bool checkRanges = (rangeStart != -1) && (rangeEnd != -1); const QVector<QmlProfilerDataModel::QmlEventData> eventList = d->modelManager->qmlModel()->getEvents(); // used by binding loop detection typedef QPair<QString, const QmlProfilerDataModel::QmlEventData*> CallStackEntry; QStack<CallStackEntry> callStack; callStack.push(CallStackEntry(QString(), 0)); // artificial root for (int i = 0; i < eventList.size(); ++i) { const QmlProfilerDataModel::QmlEventData *event = &eventList[i]; if (!d->acceptedTypes.contains((QmlDebug::QmlEventType)event->eventType)) continue; if (checkRanges) { if ((event->startTime + event->duration < rangeStart) || (event->startTime > rangeEnd)) continue; } // put event in hash QString hash = QmlProfilerDataModel::getHashString(*event); if (!d->data.contains(hash)) { QmlEventStats stats = { event->displayName, hash, event->data.join(QLatin1String(" ")), event->location, event->eventType, event->bindingType, event->duration, 1, //calls event->duration, //minTime event->duration, // maxTime 0, //timePerCall 0, //percentOfTime 0, //medianTime false //isBindingLoop }; d->data.insert(hash, stats); // for median computing durations.insert(hash, QVector<qint64>()); durations[hash].append(event->duration); } else { // update stats QmlEventStats *stats = &d->data[hash]; stats->duration += event->duration; if (event->duration < stats->minTime) stats->minTime = event->duration; if (event->duration > stats->maxTime) stats->maxTime = event->duration; stats->calls++; // for median computing durations[hash].append(event->duration); } // qml time computation if (event->startTime > lastEndTime) { // assume parent event if starts before last end qmlTime += event->duration; lastEndTime = event->startTime + event->duration; } // // binding loop detection // const QmlProfilerDataModel::QmlEventData *potentialParent = callStack.top().second; while (potentialParent && !(potentialParent->startTime + potentialParent->duration > event->startTime)) { callStack.pop(); potentialParent = callStack.top().second; } // check whether event is already in stack bool inLoop = false; for (int ii = 1; ii < callStack.size(); ++ii) { if (callStack.at(ii).first == hash) inLoop = true; if (inLoop) d->eventsInBindingLoop.insert(hash); } CallStackEntry newEntry(hash, event); callStack.push(newEntry); d->modelManager->modelProxyCountUpdated(d->modelId, i, eventList.count()*2); } // post-process: calc mean time, median time, percentoftime int i = d->data.size(); int total = i * 2; foreach (const QString &hash, d->data.keys()) { QmlEventStats* stats = &d->data[hash]; if (stats->calls > 0) stats->timePerCall = stats->duration / (double)stats->calls; QVector<qint64> eventDurations = durations.value(hash); if (!eventDurations.isEmpty()) { qSort(eventDurations); stats->medianTime = eventDurations.at(eventDurations.count()/2); } stats->percentOfTime = stats->duration * 100.0 / qmlTime; d->modelManager->modelProxyCountUpdated(d->modelId, i++, total); } // set binding loop flag foreach (const QString &eventHash, d->eventsInBindingLoop) d->data[eventHash].isBindingLoop = true; QString rootEventName = tr("<program>"); QmlDebug::QmlEventLocation rootEventLocation(rootEventName, 1, 1); // insert root event QmlEventStats rootEvent = { rootEventName, //event.displayName, rootEventName, // hash tr("Main Program"), //event.details, rootEventLocation, // location (int)QmlDebug::Binding, // event type 0, // binding type qmlTime + 1, 1, //calls qmlTime + 1, //minTime qmlTime + 1, // maxTime qmlTime + 1, //timePerCall 100.0, //percentOfTime qmlTime + 1, //medianTime; false }; d->data.insert(rootEventName, rootEvent); d->modelManager->modelProxyCountUpdated(d->modelId, 1, 1); emit dataAvailable(); }
/*! \fn void QTextTable::insertColumns(int index, int columns) Inserts a number of \a columns before the column with the specified \a index. \sa insertRows(), resize(), removeRows(), removeColumns(), appendRows(), appendColumns() */ void QTextTable::insertColumns(int pos, int num) { Q_D(QTextTable); if (num <= 0) return; if (d->dirty) d->update(); if (pos > d->nCols || pos < 0) pos = d->nCols; // qDebug() << "-------- insertCols" << pos << num; QTextDocumentPrivate *p = d->pieceTable; QTextFormatCollection *c = p->formatCollection(); p->beginEditBlock(); QList<int> extendedSpans; for (int i = 0; i < d->nRows; ++i) { int cell; if (i == d->nRows - 1 && pos == d->nCols) { cell = d->fragment_end; } else { int logicalGridIndexBeforePosition = pos > 0 ? d->findCellIndex(d->grid[i*d->nCols + pos - 1]) : -1; // Search for the logical insertion point by skipping past cells which are not the first // cell in a rowspan. This means any cell for which the logical grid index is // less than the logical cell index of the cell before the insertion. int logicalGridIndex; int gridArrayOffset = i*d->nCols + pos; do { cell = d->grid[gridArrayOffset]; logicalGridIndex = d->findCellIndex(cell); gridArrayOffset++; } while (logicalGridIndex < logicalGridIndexBeforePosition && gridArrayOffset < d->nRows*d->nCols); if (logicalGridIndex < logicalGridIndexBeforePosition && gridArrayOffset == d->nRows*d->nCols) cell = d->fragment_end; } if (pos > 0 && pos < d->nCols && cell == d->grid[i*d->nCols + pos - 1]) { // cell spans the insertion place, extend it if (!extendedSpans.contains(cell)) { QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell); QTextCharFormat fmt = c->charFormat(it->format); fmt.setTableCellColumnSpan(fmt.tableCellColumnSpan() + num); p->setCharFormat(it.position(), 1, fmt); d->dirty = true; extendedSpans << cell; } } else { /* If the next cell is spanned from the row above, we need to find the right position to insert to */ if (i > 0 && pos < d->nCols && cell == d->grid[(i-1) * d->nCols + pos]) { int gridIndex = i*d->nCols + pos; const int gridEnd = d->nRows * d->nCols - 1; while (gridIndex < gridEnd && cell == d->grid[gridIndex]) { ++gridIndex; } if (gridIndex == gridEnd) cell = d->fragment_end; else cell = d->grid[gridIndex]; } QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell); QTextCharFormat fmt = c->charFormat(it->format); fmt.setTableCellRowSpan(1); fmt.setTableCellColumnSpan(1); Q_ASSERT(fmt.objectIndex() == objectIndex()); int position = it.position(); int cfmt = p->formatCollection()->indexForFormat(fmt); int bfmt = p->formatCollection()->indexForFormat(QTextBlockFormat()); for (int i = 0; i < num; ++i) p->insertBlock(QTextBeginningOfFrame, position, bfmt, cfmt, QTextUndoCommand::MoveCursor); } } QTextTableFormat tfmt = format(); tfmt.setColumns(tfmt.columns()+num); QVector<QTextLength> columnWidths = tfmt.columnWidthConstraints(); if (! columnWidths.isEmpty()) { for (int i = num; i > 0; --i) columnWidths.insert(pos, columnWidths[qMax(0, pos-1)]); } tfmt.setColumnWidthConstraints (columnWidths); QTextObject::setFormat(tfmt); // qDebug() << "-------- end insertCols" << pos << num; p->endEditBlock(); }