Пример #1
0
bool QQuickContext2DTexture::setDirtyRect(const QRect &r)
{
    bool doDirty = false;
    if (m_tiledCanvas) {
        for (QQuickContext2DTile* t : qAsConst(m_tiles)) {
            bool dirty = t->rect().intersected(r).isValid();
            t->markDirty(dirty);
            if (dirty)
                doDirty = true;
        }
    } else {
        doDirty = m_canvasWindow.intersected(r).isValid();
    }
    return doDirty;
}
Пример #2
0
void TilesetManager::advanceTileAnimations(int ms)
{
    // TODO: This could be more optimal by keeping track of the list of
    // actually animated tiles

    for (Tileset *tileset : qAsConst(mTilesets)) {
        bool imageChanged = false;

        for (Tile *tile : tileset->tiles())
            imageChanged |= tile->advanceAnimation(ms);

        if (imageChanged)
            emit repaintTileset(tileset);
    }
}
Пример #3
0
void TilesetManager::filesChanged(const QStringList &fileNames)
{
    if (!mReloadTilesetsOnChange)
        return;

    for (const QString &fileName : fileNames)
        ImageCache::remove(fileName);

    for (Tileset *tileset : qAsConst(mTilesets)) {
        const QString fileName = tileset->imageSource().toLocalFile();
        if (fileNames.contains(fileName))
            if (tileset->loadImage())
                emit tilesetImagesChanged(tileset);
    }
}
Пример #4
0
QVariantHash ImageUploader::loadSettings(const QString &uploaderType)
{
    auto globalSettings = ScreenshotManager::instance()->settings();
    globalSettings->beginGroup("upload/" + uploaderType);
    auto keys = globalSettings->childKeys();

    QVariantHash settings;

    for (auto key : qAsConst(keys)) {
        settings[key] = globalSettings->value(key);
    }

    globalSettings->endGroup();
    return settings;
}
Пример #5
0
void BasicBlock::setStatements(const QVector<Stmt *> &newStatements)
{
    Q_ASSERT(!isRemoved());
    Q_ASSERT(newStatements.size() >= _statements.size());
    for (Stmt *s : qAsConst(_statements)) {
        if (Phi *p = s->asPhi()) {
            if (!newStatements.contains(p)) {
                // phi-node was not copied over, so:
                p->destroyData();
            }
        } else {
            break;
        }
    }
    _statements = newStatements;
}
Пример #6
0
QXcbCursor::~QXcbCursor()
{
    xcb_connection_t *conn = xcb_connection();

    if (m_gtkCursorThemeInitialized) {
        m_screen->xSettings()->removeCallbackForHandle(this);
    }

    if (!--cursorCount)
        xcb_close_font(conn, cursorFont);

#ifndef QT_NO_CURSOR
    for (xcb_cursor_t cursor : qAsConst(m_cursorHash))
        xcb_free_cursor(conn, cursor);
#endif
}
void HighlightScrollBarOverlay::drawHighlights(QPainter *painter,
                                          int docStart,
                                          int docSize,
                                          double docSizeToHandleSizeRatio,
                                          int handleOffset,
                                          const QRect &viewport)
{
    if (docSize <= 0)
        return;

    painter->save();
    painter->setClipRect(viewport);

    const double lineHeight = m_highlightController->lineHeight();

    for (const QMap<Utils::Theme::Color, QMap<int, int>> &colors : qAsConst(m_highlightCache)) {
        const auto itColorEnd = colors.constEnd();
        for (auto itColor = colors.constBegin(); itColor != itColorEnd; ++itColor) {
            const QColor &color = creatorTheme()->color(itColor.key());
            const QMap<int, int> &positions = itColor.value();
            const auto itPosEnd = positions.constEnd();
            const int firstPos = int(docStart / lineHeight);
            auto itPos = positions.upperBound(firstPos);
            if (itPos != positions.constBegin())
                --itPos;
            while (itPos != itPosEnd) {
                const double posStart = itPos.key() * lineHeight;
                const double posEnd = (itPos.value() + 1) * lineHeight;
                if (posEnd < docStart) {
                    ++itPos;
                    continue;
                }
                if (posStart > docStart + docSize)
                    break;

                const int height = qMax(qRound((posEnd - posStart) * docSizeToHandleSizeRatio), 1);
                const int top = qRound(posStart * docSizeToHandleSizeRatio) - handleOffset + viewport.y();

                const QRect rect(viewport.left(), top, viewport.width(), height);
                painter->fillRect(rect, color);
                ++itPos;
            }
        }
    }
    painter->restore();
}
Пример #8
0
void CommandLineFrontend::makeClean()
{
    if (m_parser.products().empty()) {
        for (const Project &project : qAsConst(m_projects)) {
            m_buildJobs << project.cleanAllProducts(m_parser.cleanOptions(project.profile()), this);
        }
    } else {
        const ProductMap &products = productsToUse();
        for (ProductMap::ConstIterator it = products.begin(); it != products.end(); ++it) {
            m_buildJobs.push_back(it.key().cleanSomeProducts(
                                      it.value(),
                                      m_parser.cleanOptions(it.key().profile()),
                                      this));
        }
    }
    connectBuildJobs();
}
Пример #9
0
void QV4DebugServiceImpl::signalEmitted(const QString &signal)
{
    //This function is only called by QQmlBoundSignal
    //only if there is a slot connected to the signal. Hence, there
    //is no need for additional check.

    //Parse just the name and remove the class info
    //Normalize to Lower case.
    QString signalName = signal.left(signal.indexOf(QLatin1Char('('))).toLower();

    for (const QString &signal : qAsConst(breakOnSignals)) {
        if (signal == signalName) {
            // TODO: pause debugger
            break;
        }
    }
}
Пример #10
0
/************************************************
 Any number of <MergeFile> elements may be listed below a <Menu> element, giving
 the name of another menu file to be merged into this one.
 If fileName is not an absolute path then the file to be merged should be located
 relative to the location of this menu.

 If the type attribute is missing or set to "path" then the contents of the
 <MergeFile> element indicates the file to be merged.

 If the type attribute is set to "parent" and the file that contains this
 <MergeFile> element is located under one of the paths specified by
 $XDG_CONFIG_DIRS, the contents of the element should be ignored and the remaining
 paths specified by $XDG_CONFIG_DIRS are searched for a file with the same relative
 filename. The first file encountered should be merged. There should be no merging
 at all if no matching file is found. ( Libmenu additional scans ~/.config/menus.)
 ************************************************/
void XdgMenuReader::processMergeFileTag(QDomElement& element, QStringList* mergedFiles)
{
    //qDebug() << "Process " << element;// << "in" << mFileName;

    if (element.attribute(QLatin1String("type")) != QLatin1String("parent"))
    {
        mergeFile(element.text(), element, mergedFiles);
    }

    else
    {
        QString relativeName;
        QStringList configDirs = XdgDirs::configDirs();

        for (const QString &configDir : qAsConst(configDirs))
        {
            if (mFileName.startsWith(configDir))
            {
                relativeName = mFileName.mid(configDir.length());
                configDirs.removeAll(configDir);
                break;
            }
        }


        if (relativeName.isEmpty())
        {
            QString configHome = XdgDirs::configHome();
            if (mFileName.startsWith(configHome))
                relativeName = mFileName.mid(configHome.length());
        }

        if (relativeName.isEmpty())
            return;

        for (const QString &configDir : configDirs)
        {
            if (QFileInfo::exists(configDir + relativeName))
            {
                mergeFile(configDir + relativeName, element, mergedFiles);
                return;
            }
        }
    }
}
Пример #11
0
void QQuickMultiPointTouchArea::addTouchPoint(const QMouseEvent *e)
{
    QQuickTouchPoint *dtp = 0;
    for (QQuickTouchPoint *tp : qAsConst(_touchPrototypes))
        if (!tp->inUse()) {
            tp->setInUse(true);
            dtp = tp;
            break;
        }

    if (dtp == 0)
        dtp = new QQuickTouchPoint(false);
    updateTouchPoint(dtp, e);
    dtp->setPressed(true);
    _touchPoints.insert(-1, dtp);
    _pressedTouchPoints.append(dtp);
    _mouseTouchPoint = dtp;
}
void PerfTimelineModelManager::finalize()
{
    QVector<PerfTimelineModel *> finished;
    QHash<quint32, PerfProfilerTraceManager::Thread> threads = m_traceManager->threads();
    for (auto it = m_unfinished.begin(), end = m_unfinished.end(); it != end; ++it) {
        PerfTimelineModel *model = *it;

        const PerfProfilerTraceManager::Thread &thread = m_traceManager->thread(model->tid());
        if (thread.enabled) {
            model->setDisplayName(displayNameForThread(thread, m_traceManager));
            model->finalize();
            finished.append(model);
        } else {
            delete model;
        }
    }
    m_unfinished.clear();

    const qint64 frequency = m_traceManager->samplingFrequency();
    for (PerfTimelineModel *model : qAsConst(finished)) {
        model->setSamplingFrequency(frequency);
        threads.remove(model->tid());
    }

    for (const PerfProfilerTraceManager::Thread &remaining : threads) {
        if (!remaining.enabled)
            continue;
        PerfTimelineModel *model = new PerfTimelineModel(
                    remaining.pid, remaining.tid, remaining.firstEvent, remaining.lastEvent, this);
        model->setDisplayName(displayNameForThread(remaining, m_traceManager));
        model->finalize();
        model->setSamplingFrequency(frequency);
        finished.append(model);
    }

    std::sort(finished.begin(), finished.end(), [](PerfTimelineModel *a, PerfTimelineModel *b) {
        return a->tid() < b->tid();
    });

    QVariantList modelsToAdd;
    for (PerfTimelineModel *model : finished)
        modelsToAdd.append(QVariant::fromValue(model));
    setModels(modelsToAdd);
}
Пример #13
0
/**
 * This function will first remove system cache files, e.g. `Thumbs.db`,
 * `.DS_Store`. Then will try to remove the whole tree if the tree consist
 * only of folders
 */
bool Utils::Fs::smartRemoveEmptyFolderTree(const QString &path)
{
    if (path.isEmpty() || !QDir(path).exists())
        return true;

    static const QStringList deleteFilesList = {
        // Windows
        "Thumbs.db",
        "desktop.ini",
        // Linux
        ".directory",
        // Mac OS
        ".DS_Store"
    };

    // travel from the deepest folder and remove anything unwanted on the way out.
    QStringList dirList(path + "/");  // get all sub directories paths
    QDirIterator iter(path, (QDir::AllDirs | QDir::NoDotAndDotDot), QDirIterator::Subdirectories);
    while (iter.hasNext())
        dirList << iter.next() + "/";
    // sort descending by directory depth
    std::sort(dirList.begin(), dirList.end()
              , [](const QString &l, const QString &r) { return l.count("/") > r.count("/"); });

    for (const QString &p : qAsConst(dirList)) {
        // remove unwanted files
        for (const QString &f : deleteFilesList) {
            forceRemove(p + f);
        }

        // remove temp files on linux (file ends with '~'), e.g. `filename~`
        QDir dir(p);
        QStringList tmpFileList = dir.entryList(QDir::Files);
        for (const QString &f : tmpFileList) {
            if (f.endsWith("~"))
                forceRemove(p + f);
        }

        // remove directory if empty
        dir.rmdir(p);
    }

    return QDir(path).exists();
}
Пример #14
0
void QQuickMultiPointTouchArea::addTouchPoint(const QTouchEvent::TouchPoint *p)
{
    QQuickTouchPoint *dtp = 0;
    for (QQuickTouchPoint* tp : qAsConst(_touchPrototypes)) {
        if (!tp->inUse()) {
            tp->setInUse(true);
            dtp = tp;
            break;
        }
    }

    if (dtp == 0)
        dtp = new QQuickTouchPoint(false);
    dtp->setPointId(p->id());
    updateTouchPoint(dtp,p);
    dtp->setPressed(true);
    _touchPoints.insert(p->id(),dtp);
    _pressedTouchPoints.append(dtp);
}
Пример #15
0
/**
 * Returns the value of the property \a name, taking into account that it may
 * be inherited from another object or from the type.
 *
 * - A Tile instance can inherit properties based on its type
 * - A MapObject instance can inherit properties based on:
 *      - Its template object
 *      - Its tile
 *      - Its type (or the type of its tile)
 */
QVariant Object::inheritedProperty(const QString &name) const
{
    if (hasProperty(name))
        return property(name);

    QString objectType;

    switch (typeId()) {
    case MapObjectType: {
        auto mapObject = static_cast<const MapObject*>(this);
        objectType = mapObject->type();

        if (const MapObject *templateObject = mapObject->templateObject())
            if (templateObject->hasProperty(name))
                return templateObject->property(name);

        if (Tile *tile = mapObject->cell().tile()) {
            if (tile->hasProperty(name))
                return tile->property(name);

            if (objectType.isEmpty())
                objectType = tile->type();
        }

        break;
    }
    case TileType:
        objectType = static_cast<const Tile*>(this)->type();
        break;
    default:
        return QVariant();
    }

    if (!objectType.isEmpty()) {
        for (const ObjectType &type : qAsConst(mObjectTypes)) {
            if (type.name == objectType)
                if (type.defaultProperties.contains(name))
                    return type.defaultProperties.value(name);
        }
    }

    return QVariant();
}
Пример #16
0
void ServiceDiscovery::updateServices()
{
    QMap<QString, QList<ServiceDiscoveryItem*> > oldServiceTypeMap;

    oldServiceTypeMap = m_serviceItemsMap;

    // Iterate through all services and update all service types
    for (ServiceList *serviceList: qAsConst(m_serviceLists))
    {
        for (Service *service: *serviceList)
        {
            disconnect(service, &Service::queriesChanged,
                       this, &ServiceDiscovery::updateServices);
            connect(service, &Service::queriesChanged,
                    this, &ServiceDiscovery::updateServices);
            for (ServiceDiscoveryQuery *query: *service)
            {
                if (!query->serviceType().isEmpty())
                {
                    addServiceType(query->serviceType(), query->queryType());
                    oldServiceTypeMap.remove(query->serviceType());
                    if (m_running && m_networkReady)
                    {
                        startQuery(query->serviceType());
                    }
                }
            }
        }
    }

    // Iterate trough all items that are left and remove them
    for (auto iter = oldServiceTypeMap.begin(); iter != oldServiceTypeMap.end(); ++iter)
    {
        if (m_running && m_networkReady)
        {
            stopQuery(iter.key());
        }
        removeServiceType(iter.key());
    }

    updateAllServiceTypes(); // now we need to refill all queries with fresh data
}
Пример #17
0
ProductData CommandLineFrontend::getTheOneRunnableProduct()
{
    QBS_CHECK(m_projects.size() == 1); // Has been checked earlier.

    if (m_parser.products().size() == 1) {
        const auto products = m_projects.front().projectData().allProducts();
        for (const ProductData &p : products) {
            if (p.name() == m_parser.products().constFirst())
                return p;
        }
        QBS_CHECK(false);
    }
    QBS_CHECK(m_parser.products().size() == 0);

    QList<ProductData> runnableProducts;
    const auto products = m_projects.front().projectData().allProducts();
    for (const ProductData &p : products) {
        if (p.isRunnable())
            runnableProducts.push_back(p);
    }

    if (runnableProducts.size() == 1)
        return runnableProducts.front();

    if (runnableProducts.empty()) {
        throw ErrorInfo(Tr::tr("Cannot execute command '%1': Project has no runnable product.")
                        .arg(m_parser.commandName()));
    }

    ErrorInfo error(Tr::tr("Ambiguous use of command '%1': No product given, but project "
                           "has more than one runnable product.").arg(m_parser.commandName()));
    error.append(Tr::tr("Use the '--products' option with one of the following products:"));
    for (const ProductData &p : qAsConst(runnableProducts)) {
        QString productRepr = QLatin1String("\t") + p.name();
        if (p.profile() != m_projects.front().profile()) {
            productRepr.append(QLatin1String(" [")).append(p.profile())
                    .append(QLatin1Char(']'));
        }
        error.append(productRepr);
    }
    throw error;
}
Пример #18
0
/************************************************
 The element has no content. The element should be treated as if it were a list of
 <MergeDir> elements containing the default merge directory locations. When expanding
 <DefaultMergeDirs> to a list of <MergeDir>, the default locations that are earlier
 in the search path go later in the <Menu> so that they have priority.

 Note that a system that uses either gnome-applications.menu or kde-applications.menu
 depending on the desktop environment in use must still use applications-merged as the
 default merge directory in both cases.

 Implementations may chose to use .menu files with names other than application.menu
 for tasks or menus other than the main application menu. In that case the first part
 of the name of the default merge directory is derived from the name of the .menu file.
 ************************************************/
void XdgMenuReader::processDefaultMergeDirsTag(QDomElement& element, QStringList* mergedFiles)
{
    //qDebug() << "Process " << element;// << "in" << mFileName;

    QString menuBaseName = QFileInfo(mMenu->menuFileName()).baseName();
    int n = menuBaseName.lastIndexOf(QLatin1Char('-'));
    if (n>-1)
        menuBaseName = menuBaseName.mid(n+1);

    QStringList dirs = XdgDirs::configDirs();
    dirs << XdgDirs::configHome();

    for (const QString &dir : qAsConst(dirs))
    {
        mergeDir(QString::fromLatin1("%1/menus/%2-merged").arg(dir, menuBaseName), element, mergedFiles);
    }

    if (menuBaseName == QLatin1String("applications"))
        mergeFile(QString::fromLatin1("%1/menus/applications-kmenuedit.menu").arg(XdgDirs::configHome()), element, mergedFiles);
}
Пример #19
0
void ScreenshotManager::uploadDone(const QString &fileName, const QString &url, const QString &deleteHash)
{
    for (Screenshot *screenshot : qAsConst(mScreenshots)) {
        if (screenshot->options().fileName == fileName
                || screenshot->unloadedFileName() == fileName) {
            screenshot->uploadDone(url);

            if (screenshot->options().file) {
                updateHistory(fileName, url, deleteHash);
            } else {
                saveHistory("", url, deleteHash);
            }

            return;
        }
    }

    // If we get here, it's because the screenshot upload wasn't on the current screenshot list, which means it's a View History/Upload Later upload.
    updateHistory(fileName, url, deleteHash);
}
Пример #20
0
void ServiceDiscovery::startQuery(const QString &serviceType)
{
    int queryId;

    for (const auto &value: qAsConst(m_queryIdServiceMap))
    {
        if (value == serviceType)  // query with the type already running
        {
            return;
        }
    }

    QJDns::Type queryType = m_serviceTypeMap.value(serviceType);

    queryId = m_jdns->queryStart(serviceType.toLocal8Bit(), queryType);
    m_queryIdTypeMap.insert(queryId, queryType);
    m_queryIdServiceMap.insert(queryId, serviceType);

    DEBUG_TAG(1, "SD", "Started query" << queryId << serviceType << queryType);
}
Пример #21
0
void EngineManagementWidget::removeEngine()
{
	const QItemSelection selection =
		m_filteredModel->mapSelectionToSource(ui->m_enginesList->selectionModel()->selection());
	QModelIndexList selected = selection.indexes();

	// Can't use std::greater because operator> isn't implemented
	// for QModelIndex.
	std::sort(selected.begin(), selected.end(),
	[](const QModelIndex &a, const QModelIndex &b)
	{
		return b < a;
	});

	if (!selected.isEmpty())
	{
		for (const QModelIndex& index : qAsConst(selected))
			m_engineManager->removeEngineAt(index.row());
		m_hasChanged = true;
	}
}
Пример #22
0
QString XdgMimeType::iconName() const
{
    if (dx->computed) {
        return dx->iconName;
    } else {
        dx->iconName.clear();
        QStringList names;

        names.append(QMimeType::iconName());
        names.append(QMimeType::genericIconName());

        for (const QString &s : qAsConst(names)) {
            if (!XdgIcon::fromTheme(s).isNull()) {
                dx->iconName = s;
                break;
            }
        }
        dx->computed = true;
        return dx->iconName;
    }
}
Пример #23
0
void QQuickAnimatorController::windowNodesDestroyed()
{
    for (const QSharedPointer<QAbstractAnimationJob> &toStop : qAsConst(m_rootsPendingStop)) {
        qquickanimator_invalidate_jobs(toStop.data());
        toStop->stop();
    }
    m_rootsPendingStop.clear();

    // Clear animation roots and iterate over a temporary to avoid that job->stop()
    // modifies the m_animationRoots and messes with our iteration
    const auto roots = m_animationRoots;
    m_animationRoots.clear();
    for (const QSharedPointer<QAbstractAnimationJob> &job : roots) {
        qquickanimator_invalidate_jobs(job.data());

        // Stop it and add it to the list of pending start so it might get
        // started later on.
        job->stop();
        m_rootsPendingStart.insert(job);
    }
}
Пример #24
0
void ServiceDiscovery::updateNameServers()
{
    QList<QJDns::NameServer> nameServers;

    if ((m_jdns.isNull()) || (m_lookupMode != UnicastDNS))
    {
        return;
    }

    for (const NameServer *nameServer: qAsConst(m_nameServers))
    {
        QJDns::NameServer host;

        if (nameServer->hostAddress().isNull())
        {
            continue;
        }

        host.address = nameServer->hostAddress();
        host.port = nameServer->port();
        nameServers.append(host);
    }

    if (nameServers.isEmpty())
    {
        nameServers = QJDns::systemInfo().nameServers;
    }

    if (nameServers.isEmpty())
    {
        qWarning() << "Warning: no name servers";
    }

    m_jdns->setNameServers(nameServers);

    if (m_running)
    {
        refreshAllQueries();
    }
}
Пример #25
0
void QQuickShapeSoftwareRenderNode::render(const RenderState *state)
{
    if (m_sp.isEmpty())
        return;

    QSGRendererInterface *rif = m_item->window()->rendererInterface();
    QPainter *p = static_cast<QPainter *>(rif->getResource(m_item->window(), QSGRendererInterface::PainterResource));
    Q_ASSERT(p);

    const QRegion *clipRegion = state->clipRegion();
    if (clipRegion && !clipRegion->isEmpty())
        p->setClipRegion(*clipRegion, Qt::ReplaceClip); // must be done before setTransform

    p->setTransform(matrix()->toTransform());
    p->setOpacity(inheritedOpacity());

    for (const ShapePathRenderData &d : qAsConst(m_sp)) {
        p->setPen(d.strokeWidth >= 0.0f && d.pen.color() != Qt::transparent ? d.pen : Qt::NoPen);
        p->setBrush(d.brush.color() != Qt::transparent ? d.brush : Qt::NoBrush);
        p->drawPath(d.path);
    }
}
Пример #26
0
void NavigationBar::aboutToShowToolsMenu()
{
    m_menuTools->clear();

    m_window->createToolbarsMenu(m_menuTools->addMenu(tr("Toolbars")));
    m_window->createSidebarsMenu(m_menuTools->addMenu(tr("Sidebar")));
    m_menuTools->addSeparator();

    for (const WidgetData &data : qAsConst(m_widgets)) {
        AbstractButtonInterface *button = data.button;
        if (button && (!button->isVisible() || !m_layoutIds.contains(data.id))) {
            QString title = button->title();
            if (!button->badgeText().isEmpty()) {
                title.append(QSL(" (%1)").arg(button->badgeText()));
            }
            m_menuTools->addAction(button->icon(), title, this, &NavigationBar::toolActionActivated)->setData(data.id);
        }
    }

    m_menuTools->addSeparator();
    m_menuTools->addAction(IconProvider::settingsIcon(), tr("Configure Toolbar"), this, SLOT(openConfigurationDialog()));
}
Пример #27
0
QJsonObject TileStamp::toJson(const QDir &dir) const
{
    QJsonObject json;
    json.insert(QLatin1String("name"), d->name);

    if (d->quickStampIndex != -1)
        json.insert(QLatin1String("quickStampIndex"), d->quickStampIndex);

    QJsonArray variations;
    for (const TileStampVariation &variation : qAsConst(d->variations)) {
        MapToVariantConverter converter;
        QVariant mapVariant = converter.toVariant(*variation.map, dir);
        QJsonValue mapJson = QJsonValue::fromVariant(mapVariant);

        QJsonObject variationJson;
        variationJson.insert(QLatin1String("probability"), variation.probability);
        variationJson.insert(QLatin1String("map"), mapJson);
        variations.append(variationJson);
    }
    json.insert(QLatin1String("variations"), variations);

    return json;
}
Пример #28
0
void MimetypeViewer::loadAllMimeTypes()
{
    mediaTypes.clear();
    mGroupItems.clear();
    mItemList.clear();
    QStringList selectedMimeTypes;

    QMimeDatabase db;
    QList<QMimeType> mimetypes = db.allMimeTypes();

    qSort(mimetypes.begin(), mimetypes.end(), mimeTypeLessThan);
    for (const QMimeType &mt : qAsConst(mimetypes)) {
        const QString mimetype = mt.name();
        const int i = mimetype.indexOf(QLatin1Char('/'));
        const QString mediaType = mimetype.left(i);
        const QString subType = mimetype.mid(i + 1);

        MimeTypeData* data = new MimeTypeData(mt);

        if (!mediaTypes.contains(mediaType)) { // A new type of media
            mediaTypes.append(mediaType);
            QTreeWidgetItem *item = new QTreeWidgetItem(widget.mimetypeTreeWidget, GroupType);
            item->setText(0, mediaType);
            widget.mimetypeTreeWidget->insertTopLevelItem(0, item);
            mGroupItems.insert(mediaType, item);
        }
        QTreeWidgetItem *item = new QTreeWidgetItem(mGroupItems.value(mediaType), EntrieType);
        QVariant v;
        v.setValue(*data);
        item->setData(0, Qt::UserRole, v);
        item->setText(0, subType);
        mItemList.append(item);
    }

    widget.mimetypeTreeWidget->resizeColumnToContents(1);
    widget.mimetypeTreeWidget->show();
}
Пример #29
0
void LdapNetworkObjectDirectory::update()
{
	LdapDirectory ldapDirectory( m_configuration );

	const auto computerRooms = ldapDirectory.computerRooms();
	const NetworkObject rootObject( NetworkObject::Root );

	for( const auto& computerRoom : qAsConst( computerRooms ) )
	{
		NetworkObject computerRoomObject( NetworkObject::Group, computerRoom );

		if( m_objects.contains( computerRoomObject ) == false )
		{
			emit objectsAboutToBeInserted( rootObject, m_objects.count(), 1 );
			m_objects[computerRoomObject] = QList<NetworkObject>();
			emit objectsInserted();
		}

		updateComputerRoom( ldapDirectory, computerRoom );
	}

	int index = 0;
	for( auto it = m_objects.begin(); it != m_objects.end(); )
	{
		if( computerRooms.contains( it.key().name() ) == false )
		{
			emit objectsAboutToBeRemoved( rootObject, index, 1 );
			it = m_objects.erase( it );
			emit objectsRemoved();
		}
		else
		{
			++it;
			++index;
		}
	}
}
BatteryInfoDialog::BatteryInfoDialog(QList<Solid::Battery*> batteries, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::BatteryInfoDialog)
{
    ui->setupUi(this);

    setWindowTitle(tr("Battery Info"));

    if (batteries.size() == 1)
    {
        BatteryInfoFrame *batteryInfoFrame = new BatteryInfoFrame(batteries[0]);
        ui->verticalLayout->insertWidget(0, batteryInfoFrame);
    }
    else
    {
        QTabWidget *tabWidget = new QTabWidget(this);
        ui->verticalLayout->insertWidget(0, tabWidget);
        for (Solid::Battery *const battery : qAsConst(batteries))
        {
            BatteryInfoFrame *batteryInfoFrame = new BatteryInfoFrame(battery);
            tabWidget->addTab(batteryInfoFrame, QSL("BAT"));
        }
    }
}